comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/**
An internal function to actually perform the delegation of votes.
@param delegator The address delegating to `delegatee`.
@param delegatee The address receiving delegated votes.
*/ | function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
/* console.log('a-', currentDelegate, delegator, delegatee); */
emit DelegateChanged(delegator... | 0.6.12 |
/**
An internal function to move delegated vote amounts between addresses.
@param srcRep the previous representative who received delegated votes.
@param dstRep the new representative to receive these delegated votes.
@param amount the amount of delegated votes to move between representatives.
*/ | function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
// Decrease the number of votes delegated to the previous representative.
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepO... | 0.6.12 |
/**
An internal function to write a checkpoint of modified vote amounts.
This function is guaranteed to add at most one checkpoint per block.
@param delegatee The address whose vote count is changed.
@param nCheckpoints The number of checkpoints by address `delegatee`.
@param oldVotes The prior vote count ... | function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Block number exceeds 32 bits.");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegat... | 0.6.12 |
// Add a new launchpad project to the pool. Can only be called by the owner. | function add( IERC20 _launchToken,IERC20 _payToken, uint256 _timeStart, uint256 _timeEnd , uint256 _tokenAmount,uint256 _priceBasedPayToken,uint256 _maxPerAddress,
uint256 _launchMaxPay, uint256 _releaseStart, uint256 _lockPeriod) public onlyGovernor {
require( _timeStart > block.timestamp &... | 0.8.4 |
//user deposit to enter launchpad | function deposit(uint8 _pid, uint256 _amount) public {
LaunchPadInfo storage pool = launchPadInfo[_pid];
UserInfo storage user = userInfo[_pid][ msg.sender ];
require( pool.launchStatus == 1 , "invalid status");
require( pool.timeEnd > block.timestamp, "invalid time");
... | 0.8.4 |
//claim release reward token | function claimReward(uint8 _pid) public {
LaunchPadInfo storage pool = launchPadInfo[_pid];
UserInfo storage user = userInfo[_pid][ msg.sender ];
if( user.lockedAmount > user.pickedAmount ){
uint256 _pickedAmount = 0;
if( block.timestamp > pool.releaseStart ){
... | 0.8.4 |
//allow owner to transfer surplus | function ownerTransfer(address to, uint value)
public
onlyOwner
{
uint current_balance_all = 0;
for (uint i = 0; i < accounts.length; i++)
current_balance_all += account_data[accounts[i]].current_balance;
require(getBalance() > current_balance_all && value <= getBalance() - current_ba... | 0.4.23 |
// Check what tokenIds are owned by a given wallets | function walletOfOwner(address _owner) external view returns (uint256[] memory) {
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
... | 0.8.4 |
// Gives the tokenURI for a given tokenId | function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory currentBaseURI = _baseURI();
// If not revealed, show non-revealed image
if (!revealed) {
return byt... | 0.8.4 |
// Will be used to gift the team | function gift(uint256 _mintAmount, address destination) external onlyOwner {
require(_mintAmount > 0, "need to mint at least 1 NFT");
uint256 supply = totalSupply();
require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");
for (uint256 i = 1; i <= _mintAmount; i++) {
... | 0.8.4 |
// count number of bytes required to represent an unsigned integer | function count_bytes(uint256 n) constant internal returns (uint256 c) {
uint i = 0;
uint mask = 1;
while (n >= mask) {
i += 1;
mask *= 256;
}
return i;
} | 0.4.16 |
// Spec: Send `value` amount of tokens from address `from` to address `to` | function transferFrom(address from, address to, uint256 value) public returns (bool success) {
address spender = msg.sender;
if(value <= s_allowances[from][spender] && internalTransfer(from, to, value)) {
s_allowances[from][spender] -= value;
return true;
} else {
... | 0.4.16 |
// Spec: Allow `spender` to withdraw from your account, multiple times, up
// to the `value` amount. If this function is called again it overwrites the
// current allowance with `value`. | function approve(address spender, uint256 value) public returns (bool success) {
address owner = msg.sender;
if (value != 0 && s_allowances[owner][spender] != 0) {
return false;
}
s_allowances[owner][spender] = value;
Approval(owner, spender, value);
re... | 0.4.16 |
// Destroys `value` child contracts and updates s_tail.
//
// This function is affected by an issue in solc: https://github.com/ethereum/solidity/issues/2999
// The `mk_contract_address(this, i).call();` doesn't forward all available gas, but only GAS - 25710.
// As a result, when this line is executed with e.g. 30000 ... | function destroyChildren(uint256 value) internal {
uint256 tail = s_tail;
// tail points to slot behind the last contract in the queue
for (uint256 i = tail + 1; i <= tail + value; i++) {
mk_contract_address(this, i).call();
}
s_tail = tail + value;
} | 0.4.16 |
// Frees `value` sub-tokens owned by address `from`. Requires that `msg.sender`
// has been approved by `from`.
// You should ensure that you pass at least 25710 + `value` * (1148 + 5722 + 150) gas
// when calling this function. For details, see the comment above `destroyChilden`. | function freeFrom(address from, uint256 value) public returns (bool success) {
address spender = msg.sender;
uint256 from_balance = s_balances[from];
if (value > from_balance) {
return false;
}
mapping(address => uint256) from_allowances = s_allowances[from];
... | 0.4.16 |
// Frees up to `value` sub-tokens owned by address `from`. Returns how many tokens were freed.
// Otherwise, identical to `freeFrom`.
// You should ensure that you pass at least 25710 + `value` * (1148 + 5722 + 150) gas
// when calling this function. For details, see the comment above `destroyChilden`. | function freeFromUpTo(address from, uint256 value) public returns (uint256 freed) {
address spender = msg.sender;
uint256 from_balance = s_balances[from];
if (value > from_balance) {
value = from_balance;
}
mapping(address => uint256) from_allowances = s_allow... | 0.4.16 |
/* generates a number from 0 to 2^n based on the last n blocks */ | function multiBlockRandomGen(uint seed, uint size) constant returns (uint randomNumber) {
uint n = 0;
for (uint i = 0; i < size; i++){
if (uint(sha3(block.blockhash(block.number-i-1), seed ))%2==0)
n += 2**i;
}
return n;
} | 0.2.1 |
// Deposit Token | function deposit(uint256 _amount) external {
lpToken.safeTransferFrom(msg.sender,address(this),_amount);
UserInfo storage user = userInfo[msg.sender];
if(user.amount != 0) {
user.pointsDebt = pointsBalance(msg.sender);
}
if(participationFee > 0){
... | 0.8.0 |
// redeem NFT with points earned | function redeem(uint256 _nftIndex) public {
NFTInfo storage nft = nftInfo[_nftIndex];
require(nft.redeemed == false, "Token is already redeemed");
require(pointsBalance(msg.sender) >= nft.price, "Insufficient Points");
UserInfo storage user = userInfo[msg.sender];
// ded... | 0.8.0 |
/* Before first sending, make sure to allow this contract spending from token contract with function approve(address _spender, uint256 _value)
** and to update tokensApproved with function updateTokensApproved () */ | function dropCoinsSingle(address[] dests, uint256 tokens) {
require(msg.sender == _multiSendOwner && tokensApproved >= (dests.length * tokens));
uint256 i = 0;
while (i < dests.length) {
_STCnContract.transferFrom(_multiSendOwner, dests[i], tokens);
i += 1;
... | 0.4.19 |
// update users' productivity by value with boolean value indicating increase or decrease. | function _updateProductivity(Productivity storage user, uint value, bool increase) private {
user.product = user.product.add(_computeProductivity(user));
global.product = global.product.add(_computeProductivity(global));
require(global.product <= uint(-1), 'GLOBAL_PRODUCT_OVERFLOW')... | 0.6.8 |
// External function call
// This function adjust how many token will be produced by each block, eg:
// changeAmountPerBlock(100)
// will set the produce rate to 100/block. | function changeAmountPerBlock(uint value) external requireGovernor returns (bool) {
uint old = grossProduct.amount;
require(value != old, 'AMOUNT_PER_BLOCK_NO_CHANGE');
uint product = _computeBlockProduct();
grossProduct.total = grossProduct.total.add(produc... | 0.6.8 |
// External function call
// This function increase user's productivity and updates the global productivity.
// the users' actual share percentage will calculated by:
// Formula: user_productivity / global_productivity | function increaseProductivity(address user, uint value) external requireImpl returns (bool) {
require(value > 0, 'PRODUCTIVITY_VALUE_MUST_BE_GREATER_THAN_ZERO');
Productivity storage product = users[user];
if (product.block == 0) {
product.gross = grossProduct.total.add(... | 0.6.8 |
// External function call
// This function will decreases user's productivity by value, and updates the global productivity
// it will record which block this is happenning and accumulates the area of (productivity * time) | function decreaseProductivity(address user, uint value) external requireImpl returns (bool) {
Productivity storage product = users[user];
require(value > 0 && product.total >= value, 'INSUFFICIENT_PRODUCTIVITY');
_updateProductivity(product, value, false);
emit Productivi... | 0.6.8 |
// External function call
// When user calls this function, it will calculate how many token will mint to user from his productivity * time
// Also it calculates global token supply from last time the user mint to this time. | function mint() external lock returns (uint) {
(uint gp, uint userProduct, uint globalProduct, uint amount) = _computeUserProduct();
require(amount > 0, 'NO_PRODUCTIVITY');
Productivity storage product = users[msg.sender];
product.gross = gp;
product.user = userProduct;... | 0.6.8 |
// Returns how many token he will be able to mint. | function _computeUserProduct() private view returns (uint gp, uint userProduct, uint globalProduct, uint amount) {
Productivity memory product = users[msg.sender];
gp = grossProduct.total.add(_computeBlockProduct());
userProduct = product.product.add(_computeProductivity... | 0.6.8 |
/// @notice deposit
/// @param asset either Aave or stkAave
/// @param recipient address to mint the receipt tokens
/// @param amount amount of tokens to deposit
/// @param claim claim stk aave rewards from Aave | function deposit(
IERC20 asset,
address recipient,
uint128 amount,
bool claim
) external override whenNotPaused nonReentrant {
if (asset == aaveToken) {
_deposit(asset, wrapperAaveToken, recipient, amount, claim);
} else {
_deposit(stkAaveToken... | 0.8.4 |
/// @dev refund bid for a cancelled proposal ONLY if it was not voted on
/// @param proposalId proposal id | function refund(uint256 proposalId) external nonReentrant {
IAaveGovernanceV2.ProposalState state = IAaveGovernanceV2(aaveGovernance).getProposalState(
proposalId
);
require(state == IAaveGovernanceV2.ProposalState.Canceled, "PROPOSAL_ACTIVE");
Bid storage currentBid = bids... | 0.8.4 |
/// @dev distribute rewards for the proposal
/// @notice called in children's vote function (after bidding process ended)
/// @param proposalId id of proposal to distribute rewards fo | function distributeRewards(uint256 proposalId) public {
Bid storage currentBid = bids[proposalId];
// ensure that the bidding period has ended
require(block.timestamp > currentBid.endTime, "BID_ACTIVE");
if (currentBid.voted) return;
uint128 highestBid = currentBid.highestBid;... | 0.8.4 |
/// @dev withdrawFees withdraw fees
/// Enables ONLY the fee receipient to withdraw the pool accrued fees | function withdrawFees() external override nonReentrant returns (uint256 feeAmount) {
require(msg.sender == feeReceipient, "ONLY_RECEIPIENT");
feeAmount = feesReceived;
if (feeAmount > 0) {
feesReceived = 0;
bidAsset.safeTransfer(feeReceipient, feeAmount);
}
... | 0.8.4 |
/// @dev get reward amount for user specified by `user`
/// @param user address of user to check balance of | function rewardBalanceOf(address user)
external
view
returns (
uint256 totalPendingBidReward,
uint256 totalPendingStkAaveReward,
uint256 totalPendingBribeReward
)
{
uint256 userAaveBalance = wrapperAaveToken.balanceOf(user);
uint256... | 0.8.4 |
/// @dev claimReward for msg.sender
/// @param to address to send the rewards to
/// @param executor An external contract to call with
/// @param data data to call the executor contract
/// @param claim claim stk aave rewards from Aave | function claimReward(
address to,
IBribeExecutor executor,
bytes calldata data,
bool claim
) external whenNotPaused nonReentrant {
// accrue rewards for both stkAave and Aave token balances
_accrueRewards(msg.sender, claim);
UserInfo storage _currentUser = us... | 0.8.4 |
/// @dev block a proposalId from used in the pool
/// @param proposalId proposalId | function blockProposalId(uint256 proposalId) external onlyOwner {
require(blockedProposals[proposalId] == false, "PROPOSAL_INACTIVE");
Bid storage currentBid = bids[proposalId];
// check if the propoal has already been voted on
require(currentBid.voted == false, "BID_DISTRIBUTED");
... | 0.8.4 |
/// @notice setStartTimestamp
/// @param startTimestamp when to start distributing rewards
/// @param rewardPerSecond reward to distribute per second | function setStartTimestamp(uint64 startTimestamp, uint128 rewardPerSecond) external onlyOwner {
require(startTimestamp > block.timestamp, "INVALID_START_TIMESTAMP");
if (bribeRewardConfig.endTimestamp != 0) {
require(startTimestamp < bribeRewardConfig.endTimestamp, "HIGH_TIMESTAMP");
... | 0.8.4 |
/// @dev deposit governance token
/// @param asset asset to withdraw
/// @param receiptToken asset wrapper token
/// @param recipient address to award the receipt tokens
/// @param amount amount to deposit
/// @param claim claim pending stk aave rewards
/// @notice emit {Deposit} event | function _deposit(
IERC20 asset,
IWrapperToken receiptToken,
address recipient,
uint128 amount,
bool claim
) internal {
require(amount > 0, "INVALID_AMOUNT");
// accrue user pending rewards
_accrueRewards(recipient, claim);
asset.safeTransfer... | 0.8.4 |
/// @dev _calculateBribeRewardIndex | function _calculateBribeRewardIndex() internal view returns (uint256 amount) {
if (
bribeRewardConfig.startTimestamp == 0 ||
bribeRewardConfig.startTimestamp > block.timestamp
) return 0;
uint64 startTimestamp = (bribeRewardConfig.startTimestamp >
assetIndex.... | 0.8.4 |
/// @dev _userPendingBribeReward
/// @param userBalance user aave + stkAave balance
/// @param userLastPricePerShare user last price per share
/// @param currentBribeRewardPerShare current reward per share | function _userPendingBribeReward(
uint256 userBalance,
uint256 userLastPricePerShare,
uint256 currentBribeRewardPerShare
) internal pure returns (uint256 pendingReward) {
if (userBalance > 0 && currentBribeRewardPerShare > 0) {
pendingReward = ((userBalance * (currentBrib... | 0.8.4 |
/// @dev returns the user bid reward share
/// @param receiptToken wrapper token
/// @param user user
/// @param userLastBidId user last bid id | function _userPendingBidRewards(
uint128 currentBidIndex,
IWrapperToken receiptToken,
address user,
uint128 userLastBidId
) internal view returns (uint256 accrueBidId, uint256 totalPendingReward) {
if (currentBidIndex == 0) return (0, 0);
uint256 currentBidRewardCoun... | 0.8.4 |
/// @dev _calculateUserPendingBidRewards
/// @param receiptToken wrapper token
/// @param user user
/// @param userLastBidId user last bid id
/// @param maxRewardId maximum bid id to accrue rewards to | function _calculateUserPendingBidRewards(
IWrapperToken receiptToken,
address user,
uint256 userLastBidId,
uint256 maxRewardId
) internal view returns (uint256 totalPendingReward) {
for (uint256 i = userLastBidId; i < maxRewardId; i++) {
uint256 proposalId = bidId... | 0.8.4 |
/// @dev _calculateStkAaveRewardPerShare
/// @param rewardsToReceive amount of aave rewards to receive | function _calculateStkAaveRewardPerShare(uint256 rewardsToReceive)
internal
view
returns (uint128 newRewardPerShare)
{
uint256 increaseRewardSharePrice;
if (rewardsToReceive > 0) {
increaseRewardSharePrice = ((rewardsToReceive * SHARE_SCALE) /
wrap... | 0.8.4 |
/// @dev get the user stkAave aave reward share
/// @param user user address
/// @param userLastPricePerShare userLastPricePerShare
/// @param currentStkAaveRewardPerShare the latest reward per share
/// @param receiptToken stak aave wrapper token | function _userPendingstkAaveRewards(
address user,
uint128 userLastPricePerShare,
uint128 currentStkAaveRewardPerShare,
IWrapperToken receiptToken
) internal view returns (uint256 pendingReward) {
uint256 userBalance = receiptToken.balanceOf(user);
if (userBalance > ... | 0.8.4 |
/**
* For future use only whne we will need more tokens for our main application
* Create mintedAmount new tokens and give new created tokens to target.
* May only be called by smart contract owner.
* @param mintedAmount number of tokens to create
* @return true if tokens were created successfully, false othe... | function mintToken(address target, uint256 mintedAmount)
returns (bool success) {
require (msg.sender == owner);
if (mintedAmount > 0) {
accounts [target] = safeAdd (accounts [target], mintedAmount);
tokenCount = safeAdd (tokenCount, mintedAmount);
// adding transfer event an... | 0.4.19 |
/** @notice A distinct Uniform Resource Identifier (URI) for a given asset.
* @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
* 3986. The URI may point to a JSON file that conforms to the "ERC721
* Metadata JSON Schema".
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*... | function tokenURI(
uint256 _tokenId
) external
view
isKey(_tokenId)
returns(string memory)
{
string memory URI;
if(bytes(baseTokenURI).length == 0) {
URI = unlockProtocol.globalBaseTokenURI();
} else {
URI = baseTokenURI;
}
return URI.strConcat(
... | 0.5.14 |
/**
* Ensures that the msg.sender has paid at least the price stated.
*
* With ETH, this means the function originally called was `payable` and the
* transaction included at least the amount requested.
*
* Security: be wary of re-entrancy when calling this function.
*/ | function _chargeAtLeast(
uint _price
) internal returns (uint)
{
if(_price > 0) {
if(tokenAddress == address(0)) {
require(msg.value >= _price, 'NOT_ENOUGH_FUNDS');
return msg.value;
} else {
IERC20 token = IERC20(tokenAddress);
token.safeTransferFrom(ms... | 0.5.14 |
/**
* Transfers funds from the contract to the account provided.
*
* Security: be wary of re-entrancy when calling this function.
*/ | function _transfer(
address _tokenAddress,
address _to,
uint _amount
) internal
{
if(_amount > 0) {
if(_tokenAddress == address(0)) {
// https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/
address(uint160(_to)).sendValue(_amount);
} e... | 0.5.14 |
/**
* @notice Validate a transmission
* @dev Must be called by either the `s_currentAggregator.target`, or the `s_proposedAggregator`.
* If called by the `s_currentAggregator.target` this function passes the call on to the `s_currentValidator.target`
* and the `s_proposedValidator`, if it is set.
* If called by th... | function validate(
uint256 previousRoundId,
int256 previousAnswer,
uint256 currentRoundId,
int256 currentAnswer
) external override returns (bool) {
address currentAggregator = s_currentAggregator.target;
if (msg.sender != currentAggregator) {
address proposedAggregator = s_proposedAggre... | 0.8.6 |
/**
* @notice Propose an aggregator
* @dev A zero address can be used to unset the proposed aggregator. Only owner can call.
* @param proposed address
*/ | function proposeNewAggregator(address proposed) external onlyOwner {
require(s_proposedAggregator != proposed && s_currentAggregator.target != proposed, "Invalid proposal");
s_proposedAggregator = proposed;
// If proposed is zero address, hasNewProposal = false
s_currentAggregator.hasNewProposal = (prop... | 0.8.6 |
/**
* @notice Upgrade the aggregator by setting the current aggregator as the proposed aggregator.
* @dev Must have a proposed aggregator. Only owner can call.
*/ | function upgradeAggregator() external onlyOwner {
// Get configuration in memory
AggregatorConfiguration memory current = s_currentAggregator;
address previous = current.target;
address proposed = s_proposedAggregator;
// Perform the upgrade
require(current.hasNewProposal, "No proposal");
s... | 0.8.6 |
// Reserves 30 planets | function reservePlanets() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < 30; i++) {
_safeMint(msg.sender, supply + i);
count += 1;
}
emit Increment(msg.sender);
} | 0.7.0 |
//public mint function | function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
require(!paused, "The contract is paused!");
require(!isWhiteListActive, "Whitelist minting is still active!");
if(msg.sender != owner()) {
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPer... | 0.8.7 |
// whitelist mint function | function whiteListMint(uint256 _mintAmount, bytes32[] calldata proof) public payable mintCompliance(_mintAmount) {
require(!paused, "The contract is paused!");
require(isWhiteListActive, "Whitelist minting isn't active anymore!");
require(
MerkleProof.verify(proof, merkleRoot, ge... | 0.8.7 |
//call contract owner & id owner function | function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
... | 0.8.7 |
//call URL of token function | function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
retur... | 0.8.7 |
//withdraw function | function withdraw() public onlyOwner {
//50% goes to community wallet
(bool hs, ) = payable(0xfc2f6C88Da2045846EbE84ede4dA3b3D9da1B87F).call{value: address(this).balance * 50 / 100}("");
require(hs);
//rest to team wallet
(bool os, ) = payable(owner()).call{value: address(th... | 0.8.7 |
/* pure functions */ | function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp)
public
pure
override
returns (uint256 totalStakeUnits)
{
for (uint256 index; index < stakes.length; index++) {
// reference stake
StakeData memory stakeData = stakes[index]... | 0.7.6 |
/// @notice Add funds to the Hypervisor
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope:
/// - increase _hypervisor.rewardSharesOutstanding
/// - append to _hypervisor.rewardSchedules
/// token transfer: transfer staking tokens from msg.send... | function fund(uint256 amount, uint256 duration) external onlyOwner onlyOnline {
// validate duration
require(duration != 0, "Hypervisor: invalid duration");
// create new reward shares
// if existing rewards on this Hypervisor
// mint new shares proportional to % change in rew... | 0.7.6 |
/// @notice Register bonus token for distribution
/// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope:
/// - append to _bonusTokenSet
/// token transfer... | function registerBonusToken(address bonusToken) external onlyOwner onlyOnline {
// verify valid bonus token
_validateAddress(bonusToken);
// verify bonus token count
require(_bonusTokenSet.length() < MAX_REWARD_TOKENS, "Hypervisor: max bonus tokens reached ");
// add token to s... | 0.7.6 |
/// @notice Rescue tokens from RewardPool
/// @dev use this function to rescue tokens from RewardPool contract
/// without distributing to stakers or triggering emergency shutdown
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope: none
/// to... | function rescueTokensFromRewardPool(
address token,
address recipient,
uint256 amount
) external onlyOwner onlyOnline {
// verify recipient
_validateAddress(recipient);
// check not attempting to unstake reward token
require(token != _hypervisor.rewardToken, ... | 0.7.6 |
/// @notice Stake tokens
/// @dev anyone can stake to any vault if they have valid permission
/// access control: anyone
/// state machine:
/// - can be called multiple times
/// - only online
/// - when vault exists on this Hypervisor
/// state scope:
/// - append to _vaults[vault].stakes
/// - increase _vau... | function stake(
address vault,
uint256 amount,
bytes calldata permission
) external override onlyOnline {
// verify vault is valid
require(isValidVault(vault), "Hypervisor: vault is not registered");
// verify non-zero amount
require(amount != 0, "Hypervisor:... | 0.7.6 |
/// @notice Exit Hypervisor without claiming reward
/// @dev This function should never revert when correctly called by the vault.
/// A max number of stakes per vault is set with MAX_STAKES_PER_VAULT to
/// place an upper bound on the for loop in calculateTotalStakeUnits().
/// access control: only callable ... | function rageQuit() external override {
// fetch vault storage reference
VaultData storage _vaultData = _vaults[msg.sender];
// revert if no active stakes
require(_vaultData.stakes.length != 0, "Hypervisor: no stake");
// update cached sum of stake units across all vaults
... | 0.7.6 |
/**
* @dev returns the expected target amount of converting one reserve to another along with the fee
*
* @param _sourceToken contract address of the source reserve token
* @param _targetToken contract address of the target reserve token
* @param _amount amount of tokens received from the user
*
* @r... | function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount)
public
view
active
validReserve(_sourceToken)
validReserve(_targetToken)
returns (uint256, uint256)
{
// validate input
require(_sourceToken != _t... | 0.4.26 |
/**
* @dev converts a specific amount of source tokens to target tokens
* can only be called by the bancor network contract
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader ... | function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address _beneficiary)
internal
returns (uint256)
{
// get expected target amount and fee
(uint256 amount, uint256 fee) = targetAmountAndFee(_sourceToken, _targetToken, _amoun... | 0.4.26 |
/**
* @dev decreases the pool's liquidity and burns the caller's shares in the pool
* note that prior to version 28, you should use 'liquidate' instead
*
* @param _amount token amount
* @param _reserveTokens address of each reserve token
* @param _reserveMinReturnAmounts minimum r... | function removeLiquidity(uint256 _amount, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts)
public
protected
active
{
// verify the user input
verifyLiquidityInput(_reserveTokens, _reserveMinReturnAmounts, _amount);
// get the to... | 0.4.26 |
/**
* @dev decreases the pool's liquidity and burns the caller's shares in the pool
* for example, if the holder sells 10% of the supply,
* then they will receive 10% of each reserve token balance in return
* note that starting from version 28, you should use 'removeLiquidity' instead
*
* @param _amount am... | function liquidate(uint256 _amount) public protected {
require(_amount > 0, "ERR_ZERO_AMOUNT");
uint256 totalSupply = ISmartToken(anchor).totalSupply();
ISmartToken(anchor).destroy(msg.sender, _amount);
uint256[] memory reserveMinReturnAmounts = new uint256[](reserveTokens.length... | 0.4.26 |
/**
* @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens
* we take this input in order to allow specifying the corresponding reserve amounts in any order
*
* @param _reserveTokens array of reserve tokens
* @param _reserveAmounts array of reserve amounts
* @... | function verifyLiquidityInput(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _amount) private view {
uint256 i;
uint256 j;
uint256 length = reserveTokens.length;
require(length == _reserveTokens.length, "ERR_INVALID_RESERVE");
require(length... | 0.4.26 |
/**
* @dev adds liquidity (reserve) to the pool when it's empty
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
*/ | function addLiquidityToEmptyPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts)
private
returns (uint256)
{
// calculate the geometric-mean of the reserve amounts approved by the user
uint256 amount = geometricMean(_reserveAmounts);
// transfer... | 0.4.26 |
/**
* @dev removes liquidity (reserve) from the pool
*
* @param _reserveTokens address of each reserve token
* @param _reserveMinReturnAmounts minimum return-amount of each reserve token
* @param _totalSupply token total supply
* @param _amount token amount
*/ | function removeLiquidityFromPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts, uint256 _totalSupply, uint256 _amount)
private
{
syncReserveBalances();
IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
uint256 newPoolTokenSupp... | 0.4.26 |
/**
* @dev calculates the average number of decimal digits in a given list of values
*
* @param _values list of values (each of which assumed positive)
* @return the average number of decimal digits in the given list of values
*/ | function geometricMean(uint256[] memory _values) public pure returns (uint256) {
uint256 numOfDigits = 0;
uint256 length = _values.length;
for (uint256 i = 0; i < length; i++)
numOfDigits += decimalLength(_values[i]);
return uint256(10) ** (roundDiv(numOfDigits, length) ... | 0.4.26 |
/**
* @dev dispatches rate events for both reserves / pool tokens
* only used to circumvent the `stack too deep` compiler error
*
* @param _sourceToken address of the source reserve token
* @param _targetToken address of the target reserve token
*/ | function dispatchRateEvents(IERC20Token _sourceToken, IERC20Token _targetToken) private {
uint256 poolTokenSupply = ISmartToken(anchor).totalSupply();
uint256 sourceReserveBalance = reserveBalance(_sourceToken);
uint256 targetReserveBalance = reserveBalance(_targetToken);
uint32 sour... | 0.4.26 |
//backend mint | function mintInternal(address wallet, uint amount) internal {
uint currentTokenSupply = _tokenIdCounter.current();
require((currentTokenSupply + amount) <= maxSupply, "Not enough tokens left");
for(uint i = 0; i< amount; i++){
currentTokenSupply++;
_safeMint(wall... | 0.8.7 |
/** Used to determine if a staked token is owned. Used to allow game logic to occur outside this contract.
* This might not be necessary if the training mechanic is in this contract instead */ | function ownsToken(uint256 tokenId) external view returns (bool) {
uint64 lastTokenWrite = wndNFT.getTokenWriteBlock(tokenId);
// Must check this, as getTokenTraits will be allowed since this contract is an admin
require(lastTokenWrite < block.number, "hmmmm what doing?");
IWnD.WizardDragon memory s = w... | 0.8.4 |
/**
* adds Wizards and Dragons to the Tower and Flight
* @param tokenIds the IDs of the Wizards and Dragons to stake
*/ | function addManyToTowerAndFlight(address tokenOwner, uint16[] calldata tokenIds) external override nonReentrant {
require(admins[_msgSender()], "Only admins can stake");
for (uint i = 0; i < tokenIds.length; i++) {
if (wndNFT.ownerOf(tokenIds[i]) != address(this)) { // a mint + stake will send directly to... | 0.8.4 |
/**
* adds Wizards and Dragons to the Tower and Flight
* @param seed the seed for random logic
* @param tokenIds the IDs of the Wizards and Dragons to stake
*/ | function addManyToTrainingAndFlight(uint256 seed, address tokenOwner, uint16[] calldata tokenIds) external override nonReentrant {
require(admins[_msgSender()], "Only admins can stake");
for (uint i = 0; i < tokenIds.length; i++) {
require(wndNFT.ownerOf(tokenIds[i]) == tokenOwner, "You don't own this t... | 0.8.4 |
/**
* adds a single Dragon to the Flight
* @param account the address of the staker
* @param tokenId the ID of the Dragon to add to the Flight
*/ | function _addDragonToFlight(address account, uint256 tokenId) internal {
uint8 rank = _rankForDragon(tokenId);
totalRankStaked += rank; // Portion of earnings ranges from 8 to 5
flightIndices[tokenId] = flight[rank].length; // Store the location of the dragon in the Flight
flight[rank].push(StakeDragon(... | 0.8.4 |
/**
* realize $GP earnings and optionally unstake tokens from the Tower / Flight
* to unstake a Wizard it will require it has 2 days worth of $GP unclaimed
* @param tokenIds the IDs of the tokens to claim earnings from
* @param unstake whether or not to unstake ALL of the tokens listed in tokenIds
*/ | function claimManyFromTowerAndFlight(address tokenOwner, uint16[] calldata tokenIds, bool unstake) external override whenNotPaused _updateEarnings nonReentrant {
require(admins[_msgSender()], "Only admins can stake");
uint256 owed = 0;
uint16 owedRunes = 0;
for (uint i = 0; i < tokenIds.length; i++) {
... | 0.8.4 |
/** Get the tax percent owed to dragons. If the address doesn't contain a 1:10 ratio of whips to staked wizards,
* they are subject to an untrained tax */ | function getTaxPercent(address addr) internal returns (uint256) {
if(_deposits[addr].towerWizards.length() <= 10) {
//
return alter.balanceOf(addr, whip) >= 1 ? GP_CLAIM_TAX_PERCENTAGE : GP_CLAIM_TAX_PERCENTAGE_UNTRAINED;
}
return alter.balanceOf(addr, whip) >= _deposits[addr].tow... | 0.8.4 |
/**
* chooses a random Dragon thief when a newly minted token is stolen
* @param seed a random value to choose a Dragon from
* @return the owner of the randomly selected Dragon thief
*/ | function randomDragonOwner(uint256 seed) public view override returns (address) {
if (totalRankStaked == 0) {
return address(0x0);
}
uint256 bucket = (seed & 0xFFFFFFFF) % totalRankStaked; // choose a value from 0 to total rank staked
uint256 cumulative;
seed >>= 32;
// loop through each b... | 0.8.4 |
/**
* add $GP to claimable pot for the Flight
* @param amount $GP to add to the pot
*/ | function _payDragonTax(uint256 amount) internal {
if (totalRankStaked == 0) { // if there's no staked dragons
unaccountedRewards += amount; // keep track of $GP due to dragons
return;
}
// makes sure to include any unaccounted $GP
gpPerRank += (amount + unaccountedRewards) / totalRankStaked... | 0.8.4 |
// Overrides | function tokenURI(uint256 tokenId)
public
view
override(ERC721)
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return unreveale... | 0.8.11 |
/// @dev send ETH from this contract to its creator | function sendETHToCreator(uint256 _amount) external {
require(msg.sender == creator, "Sender must be creator");
// we use `call` here following the recommendation from
// https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/
(bool success, ) = creator.call{... | 0.6.12 |
// to caclulate the amounts for recipient and distributer after fees have been applied | function calculateFeesBeforeSend(
address sender,
address recipient,
uint256 amount
) public view returns (uint256, uint256) {
if(UniSwapReciever[recipient] && UniSwapSaleEnds){
uint256 timeNow = block.timestamp;
uint256 sfee = 5; //5% fee defa... | 0.8.0 |
/* @notice Convert boolean value into bytes
* @param b The boolean value
* @return Converted bytes array
*/ | function WriteBool(bool b) internal pure returns (bytes memory) {
bytes memory buff;
assembly{
buff := mload(0x40)
mstore(buff, 1)
switch iszero(b)
case 1 {
mstore(add(buff, 0x20), shl(248, 0x00))
// mstore8(add(buff... | 0.6.12 |
/* @notice Convert uint8 value into bytes
* @param v The uint8 value
* @return Converted bytes array
*/ | function WriteUint8(uint8 v) internal pure returns (bytes memory) {
bytes memory buff;
assembly{
buff := mload(0x40)
mstore(buff, 1)
mstore(add(buff, 0x20), shl(248, v))
// mstore(add(buff, 0x20), byte(0x1f, v))
mstore(0x40, add(buff, 0x... | 0.6.12 |
/* @notice Convert uint16 value into bytes
* @param v The uint16 value
* @return Converted bytes array
*/ | function WriteUint16(uint16 v) internal pure returns (bytes memory) {
bytes memory buff;
assembly{
buff := mload(0x40)
let byteLen := 0x02
mstore(buff, byteLen)
for {
let mindex := 0x00
let vindex := 0x1f
... | 0.6.12 |
/* @notice Convert limited uint256 value into bytes
* @param v The uint256 value
* @return Converted bytes array
*/ | function WriteUint255(uint256 v) internal pure returns (bytes memory) {
require(v <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds uint255 range");
bytes memory buff;
assembly{
buff := mload(0x40)
let byteLen := 0x20
... | 0.6.12 |
/* @notice Convert the bytes array to bytes32 type, the bytes array length must be 32
* @param _bs Source bytes array
* @return bytes32
*/ | function bytesToBytes32(bytes memory _bs) internal pure returns (bytes32 value) {
require(_bs.length == 32, "bytes length is not 32.");
assembly {
// load 32 bytes from memory starting from position _bs + 0x20 since the first 0x20 bytes stores _bs length
value := mload(add(_b... | 0.6.12 |
/* @notice Convert bytes to uint256
* @param _b Source bytes should have length of 32
* @return uint256
*/ | function bytesToUint256(bytes memory _bs) internal pure returns (uint256 value) {
require(_bs.length == 32, "bytes length is not 32.");
assembly {
// load 32 bytes from memory starting from position _bs + 32
value := mload(add(_bs, 0x20))
}
require(value <= ... | 0.6.12 |
/* @notice Convert uint256 to bytes
* @param _b uint256 that needs to be converted
* @return bytes
*/ | function uint256ToBytes(uint256 _value) internal pure returns (bytes memory bs) {
require(_value <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds the range");
assembly {
// Get a location of some free memory and store it in result as
// So... | 0.6.12 |
/* @notice Convert bytes to address
* @param _bs Source bytes: bytes length must be 20
* @return Converted address from source bytes
*/ | function bytesToAddress(bytes memory _bs) internal pure returns (address addr)
{
require(_bs.length == 20, "bytes length does not match address");
assembly {
// for _bs, first word store _bs.length, second word store _bs.value
// load 32 bytes from mem[_bs+20], convert i... | 0.6.12 |
/* @notice Convert address to bytes
* @param _addr Address need to be converted
* @return Converted bytes from address
*/ | function addressToBytes(address _addr) internal pure returns (bytes memory bs){
assembly {
// Get a location of some free memory and store it in result as
// Solidity does for memory variables.
bs := mload(0x40)
// Put 20 (address byte length) at the first wo... | 0.6.12 |
/* @notice Check if the elements number of _signers within _keepers array is no less than _m
* @param _keepers The array consists of serveral address
* @param _signers Some specific addresses to be looked into
* @param _m The number requirement paramter
* @return ... | function containMAddresses(address[] memory _keepers, address[] memory _signers, uint _m) internal pure returns (bool){
uint m = 0;
for(uint i = 0; i < _signers.length; i++){
for (uint j = 0; j < _keepers.length; j++) {
if (_signers[i] == _keepers[j]) {
... | 0.6.12 |
/* @notice TODO
* @param key
* @return
*/ | function compressMCPubKey(bytes memory key) internal pure returns (bytes memory newkey) {
require(key.length >= 67, "key lenggh is too short");
newkey = slice(key, 0, 35);
if (uint8(key[66]) % 2 == 0){
newkey[2] = byte(0x02);
} else {
newkey[2] = byte(... | 0.6.12 |
/**
@notice allow approved address to deposit an asset for OHM
@param _amount uint
@param _token address
@param _profit uint
@return send_ uint
*/ | function deposit( uint _amount, address _token, uint _profit ) external returns ( uint send_ ) {
require( isReserveToken[ _token ] || isLiquidityToken[ _token ], "Not accepted" );
IERC20( _token ).safeTransferFrom( msg.sender, address(this), _amount );
if ( isReserveToken[ _token ] ) {
... | 0.7.5 |
/**
@notice allow approved address to burn OHM for reserves
@param _amount uint
@param _token address
*/ | function withdraw( uint _amount, address _token ) external {
require( isReserveToken[ _token ], "Not accepted" ); // Only reserves can be used for redemptions
require( isReserveSpender[ msg.sender ] == true, "Not approved" );
uint value = valueOf( _token, _amount );
IOHMERC20( OHM ).bur... | 0.7.5 |
/**
@notice allow approved address to borrow reserves
@param _amount uint
@param _token address
*/ | function incurDebt( uint _amount, address _token ) external {
require( isDebtor[ msg.sender ], "Not approved" );
require( isReserveToken[ _token ], "Not accepted" );
uint value = valueOf( _token, _amount );
uint maximumDebt = IERC20( sOHM ).balanceOf( msg.sender ); // Can only borrow a... | 0.7.5 |
/**
@notice allow approved address to repay borrowed reserves with OHM
@param _amount uint
*/ | function repayDebtWithOHM( uint _amount ) external {
require( isDebtor[ msg.sender ], "Not approved" );
IOHMERC20( OHM ).burnFrom( msg.sender, _amount );
debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( _amount );
totalDebt = totalDebt.sub( _amount );
emit RepayD... | 0.7.5 |
/**
@notice allow approved address to withdraw assets
@param _token address
@param _amount uint
*/ | function manage( address _token, uint _amount ) external {
if( isLiquidityToken[ _token ] ) {
require( isLiquidityManager[ msg.sender ], "Not approved" );
} else {
require( isReserveManager[ msg.sender ], "Not approved" );
}
uint value = valueOf(_token, _amount);... | 0.7.5 |
/**
@notice takes inventory of all tracked assets
@notice always consolidate to recognized reserves before audit
*/ | function auditReserves() external onlyManager() {
uint reserves;
for( uint i = 0; i < reserveTokens.length; i++ ) {
reserves = reserves.add (
valueOf( reserveTokens[ i ], IERC20( reserveTokens[ i ] ).balanceOf( address(this) ) )
);
}
for( uint i = ... | 0.7.5 |
/**
@notice returns OHM valuation of asset
@param _token address
@param _amount uint
@return value_ uint
*/ | function valueOf( address _token, uint _amount ) public view returns ( uint value_ ) {
if ( isReserveToken[ _token ] ) {
// convert amount to match OHM decimals
value_ = _amount.mul( 10 ** IERC20( OHM ).decimals() ).div( 10 ** IERC20( _token ).decimals() );
} else if ( isLiquidit... | 0.7.5 |
/**
@notice checks requirements and returns altered structs
@param queue_ mapping( address => uint )
@param status_ mapping( address => bool )
@param _address address
@return bool
*/ | function requirements(
mapping( address => uint ) storage queue_,
mapping( address => bool ) storage status_,
address _address
) internal view returns ( bool ) {
if ( !status_[ _address ] ) {
require( queue_[ _address ] != 0, "Must queue" );
require( queue_[ _... | 0.7.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.