comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/// @notice this function is used to get total annuity benefits between two months
/// @param _stakerAddress: address of staker who has a PET
/// @param _petId: id of PET in staker address portfolio
/// @param _startAnnuityMonthId: this is the month (inclusive) to start from
/// @param _endAnnuityMonthId: this is the m... | function getSumOfMonthlyAnnuity(
address _stakerAddress,
uint256 _petId,
uint256 _startAnnuityMonthId,
uint256 _endAnnuityMonthId
) public view returns (uint256) {
/// @notice get the storage references of staker's PET and Plan
PET storage _pet = pets[_stakerAddress][_petId];
PETPl... | 0.5.16 |
/// @notice calculating power booster amount
/// @param _stakerAddress: address of staker who has PET
/// @param _petId: id of PET in staket address portfolio
/// @return single power booster amount | function calculatePowerBoosterAmount(
address _stakerAddress,
uint256 _petId
) public view returns (uint256) {
/// @notice get the storage reference of staker's PET
PET storage _pet = pets[_stakerAddress][_petId];
uint256 _totalDepositedIncludingPET;
/// @notice calculating total de... | 0.5.16 |
/// @notice this function is used internally to burn penalised booster tokens
/// @param _stakerAddress: address of staker who has a PET
/// @param _petId: id of PET in staker address portfolio | function _burnPenalisedPowerBoosterTokens(
address _stakerAddress,
uint256 _petId
) private {
/// @notice get the storage references of staker's PET
PET storage _pet = pets[_stakerAddress][_petId];
uint256 _unachieveTargetCount;
/// @notice calculating number of unacheived targets
... | 0.5.16 |
/// @notice this function is used by contract to get total deposited amount including PET
/// @param _amount: amount of ES which is deposited
/// @param _monthlyCommitmentAmount: commitment amount of staker
/// @return staker plus pet deposit amount based on acheivement of commitment | function _getTotalDepositedIncludingPET(
uint256 _amount,
uint256 _monthlyCommitmentAmount
) private pure returns (uint256) {
uint256 _petAmount;
/// @notice if there is topup then add half of topup to pet
if(_amount > _monthlyCommitmentAmount) {
uint256 _topupAmount = _amount.sub(_... | 0.5.16 |
// **PUBLIC PAYABLE functions**
// Example: _collToken = Eth, _borrowToken = USDC | function deposit(
address _collToken, address _cCollToken, uint _collAmount, address _borrowToken, address _cBorrowToken, uint _borrowAmount
) public payable authCheck {
// add _cCollToken to market
enterMarketInternal(_cCollToken);
// mint _cCollToken
mintInternal(_c... | 0.5.17 |
// Example: _collToken = Eth, _borrowToken = USDC | function withdraw(
address _collToken, address _cCollToken, uint256 cAmountRedeem, address _borrowToken, address _cBorrowToken, uint256 amountRepay
) public payable authCheck returns (uint256) {
// repayBorrow _cBorrowToken
paybackInternal(_borrowToken, _cBorrowToken, amountRepay);
... | 0.5.17 |
/// @notice Adds to governance contract staking reward tokens to be sent to vote process participants.
/// @param _reward Amount of staking rewards token in wei | function notifyRewardAmount(uint256 _reward)
external
onlyRewardDistribution
override
updateReward(address(0))
{
IERC20(rewardsToken).safeTransferFrom(_msgSender(), address(this), _reward);
if (block.timestamp >= periodFinish) {
rewardRate = _rewar... | 0.6.3 |
/// @notice Creates a proposal to vote
/// @param _executor Executor contract address
/// @param _hash IPFS hash of the proposal document | function propose(address _executor, string memory _hash) public {
require(votesOf(_msgSender()) > minimum, "<minimum");
proposals[proposalCount] = Proposal({
id: proposalCount,
proposer: _msgSender(),
totalForVotes: 0,
totalAgainstVotes: 0,
... | 0.6.3 |
/// @notice Called by third party to execute the proposal conditions
/// @param _id ID of the proposal | function execute(uint256 _id) public {
(uint256 _for, uint256 _against, uint256 _quorum) = getStats(_id);
require(proposals[_id].quorumRequired < _quorum, "!quorum");
require(proposals[_id].end < block.number , "!end");
if (proposals[_id].open) {
tallyVotes(_id);
... | 0.6.3 |
/// @notice Called by anyone to obtain the voting process statistics for specific proposal
/// @param _id ID of the proposal
/// @return _for 'For' percentage in base points
/// @return _against 'Against' percentage in base points
/// @return _quorum Current quorum percentage in base points | function getStats(uint256 _id)
public
view
returns(
uint256 _for,
uint256 _against,
uint256 _quorum
)
{
_for = proposals[_id].totalForVotes;
_against = proposals[_id].totalAgainstVotes;
uint256 _total = _for.add(_... | 0.6.3 |
/// @notice Nullify (revoke) all the votes staked by msg.sender | function revoke() public {
require(voters[_msgSender()], "!voter");
voters[_msgSender()] = false;
/// @notice Edge case dealt with in openzeppelin trySub methods.
/// The case should be impossible, but this is defi.
(,totalVotes) = totalVotes.trySub(votes[_msgSender()]);
... | 0.6.3 |
/* Public Functions - Start */ | function register(
address _tenant,
address[] memory _creators,
address[] memory _admins,
uint8 _quorum
) public returns (bool success) {
require(
msg.sender == _tenant || msg.sender == Ownable(_tenant).owner(),
"ONLY_TENANT_OR_TENANT_OWNER"
);
return _register(_ten... | 0.5.4 |
/// @notice Allow registered voter to vote 'against' proposal
/// @param _id Proposal id | function voteAgainst(uint256 _id) public {
require(proposals[_id].start < block.number, "<start");
require(proposals[_id].end > block.number, ">end");
uint256 _for = proposals[_id].forVotes[_msgSender()];
if (_for > 0) {
proposals[_id].totalForVotes = proposals[_id].to... | 0.6.3 |
/// @notice Allow to remove old governance tokens from voter weight, simultaneosly it recalculates reward size according to new weight
/// @param _amount Amount of governance token to withdraw | function withdraw(uint256 _amount) public override updateReward(_msgSender()) {
require(_amount > 0, "!withdraw 0");
if (voters[_msgSender()]) {
votes[_msgSender()] = votes[_msgSender()].sub(_amount);
totalVotes = totalVotes.sub(_amount);
}
if (!breaker) {
... | 0.6.3 |
/// @notice Transfer staking reward tokens to voter (msg.sender), simultaneosly it recalculates reward size according to new weight and rewards remaining | function getReward() public updateReward(_msgSender()) {
if (!breaker) {
require(voteLock[_msgSender()] > block.number, "!voted");
}
uint256 reward = earned(_msgSender());
if (reward > 0) {
rewards[_msgSender()] = 0;
rewardsToken.transfer(_msgSe... | 0.6.3 |
/** TRANSFER SECTION by Beni Syahroni,S.Pd.I
*/ | function _transfer(address _from, address _to, uint _value) internal {
require(_to !=0x0);
require(balanceOf[_from] >=_value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
require(!frozenAccount[msg.sender]);
uint previousBalances = balanceOf[_from... | 0.4.24 |
/**
* @dev
* Encode team distribution percentage
* Embed all individuals equity and payout to seedz project
* retain at least 0.1 ether in the smart contract
*/ | function withdraw() public onlyOwner {
/* Minimum balance */
require(address(this).balance > 0.5 ether);
uint256 balance = address(this).balance - 0.1 ether;
for (uint256 i = 0; i < _team.length; i++) {
Team storage _st = _team[i];
_st.addr.transfer((balance * _st.percentage) / 100);
}
} | 0.8.7 |
/**
* Set some Apes aside
* We will set aside 50 Vapenapes for community giveaways and promotions
*/ | function reserveApes() public onlyOwner {
require(totalSupply().add(NUM_TO_RESERVE) <= MAX_APES, "Reserve would exceed max supply");
uint256 supply = totalSupply();
for (uint256 i = 0; i < NUM_TO_RESERVE; i++) {
_safeMint(_msgSender(), supply + i);
}
} | 0.8.7 |
/**
* Mints Apes
*/ | function mintApe(uint256 numberOfTokens) public payable saleIsOpen {
require(numberOfTokens <= MAX_APE_PURCHASE, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_APES, "Purchase would exceed max supply of Apes");
require(APE_SALEPRICE.mul(numberOfTokens) <= msg.value, "Ether... | 0.8.7 |
/**
* @dev IFoundation
*/ | function getFees(uint256 tokenId)
external
view
virtual
returns (address payable[] memory, uint256[] memory)
{
require(_existsRoyalties(tokenId), "Nonexistent token");
address payable[] memory receivers = new address payable[](1);
uint256[] memory bp... | 0.8.9 |
/**
* CONSTRUCTOR
*
* @dev Initialize the EtherSportCrowdsale
* @param _startTime Start time timestamp
* @param _endTime End time timestamp
* @param _token EtherSport ERC20 token
* @param _from Wallet address with token allowance
* @param _wallet Wallet address to transfer direct funding to
*/ | function EtherSportCrowdsale(
uint256 _startTime,
uint256 _endTime,
address _token,
address _from,
address _wallet
)
public
{
require(_startTime < _endTime);
require(_token != address(0));
require(_from != address(0));
... | 0.4.19 |
/**
* @dev Makes order for tokens purchase.
* @param _beneficiary Who will get the tokens
* @param _referer Beneficiary's referer (optional)
*/ | function buyTokensFor(
address _beneficiary,
address _referer
)
public
payable
{
require(_beneficiary != address(0));
require(_beneficiary != _referer);
require(msg.value >= MIN_FUNDING_AMOUNT);
require(liveEtherSportCampaign());
... | 0.4.19 |
/**
* @dev Get current rate from oraclize and transfer tokens.
* @param _orderId Oraclize order id
* @param _result Current rate
*/ | function __callback(bytes32 _orderId, string _result) public { // solium-disable-line mixedcase
require(msg.sender == oraclize_cbAddress());
uint256 _rate = parseInt(_result, RATE_EXPONENT);
address _beneficiary = orders[_orderId].beneficiary;
uint256 _funds = orders[_orderId].fu... | 0.4.19 |
// View function to see pending pheonix on frontend. | function pendingPHX(address _user)
external
view
returns (uint256)
{
UserInfo storage user = userInfo[_user];
uint256 lpSupply = lpToken.balanceOf(address(this));
uint256 accPhx = accPhxPerShare;
if (block.number > lastRewardBlock && lpSupply != 0) {
... | 0.8.7 |
// Deposit LP tokens to MasterChef for CAKE allocation. | function deposit( uint256 _amount) public {
UserInfo storage user = userInfo[msg.sender];
updatePool();
if (user.amount > 0) {
uint256 pending = user.amount.mul(accPhxPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
phx.transfer(msg.sender, pend... | 0.8.7 |
// function acc() public view returns(uint256){
// return accPhxPerShare;
// }
// function userInf() public view returns(uint256,uint256){
// return (userInfo[msg.sender].amount,userInfo[msg.sender].rewardDebt);
// }
// function utils() public view returns(uint256){
// return (block.number);
// }
// functio... | function withdraw(uint256 _amount) public {
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool();
uint256 pending = user.amount.mul(accPhxPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
phx.tran... | 0.8.7 |
/**
* Returns the ratio of the first argument to the second argument.
*/ | function outOf(uint256 _a, uint256 _b)
internal
pure
returns (uint256 result)
{
if (_a == 0) {
return 0;
}
uint256 a = _a.mul(basisValue);
if (a < _b) {
return 0;
}
return (a.div(_b));
} | 0.5.17 |
/**
* Validates passed address equals to the three addresses.
*/ | function validate3Addresses(
address _addr,
address _target1,
address _target2,
address _target3
) external pure {
if (_addr == _target1) {
return;
}
if (_addr == _target2) {
return;
}
require(_addr == _target3, errorMessage);
} | 0.5.17 |
/**
* @dev Updates the token metadata if the owner is also the creator.
* @param _tokenId uint256 ID of the token.
* @param _uri string metadata URI.
*/ | function updateTokenMetadata(uint256 _tokenId, string memory _uri)
public
{
require(_isApprovedOrOwner(msg.sender, _tokenId), "BcaexOwnershipV2: transfer caller is not owner nor approved");
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
_setTokenURI... | 0.6.2 |
//~~ Methods based on Token.sol from Ethereum Foundation
//~ Transfer FLIP | function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw;
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
balanceOf[msg.sender] -= _value;
balanceOf[_t... | 0.4.11 |
// ------------------------------------------------------------------------
// 2000000 FCOM Tokens per 1 ETH
// ------------------------------------------------------------------------ | function () public payable {
require(now >= startDate && now <= endDate);
uint tokens;
/*
if (now <= bonusEnds) {
tokens = msg.value * 1200;
} else {
tokens = msg.value * 2000000;
}
*/
tokens = msg.value * 2000000;
balance... | 0.4.21 |
//function calcAmount(address _beneficiar) canMint public returns (uint256 amount) { //for test's | function calcAmount(address _beneficiar) canMint internal returns (uint256 amount) {
if (countClaimsToken[_beneficiar] == 0) {
countClaimsToken[_beneficiar] = 1;
}
if (countClaimsToken[_beneficiar] >= 1000) {
return 0;
}
uint step = countClaimsToken... | 0.4.24 |
//initialize rewards for v2 starting staking contracts | function setStakingRewards(
INameService ns,
address[] memory contracts,
uint256[] memory rewards
) external onlyOwner {
require(contracts.length == rewards.length, "staking length mismatch");
for (uint256 i = 0; i < contracts.length; i++) {
(bool ok, ) = controller.genericCall(
ns.getAddress("FUND_MA... | 0.8.8 |
//add new reserve as minter
//renounace minter from avatar
//add reserve as global constraint on controller | function _setReserveSoleMinter(INameService ns) internal {
bool ok;
(ok, ) = controller.genericCall(
ns.getAddress("GOODDOLLAR"),
abi.encodeWithSignature("addMinter(address)", ns.getAddress("RESERVE")),
avatar,
0
);
require(ok, "Calling addMinter failed");
(ok, ) = controller.genericCall(
addr... | 0.8.8 |
//transfer funds(cdai + comp) from old reserve to new reserve/avatar
//end old reserve
//initialize new marketmaker with current cdai price, rr, reserves | function _setNewReserve(INameService ns) internal {
bool ok;
address cdai = ns.getAddress("CDAI");
uint256 oldReserveCdaiBalance = ERC20(cdai).balanceOf(avatar);
ok = controller.externalTokenTransfer(
cdai,
ns.getAddress("RESERVE"),
oldReserveCdaiBalance,
avatar
);
require(ok, "transfer cdai ... | 0.8.8 |
//set contracts in nameservice that are deployed after INameService is created
// FUND_MANAGER RESERVE REPUTATION GDAO_STAKING GDAO_CLAIMERS ... | function _setNameServiceContracts(
INameService ns,
bytes32[] memory names,
address[] memory addresses
) internal {
(bool ok, ) = controller.genericCall(
address(ns),
abi.encodeWithSignature(
"setAddresses(bytes32[],address[])",
names,
addresses
),
avatar,
0
);
require(ok, "Calli... | 0.8.8 |
// Deposit LP tokens to Hulkfarmer for HULK allocation. | function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
// if user has any LP tokens staked, we would send the reward here
// but NOT ANYMORE
//
// if (user.amount > 0) {
// uint256 pe... | 0.6.12 |
// Initialize to have owner have 100,000,000,000 CL on contract creation
// Constructor is called only once and can not be called again (Ethereum Solidity specification) | function CL() public {
// Ensure token gets created once only
require(tokenCreated == false);
tokenCreated = true;
owner = msg.sender;
balances[owner] = totalSupply;
// Final sanity check to ensure owner balance is greater than zero
require(ba... | 0.4.21 |
// Function to distribute tokens to list of addresses by the provided amount
// Verify and require that:
// - Balance of owner cannot be negative
// - All transfers can be fulfilled with remaining owner balance
// - No new tokens can ever be minted except originally created 100,000,000,000 | function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public {
// Only allow undrop while token is locked
// After token is unlocked, this method becomes permanently disabled
//require(unlocked);
// Amount is in Wei, convert to CL amount in 8 decimal places
... | 0.4.21 |
// Withdraw LP tokens from Hulkfarmer. | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accPerShare).div(1e12).sub(
user.reward... | 0.6.12 |
// Standard function transfer similar to ERC223 transfer with no _data .
// Added due to backwards compatibility reasons . | function transfer(address _to, uint _value) public returns (bool success) {
// Only allow transfer once unlocked
// Once it is unlocked, it is unlocked forever and no one can lock again
//require(unlocked);
//standard function transfer similar to ERC223 transfer with no _data
... | 0.4.21 |
// Allow transfers if the owner provided an allowance
// Prevent from any transfers if token is not yet unlocked
// Use SafeMath for the main logic | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
// Only allow transfer once unlocked
// Once it is unlocked, it is unlocked forever and no one can lock again
//require(unlocked);
// Protect against wrapping uints.
require(bal... | 0.4.21 |
/// @param _amount amount in BASED to deposit | function deposit(uint _amount) public {
require(_amount > 0, "Nothing to deposit");
uint _pool = balance();
based.transferFrom(msg.sender, address(this), _amount);
uint _after = balance();
_amount = _after.sub(_pool); // Additional check for deflationary baseds
ui... | 0.5.17 |
/**
* Passthrough to `Lockup.difference` function.
*/ | function difference(
WithdrawStorage withdrawStorage,
address _property,
address _user
)
private
view
returns (
uint256 _reward,
uint256 _holdersAmount,
uint256 _holdersPrice,
uint256 _interestAmount,
uint256 _interestPrice
)
{
/**
* Gets and passes the last recorded ... | 0.5.17 |
/**
* Returns the holder reward.
*/ | function _calculateAmount(address _property, address _user)
private
view
returns (uint256 _amount, uint256 _price)
{
WithdrawStorage withdrawStorage = getStorage();
/**
* Gets the latest cumulative sum of the maximum mint amount,
* and the difference to the previous withdrawal of holder rewar... | 0.5.17 |
/**
* Returns the total rewards currently available for withdrawal. (For calling from inside the contract)
*/ | function _calculateWithdrawableAmount(address _property, address _user)
private
view
returns (uint256 _amount, uint256 _price)
{
/**
* Gets the latest withdrawal reward amount.
*/
(uint256 _value, uint256 price) = _calculateAmount(_property, _user);
/**
* If the passed Property has not... | 0.5.17 |
/**
* Returns the cumulative sum of the holder rewards of the passed Property.
*/ | function calculateTotalWithdrawableAmount(address _property)
external
view
returns (uint256)
{
(, uint256 _amount, , , ) = ILockup(config().lockup()).difference(
_property,
0
);
/**
* Adjusts decimals to 10^18 and returns the result.
*/
return _amount.divBasis().divBasis();
} | 0.5.17 |
/**
* Returns the reward amount of the calculation model before DIP4.
* It can be calculated by subtracting "the last cumulative sum of reward unit price" from
* "the current cumulative sum of reward unit price," and multiplying by the balance of the user.
*/ | function __legacyWithdrawableAmount(address _property, address _user)
private
view
returns (uint256)
{
WithdrawStorage withdrawStorage = getStorage();
uint256 _last = withdrawStorage.getLastWithdrawalPrice(
_property,
_user
);
uint256 price = withdrawStorage.getCumulativePrice(_property);... | 0.5.17 |
/**
* @notice Approves tokens from signatory to be spent by `spender`
* @param spender The address to receive the tokens
* @param rawAmount The amount of tokens to be sent to spender
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
*... | function approveBySig(address spender, uint rawAmount, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 structHash = keccak256(abi.encode(APPROVE_TYPE_HASH, spender, rawAmount, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)... | 0.5.13 |
// these are for communication from router to gateway | function encodeFromRouterToGateway(address _from, bytes calldata _data)
internal
pure
returns (bytes memory res)
{
// abi decode may revert, but the encoding is done by L1 gateway, so we trust it
return abi.encode(_from, _data);
} | 0.6.12 |
/**
* Multiply two uint256 values, throw in case of overflow.
*
* @param x first value to multiply
* @param y second value to multiply
* @return x * y
*/ | function safeMul (uint256 x, uint256 y)
pure internal
returns (uint256 z) {
if (y == 0) return 0; // Prevent division by zero at the next line
assert (x <= MAX_UINT256 / y);
return x * y;
} | 0.4.20 |
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/ | function transfer (address _to, uint256 _value)
public returns (bool success) {
uint256 fromBalance = accounts [msg.sender];
if (fromBalance < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (fromBalance, _value);
accounts [_to] = safeAdd (acc... | 0.4.20 |
/**
* Burn given number of tokens belonging to message sender.
*
* @param _value number of tokens to burn
* @return true on success, false on error
*/ | function burnTokens (uint256 _value) public returns (bool success) {
if (_value > accounts [msg.sender]) return false;
else if (_value > 0) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
tokenCount = safeSub (tokenCount, _value);
Transfer (msg.sender, address (0), _v... | 0.4.20 |
/// @notice Function to mint non-fungible tokens, pause contract, check amount minted is > 0, and doesn't exceed the maxMintAmount or maxSupply
/// @param _mintAmount tracks number of NFTs minted | function mint(uint256 _mintAmount) public payable {
require(!paused, "the contract is paused");
uint256 supply = totalSupply();
require(_mintAmount > 0, "need to mint at least 1 NFT");
require(
_mintAmount <= maxMintAmount,
"max mint amount per session exceeded"
... | 0.8.10 |
/// @notice we keep track of tokenIds owner possesses
/// @dev tokenIds are kept in memory for efficiency
/// @return tokenIds of wallet owner | function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerB... | 0.8.10 |
/// @notice we require a token Id to exist
/// @dev if contract is not revealed, show temporary uniform resource identifier
/// @return current base uniform resource identifier, or return nothing | function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return notRevealedUr... | 0.8.10 |
/// @notice only owner can withdraw ether from contract | function withdraw() public payable onlyOwner {
/// @notice Donate 10% to Assemble Pittsburgh
(bool assemble, ) = payable(0xc1353fE8bd78aE6f5449da47203523D2edEaCc59)
.call{value: (address(this).balance * 10) / 100}("");
require(assemble);
/// @notice Donate 10% to Black Girls... | 0.8.10 |
/**
* @notice internal utility function used to handle when no contract is deployed at expected address
*/ | function handleNoContract(
address _l1Token,
address, /* expectedL2Address */
address _from,
address, /* _to */
uint256 _amount,
bytes memory /* gatewayData */
) internal override returns (bool shouldHalt) {
// it is assumed that the custom token is deployed i... | 0.6.12 |
/**
* @notice Allows L1 Token contract to trustlessly register its custom L2 counterpart.
* param _l2Address counterpart address of L1 token
* param _maxGas max gas for L2 retryable exrecution
* param _gasPriceBid gas price for L2 retryable ticket
* param _maxSubmissionCost base submission cost L2 retryable tick... | function registerTokenToL2(
address _l2Address,
uint256 _maxGas,
uint256 _gasPriceBid,
uint256 _maxSubmissionCost,
address _creditBackAddress
) public payable returns (uint256) {
require(
ArbitrumEnabledToken(msg.sender).isArbitrumEnabled() == uint8(0xa4b1... | 0.6.12 |
/**
* @notice Allows owner to force register a custom L1/L2 token pair.
* @dev _l1Addresses[i] counterpart is assumed to be _l2Addresses[i]
* @param _l1Addresses array of L1 addresses
* @param _l2Addresses array of L2 addresses
* @param _maxGas max gas for L2 retryable exrecution
* @param _gasPriceBid gas price f... | function forceRegisterTokenToL2(
address[] calldata _l1Addresses,
address[] calldata _l2Addresses,
uint256 _maxGas,
uint256 _gasPriceBid,
uint256 _maxSubmissionCost
) external payable returns (uint256) {
require(msg.sender == owner, "ONLY_OWNER");
require(_l1A... | 0.6.12 |
/**
* @dev Returns the protocol fee amount to charge for a flash loan of `amount`.
*/ | function _calculateFlashLoanFeeAmount(uint256 amount) internal view returns (uint256) {
// Fixed point multiplication introduces error: we round up, which means in certain scenarios the charged
// percentage can be slightly higher than intended.
uint256 percentage = getProtocolFeesCollector().ge... | 0.7.1 |
/**
* @dev Extracts the signature parameters from extra calldata.
*
* This function returns bogus data if no signature is included. This is not a security risk, as that data would not
* be considered a valid signature in the first place.
*/ | function _signature()
internal
pure
returns (
uint8 v,
bytes32 r,
bytes32 s
)
{
// v, r and s are appended after the signature deadline, in that order.
v = uint8(uint256(_decodeExtraCalldataWord(0x20)));
r = _decodeExtraCall... | 0.7.1 |
/**
* @dev Allows this contract to make approve call for a token
* This method is expected to be called using externalCall method.
* @param token The address of the token
* @param to The address of the spender
* @param amount The amount to be approved
*/ | function approve(
address token,
address to,
uint256 amount
)
external
onlySelf
{
require(amount > 0, "Amount should be greater than 0!!");
//1. Check for valid whitelisted address
require(
isWhitelisted(to),
"AugustusSw... | 0.5.10 |
/**
* @dev The function which performs the actual swap.
* The call data to the actual exchanges must be built offchain
* and then sent to this method. It will be call those external exchanges using
* data passed through externalCall function
* It is a nonreentrant function
* @param sourceToken Address of th... | function swap(
address sourceToken,
address destinationToken,
uint256 sourceAmount,
uint256 minDestinationAmount,
address[] memory callees,
bytes memory exchangeData,
uint256[] memory startIndexes,
uint256[] memory values,
string memory re... | 0.5.10 |
/**
* @dev Helper method to refund gas using gas tokens
*/ | function refundGas(uint256 initialGas, uint256 mintPrice) private {
uint256 mintBase = 32254;
uint256 mintToken = 36543;
uint256 freeBase = 14154;
uint256 freeToken = 6870;
uint256 reimburse = 24000;
uint256 tokens = initialGas.sub(
gasleft()).add(f... | 0.5.10 |
/**
* @dev Helper method to free gas tokens
*/ | function freeGasTokens(uint256 tokens) private {
uint256 tokensToFree = tokens;
uint256 safeNumTokens = 0;
uint256 gas = gasleft();
if (gas >= 27710) {
safeNumTokens = gas.sub(27710).div(1148 + 5722 + 150);
}
if (tokensToFree > safeNumTokens) {
... | 0.5.10 |
/**
* @dev Helper method to calculate fees
* @param receivedAmount Received amount of tokens
*/ | function calculateFee(
address sourceToken,
uint256 receivedAmount,
uint256 calleesLength
)
private
view
returns (uint256)
{
uint256 fee = 0;
if (sourceToken == ETH_ADDRESS && calleesLength == 1) {
return 0;
}
else if... | 0.5.10 |
/**
* @dev Source take from GNOSIS MultiSigWallet
* @dev https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol
*/ | function externalCall(
address destination,
uint256 value,
uint256 dataOffset,
uint dataLength,
bytes memory data
)
private
returns (bool)
{
bool result = false;
assembly {
let x := mload(0x40) // "Allocate" memory for out... | 0.5.10 |
/**
* @dev Returns the original calldata, without the extra bytes containing the signature.
*
* This function returns bogus data if no signature is included.
*/ | function _calldata() internal pure returns (bytes memory result) {
result = msg.data; // A calldata to memory assignment results in memory allocation and copy of contents.
if (result.length > _EXTRA_CALLDATA_LENGTH) {
// solhint-disable-next-line no-inline-assembly
assembly {
... | 0.7.1 |
/**
* @notice Finalizes a withdrawal via Outbox message; callable only by L2Gateway.outboundTransfer
* @param _token L1 address of token being withdrawn from
* @param _from initiator of withdrawal
* @param _to address the L2 withdrawal call set as the destination.
* @param _amount Token amount being withdrawn
* @... | function finalizeInboundTransfer(
address _token,
address _from,
address _to,
uint256 _amount,
bytes calldata _data
) external payable override onlyCounterpartGateway {
(uint256 exitNum, bytes memory callHookData) = GatewayMessageHandler.parseToL1GatewayMsg(
... | 0.6.12 |
/**
* @dev Creates a Pool ID.
*
* These are deterministically created by packing the Pool's contract address and its specialization setting into
* the ID. This saves gas by making this data easily retrievable from a Pool ID with no storage accesses.
*
* Since a single contract can register multiple Pools, a uniqu... | function _toPoolId(
address pool,
PoolSpecialization specialization,
uint80 nonce
) internal pure returns (bytes32) {
bytes32 serialized;
serialized |= bytes32(uint256(nonce));
serialized |= bytes32(uint256(specialization)) << (10 * 8);
serialized |= bytes32(... | 0.7.1 |
/**
* @dev Returns the address of a Pool's contract.
*
* Due to how Pool IDs are created, this is done with no storage accesses and costs little gas.
*/ | function _getPoolAddress(bytes32 poolId) internal pure returns (address) {
// 12 byte logical shift left to remove the nonce and specialization setting. We don't need to mask,
// since the logical shift already sets the upper bits to zero.
return address(uint256(poolId) >> (12 * 8));
} | 0.7.1 |
//low level function to buy tokens | function buyTokens(address beneficiary) internal {
require(beneficiary != 0x0);
require(whitelist[beneficiary]);
require(validPurchase());
//derive amount in wei to buy
uint256 weiAmount = msg.value;
// check if contribution is in the first 24h hours
i... | 0.4.18 |
//Only owner can manually finalize the sale | function finalize() onlyOwner {
require(!isFinalized);
require(hasEnded());
if (goalReached()) {
//Close the vault
vault.close();
//Unpause the token
token.unpause();
//give ownership back to deployer
token.trans... | 0.4.18 |
// @return true if the transaction can buy tokens | function validPurchase() internal constant returns (bool) {
bool withinPeriod = getBlockTimestamp() >= startTime && getBlockTimestamp() <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool capNotReached = weiRaised < cap;
return withinPeriod && nonZeroPurchase && capNotReached;
... | 0.4.18 |
//Note: owner (or their advocate) is expected to have audited what they commit to,
// including confidence that the terms are guaranteed not to change. i.e. the smartInvoice is trusted | function commit(SmartInvoice smartInvoice) external isOwner returns (bool) {
require(smartInvoice.payer() == address(this), "not smart invoice payer");
require(smartInvoice.status() == SmartInvoice.Status.UNCOMMITTED, "smart invoice already committed");
require(smartInvoice.assetToken() == this.assetToken(... | 0.5.0 |
// @dev convinence function for returning the offset token ID | function xhouseID(uint256 _id) public view returns (uint256 houseID) {
for (uint256 i = 1; i <= SEASON_COUNT; i++) {
if (_id < seasons[i].unit_count) {
return (_id + seasons[i].tokenOffset) % seasons[i].unit_count;
}
}
} | 0.8.7 |
// onlyOwner functions | function addSeason(
uint256 _seasonNum,
uint256 _price,
uint256 _count,
uint256 _walletLimit,
string memory _provenance,
string memory _baseURI
) external onlyOwner {
require(seasons[_seasonNum].unit_count == 0, "Season Already exists");
seasons[_seaso... | 0.8.7 |
// @dev gift a single token to each address passed in through calldata
// @param _season uint256 season number
// @param _recipients Array of addresses to send a single token to | function gift(uint256 _season, address[] calldata _recipients)
external
onlyOwner
{
require(
_recipients.length + season_minted[_season] <=
seasons[_season].unit_count,
"Number of gifts exceeds season supply"
);
for (uint256 i = 0; i <... | 0.8.7 |
/**
* Inserts new value by moving existing value at provided index to end of array and setting provided value at provided index
*/ | function _insert(Set storage set_, uint256 index_, bytes32 valueToInsert_ ) private returns ( bool ) {
require( set_._values.length > index_ );
require( !_contains( set_, valueToInsert_ ), "Remove value you wish to insert if you wish to reorder array." );
bytes32 existingValue_ = _at( set_, index_ );
s... | 0.7.5 |
/**
* TODO Might require explicit conversion of bytes32[] to address[].
* Might require iteration.
*/ | function getValues( AddressSet storage set_ ) internal view returns ( address[] memory ) {
address[] memory addressArray;
for( uint256 iteration_ = 0; _length(set_._inner) >= iteration_; iteration_++ ){
addressArray[iteration_] = at( set_, iteration_ );
}
return addressArray;
} | 0.7.5 |
// mine token | function earned(uint256 _tokenId) public view returns (uint256) {
if(!_exists(_tokenId)) {
return 0;
}
Property memory prop = cardProperties[_tokenId];
uint256 _startTime = Math.max(prop.lastUpdateTime, mineStartTime);
uint256 _endTime = Math.min(block.timestamp... | 0.6.12 |
// Compose intermediate cards | function composeToIntermediateCards(uint256[] memory _tokenIds) external {
require(hasComposeToIntermediateStarted, "Compose to intermediate card has not started");
uint256 count = _tokenIds.length / 2;
require(_tokenIds.length % 2 == 0 && count > 0 && count <= 5, "Number of cards does not ma... | 0.6.12 |
// Compose advanced cards | function composeToAdvancedCards(uint256[] memory _tokenIds) external {
require(hasComposeToAdvancedStarted, "Compose to advance card has not started");
uint256 count = _tokenIds.length / 2;
require(_tokenIds.length % 2 == 0 && count > 0 && count <= 5, "Number of cards does not match or exceed... | 0.6.12 |
/**
* @dev Overrides Crowdsale fund forwarding, sending funds to vault if not finalised, otherwise to wallet
*/ | function _forwardFunds() internal {
// once finalized all contributions got to the wallet
if (isFinalized) {
wallet.transfer(msg.value);
}
// otherwise send to vault to allow refunds, if required
else {
vault.deposit.value(msg.value)(msg.sender);
}
} | 0.4.24 |
/**
* @dev Extend parent behavior requiring contract to not be paused.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/ | function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(isCrowdsaleOpen(), "Crowdsale not open");
require(weiRaised.add(_weiAmount) <= hardCap, "Exceeds maximum cap");
require(_weiAmount >= minimumContribu... | 0.4.24 |
/**
* @dev Registers tokens in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*
* Requirements:
*
* - `tokenX` and `tokenY` must not be the same
* - The tokens must be ordered: tokenX < tokenY
*/ | function _registerTwoTokenPoolTokens(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
) internal {
// Not technically true since we didn't register yet, but this is consistent with the error messages of other
// specialization settings.
_require(tokenX != tokenY, Errors.... | 0.7.1 |
/**
* @dev Deregisters tokens in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*
* Requirements:
*
* - `tokenX` and `tokenY` must be registered in the Pool
* - both tokens must have zero balance in the Vault
*/ | function _deregisterTwoTokenPoolTokens(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
) internal {
(
bytes32 balanceA,
bytes32 balanceB,
TwoTokenPoolBalances storage poolBalances
) = _getTwoTokenPoolSharedBalances(poolId, tokenX, tokenY);
... | 0.7.1 |
/**
* @dev Sets `token`'s balance in a Two Token Pool to the result of the `mutation` function when called with
* the current balance and `amount`.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the manag... | function _updateTwoTokenPoolSharedBalance(
bytes32 poolId,
IERC20 token,
function(bytes32, uint256) returns (bytes32) mutation,
uint256 amount
) private returns (int256) {
(
TwoTokenPoolBalances storage balances,
IERC20 tokenA,
bytes32 bala... | 0.7.1 |
/*
* @dev Returns an array with all the tokens and balances in a Two Token Pool. The order may change when
* tokens are registered or deregistered.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*/ | function _getTwoTokenPoolTokens(bytes32 poolId)
internal
view
returns (IERC20[] memory tokens, bytes32[] memory balances)
{
(, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId);
// Both tokens will either be zero (if unregis... | 0.7.1 |
//return of interest on the deposit | function collectPercent() isIssetUser timePayment internal {
//if the user received 200% or more of his contribution, delete the user
if ((userDeposit[msg.sender].mul(2)) <= persentWithdraw[msg.sender]) {
userDeposit[msg.sender] = 0;
userTime[msg.sender] = 0;
per... | 0.4.25 |
//calculation of the current interest rate on the deposit | function persentRate() public view returns(uint) {
//get contract balance
uint balance = address(this).balance;
//calculate persent rate
if (balance < stepLow) {
return (startPercent);
}
if (balance >= stepLow && balance < stepMiddle) {
ret... | 0.4.25 |
//make a contribution to the system | function makeDeposit() private {
if (msg.value > 0) {
if (userDeposit[msg.sender] == 0) {
countOfInvestors += 1;
}
if (userDeposit[msg.sender] > 0 && now > userTime[msg.sender].add(chargingTime)) {
collectPercent();
}
... | 0.4.25 |
//return of deposit balance | function returnDeposit() isIssetUser private {
//userDeposit-persentWithdraw-(userDeposit*8/100)
uint withdrawalAmount = userDeposit[msg.sender].sub(persentWithdraw[msg.sender]).sub(userDeposit[msg.sender].mul(projectPercent).div(100));
//check that the user's balance is greater than the inte... | 0.4.25 |
/**
* @dev Same as `_getTwoTokenPoolTokens`, except it returns the two tokens and balances directly instead of using
* an array, as well as a storage pointer to the `TwoTokenPoolBalances` struct, which can be used to update it
* without having to recompute the pair hash and storage slot.
*/ | function _getTwoTokenPoolBalances(bytes32 poolId)
private
view
returns (
TwoTokenPoolBalances storage poolBalances,
IERC20 tokenA,
bytes32 balanceA,
IERC20 tokenB,
bytes32 balanceB
)
{
TwoTokenPoolTokens storage pool... | 0.7.1 |
/**
* @dev Returns the balance of a token in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* This function is convenient but not particularly gas efficient, and should be avoided during gas-sensitive
* operations, such as swaps. For those, _ge... | function _getTwoTokenPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) {
// We can't just read the balance of token, because we need to know the full pair in order to compute the pair
// hash and access the balance mapping. We therefore rely on `_getTwoTokenPoolBalances`.
... | 0.7.1 |
/**
* @dev Returns true if `token` is registered in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*/ | function _isTwoTokenPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) {
TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];
// The zero address can never be a registered token.
return (token == poolTokens.tokenA || token == poolTokens.tokenB) && tok... | 0.7.1 |
/**
* ERC20 Token Transfer
*/ | function sendwithgas(address _from, address _to, uint256 _value, uint256 _fee) public onlyOwner notFrozen(_from) returns (bool) {
uint256 _total;
_total = _value.add(_fee);
require(!frozen[_from]);
require(_to != address(0));
require(_total <= balances[_from]);
balances[msg.sender] = balances[msg.sender].add(_f... | 0.4.24 |
/**
* @dev Returns the sequence for a given tokenId
* @dev Deterministic based on tokenId and seedNumber from lobsterBeachClub
* @dev One trait is selected and appended to sequence based on rarity
* @dev Returns geneSequence of asset if tokenId is chosen for an asset
*/ | function getGeneSequence(uint256 tokenId) public view returns (uint256 _geneSequence) {
uint256 assetOwned = getAssetOwned(tokenId);
if (assetOwned != 0) {
return assetOwned;
}
uint256 seedNumber = lobsterBeachClub.seedNumber();
uint256 geneSequenceSeed = uint256(kecc... | 0.8.7 |
/// @author Marlin
/// @dev add functionality to forward the balance as well. | function() external payable {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
let contractLogic := sload(slot)
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(
sub(gas(), 10000),
contractLogic,
... | 0.5.17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.