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
|
|---|---|---|---|---|
39
|
// DEFENDER WINS
|
if (checkRandom(_random, _threshold)) {
|
if (checkRandom(_random, _threshold)) {
| 45,483
|
48
|
// Rate and cap for tier 2
|
uint256 public tier_rate_2 = 1440;
uint256 public tier_cap_2 = 14400000;
|
uint256 public tier_rate_2 = 1440;
uint256 public tier_cap_2 = 14400000;
| 51,794
|
10
|
// ILendingPool interface
|
function claimRewards(address[] calldata assets,
uint256 amount,
address to)
|
function claimRewards(address[] calldata assets,
uint256 amount,
address to)
| 44,983
|
3
|
// Mapping from owner to number of owned token
|
mapping (address => uint256) internal ownedTokensCount;
|
mapping (address => uint256) internal ownedTokensCount;
| 6,127
|
292
|
// checkpoint or cap to duration -> 0 ~ duration
|
return uint8(Math.min(checkpoint, uint256(duration)));
|
return uint8(Math.min(checkpoint, uint256(duration)));
| 75,126
|
2
|
// triggered when a liquidity pool is added to the registryliquidityPool liquidity pool /
|
event LiquidityPoolAdded(IConverterAnchor indexed liquidityPool);
|
event LiquidityPoolAdded(IConverterAnchor indexed liquidityPool);
| 11,226
|
108
|
// calculate value of userLPEndTimestamp. For that first calculate the time of emission end and last LP Supply timeshare updated timestamp
|
_lpTimeShareTimestampEnd = _rewardEmissionTimestamp[holderAddress][
rewardTokenAddress
].length;
_emissionEnd = _rewardEmissionTimestamp[holderAddress][
rewardTokenAddress
][(_lpTimeShareTimestampEnd).sub(1)];
_lpTimeShareTimestampEnd = _lastLPTimeShareTimestampArray[
lpTokenAddress
][(_lastLPTimeShareTimestampArray[lpTokenAddress].length).sub(1)];
|
_lpTimeShareTimestampEnd = _rewardEmissionTimestamp[holderAddress][
rewardTokenAddress
].length;
_emissionEnd = _rewardEmissionTimestamp[holderAddress][
rewardTokenAddress
][(_lpTimeShareTimestampEnd).sub(1)];
_lpTimeShareTimestampEnd = _lastLPTimeShareTimestampArray[
lpTokenAddress
][(_lastLPTimeShareTimestampArray[lpTokenAddress].length).sub(1)];
| 43,315
|
11
|
// sanity checks
|
if (_amount == 0) revert InvalidAmount();
if (_beneficiary == address(0)) revert InvalidBeneficiary();
if (_startTimestamp == 0) revert InvalidStartTimestamp();
if (_durationInSeconds == 0) revert InvalidDuration();
if (_cliffDate <= _startTimestamp) revert InvalidCliffStart(_cliffDate, _startTimestamp);
if (_cliffDate > _startTimestamp + _durationInSeconds) revert InvalidCliffStart(_cliffDate, _startTimestamp + _durationInSeconds);
|
if (_amount == 0) revert InvalidAmount();
if (_beneficiary == address(0)) revert InvalidBeneficiary();
if (_startTimestamp == 0) revert InvalidStartTimestamp();
if (_durationInSeconds == 0) revert InvalidDuration();
if (_cliffDate <= _startTimestamp) revert InvalidCliffStart(_cliffDate, _startTimestamp);
if (_cliffDate > _startTimestamp + _durationInSeconds) revert InvalidCliffStart(_cliffDate, _startTimestamp + _durationInSeconds);
| 35,123
|
4
|
// EVENTS//CONSTRUCTOR/
|
) public onlyRoot {
_data = data;
_prices = prices;
_userSubscriptionCode = userSubscriptionCode;
_active = true;
keepBalance(Balances.SUBSCRIPTION_PLAN_BALANCE);
}
|
) public onlyRoot {
_data = data;
_prices = prices;
_userSubscriptionCode = userSubscriptionCode;
_active = true;
keepBalance(Balances.SUBSCRIPTION_PLAN_BALANCE);
}
| 19,174
|
30
|
// This is for per user
|
library AccountTokenLib {
using SafeMath for uint256;
struct TokenInfo {
// Deposit info
uint256 depositPrincipal; // total deposit principal of ther user
uint256 depositInterest; // total deposit interest of the user
uint256 lastDepositBlock; // the block number of user's last deposit
// Borrow info
uint256 borrowPrincipal; // total borrow principal of ther user
uint256 borrowInterest; // total borrow interest of ther user
uint256 lastBorrowBlock; // the block number of user's last borrow
}
uint256 constant BASE = 10**18;
// returns the principal
function getDepositPrincipal(TokenInfo storage self) public view returns(uint256) {
return self.depositPrincipal;
}
function getBorrowPrincipal(TokenInfo storage self) public view returns(uint256) {
return self.borrowPrincipal;
}
function getDepositBalance(TokenInfo storage self, uint accruedRate) public view returns(uint256) {
return self.depositPrincipal.add(calculateDepositInterest(self, accruedRate));
}
function getBorrowBalance(TokenInfo storage self, uint accruedRate) public view returns(uint256) {
return self.borrowPrincipal.add(calculateBorrowInterest(self, accruedRate));
}
function getLastDepositBlock(TokenInfo storage self) public view returns(uint256) {
return self.lastDepositBlock;
}
function getLastBorrowBlock(TokenInfo storage self) public view returns(uint256) {
return self.lastBorrowBlock;
}
function getDepositInterest(TokenInfo storage self) public view returns(uint256) {
return self.depositInterest;
}
function getBorrowInterest(TokenInfo storage self) public view returns(uint256) {
return self.borrowInterest;
}
function borrow(TokenInfo storage self, uint256 amount, uint256 accruedRate, uint256 _block) public {
newBorrowCheckpoint(self, accruedRate, _block);
self.borrowPrincipal = self.borrowPrincipal.add(amount);
}
/**
* Update token info for withdraw. The interest will be withdrawn with higher priority.
*/
function withdraw(TokenInfo storage self, uint256 amount, uint256 accruedRate, uint256 _block) public {
newDepositCheckpoint(self, accruedRate, _block);
if (self.depositInterest >= amount) {
self.depositInterest = self.depositInterest.sub(amount);
} else if (self.depositPrincipal.add(self.depositInterest) >= amount) {
self.depositPrincipal = self.depositPrincipal.sub(amount.sub(self.depositInterest));
self.depositInterest = 0;
} else {
self.depositPrincipal = 0;
self.depositInterest = 0;
}
}
/**
* Update token info for deposit
*/
function deposit(TokenInfo storage self, uint256 amount, uint accruedRate, uint256 _block) public {
newDepositCheckpoint(self, accruedRate, _block);
self.depositPrincipal = self.depositPrincipal.add(amount);
}
function repay(TokenInfo storage self, uint256 amount, uint accruedRate, uint256 _block) public {
// updated rate (new index rate), applying the rate from startBlock(checkpoint) to currBlock
newBorrowCheckpoint(self, accruedRate, _block);
// user owes money, then he tries to repays
if (self.borrowInterest > amount) {
self.borrowInterest = self.borrowInterest.sub(amount);
} else if (self.borrowPrincipal.add(self.borrowInterest) > amount) {
self.borrowPrincipal = self.borrowPrincipal.sub(amount.sub(self.borrowInterest));
self.borrowInterest = 0;
} else {
self.borrowPrincipal = 0;
self.borrowInterest = 0;
}
}
function newDepositCheckpoint(TokenInfo storage self, uint accruedRate, uint256 _block) public {
self.depositInterest = calculateDepositInterest(self, accruedRate);
self.lastDepositBlock = _block;
}
function newBorrowCheckpoint(TokenInfo storage self, uint accruedRate, uint256 _block) public {
self.borrowInterest = calculateBorrowInterest(self, accruedRate);
self.lastBorrowBlock = _block;
}
// Calculating interest according to the new rate
// calculated starting from last deposit checkpoint
function calculateDepositInterest(TokenInfo storage self, uint accruedRate) public view returns(uint256) {
return self.depositPrincipal.add(self.depositInterest).mul(accruedRate).sub(self.depositPrincipal.mul(BASE)).div(BASE);
}
function calculateBorrowInterest(TokenInfo storage self, uint accruedRate) public view returns(uint256) {
uint256 _balance = self.borrowPrincipal;
if(accruedRate == 0 || _balance == 0 || BASE >= accruedRate) {
return self.borrowInterest;
} else {
return _balance.add(self.borrowInterest).mul(accruedRate).sub(_balance.mul(BASE)).div(BASE);
}
}
}
|
library AccountTokenLib {
using SafeMath for uint256;
struct TokenInfo {
// Deposit info
uint256 depositPrincipal; // total deposit principal of ther user
uint256 depositInterest; // total deposit interest of the user
uint256 lastDepositBlock; // the block number of user's last deposit
// Borrow info
uint256 borrowPrincipal; // total borrow principal of ther user
uint256 borrowInterest; // total borrow interest of ther user
uint256 lastBorrowBlock; // the block number of user's last borrow
}
uint256 constant BASE = 10**18;
// returns the principal
function getDepositPrincipal(TokenInfo storage self) public view returns(uint256) {
return self.depositPrincipal;
}
function getBorrowPrincipal(TokenInfo storage self) public view returns(uint256) {
return self.borrowPrincipal;
}
function getDepositBalance(TokenInfo storage self, uint accruedRate) public view returns(uint256) {
return self.depositPrincipal.add(calculateDepositInterest(self, accruedRate));
}
function getBorrowBalance(TokenInfo storage self, uint accruedRate) public view returns(uint256) {
return self.borrowPrincipal.add(calculateBorrowInterest(self, accruedRate));
}
function getLastDepositBlock(TokenInfo storage self) public view returns(uint256) {
return self.lastDepositBlock;
}
function getLastBorrowBlock(TokenInfo storage self) public view returns(uint256) {
return self.lastBorrowBlock;
}
function getDepositInterest(TokenInfo storage self) public view returns(uint256) {
return self.depositInterest;
}
function getBorrowInterest(TokenInfo storage self) public view returns(uint256) {
return self.borrowInterest;
}
function borrow(TokenInfo storage self, uint256 amount, uint256 accruedRate, uint256 _block) public {
newBorrowCheckpoint(self, accruedRate, _block);
self.borrowPrincipal = self.borrowPrincipal.add(amount);
}
/**
* Update token info for withdraw. The interest will be withdrawn with higher priority.
*/
function withdraw(TokenInfo storage self, uint256 amount, uint256 accruedRate, uint256 _block) public {
newDepositCheckpoint(self, accruedRate, _block);
if (self.depositInterest >= amount) {
self.depositInterest = self.depositInterest.sub(amount);
} else if (self.depositPrincipal.add(self.depositInterest) >= amount) {
self.depositPrincipal = self.depositPrincipal.sub(amount.sub(self.depositInterest));
self.depositInterest = 0;
} else {
self.depositPrincipal = 0;
self.depositInterest = 0;
}
}
/**
* Update token info for deposit
*/
function deposit(TokenInfo storage self, uint256 amount, uint accruedRate, uint256 _block) public {
newDepositCheckpoint(self, accruedRate, _block);
self.depositPrincipal = self.depositPrincipal.add(amount);
}
function repay(TokenInfo storage self, uint256 amount, uint accruedRate, uint256 _block) public {
// updated rate (new index rate), applying the rate from startBlock(checkpoint) to currBlock
newBorrowCheckpoint(self, accruedRate, _block);
// user owes money, then he tries to repays
if (self.borrowInterest > amount) {
self.borrowInterest = self.borrowInterest.sub(amount);
} else if (self.borrowPrincipal.add(self.borrowInterest) > amount) {
self.borrowPrincipal = self.borrowPrincipal.sub(amount.sub(self.borrowInterest));
self.borrowInterest = 0;
} else {
self.borrowPrincipal = 0;
self.borrowInterest = 0;
}
}
function newDepositCheckpoint(TokenInfo storage self, uint accruedRate, uint256 _block) public {
self.depositInterest = calculateDepositInterest(self, accruedRate);
self.lastDepositBlock = _block;
}
function newBorrowCheckpoint(TokenInfo storage self, uint accruedRate, uint256 _block) public {
self.borrowInterest = calculateBorrowInterest(self, accruedRate);
self.lastBorrowBlock = _block;
}
// Calculating interest according to the new rate
// calculated starting from last deposit checkpoint
function calculateDepositInterest(TokenInfo storage self, uint accruedRate) public view returns(uint256) {
return self.depositPrincipal.add(self.depositInterest).mul(accruedRate).sub(self.depositPrincipal.mul(BASE)).div(BASE);
}
function calculateBorrowInterest(TokenInfo storage self, uint accruedRate) public view returns(uint256) {
uint256 _balance = self.borrowPrincipal;
if(accruedRate == 0 || _balance == 0 || BASE >= accruedRate) {
return self.borrowInterest;
} else {
return _balance.add(self.borrowInterest).mul(accruedRate).sub(_balance.mul(BASE)).div(BASE);
}
}
}
| 28,224
|
32
|
// The flag indicates if the crowdsale contract is in Funding state.
|
bool public fundraising = true;
|
bool public fundraising = true;
| 30,024
|
25
|
// Set Hierarchy information to a specific node with locationId in batchparam locationIds A batch of locationIdparam parentLocationIds A batch of parentLocationIdsparam listChildLocationIds A batch of childLocationIds /
|
function setHierarchy(
uint16[] memory locationIds,
uint16[] memory parentLocationIds,
uint16[][] memory listChildLocationIds
|
function setHierarchy(
uint16[] memory locationIds,
uint16[] memory parentLocationIds,
uint16[][] memory listChildLocationIds
| 78,647
|
67
|
// Set the prize pool percentage the winner will receive.
|
winningPercentage = _newValue;
return;
|
winningPercentage = _newValue;
return;
| 6,829
|
0
|
// This interface extends the IFilteredMinterV0 interface in order toadd support for including owned NFT token address and token ID information. Art Blocks Inc. /
|
interface IFilteredMinterHolderV0 is IFilteredMinterV0 {
/**
* @notice Registered holders of NFTs at address `_NFTAddress` to be
* considered for minting.
*/
event RegisteredNFTAddress(address indexed _NFTAddress);
/**
* @notice Unregistered holders of NFTs at address `_NFTAddress` to be
* considered for minting.
*/
event UnregisteredNFTAddress(address indexed _NFTAddress);
/**
* @notice Allow holders of NFTs at addresses `_ownedNFTAddresses`, project
* IDs `_ownedNFTProjectIds` to mint on project `_projectId`.
* `_ownedNFTAddresses` assumed to be aligned with `_ownedNFTProjectIds`.
* e.g. Allows holders of project `_ownedNFTProjectIds[0]` on token
* contract `_ownedNFTAddresses[0]` to mint.
*/
event AllowedHoldersOfProjects(
uint256 indexed _projectId,
address[] _ownedNFTAddresses,
uint256[] _ownedNFTProjectIds
);
/**
* @notice Remove holders of NFTs at addresses `_ownedNFTAddresses`,
* project IDs `_ownedNFTProjectIds` to mint on project `_projectId`.
* `_ownedNFTAddresses` assumed to be aligned with `_ownedNFTProjectIds`.
* e.g. Removes holders of project `_ownedNFTProjectIds[0]` on token
* contract `_ownedNFTAddresses[0]` from mint allowlist.
*/
event RemovedHoldersOfProjects(
uint256 indexed _projectId,
address[] _ownedNFTAddresses,
uint256[] _ownedNFTProjectIds
);
// Triggers a purchase of a token from the desired project, to the
// TX-sending address, using owned ERC-721 NFT to claim right to purchase.
function purchase(
uint256 _projectId,
address _ownedNftAddress,
uint256 _ownedNftTokenId
) external payable returns (uint256 tokenId);
// Triggers a purchase of a token from the desired project, to the specified
// receiving address, using owned ERC-721 NFT to claim right to purchase.
function purchaseTo(
address _to,
uint256 _projectId,
address _ownedNftAddress,
uint256 _ownedNftTokenId
) external payable returns (uint256 tokenId);
}
|
interface IFilteredMinterHolderV0 is IFilteredMinterV0 {
/**
* @notice Registered holders of NFTs at address `_NFTAddress` to be
* considered for minting.
*/
event RegisteredNFTAddress(address indexed _NFTAddress);
/**
* @notice Unregistered holders of NFTs at address `_NFTAddress` to be
* considered for minting.
*/
event UnregisteredNFTAddress(address indexed _NFTAddress);
/**
* @notice Allow holders of NFTs at addresses `_ownedNFTAddresses`, project
* IDs `_ownedNFTProjectIds` to mint on project `_projectId`.
* `_ownedNFTAddresses` assumed to be aligned with `_ownedNFTProjectIds`.
* e.g. Allows holders of project `_ownedNFTProjectIds[0]` on token
* contract `_ownedNFTAddresses[0]` to mint.
*/
event AllowedHoldersOfProjects(
uint256 indexed _projectId,
address[] _ownedNFTAddresses,
uint256[] _ownedNFTProjectIds
);
/**
* @notice Remove holders of NFTs at addresses `_ownedNFTAddresses`,
* project IDs `_ownedNFTProjectIds` to mint on project `_projectId`.
* `_ownedNFTAddresses` assumed to be aligned with `_ownedNFTProjectIds`.
* e.g. Removes holders of project `_ownedNFTProjectIds[0]` on token
* contract `_ownedNFTAddresses[0]` from mint allowlist.
*/
event RemovedHoldersOfProjects(
uint256 indexed _projectId,
address[] _ownedNFTAddresses,
uint256[] _ownedNFTProjectIds
);
// Triggers a purchase of a token from the desired project, to the
// TX-sending address, using owned ERC-721 NFT to claim right to purchase.
function purchase(
uint256 _projectId,
address _ownedNftAddress,
uint256 _ownedNftTokenId
) external payable returns (uint256 tokenId);
// Triggers a purchase of a token from the desired project, to the specified
// receiving address, using owned ERC-721 NFT to claim right to purchase.
function purchaseTo(
address _to,
uint256 _projectId,
address _ownedNftAddress,
uint256 _ownedNftTokenId
) external payable returns (uint256 tokenId);
}
| 8,724
|
176
|
// Forcibly cancel delegate lock/This function will attempt to notify the delegate of the rage quit using/a fixed amount of gas./ access control: only owner/ state machine: after valid lock from delegate/ state scope:/ - remove item from _locks/ token transfer: none/delegate Address of delegate/token Address of token being unlocked
|
function rageQuit(address delegate, address token)
external
override
onlyOwner
returns (bool notified, string memory error)
|
function rageQuit(address delegate, address token)
external
override
onlyOwner
returns (bool notified, string memory error)
| 33,656
|
218
|
// Caller must be initialized module and module must be enabled on the controller /
|
function _validateOnlyModule(ISetToken _setToken) internal view {
require(
_setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
}
|
function _validateOnlyModule(ISetToken _setToken) internal view {
require(
_setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
}
| 60,895
|
108
|
// Check whether we need to refresh the daily limit
|
bytes32 history = accountsBoughtZoAsset[msg.sender];
if (accountsZoLastRefreshTime[msg.sender] == uint256(0)) {
|
bytes32 history = accountsBoughtZoAsset[msg.sender];
if (accountsZoLastRefreshTime[msg.sender] == uint256(0)) {
| 75,563
|
8
|
// mapping address-> VCA token used for VCA divs calculation. The way the system works is that deductBalances is starting as totalSharesOf x price of the respective token. So when the token price appreciates, the interest earned is the difference between totalSharesOf x new price - deductBalance [respective token]
|
mapping(address => mapping(address => uint256)) internal deductBalances;
bool internal paused;
|
mapping(address => mapping(address => uint256)) internal deductBalances;
bool internal paused;
| 50,991
|
1
|
// How much decay this side of the pool accrued between (0, this user's entry block), stored as a multiplier expressed as an 18-decimal mantissa. For example, if this side of the pool accrued a decay of 20% during this time period, we'd store 1.2e18 (staking side) or 0.8e18 (challenger side).
|
uint256 startDecayMultiplier;
|
uint256 startDecayMultiplier;
| 1,165
|
113
|
// Attempt to issue tokens
|
if (!dnnToken.issueTokens(beneficiary, tokenCount, allocationType)) {
revert();
}
|
if (!dnnToken.issueTokens(beneficiary, tokenCount, allocationType)) {
revert();
}
| 46,040
|
122
|
// MasterChef is the master of rewardToken. He can make rewardToken and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once rewardToken is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless.
|
contract FEIIMasterChef is Authorizable,UniswapUtils {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of rewardTokens
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accrewardTokenPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accrewardTokenPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. rewardTokens to distribute per block.
uint256 lastRewardBlock; // Last block number that rewardTokens distribution occurs.
uint256 accrewardTokenPerShare; // Accumulated rewardTokens per share, times 1e12. See below.
}
// The rewardToken TOKEN!
IRewardToken public rewardToken;
address public uniswapRouter;
// Dev address.
address public devAddr;
uint256 public protocolFee = 1000; //1%
uint256 public devRewardAmount;
// rewardToken tokens created per block.
uint256 public rewardTokenPerBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when rewardToken mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount,uint256 rewardToken);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount,uint256 rewardToken);
constructor(
address _uniswapRouter,
address _rewardToken,
uint256 _rewardTokenPerBlock,
uint256 _startBlock
) public {
rewardToken = IRewardToken(_rewardToken);
devAddr = msg.sender;
uniswapRouter = _uniswapRouter;
rewardTokenPerBlock = _rewardTokenPerBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyAuthorized {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock =
block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accrewardTokenPerShare: 0
})
);
}
// Update the given pool's rewardToken allocation point. Can only be called by the owner.
function set(uint256 _pid,uint256 _allocPoint, bool _withUpdate) public onlyAuthorized {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
function updateDevAddr(address _dev,uint256 _fee) public onlyAuthorized{
devAddr = _dev;
protocolFee = _fee;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256){
return _to.sub(_from);
}
// View function to see pending rewardTokens on frontend.
function pendingrewardToken(uint256 _pid, address _user)external view returns (uint256){
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accrewardTokenPerShare = pool.accrewardTokenPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier =
getMultiplier(pool.lastRewardBlock, block.number);
uint256 rewardTokenReward =
multiplier.mul(rewardTokenPerBlock).mul(pool.allocPoint).div(
totalAllocPoint
);
accrewardTokenPerShare = accrewardTokenPerShare.add(
rewardTokenReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accrewardTokenPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 rewardTokenReward = multiplier.mul(rewardTokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
devRewardAmount = devRewardAmount.add(rewardTokenReward.div(10));
rewardToken.mint(address(this), rewardTokenReward);
pool.accrewardTokenPerShare = pool.accrewardTokenPerShare.add(
rewardTokenReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for rewardToken allocation.
function deposit(uint256 _pid, uint256 _amount) public {
require(block.number >= startBlock,"!start");
uint256 pending = 0;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
pending = user.amount.mul(pool.accrewardTokenPerShare).div(1e12).sub(user.rewardDebt);
safeRewardTokenTransfer(msg.sender, pending);
}
//save gas for claimReward
if(_amount > 0){
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accrewardTokenPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount,pending);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
UserInfo storage dever = userInfo[_pid][devAddr];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accrewardTokenPerShare).div(1e12).sub(user.rewardDebt);
safeRewardTokenTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accrewardTokenPerShare).div(1e12);
uint256 _fee = _amount.mul(protocolFee).div(PERCENT);
dever.amount = dever.amount.add(_fee);
pool.lpToken.safeTransfer(address(msg.sender), _amount.sub(_fee));
emit Withdraw(msg.sender, _pid, _amount,pending);
}
function claimReward(uint256 _pid) public {
deposit(_pid,0);
}
function rewardTokenLiquidity(address _pair,uint256 _lpp,uint256 _cp) public onlyAuthorized{
address _token = address(rewardToken);
//only guard rewardToken
address _currency = getPairToken(_pair,_token);
LiquidityItem memory q = LiquidityItem(0,0,0,0,0,0,0,0);
//removeLiquidity
(q.tokenRemoved,q.currencyRemoved,q.liquidityRemoved) = _removeLiquidity(uniswapRouter, _pair, _token, _currency,_lpp);
//swap rewardToken
q.currencyIn = q.currencyRemoved.mul(_cp).div(PERCENT);
q.tokenOut = _swapToken(uniswapRouter,_currency,_token,q.currencyIn);
//addLiquidity
uint256 tokenRemain = q.tokenRemoved.add(q.tokenOut);
uint256 currencyRemain = q.currencyRemoved.sub(q.currencyIn);
(q.tokenAdded, q.currencyAdded, q.liquidityAdded) = _addLiquidity(uniswapRouter, _token,_currency,
tokenRemain,currencyRemain,
0,currencyRemain);
tokenRemain = tokenRemain.sub(q.tokenAdded);
//burn rewardToken
rewardToken.burn(tokenRemain);
emit LiquidityInfo(_token,_currency,_lpp,_cp,q,tokenRemain);
}
// Safe rewardToken transfer function, just in case if rounding error causes pool to not have enough rewardTokens.
function safeRewardTokenTransfer(address _to, uint256 _amount) internal {
uint256 rewardTokenBal = rewardToken.balanceOf(address(this));
if (_amount > rewardTokenBal) {
rewardToken.transfer(_to, rewardTokenBal);
} else {
rewardToken.transfer(_to, _amount);
}
}
function claimDevReward(uint256 _p) public onlyAuthorized{
require(devRewardAmount > 0,"No community rate");
uint256 _community_amount = devRewardAmount.mul(_p).div(PERCENT);
devRewardAmount = devRewardAmount.sub(_community_amount);
rewardToken.mint(msg.sender,_community_amount);
}
function updateRewardRate(uint256 _rewardTokenPerBlock,uint256 _startBlock) public onlyAuthorized{
rewardTokenPerBlock = _rewardTokenPerBlock;
startBlock = _startBlock;
}
}
|
contract FEIIMasterChef is Authorizable,UniswapUtils {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of rewardTokens
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accrewardTokenPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accrewardTokenPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. rewardTokens to distribute per block.
uint256 lastRewardBlock; // Last block number that rewardTokens distribution occurs.
uint256 accrewardTokenPerShare; // Accumulated rewardTokens per share, times 1e12. See below.
}
// The rewardToken TOKEN!
IRewardToken public rewardToken;
address public uniswapRouter;
// Dev address.
address public devAddr;
uint256 public protocolFee = 1000; //1%
uint256 public devRewardAmount;
// rewardToken tokens created per block.
uint256 public rewardTokenPerBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when rewardToken mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount,uint256 rewardToken);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount,uint256 rewardToken);
constructor(
address _uniswapRouter,
address _rewardToken,
uint256 _rewardTokenPerBlock,
uint256 _startBlock
) public {
rewardToken = IRewardToken(_rewardToken);
devAddr = msg.sender;
uniswapRouter = _uniswapRouter;
rewardTokenPerBlock = _rewardTokenPerBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyAuthorized {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock =
block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accrewardTokenPerShare: 0
})
);
}
// Update the given pool's rewardToken allocation point. Can only be called by the owner.
function set(uint256 _pid,uint256 _allocPoint, bool _withUpdate) public onlyAuthorized {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
function updateDevAddr(address _dev,uint256 _fee) public onlyAuthorized{
devAddr = _dev;
protocolFee = _fee;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256){
return _to.sub(_from);
}
// View function to see pending rewardTokens on frontend.
function pendingrewardToken(uint256 _pid, address _user)external view returns (uint256){
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accrewardTokenPerShare = pool.accrewardTokenPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier =
getMultiplier(pool.lastRewardBlock, block.number);
uint256 rewardTokenReward =
multiplier.mul(rewardTokenPerBlock).mul(pool.allocPoint).div(
totalAllocPoint
);
accrewardTokenPerShare = accrewardTokenPerShare.add(
rewardTokenReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accrewardTokenPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 rewardTokenReward = multiplier.mul(rewardTokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
devRewardAmount = devRewardAmount.add(rewardTokenReward.div(10));
rewardToken.mint(address(this), rewardTokenReward);
pool.accrewardTokenPerShare = pool.accrewardTokenPerShare.add(
rewardTokenReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for rewardToken allocation.
function deposit(uint256 _pid, uint256 _amount) public {
require(block.number >= startBlock,"!start");
uint256 pending = 0;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
pending = user.amount.mul(pool.accrewardTokenPerShare).div(1e12).sub(user.rewardDebt);
safeRewardTokenTransfer(msg.sender, pending);
}
//save gas for claimReward
if(_amount > 0){
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accrewardTokenPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount,pending);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
UserInfo storage dever = userInfo[_pid][devAddr];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accrewardTokenPerShare).div(1e12).sub(user.rewardDebt);
safeRewardTokenTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accrewardTokenPerShare).div(1e12);
uint256 _fee = _amount.mul(protocolFee).div(PERCENT);
dever.amount = dever.amount.add(_fee);
pool.lpToken.safeTransfer(address(msg.sender), _amount.sub(_fee));
emit Withdraw(msg.sender, _pid, _amount,pending);
}
function claimReward(uint256 _pid) public {
deposit(_pid,0);
}
function rewardTokenLiquidity(address _pair,uint256 _lpp,uint256 _cp) public onlyAuthorized{
address _token = address(rewardToken);
//only guard rewardToken
address _currency = getPairToken(_pair,_token);
LiquidityItem memory q = LiquidityItem(0,0,0,0,0,0,0,0);
//removeLiquidity
(q.tokenRemoved,q.currencyRemoved,q.liquidityRemoved) = _removeLiquidity(uniswapRouter, _pair, _token, _currency,_lpp);
//swap rewardToken
q.currencyIn = q.currencyRemoved.mul(_cp).div(PERCENT);
q.tokenOut = _swapToken(uniswapRouter,_currency,_token,q.currencyIn);
//addLiquidity
uint256 tokenRemain = q.tokenRemoved.add(q.tokenOut);
uint256 currencyRemain = q.currencyRemoved.sub(q.currencyIn);
(q.tokenAdded, q.currencyAdded, q.liquidityAdded) = _addLiquidity(uniswapRouter, _token,_currency,
tokenRemain,currencyRemain,
0,currencyRemain);
tokenRemain = tokenRemain.sub(q.tokenAdded);
//burn rewardToken
rewardToken.burn(tokenRemain);
emit LiquidityInfo(_token,_currency,_lpp,_cp,q,tokenRemain);
}
// Safe rewardToken transfer function, just in case if rounding error causes pool to not have enough rewardTokens.
function safeRewardTokenTransfer(address _to, uint256 _amount) internal {
uint256 rewardTokenBal = rewardToken.balanceOf(address(this));
if (_amount > rewardTokenBal) {
rewardToken.transfer(_to, rewardTokenBal);
} else {
rewardToken.transfer(_to, _amount);
}
}
function claimDevReward(uint256 _p) public onlyAuthorized{
require(devRewardAmount > 0,"No community rate");
uint256 _community_amount = devRewardAmount.mul(_p).div(PERCENT);
devRewardAmount = devRewardAmount.sub(_community_amount);
rewardToken.mint(msg.sender,_community_amount);
}
function updateRewardRate(uint256 _rewardTokenPerBlock,uint256 _startBlock) public onlyAuthorized{
rewardTokenPerBlock = _rewardTokenPerBlock;
startBlock = _startBlock;
}
}
| 41,596
|
205
|
// Get all the credit positions underlying assets. /
|
function getPositionAssets() external view returns (ERC20[] memory assets) {
assets = new ERC20[](creditPositions.length);
for (uint256 i = 0; i < creditPositions.length; ++i) {
assets[i] = _assetOf(creditPositions[i]);
}
}
|
function getPositionAssets() external view returns (ERC20[] memory assets) {
assets = new ERC20[](creditPositions.length);
for (uint256 i = 0; i < creditPositions.length; ++i) {
assets[i] = _assetOf(creditPositions[i]);
}
}
| 3,933
|
55
|
// We allocated tokens for investor
|
event Invested(address investor, uint256 amount, uint256 hour);
|
event Invested(address investor, uint256 amount, uint256 hour);
| 6,943
|
6
|
// Give this address a balance to force operations to fail.
|
address payable constant public FAILURE_ADDRESS = 0xe9dB8717BC5DFB20aaf538b4a5a02B7791FF430C;
|
address payable constant public FAILURE_ADDRESS = 0xe9dB8717BC5DFB20aaf538b4a5a02B7791FF430C;
| 10,488
|
29
|
// Transfer token for a specified addresses from The address to transfer from. to The address to transfer to. value The amount to be transferred. /
|
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
|
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
| 8,540
|
150
|
// ========================================================================================= // Fee Logic // ========================================================================================= /
|
{
if (_feeDivisor > 0) {
fee = _value.div(_feeDivisor);
}
}
|
{
if (_feeDivisor > 0) {
fee = _value.div(_feeDivisor);
}
}
| 14,408
|
72
|
// src/interfaces/IERC223.sol/ pragma solidity ^0.6.7; /
|
interface IERC223 {
function transfer(address to, uint amount, bytes calldata data) external returns (bool ok);
function transferFrom(address from, address to, uint256 amount, bytes calldata data) external returns (bool ok);
}
|
interface IERC223 {
function transfer(address to, uint amount, bytes calldata data) external returns (bool ok);
function transferFrom(address from, address to, uint256 amount, bytes calldata data) external returns (bool ok);
}
| 22,018
|
441
|
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. We elect to return the amount that the global collateral is decreased by, rather than the individual position's collateral, because we need to maintain the invariant that the global collateral is always <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
|
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
|
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
| 17,319
|
40
|
// transfer fee to receiver and request MASS token as compensation.
|
function transferFee(uint256 feeAmount, address user) internal {
TransferHelper.safeTransferETH(feeReceiver, feeAmount);
if(contractSmart != address(0) && !isExcludedSender[msg.sender]) {
ISmart(contractSmart).requestCompensation(user, feeAmount);
}
}
|
function transferFee(uint256 feeAmount, address user) internal {
TransferHelper.safeTransferETH(feeReceiver, feeAmount);
if(contractSmart != address(0) && !isExcludedSender[msg.sender]) {
ISmart(contractSmart).requestCompensation(user, feeAmount);
}
}
| 75,596
|
58
|
// Returns the token generator version. /
|
function version() public view returns (string memory) {
return _version;
}
|
function version() public view returns (string memory) {
return _version;
}
| 1,656
|
91
|
// ERC-721 methods shipped in OpenZeppelin v1.7.0, removed in the latest version of the standard Only use this interface for compatibility with previously deployed contracts Use ERC721 for interacting with new contracts which are standard-compliant /
|
contract DeprecatedERC721 is ERC721 {
function takeOwnership(uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
function tokensOf(address _owner) public view returns (uint256[]);
}
|
contract DeprecatedERC721 is ERC721 {
function takeOwnership(uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
function tokensOf(address _owner) public view returns (uint256[]);
}
| 34,971
|
301
|
// what's the equivalent amount of snx for the amountToLiquidate?
|
uint snxRedeemed = _usdToSnx(amountToLiquidate, snxRate);
|
uint snxRedeemed = _usdToSnx(amountToLiquidate, snxRate);
| 51,183
|
219
|
// Return the amount of token minted, taking into account for the boost/amount of token the msg.sender paid for
|
function nitroBoost(uint256 amount) internal view returns (uint256) {
uint256 globalAmount = amount;
if (tokenIdCount._value < roundOneSupply) {
globalAmount = uint256((globalAmount * 150) / 100);
} else if (tokenIdCount._value < roundTwoSupply) {
globalAmount = uint256((globalAmount * 125) / 100);
}
return globalAmount;
}
|
function nitroBoost(uint256 amount) internal view returns (uint256) {
uint256 globalAmount = amount;
if (tokenIdCount._value < roundOneSupply) {
globalAmount = uint256((globalAmount * 150) / 100);
} else if (tokenIdCount._value < roundTwoSupply) {
globalAmount = uint256((globalAmount * 125) / 100);
}
return globalAmount;
}
| 80,794
|
234
|
// Calculate redemption outputs
|
uint256[] memory outputs = _calculateRedeemOutputs(_amount);
|
uint256[] memory outputs = _calculateRedeemOutputs(_amount);
| 78,501
|
76
|
// Returns a copy of the given MoneyPool with reset sustainments, and/that starts when the given MoneyPool expired.
|
function createMoneyPoolFromId(uint256 moneyPoolId)
private
returns (MoneyPool storage)
|
function createMoneyPoolFromId(uint256 moneyPoolId)
private
returns (MoneyPool storage)
| 18,987
|
0
|
// create a company type institution
|
function Institution(
string calldata name,
string calldata symbol,
uint8 iType
|
function Institution(
string calldata name,
string calldata symbol,
uint8 iType
| 30,934
|
128
|
// Since BPS map is initialized to 0, we will treat any BPS greater than the max to be a bps of 0;
|
if (bps > MAX_EASELY_FEE_BPS) {
bps = 0;
}
|
if (bps > MAX_EASELY_FEE_BPS) {
bps = 0;
}
| 24,275
|
594
|
// Ensure we have enough ETH to cover the protocol fee.
|
if (ethRemaining < singleProtocolFee) {
LibTransformERC20RichErrors
.InsufficientProtocolFeeError(ethRemaining, singleProtocolFee)
.rrevert();
}
|
if (ethRemaining < singleProtocolFee) {
LibTransformERC20RichErrors
.InsufficientProtocolFeeError(ethRemaining, singleProtocolFee)
.rrevert();
}
| 15,169
|
10
|
// only upfront fee
|
_fee = feeUpfront;
|
_fee = feeUpfront;
| 31,608
|
7
|
// Get info about specified player.addr Adrress of specified player. return input Input of specified player. return timestamp Timestamp of specified player. return exist Whether specified player in storage or not./
|
function playerInfo(address addr)
public
view
onlyOwner()
returns(uint256 input, uint256 timestamp, bool exist)
|
function playerInfo(address addr)
public
view
onlyOwner()
returns(uint256 input, uint256 timestamp, bool exist)
| 14,955
|
38
|
// Function used for unlocking tokens goes nextUnlocks the unlockable tokens of a specified address_of Address of user, claiming back unlockable tokens
|
function unlock(address _of) public returns (uint256 unlockableTokens) {
uint256 lockedTokens;
for (uint256 i = 0; i < lockReason[_of].length; i++) {
lockedTokens = tokensUnlockable(_of, lockReason[_of][i]);
if (lockedTokens > 0) {
unlockableTokens = unlockableTokens.add(lockedTokens);
locked[_of][lockReason[_of][i]].claimed = true;
emit Unlocked(_of, lockReason[_of][i], lockedTokens);
}
}
if (unlockableTokens > 0)
this.transfer(_of, unlockableTokens);
}
|
function unlock(address _of) public returns (uint256 unlockableTokens) {
uint256 lockedTokens;
for (uint256 i = 0; i < lockReason[_of].length; i++) {
lockedTokens = tokensUnlockable(_of, lockReason[_of][i]);
if (lockedTokens > 0) {
unlockableTokens = unlockableTokens.add(lockedTokens);
locked[_of][lockReason[_of][i]].claimed = true;
emit Unlocked(_of, lockReason[_of][i], lockedTokens);
}
}
if (unlockableTokens > 0)
this.transfer(_of, unlockableTokens);
}
| 33,910
|
29
|
// Transfers the current balance to the owner and terminates the contract. /
|
function destroy() onlyOwner public {
selfdestruct(owner);
}
|
function destroy() onlyOwner public {
selfdestruct(owner);
}
| 46,158
|
55
|
// 转账
|
if (_eth > 0) {
plyr_[_pID].addr.transfer(_eth);
}
|
if (_eth > 0) {
plyr_[_pID].addr.transfer(_eth);
}
| 49,775
|
225
|
// execute arbitrary calls cannot be called when system is partiallyPaused or fullyPaused _args Call action /
|
function _call(Actions.CallArgs memory _args)
internal
notPartiallyPaused
onlyWhitelistedCallee(_args.callee)
returns (uint256)
|
function _call(Actions.CallArgs memory _args)
internal
notPartiallyPaused
onlyWhitelistedCallee(_args.callee)
returns (uint256)
| 9,520
|
1
|
// ============ Params Setting Functions ============
|
function setOracle(address newOracle) external onlyOwner {
_ORACLE_ = newOracle;
}
|
function setOracle(address newOracle) external onlyOwner {
_ORACLE_ = newOracle;
}
| 15,850
|
18
|
// Transfer funds to account
|
x2y2Token.safeTransfer(account, pendingRewards);
emit TokensTransferred(account, pendingRewards);
|
x2y2Token.safeTransfer(account, pendingRewards);
emit TokensTransferred(account, pendingRewards);
| 68,415
|
44
|
// Transfer the balance from owner's account to another account
|
function transfer(address _to, uint256 _amount)public returns (bool success) {
require( _to != 0x0);
require(balances[msg.sender] >= _amount && _amount >= 0);
balances[msg.sender] = (balances[msg.sender]).sub(_amount);
balances[_to] = (balances[_to]).add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
}
|
function transfer(address _to, uint256 _amount)public returns (bool success) {
require( _to != 0x0);
require(balances[msg.sender] >= _amount && _amount >= 0);
balances[msg.sender] = (balances[msg.sender]).sub(_amount);
balances[_to] = (balances[_to]).add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
}
| 47,084
|
42
|
// Withdraws the total amount of ETH raised to the owners address. This function can only becalled by the owner of the contract given that the ICO is a success and the duration has passed. /
|
function withdraw() public onlyOwner {
uint256 inCirculation = tokensSold.add(bountiesIssued);
ETCL.mint(owner, inCirculation.mul(25).div(100));
owner.transfer(this.balance);
}
|
function withdraw() public onlyOwner {
uint256 inCirculation = tokensSold.add(bountiesIssued);
ETCL.mint(owner, inCirculation.mul(25).div(100));
owner.transfer(this.balance);
}
| 8,495
|
65
|
// Internal method that allows derived contracts to create a role for withdrawal. Either this method or `setWithdrawRole` must be called by the derived class for this contract to functionproperly. /
|
function createWithdrawRole(uint roleId, uint managingRoleId, address owner) internal {
_roleId = roleId;
_createExclusiveRole(roleId, managingRoleId, owner);
}
|
function createWithdrawRole(uint roleId, uint managingRoleId, address owner) internal {
_roleId = roleId;
_createExclusiveRole(roleId, managingRoleId, owner);
}
| 13,678
|
32
|
// Stake sphynx tokens to MasterChef
|
function enterStaking(uint256 _amount) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
updatePool(0);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSphynxPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeSphynxTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accSphynxPerShare).div(1e12);
emit Deposit(msg.sender, 0, _amount);
}
|
function enterStaking(uint256 _amount) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
updatePool(0);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSphynxPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeSphynxTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accSphynxPerShare).div(1e12);
emit Deposit(msg.sender, 0, _amount);
}
| 45,730
|
200
|
// Returns the key-value pair stored at position `index` in the map. O(1). Note that there are no guarantees on the ordering of entries inside thearray, and it may change when more entries are added or removed. Requirements:
|
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
|
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
| 38,469
|
49
|
// Gets the version of the contract.
|
function getVersion() external pure override returns (uint8) {
return uint8(3);
}
|
function getVersion() external pure override returns (uint8) {
return uint8(3);
}
| 34,021
|
20
|
// Calculate the utilization rate: `_borrows / (_cash + _borrows - _reserves)` _cash Asset balance _borrows Asset borrows _reserves Asset reservesreturn Asset utilization [0, 1e18] /
|
function utilizationRate(
uint256 _cash,
uint256 _borrows,
uint256 _reserves
|
function utilizationRate(
uint256 _cash,
uint256 _borrows,
uint256 _reserves
| 13,074
|
95
|
// PausableERC20 Implementation of the PausableERC20 /
|
contract PausableERC20 is ERC20Decimals, ERC20Burnable, ERC20Pausable, Ownable, ServicePayer {
constructor (
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initialBalance_,
address payable feeReceiver_
)
ERC20(name_, symbol_)
ERC20Decimals(decimals_)
ServicePayer(feeReceiver_, "PausableERC20")
payable
{
require(initialBalance_ > 0, "PausableERC20: supply cannot be zero");
_mint(_msgSender(), initialBalance_);
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
function decimals() public view virtual override(ERC20, ERC20Decimals) returns (uint8) {
return super.decimals();
}
/**
* @dev See {ERC20-_beforeTokenTransfer}. See {ERC20Capped-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
|
contract PausableERC20 is ERC20Decimals, ERC20Burnable, ERC20Pausable, Ownable, ServicePayer {
constructor (
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initialBalance_,
address payable feeReceiver_
)
ERC20(name_, symbol_)
ERC20Decimals(decimals_)
ServicePayer(feeReceiver_, "PausableERC20")
payable
{
require(initialBalance_ > 0, "PausableERC20: supply cannot be zero");
_mint(_msgSender(), initialBalance_);
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
function decimals() public view virtual override(ERC20, ERC20Decimals) returns (uint8) {
return super.decimals();
}
/**
* @dev See {ERC20-_beforeTokenTransfer}. See {ERC20Capped-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
| 81,713
|
117
|
// Controller address
|
PoolController public controller;
|
PoolController public controller;
| 30,317
|
148
|
// mint token
|
_mint(collector_address, tokenId);
_setTokenURI(tokenId, tokenURI);
_setTokenIPFSHash(tokenId, ipfsHash);
|
_mint(collector_address, tokenId);
_setTokenURI(tokenId, tokenURI);
_setTokenIPFSHash(tokenId, ipfsHash);
| 46,043
|
16
|
// Initialize stage
|
Stages public stage = Stages.Deployed;
|
Stages public stage = Stages.Deployed;
| 12,079
|
2
|
// Use a global counter so batches when distributing cannot overlap.
|
uint256 private idx;
address public utuToken;
uint256 public toMint;
uint256 public distributeAfter;
bool public assigned;
|
uint256 private idx;
address public utuToken;
uint256 public toMint;
uint256 public distributeAfter;
bool public assigned;
| 31,846
|
181
|
// changes the _baseURI value/
|
function changeBaseURI(string _newBaseURI) public onlyModerators {
_baseURI = _newBaseURI;
}
|
function changeBaseURI(string _newBaseURI) public onlyModerators {
_baseURI = _newBaseURI;
}
| 5,523
|
91
|
// Mint the shares to the owner
|
_mint(msg.sender, poolIndex, ownerShares, "");
|
_mint(msg.sender, poolIndex, ownerShares, "");
| 35,277
|
197
|
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned. We will need 1 word for the trailing zeros padding, 1 word for the length, and 3 words for a maximum of 78 digits. Total: 50x20 = 0xa0.
|
let m := add(mload(0x40), 0xa0)
|
let m := add(mload(0x40), 0xa0)
| 6,313
|
9
|
// internal helper functions
|
function getERC1155AmountFromCalldata(bytes memory data)
internal
pure
returns (uint256)
|
function getERC1155AmountFromCalldata(bytes memory data)
internal
pure
returns (uint256)
| 7,126
|
79
|
// Balance Expire Traker Keeps track of expiration of user balances./
|
contract BalanceExpireTracker {
using SafeMath for uint64;
using SafeMath for uint256;
// Don't want to keep typing address(0). Typecasting just for clarity.
uint160 private constant EMPTY = uint160(address(0));
// 3 days for each step.
uint64 public constant BUCKET_STEP = 3 days;
// indicates where to start from
// points where TokenInfo with (expiredAt / BUCKET_STEP) == index
mapping(uint64 => Bucket) public checkPoints;
struct Bucket {
uint160 head;
uint160 tail;
}
// points first active nft
uint160 public head;
// points last active nft
uint160 public tail;
// maps expireId to deposit info
mapping(uint160 => ExpireMetadata) public infos;
// pack data to reduce gas
struct ExpireMetadata {
uint160 next; // zero if there is no further information
uint160 prev;
uint64 expiresAt;
}
function expired() internal view returns(bool) {
if(infos[head].expiresAt == 0) {
return false;
}
if(infos[head].expiresAt <= uint64(now)){
return true;
}
return false;
}
// using typecasted expireId to save gas
function push(uint160 expireId, uint64 expiresAt)
internal
{
require(expireId != EMPTY, "info id address(0) cannot be supported");
// If this is a replacement for a current balance, remove it's current link first.
if (infos[expireId].expiresAt > 0) pop(expireId);
uint64 bucket = uint64( (expiresAt.div(BUCKET_STEP)).mul(BUCKET_STEP) );
if (head == EMPTY) {
// all the nfts are expired. so just add
head = expireId;
tail = expireId;
checkPoints[bucket] = Bucket(expireId, expireId);
infos[expireId] = ExpireMetadata(EMPTY,EMPTY,expiresAt);
return;
}
// there is active nft. we need to find where to push
// first check if this expires faster than head
if (infos[head].expiresAt >= expiresAt) {
// pushing nft is going to expire first
// update head
infos[head].prev = expireId;
infos[expireId] = ExpireMetadata(head, EMPTY,expiresAt);
head = expireId;
// update head of bucket
Bucket storage b = checkPoints[bucket];
b.head = expireId;
if(b.tail == EMPTY) {
// if tail is zero, this bucket was empty should fill tail with expireId
b.tail = expireId;
}
// this case can end now
return;
}
// then check if depositing nft will last more than latest
if (infos[tail].expiresAt <= expiresAt) {
infos[tail].next = expireId;
// push nft at tail
infos[expireId] = ExpireMetadata(EMPTY,tail,expiresAt);
tail = expireId;
// update tail of bucket
Bucket storage b = checkPoints[bucket];
b.tail = expireId;
if(b.head == EMPTY) {
// if head is zero, this bucket was empty should fill head with expireId
b.head = expireId;
}
// this case is done now
return;
}
// so our nft is somewhere in between
if (checkPoints[bucket].head != EMPTY) {
//bucket is not empty
//we just need to find our neighbor in the bucket
uint160 cursor = checkPoints[bucket].head;
// iterate until we find our nft's next
while(infos[cursor].expiresAt < expiresAt){
cursor = infos[cursor].next;
}
infos[expireId] = ExpireMetadata(cursor, infos[cursor].prev, expiresAt);
infos[infos[cursor].prev].next = expireId;
infos[cursor].prev = expireId;
//now update bucket's head/tail data
Bucket storage b = checkPoints[bucket];
if (infos[b.head].prev == expireId){
b.head = expireId;
}
if (infos[b.tail].next == expireId){
b.tail = expireId;
}
} else {
//bucket is empty
//should find which bucket has depositing nft's closest neighbor
// step 1 find prev bucket
uint64 prevCursor = uint64( bucket.sub(BUCKET_STEP) );
while(checkPoints[prevCursor].tail == EMPTY){
prevCursor = uint64( prevCursor.sub(BUCKET_STEP) );
}
uint160 prev = checkPoints[prevCursor].tail;
uint160 next = infos[prev].next;
// step 2 link prev buckets tail - nft - next buckets head
infos[expireId] = ExpireMetadata(next,prev,expiresAt);
infos[prev].next = expireId;
infos[next].prev = expireId;
checkPoints[bucket].head = expireId;
checkPoints[bucket].tail = expireId;
}
}
function pop(uint160 expireId) internal {
uint64 expiresAt = infos[expireId].expiresAt;
uint64 bucket = uint64( (expiresAt.div(BUCKET_STEP)).mul(BUCKET_STEP) );
// check if bucket is empty
// if bucket is empty, end
if(checkPoints[bucket].head == EMPTY){
return;
}
// if bucket is not empty, iterate through
// if expiresAt of current cursor is larger than expiresAt of parameter, reverts
for(uint160 cursor = checkPoints[bucket].head; infos[cursor].expiresAt <= expiresAt; cursor = infos[cursor].next) {
ExpireMetadata memory info = infos[cursor];
// if expiresAt is same of paramter, check if expireId is same
if(info.expiresAt == expiresAt && cursor == expireId) {
// if yes, delete it
// if cursor was head, move head to cursor.next
if(head == cursor) {
head = info.next;
}
// if cursor was tail, move tail to cursor.prev
if(tail == cursor) {
tail = info.prev;
}
// if cursor was head of bucket
if(checkPoints[bucket].head == cursor){
// and cursor.next is still in same bucket, move head to cursor.next
if(infos[info.next].expiresAt.div(BUCKET_STEP) == bucket.div(BUCKET_STEP)){
checkPoints[bucket].head = info.next;
} else {
// delete whole checkpoint if bucket is now empty
delete checkPoints[bucket];
}
} else if(checkPoints[bucket].tail == cursor){
// since bucket.tail == bucket.haed == cursor case is handled at the above,
// we only have to handle bucket.tail == cursor != bucket.head
checkPoints[bucket].tail = info.prev;
}
// now we handled all tail/head situation, we have to connect prev and next
infos[info.prev].next = info.next;
infos[info.next].prev = info.prev;
// delete info and end
delete infos[cursor];
return;
}
// if not, continue -> since there can be same expires at with multiple expireId
}
//changed to return for consistency
return;
//revert("Info does not exist");
}
uint256[50] private __gap;
}
|
contract BalanceExpireTracker {
using SafeMath for uint64;
using SafeMath for uint256;
// Don't want to keep typing address(0). Typecasting just for clarity.
uint160 private constant EMPTY = uint160(address(0));
// 3 days for each step.
uint64 public constant BUCKET_STEP = 3 days;
// indicates where to start from
// points where TokenInfo with (expiredAt / BUCKET_STEP) == index
mapping(uint64 => Bucket) public checkPoints;
struct Bucket {
uint160 head;
uint160 tail;
}
// points first active nft
uint160 public head;
// points last active nft
uint160 public tail;
// maps expireId to deposit info
mapping(uint160 => ExpireMetadata) public infos;
// pack data to reduce gas
struct ExpireMetadata {
uint160 next; // zero if there is no further information
uint160 prev;
uint64 expiresAt;
}
function expired() internal view returns(bool) {
if(infos[head].expiresAt == 0) {
return false;
}
if(infos[head].expiresAt <= uint64(now)){
return true;
}
return false;
}
// using typecasted expireId to save gas
function push(uint160 expireId, uint64 expiresAt)
internal
{
require(expireId != EMPTY, "info id address(0) cannot be supported");
// If this is a replacement for a current balance, remove it's current link first.
if (infos[expireId].expiresAt > 0) pop(expireId);
uint64 bucket = uint64( (expiresAt.div(BUCKET_STEP)).mul(BUCKET_STEP) );
if (head == EMPTY) {
// all the nfts are expired. so just add
head = expireId;
tail = expireId;
checkPoints[bucket] = Bucket(expireId, expireId);
infos[expireId] = ExpireMetadata(EMPTY,EMPTY,expiresAt);
return;
}
// there is active nft. we need to find where to push
// first check if this expires faster than head
if (infos[head].expiresAt >= expiresAt) {
// pushing nft is going to expire first
// update head
infos[head].prev = expireId;
infos[expireId] = ExpireMetadata(head, EMPTY,expiresAt);
head = expireId;
// update head of bucket
Bucket storage b = checkPoints[bucket];
b.head = expireId;
if(b.tail == EMPTY) {
// if tail is zero, this bucket was empty should fill tail with expireId
b.tail = expireId;
}
// this case can end now
return;
}
// then check if depositing nft will last more than latest
if (infos[tail].expiresAt <= expiresAt) {
infos[tail].next = expireId;
// push nft at tail
infos[expireId] = ExpireMetadata(EMPTY,tail,expiresAt);
tail = expireId;
// update tail of bucket
Bucket storage b = checkPoints[bucket];
b.tail = expireId;
if(b.head == EMPTY) {
// if head is zero, this bucket was empty should fill head with expireId
b.head = expireId;
}
// this case is done now
return;
}
// so our nft is somewhere in between
if (checkPoints[bucket].head != EMPTY) {
//bucket is not empty
//we just need to find our neighbor in the bucket
uint160 cursor = checkPoints[bucket].head;
// iterate until we find our nft's next
while(infos[cursor].expiresAt < expiresAt){
cursor = infos[cursor].next;
}
infos[expireId] = ExpireMetadata(cursor, infos[cursor].prev, expiresAt);
infos[infos[cursor].prev].next = expireId;
infos[cursor].prev = expireId;
//now update bucket's head/tail data
Bucket storage b = checkPoints[bucket];
if (infos[b.head].prev == expireId){
b.head = expireId;
}
if (infos[b.tail].next == expireId){
b.tail = expireId;
}
} else {
//bucket is empty
//should find which bucket has depositing nft's closest neighbor
// step 1 find prev bucket
uint64 prevCursor = uint64( bucket.sub(BUCKET_STEP) );
while(checkPoints[prevCursor].tail == EMPTY){
prevCursor = uint64( prevCursor.sub(BUCKET_STEP) );
}
uint160 prev = checkPoints[prevCursor].tail;
uint160 next = infos[prev].next;
// step 2 link prev buckets tail - nft - next buckets head
infos[expireId] = ExpireMetadata(next,prev,expiresAt);
infos[prev].next = expireId;
infos[next].prev = expireId;
checkPoints[bucket].head = expireId;
checkPoints[bucket].tail = expireId;
}
}
function pop(uint160 expireId) internal {
uint64 expiresAt = infos[expireId].expiresAt;
uint64 bucket = uint64( (expiresAt.div(BUCKET_STEP)).mul(BUCKET_STEP) );
// check if bucket is empty
// if bucket is empty, end
if(checkPoints[bucket].head == EMPTY){
return;
}
// if bucket is not empty, iterate through
// if expiresAt of current cursor is larger than expiresAt of parameter, reverts
for(uint160 cursor = checkPoints[bucket].head; infos[cursor].expiresAt <= expiresAt; cursor = infos[cursor].next) {
ExpireMetadata memory info = infos[cursor];
// if expiresAt is same of paramter, check if expireId is same
if(info.expiresAt == expiresAt && cursor == expireId) {
// if yes, delete it
// if cursor was head, move head to cursor.next
if(head == cursor) {
head = info.next;
}
// if cursor was tail, move tail to cursor.prev
if(tail == cursor) {
tail = info.prev;
}
// if cursor was head of bucket
if(checkPoints[bucket].head == cursor){
// and cursor.next is still in same bucket, move head to cursor.next
if(infos[info.next].expiresAt.div(BUCKET_STEP) == bucket.div(BUCKET_STEP)){
checkPoints[bucket].head = info.next;
} else {
// delete whole checkpoint if bucket is now empty
delete checkPoints[bucket];
}
} else if(checkPoints[bucket].tail == cursor){
// since bucket.tail == bucket.haed == cursor case is handled at the above,
// we only have to handle bucket.tail == cursor != bucket.head
checkPoints[bucket].tail = info.prev;
}
// now we handled all tail/head situation, we have to connect prev and next
infos[info.prev].next = info.next;
infos[info.next].prev = info.prev;
// delete info and end
delete infos[cursor];
return;
}
// if not, continue -> since there can be same expires at with multiple expireId
}
//changed to return for consistency
return;
//revert("Info does not exist");
}
uint256[50] private __gap;
}
| 80,909
|
13
|
// bytes buffer to put ASCII characters into
|
bytes memory buf = new bytes(256);
|
bytes memory buf = new bytes(256);
| 40,680
|
12
|
// Bulk token claim./Can only be invoked if the escrow is NOT paused./claimArgs array encoded values (index, account, amount, timestamp, merkleProof)
|
function claimBulk(bytes[] calldata claimArgs) external whenNotPaused {
for (uint256 i = 0; i < claimArgs.length; i++) {
(uint256 index, address account, uint256 amountUSDC, uint256 amountBUMP, bytes32[] memory merkleProof) = abi.decode(
claimArgs[i],
(uint256, address, uint256, uint256, bytes32[])
);
_claim(index, account, amountUSDC, amountBUMP, merkleProof);
}
}
|
function claimBulk(bytes[] calldata claimArgs) external whenNotPaused {
for (uint256 i = 0; i < claimArgs.length; i++) {
(uint256 index, address account, uint256 amountUSDC, uint256 amountBUMP, bytes32[] memory merkleProof) = abi.decode(
claimArgs[i],
(uint256, address, uint256, uint256, bytes32[])
);
_claim(index, account, amountUSDC, amountBUMP, merkleProof);
}
}
| 44,534
|
121
|
// if any account belongs to _isExcludedFromFee account then remove the fee
|
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
|
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
| 52,858
|
59
|
// Multisignature wallet - Allows multiple parties to agree on transactions before execution./Stefan George - <<span class="__cf_email__" data-cfemail="4132352427202f6f26242e33262401222e2f32242f3238326f2f2435">[email&160;protected]</span>>
|
contract MultiSigWallet {
// flag to determine if address is for a real contract or not
bool public isMultiSigWallet = false;
uint constant public MAX_OWNER_COUNT = 50;
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
modifier onlyWallet() {
if (msg.sender != address(this)) throw;
_;
}
modifier ownerDoesNotExist(address owner) {
if (isOwner[owner]) throw;
_;
}
modifier ownerExists(address owner) {
if (!isOwner[owner]) throw;
_;
}
modifier transactionExists(uint transactionId) {
if (transactions[transactionId].destination == 0) throw;
_;
}
modifier confirmed(uint transactionId, address owner) {
if (!confirmations[transactionId][owner]) throw;
_;
}
modifier notConfirmed(uint transactionId, address owner) {
if (confirmations[transactionId][owner]) throw;
_;
}
modifier notExecuted(uint transactionId) {
if (transactions[transactionId].executed) throw;
_;
}
modifier notNull(address _address) {
if (_address == 0) throw;
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
if (ownerCount > MAX_OWNER_COUNT) throw;
if (_required > ownerCount) throw;
if (_required == 0) throw;
if (ownerCount == 0) throw;
_;
}
/// @dev Fallback function allows to deposit ether.
function()
payable
{
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
function MultiSigWallet(address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i=0; i<_owners.length; i++) {
if (isOwner[_owners[i]] || _owners[i] == 0) throw;
isOwner[_owners[i]] = true;
}
isMultiSigWallet = true;
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
/// @param index the indx of the owner to be replaced
function replaceOwnerIndexed(address owner, address newOwner, uint index)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
if (owners[index] != owner) throw;
owners[index] = newOwner;
isOwner[owner] = false;
isOwner[newOwner] = true;
OwnerRemoval(owner);
OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
Revocation(msg.sender, transactionId);
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
/*
* Internal functions
*/
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
internal
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction tx = transactions[transactionId];
tx.executed = true;
if (tx.destination.call.value(tx.value)(tx.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
tx.executed = false;
}
}
}
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return Number of confirmations.
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if ((pending && !transactions[i].executed) ||
(executed && transactions[i].executed))
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
constant
returns (address[])
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return Returns array of owner addresses.
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if ((pending && !transactions[i].executed) ||
(executed && transactions[i].executed))
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
|
contract MultiSigWallet {
// flag to determine if address is for a real contract or not
bool public isMultiSigWallet = false;
uint constant public MAX_OWNER_COUNT = 50;
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
modifier onlyWallet() {
if (msg.sender != address(this)) throw;
_;
}
modifier ownerDoesNotExist(address owner) {
if (isOwner[owner]) throw;
_;
}
modifier ownerExists(address owner) {
if (!isOwner[owner]) throw;
_;
}
modifier transactionExists(uint transactionId) {
if (transactions[transactionId].destination == 0) throw;
_;
}
modifier confirmed(uint transactionId, address owner) {
if (!confirmations[transactionId][owner]) throw;
_;
}
modifier notConfirmed(uint transactionId, address owner) {
if (confirmations[transactionId][owner]) throw;
_;
}
modifier notExecuted(uint transactionId) {
if (transactions[transactionId].executed) throw;
_;
}
modifier notNull(address _address) {
if (_address == 0) throw;
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
if (ownerCount > MAX_OWNER_COUNT) throw;
if (_required > ownerCount) throw;
if (_required == 0) throw;
if (ownerCount == 0) throw;
_;
}
/// @dev Fallback function allows to deposit ether.
function()
payable
{
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
function MultiSigWallet(address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i=0; i<_owners.length; i++) {
if (isOwner[_owners[i]] || _owners[i] == 0) throw;
isOwner[_owners[i]] = true;
}
isMultiSigWallet = true;
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
/// @param index the indx of the owner to be replaced
function replaceOwnerIndexed(address owner, address newOwner, uint index)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
if (owners[index] != owner) throw;
owners[index] = newOwner;
isOwner[owner] = false;
isOwner[newOwner] = true;
OwnerRemoval(owner);
OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
Revocation(msg.sender, transactionId);
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
/*
* Internal functions
*/
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
internal
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction tx = transactions[transactionId];
tx.executed = true;
if (tx.destination.call.value(tx.value)(tx.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
tx.executed = false;
}
}
}
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return Number of confirmations.
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if ((pending && !transactions[i].executed) ||
(executed && transactions[i].executed))
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
constant
returns (address[])
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return Returns array of owner addresses.
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if ((pending && !transactions[i].executed) ||
(executed && transactions[i].executed))
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
| 8,303
|
70
|
// Calculates the current borrow interest rate per block cash The total amount of cash the market has borrows The total amount of borrows the market has outstanding reserves The total amount of reserves the market hasreturn The borrow rate per block (as a percentage, and scaled by 1e18) /
|
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256, uint256);
|
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256, uint256);
| 38,256
|
24
|
// 投票する /
|
function voteForProposal(
address _targetDaoAddress,
uint256 _proposalId,
bool yes
|
function voteForProposal(
address _targetDaoAddress,
uint256 _proposalId,
bool yes
| 42,757
|
90
|
// 2
|
globals.dailyDataCount,
globals.stakeSharesTotal,
globals.latestStakeId,
globals.latestPoolerId,
_unclaimedHaveTotal,
_claimedHaveTotal,
_claimedEthAddrCount,
|
globals.dailyDataCount,
globals.stakeSharesTotal,
globals.latestStakeId,
globals.latestPoolerId,
_unclaimedHaveTotal,
_claimedHaveTotal,
_claimedEthAddrCount,
| 11,025
|
174
|
// calculate ppt for round mask
|
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
|
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
| 51,541
|
110
|
// This amount must be determined before arNxm mint.
|
uint256 arAmount = arNxmValue(_nAmount);
if (_isNxm) {
nxm.safeTransferFrom(msg.sender, address(this), _nAmount);
} else {
|
uint256 arAmount = arNxmValue(_nAmount);
if (_isNxm) {
nxm.safeTransferFrom(msg.sender, address(this), _nAmount);
} else {
| 62,505
|
299
|
// ========== STATE VARIABLES ========== / The IssuanceData activity that's happened in a fee period.
|
struct IssuanceData {
uint debtPercentage;
uint debtEntryIndex;
}
|
struct IssuanceData {
uint debtPercentage;
uint debtEntryIndex;
}
| 5,804
|
115
|
// Retrieve an array of lock IDs tied to a single withdrawal address withdrawalAddress address of desired withdraw ownerreturn Array of lock instance IDs /
|
function getNonceFromWithdrawalAddress(
address withdrawalAddress
|
function getNonceFromWithdrawalAddress(
address withdrawalAddress
| 13,481
|
1,128
|
// Updates the address of the interest rate strategy contract- Only callable by the LendingPoolConfigurator contract asset The address of the underlying asset of the reserve rateStrategyAddress The address of the interest rate strategy contract /
|
{
_reserves[asset].interestRateStrategyAddress = rateStrategyAddress;
}
|
{
_reserves[asset].interestRateStrategyAddress = rateStrategyAddress;
}
| 39,544
|
13
|
// encode a color string
|
function encodeStr(
uint256 h,
uint256 s,
uint256 l
|
function encodeStr(
uint256 h,
uint256 s,
uint256 l
| 43,075
|
158
|
// internal implementation of unstaking methods amount number of tokens to unstake gysr number of GYSR tokens applied to unstaking operationreturn number of reward tokens distributed /
|
function _unstake(uint256 amount, uint256 gysr)
private
nonReentrant
returns (uint256)
|
function _unstake(uint256 amount, uint256 gysr)
private
nonReentrant
returns (uint256)
| 34,665
|
26
|
// if the stake is finished, delete all data related to it (nice to have)
|
if (stakeFinished) {
delete stakes[stakeId];
}
|
if (stakeFinished) {
delete stakes[stakeId];
}
| 14,733
|
9
|
// addWorker - Adds a worker to the whiteList of authorized workers. To be added, a worker should have the `workerRole` credential inside the claimManager workerAddress - The address of the worker we want to add /
|
function addWorker(address payable workerAddress) external;
|
function addWorker(address payable workerAddress) external;
| 30,421
|
3
|
// spend 3rd party's approved token amount
|
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(allowance[_from][msg.sender] >= _value, "You can't spend more than allowed");
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
|
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(allowance[_from][msg.sender] >= _value, "You can't spend more than allowed");
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
| 4,904
|
24
|
// pause or unpause the contract /
|
function pause(bool val) public onlyOwner {
if (val == true) {
_pause();
return;
}
_unpause();
}
|
function pause(bool val) public onlyOwner {
if (val == true) {
_pause();
return;
}
_unpause();
}
| 58,748
|
98
|
// Only allows memory writes to offsets [0x00, 0x60) ∪ [min, max) in the current subcontext. If any other memory is written to, the test will fail. Can be called multiple times to add more ranges to the set.
|
function expectSafeMemory(uint64 min, uint64 max) external;
|
function expectSafeMemory(uint64 min, uint64 max) external;
| 12,923
|
118
|
// Delegate call to transfer to address to transfer to value amount to transfer origSender original msg.sender on delegate contractreturn success /
|
function delegateTransfer(
address to,
uint256 value,
address origSender
|
function delegateTransfer(
address to,
uint256 value,
address origSender
| 39,614
|
19
|
// Token sale state variables
|
bool public privatesaleFinalized;
bool public presaleFinalized;
bool public crowdsaleFinalized;
event PrivatesaleFinalized(uint tokensRemaining);
event PresaleFinalized(uint tokensRemaining);
event CrowdsaleFinalized(uint tokensRemaining);
event Burn(address indexed burner, uint256 value);
event TokensaleAddressSet(address tSeller, address from);
|
bool public privatesaleFinalized;
bool public presaleFinalized;
bool public crowdsaleFinalized;
event PrivatesaleFinalized(uint tokensRemaining);
event PresaleFinalized(uint tokensRemaining);
event CrowdsaleFinalized(uint tokensRemaining);
event Burn(address indexed burner, uint256 value);
event TokensaleAddressSet(address tSeller, address from);
| 31,189
|
70
|
// total token supply for sales
|
totalTokenSupply = 75000000 * 10 ** 18;
|
totalTokenSupply = 75000000 * 10 ** 18;
| 32,368
|
75
|
// Hook that is called after consecutive token transfers.
|
* Calling conditions are similar to {_afterTokenTransfer}.
*/
function _afterConsecutiveTokenTransfer(
address, /*from*/
address, /*to*/
uint256, /*first*/
uint96 /*size*/
) internal virtual {}
}
|
* Calling conditions are similar to {_afterTokenTransfer}.
*/
function _afterConsecutiveTokenTransfer(
address, /*from*/
address, /*to*/
uint256, /*first*/
uint96 /*size*/
) internal virtual {}
}
| 15,217
|
122
|
// Allow owner to change alpaca price /
|
function setExchangeWoolPrice(uint256 _price) public onlyOwner {
exchangeWoolPrice = _price;
}
|
function setExchangeWoolPrice(uint256 _price) public onlyOwner {
exchangeWoolPrice = _price;
}
| 6,629
|
106
|
// Transfer the tokens to the beneficiary of the funding.
|
assert(vitToken.transfer(fundingRecipient, tokensToClaim));
|
assert(vitToken.transfer(fundingRecipient, tokensToClaim));
| 26,499
|
10
|
// For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed
|
uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;
uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;
uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48;
uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;
uint256 constant IS_FROZEN_START_BIT_POSITION = 57;
uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58;
uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;
uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64;
uint256 constant MAX_VALID_LTV = 65535;
|
uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;
uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;
uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48;
uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;
uint256 constant IS_FROZEN_START_BIT_POSITION = 57;
uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58;
uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;
uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64;
uint256 constant MAX_VALID_LTV = 65535;
| 26,143
|
115
|
// Hero getter function/heroId The hero id/ return trait 1, trait 2, skill 1, skill 2
|
function getHeroTraitsSkills(uint256 heroId)
external
view
override
isValidHero(heroId)
returns (
uint8, // trait 1
uint8, // trait 2
uint8, // skill 1
uint8 // skill 2
|
function getHeroTraitsSkills(uint256 heroId)
external
view
override
isValidHero(heroId)
returns (
uint8, // trait 1
uint8, // trait 2
uint8, // skill 1
uint8 // skill 2
| 39,712
|
80
|
// Reset the reentrancy guard
|
_reentrancyMutexForTransfers = 0; // solhint-disable-line reentrancy
|
_reentrancyMutexForTransfers = 0; // solhint-disable-line reentrancy
| 24,557
|
0
|
// Base tokesn for whitelisting
|
IERC20 public baseToken;
uint256 public baseAmount;
event PoolRegistered(uint256 poolId, address manager);
event PoolApproved(uint256 poolId);
|
IERC20 public baseToken;
uint256 public baseAmount;
event PoolRegistered(uint256 poolId, address manager);
event PoolApproved(uint256 poolId);
| 4,279
|
217
|
// Sets the twap points. to control the length of our twap/_twapPoints The new twap points.
|
function setTwapPoints(uint256 _twapPoints) external onlyAdmin {
if (_twapPoints > MAX_TWAP_POINTS || _twapPoints == 0)
revert OptionToken_InvalidTwapPoints();
twapPoints = _twapPoints;
emit SetTwapPoints(_twapPoints);
}
|
function setTwapPoints(uint256 _twapPoints) external onlyAdmin {
if (_twapPoints > MAX_TWAP_POINTS || _twapPoints == 0)
revert OptionToken_InvalidTwapPoints();
twapPoints = _twapPoints;
emit SetTwapPoints(_twapPoints);
}
| 13,449
|
60
|
// REGISTER CONTRACT// Register Contract. /
|
contract Register {
using SafeMath for uint256;
// Account with the right to adjust the set of minters.
address public _owner;
// Address of the Kong ERC20 account.
address public _kongERC20Address;
// Sum of Kong amounts marked as mintable for registered devices.
uint256 public _totalMintable;
// Minters.
mapping (address => bool) public _minters;
// Minting caps.
mapping (address => uint256) public _mintingCaps;
//
struct Device {
bytes32 secondaryPublicKeyHash;
bytes32 tertiaryPublicKeyHash;
address contractAddress;
bytes32 hardwareManufacturer;
bytes32 hardwareModel;
bytes32 hardwareSerial;
bytes32 hardwareConfig;
uint256 kongAmount;
bool mintable;
}
// Registered devices.
mapping(bytes32 => Device) internal _devices;
/**
* @dev Emit when device is registered.
*/
event Registration(
bytes32 primaryPublicKeyHash,
bytes32 secondaryPublicKeyHash,
bytes32 tertiaryPublicKeyHash,
address contractAddress,
bytes32 hardwareManufacturer,
bytes32 hardwareModel,
bytes32 hardwareSerial,
bytes32 hardwareConfig,
uint256 kongAmount,
bool mintable
);
/**
* @dev Emit when minting rights are delegated / removed.
*/
event MinterAddition (
address minter,
uint256 mintingCap
);
event MinterRemoval (
address minter
);
/**
* @dev Constructor.
*/
constructor() public {
// Set address of owner.
_owner = 0xAB35D3476251C6b614dC2eb36380D7AF1232D822;
// Set address of Kong ERC20 contract.
_kongERC20Address = 0x177F2aCE25f81fc50F9F6e9193aDF5ac758e8098;
// Set minting cap of owner account.
_mintingCaps[_owner] = (2 ** 25 + 2 ** 24 + 2 ** 23 + 2 ** 22) * 10 ** 18;
}
/**
* @dev Throws if called by any account but owner.
*/
modifier onlyOwner() {
require(_owner == msg.sender, 'Can only be called by owner.');
_;
}
/**
* @dev Throws if called by any account but owner or registered minter.
*/
modifier onlyOwnerOrMinter() {
require(_owner == msg.sender || _minters[msg.sender] == true, 'Can only be called by owner or minter.');
_;
}
/**
* @dev Endow `newMinter` with right to add mintable devices up to `mintingCap`.
*/
function delegateMintingRights(
address newMinter,
uint256 mintingCap
)
public
onlyOwner
{
// Delegate minting rights.
_mintingCaps[_owner] = _mintingCaps[_owner].sub(mintingCap);
_mintingCaps[newMinter] = _mintingCaps[newMinter].add(mintingCap);
// Add newMinter to dictionary of minters.
_minters[newMinter] = true;
// Emit event.
emit MinterAddition(newMinter, _mintingCaps[newMinter]);
}
/**
* @dev Remove address from the mapping of _minters.
*/
function removeMintingRights(
address minter
)
public
onlyOwner
{
// Cannot remove rights from _owner.
require(_owner != minter, 'Cannot remove owner from minters.');
// Adjust minting rights.
_mintingCaps[_owner] = _mintingCaps[_owner].add(_mintingCaps[minter]);
_mintingCaps[minter] = 0;
// Deactivate minter.
_minters[minter] = false;
// Emit event.
emit MinterRemoval(minter);
}
/**
* @dev Register a new device.
*/
function registerDevice(
bytes32 primaryPublicKeyHash,
bytes32 secondaryPublicKeyHash,
bytes32 tertiaryPublicKeyHash,
address contractAddress,
bytes32 hardwareManufacturer,
bytes32 hardwareModel,
bytes32 hardwareSerial,
bytes32 hardwareConfig,
uint256 kongAmount,
bool mintable
)
public
onlyOwnerOrMinter
{
// Verify that this device has not been registered yet.
require(_devices[primaryPublicKeyHash].contractAddress == address(0), 'Already registered.');
// Verify the cumulative limit for mintable Kong has not been exceeded.
if (mintable) {
uint256 _maxMinted = KongERC20Interface(_kongERC20Address).getMintingLimit();
require(_totalMintable.add(kongAmount) <= _maxMinted, 'Exceeds cumulative limit.');
// Increment _totalMintable.
_totalMintable += kongAmount;
// Adjust minting cap. Throws on underflow / Guarantees minter does not exceed its limit.
_mintingCaps[msg.sender] = _mintingCaps[msg.sender].sub(kongAmount);
}
// Create device struct.
_devices[primaryPublicKeyHash] = Device(
secondaryPublicKeyHash,
tertiaryPublicKeyHash,
contractAddress,
hardwareManufacturer,
hardwareModel,
hardwareSerial,
hardwareConfig,
kongAmount,
mintable
);
// Emit event.
emit Registration(
primaryPublicKeyHash,
secondaryPublicKeyHash,
tertiaryPublicKeyHash,
contractAddress,
hardwareManufacturer,
hardwareModel,
hardwareSerial,
hardwareConfig,
kongAmount,
mintable
);
}
/**
* @dev Mint registered `kongAmount` for `_devices[primaryPublicKeyHash]`.
*/
function mintKong(
bytes32 primaryPublicKeyHash
)
external
onlyOwnerOrMinter
{
// Get Kong details.
Device memory d = _devices[primaryPublicKeyHash];
// Verify that Kong is mintable.
require(d.mintable, 'Not mintable / already minted.');
_devices[primaryPublicKeyHash].mintable = false;
// Mint.
KongERC20Interface(_kongERC20Address).mint(d.kongAmount, d.contractAddress);
}
/**
* @dev Return the stored details for a registered device.
*/
function getRegistrationDetails(
bytes32 primaryPublicKeyHash
)
external
view
returns (bytes32, bytes32, address, bytes32, bytes32, bytes32, bytes32, uint256, bool)
{
Device memory d = _devices[primaryPublicKeyHash];
return (
d.secondaryPublicKeyHash,
d.tertiaryPublicKeyHash,
d.contractAddress,
d.hardwareManufacturer,
d.hardwareModel,
d.hardwareSerial,
d.hardwareConfig,
d.kongAmount,
d.mintable
);
}
/**
* @dev Return the hashed minting key for a registered device.
*/
function getTertiaryKeyHash(
bytes32 primaryPublicKeyHash
)
external
view
returns (bytes32)
{
Device memory d = _devices[primaryPublicKeyHash];
return d.tertiaryPublicKeyHash;
}
/**
* @dev Return Kong amount for a registered device.
*/
function getKongAmount(
bytes32 primaryPublicKeyHash
)
external
view
returns (uint)
{
Device memory d = _devices[primaryPublicKeyHash];
return d.kongAmount;
}
}
|
contract Register {
using SafeMath for uint256;
// Account with the right to adjust the set of minters.
address public _owner;
// Address of the Kong ERC20 account.
address public _kongERC20Address;
// Sum of Kong amounts marked as mintable for registered devices.
uint256 public _totalMintable;
// Minters.
mapping (address => bool) public _minters;
// Minting caps.
mapping (address => uint256) public _mintingCaps;
//
struct Device {
bytes32 secondaryPublicKeyHash;
bytes32 tertiaryPublicKeyHash;
address contractAddress;
bytes32 hardwareManufacturer;
bytes32 hardwareModel;
bytes32 hardwareSerial;
bytes32 hardwareConfig;
uint256 kongAmount;
bool mintable;
}
// Registered devices.
mapping(bytes32 => Device) internal _devices;
/**
* @dev Emit when device is registered.
*/
event Registration(
bytes32 primaryPublicKeyHash,
bytes32 secondaryPublicKeyHash,
bytes32 tertiaryPublicKeyHash,
address contractAddress,
bytes32 hardwareManufacturer,
bytes32 hardwareModel,
bytes32 hardwareSerial,
bytes32 hardwareConfig,
uint256 kongAmount,
bool mintable
);
/**
* @dev Emit when minting rights are delegated / removed.
*/
event MinterAddition (
address minter,
uint256 mintingCap
);
event MinterRemoval (
address minter
);
/**
* @dev Constructor.
*/
constructor() public {
// Set address of owner.
_owner = 0xAB35D3476251C6b614dC2eb36380D7AF1232D822;
// Set address of Kong ERC20 contract.
_kongERC20Address = 0x177F2aCE25f81fc50F9F6e9193aDF5ac758e8098;
// Set minting cap of owner account.
_mintingCaps[_owner] = (2 ** 25 + 2 ** 24 + 2 ** 23 + 2 ** 22) * 10 ** 18;
}
/**
* @dev Throws if called by any account but owner.
*/
modifier onlyOwner() {
require(_owner == msg.sender, 'Can only be called by owner.');
_;
}
/**
* @dev Throws if called by any account but owner or registered minter.
*/
modifier onlyOwnerOrMinter() {
require(_owner == msg.sender || _minters[msg.sender] == true, 'Can only be called by owner or minter.');
_;
}
/**
* @dev Endow `newMinter` with right to add mintable devices up to `mintingCap`.
*/
function delegateMintingRights(
address newMinter,
uint256 mintingCap
)
public
onlyOwner
{
// Delegate minting rights.
_mintingCaps[_owner] = _mintingCaps[_owner].sub(mintingCap);
_mintingCaps[newMinter] = _mintingCaps[newMinter].add(mintingCap);
// Add newMinter to dictionary of minters.
_minters[newMinter] = true;
// Emit event.
emit MinterAddition(newMinter, _mintingCaps[newMinter]);
}
/**
* @dev Remove address from the mapping of _minters.
*/
function removeMintingRights(
address minter
)
public
onlyOwner
{
// Cannot remove rights from _owner.
require(_owner != minter, 'Cannot remove owner from minters.');
// Adjust minting rights.
_mintingCaps[_owner] = _mintingCaps[_owner].add(_mintingCaps[minter]);
_mintingCaps[minter] = 0;
// Deactivate minter.
_minters[minter] = false;
// Emit event.
emit MinterRemoval(minter);
}
/**
* @dev Register a new device.
*/
function registerDevice(
bytes32 primaryPublicKeyHash,
bytes32 secondaryPublicKeyHash,
bytes32 tertiaryPublicKeyHash,
address contractAddress,
bytes32 hardwareManufacturer,
bytes32 hardwareModel,
bytes32 hardwareSerial,
bytes32 hardwareConfig,
uint256 kongAmount,
bool mintable
)
public
onlyOwnerOrMinter
{
// Verify that this device has not been registered yet.
require(_devices[primaryPublicKeyHash].contractAddress == address(0), 'Already registered.');
// Verify the cumulative limit for mintable Kong has not been exceeded.
if (mintable) {
uint256 _maxMinted = KongERC20Interface(_kongERC20Address).getMintingLimit();
require(_totalMintable.add(kongAmount) <= _maxMinted, 'Exceeds cumulative limit.');
// Increment _totalMintable.
_totalMintable += kongAmount;
// Adjust minting cap. Throws on underflow / Guarantees minter does not exceed its limit.
_mintingCaps[msg.sender] = _mintingCaps[msg.sender].sub(kongAmount);
}
// Create device struct.
_devices[primaryPublicKeyHash] = Device(
secondaryPublicKeyHash,
tertiaryPublicKeyHash,
contractAddress,
hardwareManufacturer,
hardwareModel,
hardwareSerial,
hardwareConfig,
kongAmount,
mintable
);
// Emit event.
emit Registration(
primaryPublicKeyHash,
secondaryPublicKeyHash,
tertiaryPublicKeyHash,
contractAddress,
hardwareManufacturer,
hardwareModel,
hardwareSerial,
hardwareConfig,
kongAmount,
mintable
);
}
/**
* @dev Mint registered `kongAmount` for `_devices[primaryPublicKeyHash]`.
*/
function mintKong(
bytes32 primaryPublicKeyHash
)
external
onlyOwnerOrMinter
{
// Get Kong details.
Device memory d = _devices[primaryPublicKeyHash];
// Verify that Kong is mintable.
require(d.mintable, 'Not mintable / already minted.');
_devices[primaryPublicKeyHash].mintable = false;
// Mint.
KongERC20Interface(_kongERC20Address).mint(d.kongAmount, d.contractAddress);
}
/**
* @dev Return the stored details for a registered device.
*/
function getRegistrationDetails(
bytes32 primaryPublicKeyHash
)
external
view
returns (bytes32, bytes32, address, bytes32, bytes32, bytes32, bytes32, uint256, bool)
{
Device memory d = _devices[primaryPublicKeyHash];
return (
d.secondaryPublicKeyHash,
d.tertiaryPublicKeyHash,
d.contractAddress,
d.hardwareManufacturer,
d.hardwareModel,
d.hardwareSerial,
d.hardwareConfig,
d.kongAmount,
d.mintable
);
}
/**
* @dev Return the hashed minting key for a registered device.
*/
function getTertiaryKeyHash(
bytes32 primaryPublicKeyHash
)
external
view
returns (bytes32)
{
Device memory d = _devices[primaryPublicKeyHash];
return d.tertiaryPublicKeyHash;
}
/**
* @dev Return Kong amount for a registered device.
*/
function getKongAmount(
bytes32 primaryPublicKeyHash
)
external
view
returns (uint)
{
Device memory d = _devices[primaryPublicKeyHash];
return d.kongAmount;
}
}
| 27,741
|
179
|
// royalty payout address
|
address public royaltyPayoutAddress;
|
address public royaltyPayoutAddress;
| 82,733
|
47
|
// Approve loanAmount of erc20 tokens to msg.sender
|
uint256 loanAmount = nftProps.price * nftProps.maxSupply;
|
uint256 loanAmount = nftProps.price * nftProps.maxSupply;
| 9,840
|
91
|
// Here we calc the pool share one can withdraw given the amount of IdleToken they want to burnThis method triggers a rebalance of the pools if neededNOTE: If the contract is paused or iToken price has decreased one can still redeem but no rebalance happens.NOTE 2: If iToken price has decresed one should not redeem (but can do it) otherwise he would capitalize the loss.Ideally one should wait until the black swan event is terminated_amount : amount of IdleTokens to be burnedreturn redeemedTokens : amount of underlying tokens redeemed /
|
function redeemIdleToken(uint256 _amount) external returns (uint256 redeemedTokens);
|
function redeemIdleToken(uint256 _amount) external returns (uint256 redeemedTokens);
| 50,761
|
178
|
// Check and address to see if it has CEVA privileges or not /
|
function checkCEVA(address _identifier)
public
view
returns(bool)
|
function checkCEVA(address _identifier)
public
view
returns(bool)
| 29,342
|
158
|
// MIP40c3-SP7: Modify Protocol Engineering Core Unit Budget Hash: seth keccak -- "$(wget https:raw.githubusercontent.com/makerdao/mips/a4b2cacb79599f78d826b0f790426b38b6af92f3/MIP40/MIP40c3-Subproposals/MIP40c3-SP7.md -q -O - 2> /dev/null)"
|
string constant public MIP40c3SP7 = "0xcbc6d6da4fbfd923473656ccf5c7294407d0dc2d85846d495fcba5892be61a08";
|
string constant public MIP40c3SP7 = "0xcbc6d6da4fbfd923473656ccf5c7294407d0dc2d85846d495fcba5892be61a08";
| 34,418
|
24
|
// output = rand;
|
return rand;
|
return rand;
| 29,054
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.