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
|
---|---|---|---|---|
23 | // Alex | ambassadors_[0x008ca4F1bA79D1A265617c6206d7884ee8108a78] = true;
| ambassadors_[0x008ca4F1bA79D1A265617c6206d7884ee8108a78] = true;
| 56,475 |
19 | // refund dust eth, if any | if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
| if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
| 822 |
6 | // Address of each `IRewarder` contract in MCV2. | IRewarder[] public rewarder;
| IRewarder[] public rewarder;
| 18,078 |
80 | // update cumulative funding rate | _updateCumuFundingRate(_price);
| _updateCumuFundingRate(_price);
| 48,744 |
22 | // Maker orders num_legs > 1, set outlook to false, any wrong outcome of maker order results in positive outcome for taker. | newTakerOrder = HDGXStructs.TakerOrder(
takerOrderIDCount + 1,
sender,
valueSent,
block.timestamp,
makerOrderID,
false,
opposite_odds256
);
| newTakerOrder = HDGXStructs.TakerOrder(
takerOrderIDCount + 1,
sender,
valueSent,
block.timestamp,
makerOrderID,
false,
opposite_odds256
);
| 4,215 |
1 | // Used for identifying cases when this contract's balance of a token is to be used as an input/ This value is equivalent to 1<<255, i.e. a singular 1 in the most significant bit. | uint256 internal constant CONTRACT_BALANCE = 0x8000000000000000000000000000000000000000000000000000000000000000;
| uint256 internal constant CONTRACT_BALANCE = 0x8000000000000000000000000000000000000000000000000000000000000000;
| 20,310 |
32 | // BambooField allows you to grow your Bamboo! Buy some seeds, and then harvest them for more Bamboo! | contract BambooField is ERC20("Seed", "SEED"), Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// Info of each user that can buy seeds.
mapping (address => FarmUserInfo) public userInfo;
BambooToken public bamboo;
ZooKeeper public zooKeeper;
// Amount needed to register
uint256 public registerAmount;
// Amount locked as collateral
uint256 public depositPool;
// Minimum time to harvest. Also min time of lock in the deposit.
uint256 public minStakeTime;
struct FarmUserInfo {
uint256 amount; // Deposited Amount
uint poolId; // Pool ID of active staking LP
uint256 startTime; // Timestamp of registration
bool active; // Flag for checking if this entry is active.
uint256 endTime; // Last timestamp the user can buy seeds. Only used if this is not active
}
event RegisterAmountChanged(uint256 amount);
event StakeTimeChanged(uint256 time);
constructor(BambooToken _bamboo, ZooKeeper _zoo, uint256 _registerprice, uint256 _minstaketime) {
bamboo= _bamboo;
zooKeeper = _zoo;
registerAmount = _registerprice;
minStakeTime = _minstaketime;
}
// Register a staking pool to the user with a collateral payment
function register(uint _pid, uint256 _amount) public {
require( _pid < zooKeeper.getPoolLength() , "register: invalid pool");
require(_amount > registerAmount, "register: amount should be bigger than registerAmount");
require(userInfo[msg.sender].amount == 0, "register: already registered");
// Get the poolId
uint256 amount = zooKeeper.getLpAmount(_pid, msg.sender);
require(amount > 0, 'register: no LP on pool');
uint256 seedAmount = _amount.sub(registerAmount);
// move the registerAmount
IERC20(bamboo).safeTransferFrom(address(msg.sender), address(this), registerAmount);
depositPool = depositPool.add(registerAmount);
// save user data
userInfo[msg.sender] = FarmUserInfo(registerAmount, _pid, block.timestamp, true, 0);
// buy seeds with the rest
buy(seedAmount);
}
// Buy some Seeds with BAMBOO.
// Requires an active register of LP staking, or endTime still valid.
function buy(uint256 _amount) public {
// Checks if user is valid
if(!userInfo[msg.sender].active) {
require(userInfo[msg.sender].endTime >= block.timestamp, "buy: invalid user");
}
// Gets the amount of usable BAMBOO locked in the contract
uint256 totalBamboo = bamboo.balanceOf(address(this)).sub(depositPool);
// Gets the amount of Seeds in existence
uint256 totalShares = totalSupply();
// If no Seeds exists, mint it 1:1 to the amount put in
if (totalShares == 0 || totalBamboo == 0) {
_mint(msg.sender, _amount);
}
// Calculate and mint the amount of Seeds the BAMBOO is worth. The ratio will change overtime, as Seeds are burned/minted and BAMBOO is deposited + gained from fees / withdrawn.
else {
uint256 what = _amount.mul(totalShares).div(totalBamboo);
_mint(msg.sender, what);
}
// Lock the BAMBOO in the contract
IERC20(bamboo).safeTransferFrom(address(msg.sender), address(this), _amount);
}
// Harvest your BAMBOO
// Unlocks the staked + gained BAMBOO and burns Seeds
function harvest(uint256 _share) public {
// Checks if time is valid
require(block.timestamp.sub(userInfo[msg.sender].startTime) >= minStakeTime, "buy: cannot harvest seeds at this time");
// Gets the amount of Seeds in existence
uint256 totalShares = totalSupply();
uint256 totalBamboo = bamboo.balanceOf(address(this)).sub(depositPool);
// Calculates the amount of BAMBOO the Seeds are worth
uint256 what = _share.mul(totalBamboo).div(totalShares);
_burn(msg.sender, _share);
IERC20(bamboo).safeTransfer(msg.sender, what);
}
// Register a staking pool to the user with a collateral payment
function withdraw() public {
// Checks if timestamp is valid
require(block.timestamp.sub(userInfo[msg.sender].startTime) >= minStakeTime, "withdraw: cannot withdraw yet!");
// Harvest remaining seeds
uint256 seeds = balanceOf(msg.sender);
if (seeds>0){
harvest (seeds);
}
uint256 deposit = userInfo[msg.sender].amount;
// Reset user data
delete(userInfo[msg.sender]);
// Return deposit
IERC20(bamboo).safeTransfer(msg.sender, deposit);
depositPool = depositPool.sub(deposit);
}
// This function will be called from ZooKeeper if LP balance is withdrawn
function updatePool(address _user) external {
require(ZooKeeper(msg.sender) == zooKeeper, "updatePool: contract was not ZooKeeper");
userInfo[_user].active = false;
// Get 60 days to buy shares if you staked LP at least 60 days
if(block.timestamp - userInfo[_user].startTime >= 60 days){
userInfo[_user].endTime = block.timestamp + 60 days;
}
}
// Changes the entry collateral amount.
function setRegisterAmount(uint256 _amount) external onlyOwner {
registerAmount = _amount;
emit RegisterAmountChanged(registerAmount);
}
// Changes the min stake time in seconds.
function setStakeTime(uint256 _mintime) external onlyOwner {
minStakeTime = _mintime;
emit StakeTimeChanged(minStakeTime);
}
// Check if user is active with an specific pool
function isActive(address _user, uint _pid) public view returns(bool) {
return userInfo[_user].active && userInfo[_user].poolId == _pid;
}
}
| contract BambooField is ERC20("Seed", "SEED"), Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// Info of each user that can buy seeds.
mapping (address => FarmUserInfo) public userInfo;
BambooToken public bamboo;
ZooKeeper public zooKeeper;
// Amount needed to register
uint256 public registerAmount;
// Amount locked as collateral
uint256 public depositPool;
// Minimum time to harvest. Also min time of lock in the deposit.
uint256 public minStakeTime;
struct FarmUserInfo {
uint256 amount; // Deposited Amount
uint poolId; // Pool ID of active staking LP
uint256 startTime; // Timestamp of registration
bool active; // Flag for checking if this entry is active.
uint256 endTime; // Last timestamp the user can buy seeds. Only used if this is not active
}
event RegisterAmountChanged(uint256 amount);
event StakeTimeChanged(uint256 time);
constructor(BambooToken _bamboo, ZooKeeper _zoo, uint256 _registerprice, uint256 _minstaketime) {
bamboo= _bamboo;
zooKeeper = _zoo;
registerAmount = _registerprice;
minStakeTime = _minstaketime;
}
// Register a staking pool to the user with a collateral payment
function register(uint _pid, uint256 _amount) public {
require( _pid < zooKeeper.getPoolLength() , "register: invalid pool");
require(_amount > registerAmount, "register: amount should be bigger than registerAmount");
require(userInfo[msg.sender].amount == 0, "register: already registered");
// Get the poolId
uint256 amount = zooKeeper.getLpAmount(_pid, msg.sender);
require(amount > 0, 'register: no LP on pool');
uint256 seedAmount = _amount.sub(registerAmount);
// move the registerAmount
IERC20(bamboo).safeTransferFrom(address(msg.sender), address(this), registerAmount);
depositPool = depositPool.add(registerAmount);
// save user data
userInfo[msg.sender] = FarmUserInfo(registerAmount, _pid, block.timestamp, true, 0);
// buy seeds with the rest
buy(seedAmount);
}
// Buy some Seeds with BAMBOO.
// Requires an active register of LP staking, or endTime still valid.
function buy(uint256 _amount) public {
// Checks if user is valid
if(!userInfo[msg.sender].active) {
require(userInfo[msg.sender].endTime >= block.timestamp, "buy: invalid user");
}
// Gets the amount of usable BAMBOO locked in the contract
uint256 totalBamboo = bamboo.balanceOf(address(this)).sub(depositPool);
// Gets the amount of Seeds in existence
uint256 totalShares = totalSupply();
// If no Seeds exists, mint it 1:1 to the amount put in
if (totalShares == 0 || totalBamboo == 0) {
_mint(msg.sender, _amount);
}
// Calculate and mint the amount of Seeds the BAMBOO is worth. The ratio will change overtime, as Seeds are burned/minted and BAMBOO is deposited + gained from fees / withdrawn.
else {
uint256 what = _amount.mul(totalShares).div(totalBamboo);
_mint(msg.sender, what);
}
// Lock the BAMBOO in the contract
IERC20(bamboo).safeTransferFrom(address(msg.sender), address(this), _amount);
}
// Harvest your BAMBOO
// Unlocks the staked + gained BAMBOO and burns Seeds
function harvest(uint256 _share) public {
// Checks if time is valid
require(block.timestamp.sub(userInfo[msg.sender].startTime) >= minStakeTime, "buy: cannot harvest seeds at this time");
// Gets the amount of Seeds in existence
uint256 totalShares = totalSupply();
uint256 totalBamboo = bamboo.balanceOf(address(this)).sub(depositPool);
// Calculates the amount of BAMBOO the Seeds are worth
uint256 what = _share.mul(totalBamboo).div(totalShares);
_burn(msg.sender, _share);
IERC20(bamboo).safeTransfer(msg.sender, what);
}
// Register a staking pool to the user with a collateral payment
function withdraw() public {
// Checks if timestamp is valid
require(block.timestamp.sub(userInfo[msg.sender].startTime) >= minStakeTime, "withdraw: cannot withdraw yet!");
// Harvest remaining seeds
uint256 seeds = balanceOf(msg.sender);
if (seeds>0){
harvest (seeds);
}
uint256 deposit = userInfo[msg.sender].amount;
// Reset user data
delete(userInfo[msg.sender]);
// Return deposit
IERC20(bamboo).safeTransfer(msg.sender, deposit);
depositPool = depositPool.sub(deposit);
}
// This function will be called from ZooKeeper if LP balance is withdrawn
function updatePool(address _user) external {
require(ZooKeeper(msg.sender) == zooKeeper, "updatePool: contract was not ZooKeeper");
userInfo[_user].active = false;
// Get 60 days to buy shares if you staked LP at least 60 days
if(block.timestamp - userInfo[_user].startTime >= 60 days){
userInfo[_user].endTime = block.timestamp + 60 days;
}
}
// Changes the entry collateral amount.
function setRegisterAmount(uint256 _amount) external onlyOwner {
registerAmount = _amount;
emit RegisterAmountChanged(registerAmount);
}
// Changes the min stake time in seconds.
function setStakeTime(uint256 _mintime) external onlyOwner {
minStakeTime = _mintime;
emit StakeTimeChanged(minStakeTime);
}
// Check if user is active with an specific pool
function isActive(address _user, uint _pid) public view returns(bool) {
return userInfo[_user].active && userInfo[_user].poolId == _pid;
}
}
| 26,187 |
134 | // Since we are aiming for a CR of 4, we can mint with up to 80% of reserves We mint slightly less so we can be sure there will be enough WETH | uint256 collateral_amount = (WETH.balanceOf(RESERVES) * 79) / 100;
uint256 mint_amount = (collateral_amount * ugasReserves) /
wethReserves /
4;
_mint(collateral_amount, mint_amount);
_mintLPToken(uniswap_pair, FEB_UGAS, WETH, mint_amount, RESERVES);
completed = true;
| uint256 collateral_amount = (WETH.balanceOf(RESERVES) * 79) / 100;
uint256 mint_amount = (collateral_amount * ugasReserves) /
wethReserves /
4;
_mint(collateral_amount, mint_amount);
_mintLPToken(uniswap_pair, FEB_UGAS, WETH, mint_amount, RESERVES);
completed = true;
| 29,052 |
94 | // Gets the roll value for the hp attribute of a hero/class The hero's class id/ return The roll value for hp | function _getHpRoll(uint8 class) internal pure returns (uint8) {
// Warrior
if (class == 0) {
return 41;
}
// Mage, Necromancer, Priest
else if (class == 1 || class == 5 || class == 6) {
return 21;
}
// Druid, Paladin, Bard, Rogue
else {
return 31;
}
}
| function _getHpRoll(uint8 class) internal pure returns (uint8) {
// Warrior
if (class == 0) {
return 41;
}
// Mage, Necromancer, Priest
else if (class == 1 || class == 5 || class == 6) {
return 21;
}
// Druid, Paladin, Bard, Rogue
else {
return 31;
}
}
| 39,699 |
10 | // bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)"); | bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
string public constant name = "Flashstake";
string public constant symbol = "FLASH";
uint8 public constant decimals = 18;
address public constant FLASH_PROTOCOL = 0x15EB0c763581329C921C8398556EcFf85Cc48275;
address public constant FLASH_CLAIM = 0xf2319b6D2aB252d8D80D8CEC34DaF0079222A624;
uint256 public override totalSupply;
| bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
string public constant name = "Flashstake";
string public constant symbol = "FLASH";
uint8 public constant decimals = 18;
address public constant FLASH_PROTOCOL = 0x15EB0c763581329C921C8398556EcFf85Cc48275;
address public constant FLASH_CLAIM = 0xf2319b6D2aB252d8D80D8CEC34DaF0079222A624;
uint256 public override totalSupply;
| 20,062 |
6 | // Look up the given key. the value returns if it is found | function lookUp(
bytes32 root,
bytes memory key,
Item[] memory db
| function lookUp(
bytes32 root,
bytes memory key,
Item[] memory db
| 11,131 |
80 | // If the `depositor` has no existing shares, then they can `undelegate` themselves.This allows people a "hard reset" in their relationship after withdrawing all of their stake. / | function _undelegate(address depositor) internal {
require(investorDelegations[depositor].length == 0, "InvestmentManager._undelegate: depositor has active deposits");
delegation.undelegate(depositor);
}
| function _undelegate(address depositor) internal {
require(investorDelegations[depositor].length == 0, "InvestmentManager._undelegate: depositor has active deposits");
delegation.undelegate(depositor);
}
| 3,953 |
133 | // Gets the withdrawal recipient.//from The address of the account that does the withdrawal./to The address to which 'amount' tokens were going to be withdrawn./token The address of the token that is withdrawn ('0x0' for ETH)./amount The amount of tokens that are going to be withdrawn./storageID The storageID of the withdrawal request. | function getWithdrawalRecipient(
address from,
address to,
address token,
uint96 amount,
uint32 storageID
)
external
virtual
view
| function getWithdrawalRecipient(
address from,
address to,
address token,
uint96 amount,
uint32 storageID
)
external
virtual
view
| 80,973 |
22 | // NOTE: this doesn't sanitize inputs -> inaccurate values may be returned if there are duplicate token inputs | function queryFees(address[] calldata tokens, FeeClaimType feeType)
external
view
returns (uint256[] memory amountsHeld, uint256[] memory amountsPaid);
function priceFeeds() external view returns (address);
function swapsImpl() external view returns (address);
function logicTargets(bytes4) external view returns (address);
| function queryFees(address[] calldata tokens, FeeClaimType feeType)
external
view
returns (uint256[] memory amountsHeld, uint256[] memory amountsPaid);
function priceFeeds() external view returns (address);
function swapsImpl() external view returns (address);
function logicTargets(bytes4) external view returns (address);
| 5,427 |
640 | // Reduce the size of a position and withdraw a proportional amount of heldToken from the vault.Must be approved by both the position owner and lender. positionIdUnique ID of the positionrequestedCloseAmountPrincipal amount of the position to close. The actual amountclosed is also bounded by:1) The principal of the position2) The amount allowed by the owner if closer != owner3) The amount allowed by the lender if closer != lenderreturn Values corresponding to:1) Principal amount of position closed2) Amount of heldToken received by the msg.sender / | function closeWithoutCounterparty(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
external
closePositionStateControl
nonReentrant
returns (uint256, uint256)
| function closeWithoutCounterparty(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
external
closePositionStateControl
nonReentrant
returns (uint256, uint256)
| 67,400 |
36 | // IConstantFlowAgreementV1.getAccountFlowInfo implementation | function getAccountFlowInfo(
ISuperfluidToken token,
address account
)
external view override
returns (
uint256 timestamp,
int96 flowRate,
uint256 deposit,
uint256 owedDeposit)
| function getAccountFlowInfo(
ISuperfluidToken token,
address account
)
external view override
returns (
uint256 timestamp,
int96 flowRate,
uint256 deposit,
uint256 owedDeposit)
| 11,372 |
324 | // force balances to match reserves | function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IGothPairERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IGothPairERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
| function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IGothPairERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IGothPairERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
| 3,914 |
15 | // Get the owner of the specified token | address tokenOwner = IERC721(_tokenContract).ownerOf(_tokenId);
| address tokenOwner = IERC721(_tokenContract).ownerOf(_tokenId);
| 71,361 |
87 | // If the first position in the array is already the oldest block time then just increase the value in the map | if (_timedTransactionsMap[recipient].txBlockTimes[0] == OVER_21_DAYS_BLOCK_TIME) {
_timedTransactionsMap[recipient].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] = _timedTransactionsMap[recipient].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] + transferAmount;
return;
}
| if (_timedTransactionsMap[recipient].txBlockTimes[0] == OVER_21_DAYS_BLOCK_TIME) {
_timedTransactionsMap[recipient].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] = _timedTransactionsMap[recipient].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] + transferAmount;
return;
}
| 46,643 |
200 | // This is for adding a new (currently unbound) token to the pool It's a two-step process: commitAddToken(), then applyAddToken() | SmartPoolManager.NewTokenParams public newToken;
| SmartPoolManager.NewTokenParams public newToken;
| 6,691 |
3 | // uint256 constant MAX_HP4 = 180;uint256 constant MAX_HP5 = 160;uint256 constant MAX_SPEED1 = 50;uint256 constant MAX_SPEED2 = 75; | uint256 constant MAX_SPEED = 100;
| uint256 constant MAX_SPEED = 100;
| 29,214 |
9 | // Do the call | success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0)
| success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0)
| 36,665 |
36 | // Internal function to mint Loot upon claiming | function _claim(uint256 tokenId, address tokenOwner) internal {
// Checks
// Check that the token ID is in range
// We use >= and <= to here because all of the token IDs are 0-indexed
require(
tokenId >= tokenIdStart && tokenId <= tokenIdEnd,
"TOKEN_ID_OUT_OF_RANGE"
);
// Check thatHotfriescoin have not already been claimed this season
// for a given tokenId
require(
!seasonClaimedByTokenId[season][tokenId],
"GOLD_CLAIMED_FOR_TOKEN_ID"
);
// Effects
// Mark that Hotfriescoin has been claimed for this season for the
// given tokenId
seasonClaimedByTokenId[season][tokenId] = true;
// Interactions
// Send Hotfriescoin to the owner of the token ID
_mint(tokenOwner, HotfriescoinPerTokenId);
}
| function _claim(uint256 tokenId, address tokenOwner) internal {
// Checks
// Check that the token ID is in range
// We use >= and <= to here because all of the token IDs are 0-indexed
require(
tokenId >= tokenIdStart && tokenId <= tokenIdEnd,
"TOKEN_ID_OUT_OF_RANGE"
);
// Check thatHotfriescoin have not already been claimed this season
// for a given tokenId
require(
!seasonClaimedByTokenId[season][tokenId],
"GOLD_CLAIMED_FOR_TOKEN_ID"
);
// Effects
// Mark that Hotfriescoin has been claimed for this season for the
// given tokenId
seasonClaimedByTokenId[season][tokenId] = true;
// Interactions
// Send Hotfriescoin to the owner of the token ID
_mint(tokenOwner, HotfriescoinPerTokenId);
}
| 12,835 |
121 | // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;really i know you think you do but you don't | int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
| int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
| 15,866 |
29 | // setFundsAddress allows owner to set the funds address _fundsAddress address of the funds address / | function setFundsAddress(
address _fundsAddress
| function setFundsAddress(
address _fundsAddress
| 21,739 |
71 | // remove allocated amount from usage's approved amount | usageApprovals[userAddress][usageAddress] = approvedIce.sub(amount);
| usageApprovals[userAddress][usageAddress] = approvedIce.sub(amount);
| 33,611 |
2 | // Creates a new yVault Prize Pool as a proxy of the template instance/ return A reference to the new proxied yVault Prize Pool | function create() external returns (yVaultPrizePool) {
return yVaultPrizePool(deployMinimal(address(instance), ""));
}
| function create() external returns (yVaultPrizePool) {
return yVaultPrizePool(deployMinimal(address(instance), ""));
}
| 43,647 |
153 | // latest tilt size which is updated when updated pool. | uint256 public latestTilt;
| uint256 public latestTilt;
| 53,852 |
105 | // Price (in wei) for the published item | uint256 price;
| uint256 price;
| 1,587 |
1 | // Single minting | function safeMint(address to, string memory uri) internal {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
_setTokenURI(tokenId, uri);
}
| function safeMint(address to, string memory uri) internal {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
_setTokenURI(tokenId, uri);
}
| 9,891 |
147 | // Updates address where strategist fee earnings will go. _strategist new strategist address. / | function setStrategist(address _strategist) external {
require(msg.sender == strategist, "!strategist");
strategist = _strategist;
}
| function setStrategist(address _strategist) external {
require(msg.sender == strategist, "!strategist");
strategist = _strategist;
}
| 11,153 |
70 | // The seed of the hero, the gene encodes the power level of the hero. This is another top secret of the game! Hero's gene can be upgraded via training in a dungeon. | uint genes;
| uint genes;
| 77,177 |
43 | // TimelockVesting A token holder contract that can release its token balance gradually like atypical vesting scheme, with a cliff and vesting period. Owner has the powerto change the beneficiary who receives the vested tokens. Hourglass Foundation / | contract TimelockVesting is TwoStepOwnable {
using SafeERC20 for IERC20;
error InvalidTotalAmount();
error InvalidAmount();
error InvalidBeneficiary();
error InvalidStartTimestamp();
error InvalidCliffStart(uint256 cliffDate, uint256 paramTimestamp);
error InvalidDuration();
error InvalidReleaseAmount();
/// @notice The vesting token
address internal _vestingToken;
/// @notice Whether or not voting is enabled for elegible balances
bool public voting;
/// @notice Vesting schedule parameters
/// @param amount amount of tokens to be vested
/// @param startTimestamp unix timestamp of the start of vesting
/// @param cliff unix timestamp of the cliff, before which no vesting counts
/// @param duration duration in seconds of the period in which the tokens will vest
/// @param released amount of tokens released
struct VestingSchedule {
uint256 amount;
uint256 startTimestamp;
uint256 cliff;
uint256 duration;
uint256 released;
}
/// @notice Internal storage of beneficiary address --> vesting schedule array
mapping(address => VestingSchedule[]) internal _schedules;
/// @param vestingToken address of the token that is subject to vesting
constructor(address vestingToken) {
_setInitialOwner(msg.sender);
require(vestingToken != address(0));
_vestingToken = vestingToken;
voting = true;
}
/// @dev Call this with a script that validates that all arrays are equal length & that
/// all addresses, amounts, timestamps & durations != 0
function addBatchBeneficiaries(
address[] calldata _beneficiaries,
uint256[] calldata _amounts,
uint256[] calldata _startTimestamps,
uint256[] calldata _cliffDates,
uint256[] calldata _durationInSeconds,
uint256 _totalBatchTokenAmount
) external onlyOwner {
// pull in the tokens for this batch
IERC20(_vestingToken).safeTransferFrom(msg.sender, address(this), _totalBatchTokenAmount);
uint256 totalVestingAmount;
uint256 numVests = _beneficiaries.length;
for (uint256 i; i < numVests; i++) {
// add each vesting schedule
_schedules[_beneficiaries[i]].push(VestingSchedule(
_amounts[i],
_startTimestamps[i],
_cliffDates[i],
_durationInSeconds[i],
0
));
totalVestingAmount += _amounts[i];
// note Having event emitted for each loop is less gas efficient, but with a small
// number of vests, it's ok.
emit VestingInitialized(
_beneficiaries[i],
_amounts[i],
_startTimestamps[i],
_cliffDates[i],
_durationInSeconds[i]
);
}
if (totalVestingAmount != _totalBatchTokenAmount) {
revert InvalidTotalAmount();
}
}
/// @notice Initializes a vesting contract that vests its balance of any ERC20 token to the
/// _beneficiary in a linear fashion until duration has passed. By then all
/// of the balance will have vested.
/// @param _beneficiary address of the beneficiary to whom vested tokens are transferred
/// @param _amount amount of tokens to be vested
/// @param _startTimestamp unix timestamp of the start of vesting
/// @param _cliffDate unix timestamp of the cliff, before which no vesting counts
/// @param _durationInSeconds duration in seconds of the period in which the tokens will vest
function addBeneficiary(
address _beneficiary,
uint256 _amount,
uint256 _startTimestamp,
uint256 _cliffDate,
uint256 _durationInSeconds
) external onlyOwner {
// 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);
// add the vesting schedule
_schedules[_beneficiary].push(VestingSchedule(
_amount,
_startTimestamp,
_cliffDate,
_durationInSeconds,
0
));
// pull in the tokens for this beneficiary
IERC20(_vestingToken).safeTransferFrom(msg.sender, address(this), _amount);
emit VestingInitialized(
_beneficiary,
_amount,
_startTimestamp,
_cliffDate,
_durationInSeconds
);
}
/// @notice Transfers vested tokens to beneficiary.
/// @dev This won't revert if nothing is claimable, but nothing will be claimed.
/// @param _beneficiary Address of beneficiary to claim tokens for.
/// @param _scheduleId Id of schedule to claim tokens for.
function release(address _beneficiary, uint256 _scheduleId) external {
if (_beneficiary == address(0)) revert InvalidBeneficiary();
// Transfer vested tokens to beneficiary
IERC20(_vestingToken).safeTransfer(_beneficiary, _release(_beneficiary, _scheduleId));//releasedAmt);
}
/// @notice Allows beneficiary to claim vested tokens across multiple schedules.
/// @dev This won't revert if nothing is claimable, but nothing will be transferred.
/// @param _beneficiary Address of beneficiary to claim tokens for.
/// @param _scheduleIds Array of schedule ids to claim tokens for.
function releaseMultiple(address _beneficiary, uint256[] calldata _scheduleIds) external {
uint256 numSchedules = _scheduleIds.length;
uint256 releasedAmt;
for (uint256 i; i < numSchedules; i++) {
releasedAmt += _release(_beneficiary, _scheduleIds[i]);
}
// transfer vested tokens to beneficiary
IERC20(_vestingToken).safeTransfer(_beneficiary, releasedAmt);
}
/// @notice Updates the amount released & returns the amount to distribute for this `_scheduleId`.
function _release(address _beneficiary, uint256 _scheduleId) internal returns (uint256 vested) {
VestingSchedule memory schedule = _schedules[_beneficiary][_scheduleId];
vested = _vestedAmount(schedule);
// instead of reverting, return 0 if nothing is due so multiple schedules can be checked
if (vested == 0) {
return 0;
}
// otherwise updated released amount
_schedules[_beneficiary][_scheduleId].released += vested;
// sanity check
if (schedule.released > schedule.amount) revert InvalidReleaseAmount();
emit Released(_beneficiary, _scheduleId, vested);
}
/// @notice Calculates the amount that has already vested but hasn't been released yet.
function _vestedAmount(VestingSchedule memory schedule) internal view returns (uint256) {
// cliff hasn't passed yet neither has start time, so 0 vested
if (block.timestamp < schedule.cliff) {
return 0;
}
uint256 elapsedTime = block.timestamp - schedule.startTimestamp;
// If over vesting duration, all tokens vested
if (elapsedTime >= schedule.duration) {
// deduct already released tokens
return schedule.amount - schedule.released;
} else {
// if 75 seconds have passed of the 100 seconds, then 3/4 of the amount should be released.
uint256 vested = schedule.amount * elapsedTime / schedule.duration;
return (vested - schedule.released);
}
}
/// @notice Changes beneficiary who receives the vested token.
/// @dev Only governance can call this function. This is to be used in case the target address
/// needs to be updated. If the previous beneficiary has any unclaimed tokens, the new beneficiary
/// will be able to claim them and the rest of the vested tokens.
/// @param oldBeneficiary address of the previous beneficiary
/// @param newBeneficiary new address to become the beneficiary
/// @param scheduleIds array of schedule ids to migrate to the new beneficiary
function changeBeneficiary(address oldBeneficiary, address newBeneficiary, uint256[] calldata scheduleIds) external onlyOwner {
if (newBeneficiary == address(0)) revert InvalidBeneficiary();
if (newBeneficiary == oldBeneficiary) revert InvalidBeneficiary();
uint256 numSchedules = scheduleIds.length;
// iterate from the end to avoid having to delete & move every schedule element each iteration
for (uint256 i; i < numSchedules; i++) {
VestingSchedule memory schedule = _schedules[oldBeneficiary][scheduleIds[i]];
// migrate the schedule to the new beneficiary
_schedules[newBeneficiary].push(schedule);
// rather than deleting, set amount to the amount released & duration to 0
// to avoid having to delete & move every schedule element each iteration
// and to avoid breaking the amount released logic in _vestedAmount()
_schedules[oldBeneficiary][scheduleIds[i]].amount = schedule.released;
_schedules[oldBeneficiary][scheduleIds[i]].duration = 0;
emit SetBeneficiary(oldBeneficiary, scheduleIds[i], newBeneficiary, _schedules[newBeneficiary].length - 1);
}
}
function changeVoting() external onlyOwner {
voting = !voting;
emit BeneficiaryVotes(voting);
}
////////// Getter Functions //////////
/// @notice Checks the amount of currently vested tokens available for release.
/// @dev Note that this will return a value > 0 if there are any tokens available to claim,
/// @param _beneficiary The address of the beneficiary.
/// @param _scheduleId The index of the schedule array.
/// @return The number of tokens that are vested and available to claim.
function getClaimableAmount(address _beneficiary, uint256 _scheduleId) external view returns (uint256) {
VestingSchedule memory schedule = _schedules[_beneficiary][_scheduleId];
return _vestedAmount(schedule);
}
/// @notice Allows for beneficiaries to be able to cast votes in governance, based on the linear component.
/// @param _user Address of user to check balance for.
/// @return balance The number of tokens that are eligible for voting.
function balanceOf(address _user) external view returns (uint256 balance) {
require(voting);
uint256 numSchedules = _schedules[_user].length;
for (uint256 i; i < numSchedules; i++) {
VestingSchedule memory schedule = _schedules[_user][i];
if (block.timestamp < schedule.startTimestamp) {
continue;
} else {
uint256 elapsedTime = block.timestamp - schedule.startTimestamp;
// If over vesting duration, all tokens vested
if (elapsedTime >= schedule.duration) {
// deduct already released tokens
balance += schedule.amount - schedule.released;
} else {
// if 75 seconds have passed of the 100 seconds, then 3/4 of the amount should be released.
uint256 vested = schedule.amount * elapsedTime / schedule.duration;
balance += (vested - schedule.released);
}
}
}
}
/// @notice Obtain a specific schedule for a user.
/// @dev Note that this will return a schedule even if it has been transferred.
/// @param _beneficiary The address of the beneficiary.
/// @param _scheduleId The index of the schedule array.
/// @return The vesting schedule.
function getSchedule(address _beneficiary, uint256 _scheduleId) external view returns (VestingSchedule memory) {
return _schedules[_beneficiary][_scheduleId];
}
/// @notice Obtain the length of a user's schedule array.
/// @dev Note that this will return a length that includes deleted schedules.
/// @param _beneficiary The address of the beneficiary.
/// @return The length of the schedule array.
function getNumberSchedules(address _beneficiary) external view returns (uint256) {
return _schedules[_beneficiary].length;
}
/// @notice Obtain the total amount of tokens released to a user thus far.
/// @param _beneficiary The address of the beneficiary.
/// @return The total amount of tokens released.
function getTotalAmountReleased(address _beneficiary) external view returns (uint256) {
uint256 numSchedules = _schedules[_beneficiary].length;
uint256 totalReleased;
for (uint256 i; i < numSchedules; i++) {
totalReleased += _schedules[_beneficiary][i].released;
}
return totalReleased;
}
/// @notice Get the token being vested.
/// @return The token address.
function getVestingToken() public view returns (address) {
return _vestingToken;
}
////////// EVENTS //////////
/// @notice Emitted when a beneficiary claims vested tokens.
event Released(address indexed beneficiary, uint256 scheduleId, uint256 amount);
/// @notice Emitted when a new vesting schedule is created.
event VestingInitialized(
address indexed beneficiary,
uint256 amount,
uint256 startTimestamp,
uint256 cliff,
uint256 duration
);
/// @notice Emitted when a beneficiary is changed.
event SetBeneficiary(address indexed oldBeneficiary, uint256 oldBeneficiaryScheduleIndex, address indexed newBeneficiary, uint256 newBeneficiaryScheduleIndex);
/// @notice Emitted when whether votes can be counted is changed.
event BeneficiaryVotes(bool voting);
} | contract TimelockVesting is TwoStepOwnable {
using SafeERC20 for IERC20;
error InvalidTotalAmount();
error InvalidAmount();
error InvalidBeneficiary();
error InvalidStartTimestamp();
error InvalidCliffStart(uint256 cliffDate, uint256 paramTimestamp);
error InvalidDuration();
error InvalidReleaseAmount();
/// @notice The vesting token
address internal _vestingToken;
/// @notice Whether or not voting is enabled for elegible balances
bool public voting;
/// @notice Vesting schedule parameters
/// @param amount amount of tokens to be vested
/// @param startTimestamp unix timestamp of the start of vesting
/// @param cliff unix timestamp of the cliff, before which no vesting counts
/// @param duration duration in seconds of the period in which the tokens will vest
/// @param released amount of tokens released
struct VestingSchedule {
uint256 amount;
uint256 startTimestamp;
uint256 cliff;
uint256 duration;
uint256 released;
}
/// @notice Internal storage of beneficiary address --> vesting schedule array
mapping(address => VestingSchedule[]) internal _schedules;
/// @param vestingToken address of the token that is subject to vesting
constructor(address vestingToken) {
_setInitialOwner(msg.sender);
require(vestingToken != address(0));
_vestingToken = vestingToken;
voting = true;
}
/// @dev Call this with a script that validates that all arrays are equal length & that
/// all addresses, amounts, timestamps & durations != 0
function addBatchBeneficiaries(
address[] calldata _beneficiaries,
uint256[] calldata _amounts,
uint256[] calldata _startTimestamps,
uint256[] calldata _cliffDates,
uint256[] calldata _durationInSeconds,
uint256 _totalBatchTokenAmount
) external onlyOwner {
// pull in the tokens for this batch
IERC20(_vestingToken).safeTransferFrom(msg.sender, address(this), _totalBatchTokenAmount);
uint256 totalVestingAmount;
uint256 numVests = _beneficiaries.length;
for (uint256 i; i < numVests; i++) {
// add each vesting schedule
_schedules[_beneficiaries[i]].push(VestingSchedule(
_amounts[i],
_startTimestamps[i],
_cliffDates[i],
_durationInSeconds[i],
0
));
totalVestingAmount += _amounts[i];
// note Having event emitted for each loop is less gas efficient, but with a small
// number of vests, it's ok.
emit VestingInitialized(
_beneficiaries[i],
_amounts[i],
_startTimestamps[i],
_cliffDates[i],
_durationInSeconds[i]
);
}
if (totalVestingAmount != _totalBatchTokenAmount) {
revert InvalidTotalAmount();
}
}
/// @notice Initializes a vesting contract that vests its balance of any ERC20 token to the
/// _beneficiary in a linear fashion until duration has passed. By then all
/// of the balance will have vested.
/// @param _beneficiary address of the beneficiary to whom vested tokens are transferred
/// @param _amount amount of tokens to be vested
/// @param _startTimestamp unix timestamp of the start of vesting
/// @param _cliffDate unix timestamp of the cliff, before which no vesting counts
/// @param _durationInSeconds duration in seconds of the period in which the tokens will vest
function addBeneficiary(
address _beneficiary,
uint256 _amount,
uint256 _startTimestamp,
uint256 _cliffDate,
uint256 _durationInSeconds
) external onlyOwner {
// 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);
// add the vesting schedule
_schedules[_beneficiary].push(VestingSchedule(
_amount,
_startTimestamp,
_cliffDate,
_durationInSeconds,
0
));
// pull in the tokens for this beneficiary
IERC20(_vestingToken).safeTransferFrom(msg.sender, address(this), _amount);
emit VestingInitialized(
_beneficiary,
_amount,
_startTimestamp,
_cliffDate,
_durationInSeconds
);
}
/// @notice Transfers vested tokens to beneficiary.
/// @dev This won't revert if nothing is claimable, but nothing will be claimed.
/// @param _beneficiary Address of beneficiary to claim tokens for.
/// @param _scheduleId Id of schedule to claim tokens for.
function release(address _beneficiary, uint256 _scheduleId) external {
if (_beneficiary == address(0)) revert InvalidBeneficiary();
// Transfer vested tokens to beneficiary
IERC20(_vestingToken).safeTransfer(_beneficiary, _release(_beneficiary, _scheduleId));//releasedAmt);
}
/// @notice Allows beneficiary to claim vested tokens across multiple schedules.
/// @dev This won't revert if nothing is claimable, but nothing will be transferred.
/// @param _beneficiary Address of beneficiary to claim tokens for.
/// @param _scheduleIds Array of schedule ids to claim tokens for.
function releaseMultiple(address _beneficiary, uint256[] calldata _scheduleIds) external {
uint256 numSchedules = _scheduleIds.length;
uint256 releasedAmt;
for (uint256 i; i < numSchedules; i++) {
releasedAmt += _release(_beneficiary, _scheduleIds[i]);
}
// transfer vested tokens to beneficiary
IERC20(_vestingToken).safeTransfer(_beneficiary, releasedAmt);
}
/// @notice Updates the amount released & returns the amount to distribute for this `_scheduleId`.
function _release(address _beneficiary, uint256 _scheduleId) internal returns (uint256 vested) {
VestingSchedule memory schedule = _schedules[_beneficiary][_scheduleId];
vested = _vestedAmount(schedule);
// instead of reverting, return 0 if nothing is due so multiple schedules can be checked
if (vested == 0) {
return 0;
}
// otherwise updated released amount
_schedules[_beneficiary][_scheduleId].released += vested;
// sanity check
if (schedule.released > schedule.amount) revert InvalidReleaseAmount();
emit Released(_beneficiary, _scheduleId, vested);
}
/// @notice Calculates the amount that has already vested but hasn't been released yet.
function _vestedAmount(VestingSchedule memory schedule) internal view returns (uint256) {
// cliff hasn't passed yet neither has start time, so 0 vested
if (block.timestamp < schedule.cliff) {
return 0;
}
uint256 elapsedTime = block.timestamp - schedule.startTimestamp;
// If over vesting duration, all tokens vested
if (elapsedTime >= schedule.duration) {
// deduct already released tokens
return schedule.amount - schedule.released;
} else {
// if 75 seconds have passed of the 100 seconds, then 3/4 of the amount should be released.
uint256 vested = schedule.amount * elapsedTime / schedule.duration;
return (vested - schedule.released);
}
}
/// @notice Changes beneficiary who receives the vested token.
/// @dev Only governance can call this function. This is to be used in case the target address
/// needs to be updated. If the previous beneficiary has any unclaimed tokens, the new beneficiary
/// will be able to claim them and the rest of the vested tokens.
/// @param oldBeneficiary address of the previous beneficiary
/// @param newBeneficiary new address to become the beneficiary
/// @param scheduleIds array of schedule ids to migrate to the new beneficiary
function changeBeneficiary(address oldBeneficiary, address newBeneficiary, uint256[] calldata scheduleIds) external onlyOwner {
if (newBeneficiary == address(0)) revert InvalidBeneficiary();
if (newBeneficiary == oldBeneficiary) revert InvalidBeneficiary();
uint256 numSchedules = scheduleIds.length;
// iterate from the end to avoid having to delete & move every schedule element each iteration
for (uint256 i; i < numSchedules; i++) {
VestingSchedule memory schedule = _schedules[oldBeneficiary][scheduleIds[i]];
// migrate the schedule to the new beneficiary
_schedules[newBeneficiary].push(schedule);
// rather than deleting, set amount to the amount released & duration to 0
// to avoid having to delete & move every schedule element each iteration
// and to avoid breaking the amount released logic in _vestedAmount()
_schedules[oldBeneficiary][scheduleIds[i]].amount = schedule.released;
_schedules[oldBeneficiary][scheduleIds[i]].duration = 0;
emit SetBeneficiary(oldBeneficiary, scheduleIds[i], newBeneficiary, _schedules[newBeneficiary].length - 1);
}
}
function changeVoting() external onlyOwner {
voting = !voting;
emit BeneficiaryVotes(voting);
}
////////// Getter Functions //////////
/// @notice Checks the amount of currently vested tokens available for release.
/// @dev Note that this will return a value > 0 if there are any tokens available to claim,
/// @param _beneficiary The address of the beneficiary.
/// @param _scheduleId The index of the schedule array.
/// @return The number of tokens that are vested and available to claim.
function getClaimableAmount(address _beneficiary, uint256 _scheduleId) external view returns (uint256) {
VestingSchedule memory schedule = _schedules[_beneficiary][_scheduleId];
return _vestedAmount(schedule);
}
/// @notice Allows for beneficiaries to be able to cast votes in governance, based on the linear component.
/// @param _user Address of user to check balance for.
/// @return balance The number of tokens that are eligible for voting.
function balanceOf(address _user) external view returns (uint256 balance) {
require(voting);
uint256 numSchedules = _schedules[_user].length;
for (uint256 i; i < numSchedules; i++) {
VestingSchedule memory schedule = _schedules[_user][i];
if (block.timestamp < schedule.startTimestamp) {
continue;
} else {
uint256 elapsedTime = block.timestamp - schedule.startTimestamp;
// If over vesting duration, all tokens vested
if (elapsedTime >= schedule.duration) {
// deduct already released tokens
balance += schedule.amount - schedule.released;
} else {
// if 75 seconds have passed of the 100 seconds, then 3/4 of the amount should be released.
uint256 vested = schedule.amount * elapsedTime / schedule.duration;
balance += (vested - schedule.released);
}
}
}
}
/// @notice Obtain a specific schedule for a user.
/// @dev Note that this will return a schedule even if it has been transferred.
/// @param _beneficiary The address of the beneficiary.
/// @param _scheduleId The index of the schedule array.
/// @return The vesting schedule.
function getSchedule(address _beneficiary, uint256 _scheduleId) external view returns (VestingSchedule memory) {
return _schedules[_beneficiary][_scheduleId];
}
/// @notice Obtain the length of a user's schedule array.
/// @dev Note that this will return a length that includes deleted schedules.
/// @param _beneficiary The address of the beneficiary.
/// @return The length of the schedule array.
function getNumberSchedules(address _beneficiary) external view returns (uint256) {
return _schedules[_beneficiary].length;
}
/// @notice Obtain the total amount of tokens released to a user thus far.
/// @param _beneficiary The address of the beneficiary.
/// @return The total amount of tokens released.
function getTotalAmountReleased(address _beneficiary) external view returns (uint256) {
uint256 numSchedules = _schedules[_beneficiary].length;
uint256 totalReleased;
for (uint256 i; i < numSchedules; i++) {
totalReleased += _schedules[_beneficiary][i].released;
}
return totalReleased;
}
/// @notice Get the token being vested.
/// @return The token address.
function getVestingToken() public view returns (address) {
return _vestingToken;
}
////////// EVENTS //////////
/// @notice Emitted when a beneficiary claims vested tokens.
event Released(address indexed beneficiary, uint256 scheduleId, uint256 amount);
/// @notice Emitted when a new vesting schedule is created.
event VestingInitialized(
address indexed beneficiary,
uint256 amount,
uint256 startTimestamp,
uint256 cliff,
uint256 duration
);
/// @notice Emitted when a beneficiary is changed.
event SetBeneficiary(address indexed oldBeneficiary, uint256 oldBeneficiaryScheduleIndex, address indexed newBeneficiary, uint256 newBeneficiaryScheduleIndex);
/// @notice Emitted when whether votes can be counted is changed.
event BeneficiaryVotes(bool voting);
} | 35,152 |
23 | // Records the round data. / | function buyRoundDataRecord(uint256 _rId, uint256 _amount)
private
| function buyRoundDataRecord(uint256 _rId, uint256 _amount)
private
| 21,609 |
440 | // verify valid bonus token | require(isValidAddress(bonusToken), "invalid bonus token address or is already present");
| require(isValidAddress(bonusToken), "invalid bonus token address or is already present");
| 31,474 |
1 | // Throws if called by an account that's in lower ownership tier than expected / | modifier onlyOwnerTier(uint256 _minTier) {
require(ownerTier[msg.sender] >= _minTier, "TieredOwnable#onlyOwnerTier: OWNER_TIER_IS_TOO_LOW");
_;
}
| modifier onlyOwnerTier(uint256 _minTier) {
require(ownerTier[msg.sender] >= _minTier, "TieredOwnable#onlyOwnerTier: OWNER_TIER_IS_TOO_LOW");
_;
}
| 25,770 |
272 | // expmodsAndPoints.expmods[0] = traceGenerator^2. | mstore(expmodsAndPoints,
mulmod(traceGenerator, // traceGenerator^1
traceGenerator, // traceGenerator^1
PRIME))
| mstore(expmodsAndPoints,
mulmod(traceGenerator, // traceGenerator^1
traceGenerator, // traceGenerator^1
PRIME))
| 63,877 |
5 | // Returns the accumulators corresponding to each of `queries`. / | function getPastAccumulators(
OracleAccumulatorQuery[] memory queries
) external view returns (int256[] memory results);
| function getPastAccumulators(
OracleAccumulatorQuery[] memory queries
) external view returns (int256[] memory results);
| 4,818 |
3 | // DAI -> MIM | amount = MIM3POOL.exchange_underlying(1, 0, amount, 0, address(DEGENBOX));
(, shareReturned) = DEGENBOX.deposit(MIM, address(DEGENBOX), recipient, amount, 0);
extraShare = shareReturned - shareToMin;
| amount = MIM3POOL.exchange_underlying(1, 0, amount, 0, address(DEGENBOX));
(, shareReturned) = DEGENBOX.deposit(MIM, address(DEGENBOX), recipient, amount, 0);
extraShare = shareReturned - shareToMin;
| 79,943 |
27 | // ERC721I - ERC721I (ERC721 0xInuarashi Edition) - Gas Optimized | contract ERC721I {
string public name; string public symbol;
string internal baseTokenURI; string internal baseTokenURI_EXT;
constructor(string memory name_, string memory symbol_) {
name = name_; symbol = symbol_;
}
uint256 public totalSupply;
mapping(uint256 => address) public ownerOf;
mapping(address => uint256) public balanceOf;
mapping(uint256 => address) public getApproved;
mapping(address => mapping(address => bool)) public isApprovedForAll;
// Events
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Mint(address indexed to, uint256 tokenId);
event Approval(address indexed owner, address indexed approved,
uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator,
bool approved);
// // internal write functions
// mint
function _mint(address to_, uint256 tokenId_) internal virtual {
require(to_ != address(0x0),
"ERC721I: _mint() Mint to Zero Address");
require(ownerOf[tokenId_] == address(0x0),
"ERC721I: _mint() Token to Mint Already Exists!");
balanceOf[to_]++;
ownerOf[tokenId_] = to_;
emit Transfer(address(0x0), to_, tokenId_);
}
// transfer
function _transfer(address from_, address to_, uint256 tokenId_) internal virtual {
require(from_ == ownerOf[tokenId_],
"ERC721I: _transfer() Transfer Not Owner of Token!");
require(to_ != address(0x0),
"ERC721I: _transfer() Transfer to Zero Address!");
// checks if there is an approved address clears it if there is
if (getApproved[tokenId_] != address(0x0)) {
_approve(address(0x0), tokenId_);
}
ownerOf[tokenId_] = to_;
balanceOf[from_]--;
balanceOf[to_]++;
emit Transfer(from_, to_, tokenId_);
}
// approve
function _approve(address to_, uint256 tokenId_) internal virtual {
if (getApproved[tokenId_] != to_) {
getApproved[tokenId_] = to_;
emit Approval(ownerOf[tokenId_], to_, tokenId_);
}
}
function _setApprovalForAll(address owner_, address operator_, bool approved_)
internal virtual {
require(owner_ != operator_,
"ERC721I: _setApprovalForAll() Owner must not be the Operator!");
isApprovedForAll[owner_][operator_] = approved_;
emit ApprovalForAll(owner_, operator_, approved_);
}
// token uri
function _setBaseTokenURI(string memory uri_) internal virtual {
baseTokenURI = uri_;
}
function _setBaseTokenURI_EXT(string memory ext_) internal virtual {
baseTokenURI_EXT = ext_;
}
// // Internal View Functions
// Embedded Libraries
function _toString(uint256 value_) internal pure returns (string memory) {
if (value_ == 0) { return "0"; }
uint256 _iterate = value_; uint256 _digits;
while (_iterate != 0) { _digits++; _iterate /= 10; } // get digits in value_
bytes memory _buffer = new bytes(_digits);
while (value_ != 0) { _digits--; _buffer[_digits] = bytes1(uint8(
48 + uint256(value_ % 10 ))); value_ /= 10; } // create bytes of value_
return string(_buffer); // return string converted bytes of value_
}
// Functional Views
function _isApprovedOrOwner(address spender_, uint256 tokenId_) internal
view virtual returns (bool) {
require(ownerOf[tokenId_] != address(0x0),
"ERC721I: _isApprovedOrOwner() Owner is Zero Address!");
address _owner = ownerOf[tokenId_];
return (spender_ == _owner
|| spender_ == getApproved[tokenId_]
|| isApprovedForAll[_owner][spender_]);
}
function _exists(uint256 tokenId_) internal view virtual returns (bool) {
return ownerOf[tokenId_] != address(0x0);
}
// // public write functions
function approve(address to_, uint256 tokenId_) public virtual {
address _owner = ownerOf[tokenId_];
require(to_ != _owner,
"ERC721I: approve() Cannot approve yourself!");
require(msg.sender == _owner || isApprovedForAll[_owner][msg.sender],
"ERC721I: Caller not owner or Approved!");
_approve(to_, tokenId_);
}
function setApprovalForAll(address operator_, bool approved_) public virtual {
_setApprovalForAll(msg.sender, operator_, approved_);
}
function transferFrom(address from_, address to_, uint256 tokenId_)
public virtual {
require(_isApprovedOrOwner(msg.sender, tokenId_),
"ERC721I: transferFrom() _isApprovedOrOwner = false!");
_transfer(from_, to_, tokenId_);
}
function safeTransferFrom(address from_, address to_, uint256 tokenId_,
bytes memory data_) public virtual {
transferFrom(from_, to_, tokenId_);
if (to_.code.length != 0) {
(, bytes memory _returned) = to_.staticcall(abi.encodeWithSelector(
0x150b7a02, msg.sender, from_, tokenId_, data_));
bytes4 _selector = abi.decode(_returned, (bytes4));
require(_selector == 0x150b7a02,
"ERC721I: safeTransferFrom() to_ not ERC721Receivable!");
}
}
function safeTransferFrom(address from_, address to_, uint256 tokenId_)
public virtual {
safeTransferFrom(from_, to_, tokenId_, "");
}
// 0xInuarashi Custom Functions
function multiTransferFrom(address from_, address to_, uint256[] memory tokenIds_)
public virtual {
for (uint256 i = 0; i < tokenIds_.length; i++) {
transferFrom(from_, to_, tokenIds_[i]);
}
}
function multiSafeTransferFrom(address from_, address to_,
uint256[] memory tokenIds_, bytes memory data_) public virtual {
for (uint256 i = 0; i < tokenIds_.length; i++) {
safeTransferFrom(from_, to_, tokenIds_[i], data_);
}
}
// OZ Standard Stuff
function supportsInterface(bytes4 interfaceId_) public pure returns (bool) {
return (interfaceId_ == 0x80ac58cd || interfaceId_ == 0x5b5e139f);
}
function tokenURI(uint256 tokenId_) public view virtual returns (string memory) {
require(ownerOf[tokenId_] != address(0x0),
"ERC721I: tokenURI() Token does not exist!");
return string(abi.encodePacked(
baseTokenURI, _toString(tokenId_), baseTokenURI_EXT));
}
// // public view functions
// never use these for functions ever, they are expensive af and for view only
function walletOfOwner(address address_) public virtual view
returns (uint256[] memory) {
uint256 _balance = balanceOf[address_];
uint256[] memory _tokens = new uint256[] (_balance);
uint256 _index;
uint256 _loopThrough = totalSupply;
for (uint256 i = 0; i < _loopThrough; i++) {
if (ownerOf[i] == address(0x0) && _tokens[_balance - 1] == 0) {
_loopThrough++;
}
if (ownerOf[i] == address_) {
_tokens[_index] = i; _index++;
}
}
return _tokens;
}
// not sure when this will ever be needed but it conforms to erc721 enumerable
function tokenOfOwnerByIndex(address address_, uint256 index_) public
virtual view returns (uint256) {
uint256[] memory _wallet = walletOfOwner(address_);
return _wallet[index_];
}
}
| contract ERC721I {
string public name; string public symbol;
string internal baseTokenURI; string internal baseTokenURI_EXT;
constructor(string memory name_, string memory symbol_) {
name = name_; symbol = symbol_;
}
uint256 public totalSupply;
mapping(uint256 => address) public ownerOf;
mapping(address => uint256) public balanceOf;
mapping(uint256 => address) public getApproved;
mapping(address => mapping(address => bool)) public isApprovedForAll;
// Events
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Mint(address indexed to, uint256 tokenId);
event Approval(address indexed owner, address indexed approved,
uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator,
bool approved);
// // internal write functions
// mint
function _mint(address to_, uint256 tokenId_) internal virtual {
require(to_ != address(0x0),
"ERC721I: _mint() Mint to Zero Address");
require(ownerOf[tokenId_] == address(0x0),
"ERC721I: _mint() Token to Mint Already Exists!");
balanceOf[to_]++;
ownerOf[tokenId_] = to_;
emit Transfer(address(0x0), to_, tokenId_);
}
// transfer
function _transfer(address from_, address to_, uint256 tokenId_) internal virtual {
require(from_ == ownerOf[tokenId_],
"ERC721I: _transfer() Transfer Not Owner of Token!");
require(to_ != address(0x0),
"ERC721I: _transfer() Transfer to Zero Address!");
// checks if there is an approved address clears it if there is
if (getApproved[tokenId_] != address(0x0)) {
_approve(address(0x0), tokenId_);
}
ownerOf[tokenId_] = to_;
balanceOf[from_]--;
balanceOf[to_]++;
emit Transfer(from_, to_, tokenId_);
}
// approve
function _approve(address to_, uint256 tokenId_) internal virtual {
if (getApproved[tokenId_] != to_) {
getApproved[tokenId_] = to_;
emit Approval(ownerOf[tokenId_], to_, tokenId_);
}
}
function _setApprovalForAll(address owner_, address operator_, bool approved_)
internal virtual {
require(owner_ != operator_,
"ERC721I: _setApprovalForAll() Owner must not be the Operator!");
isApprovedForAll[owner_][operator_] = approved_;
emit ApprovalForAll(owner_, operator_, approved_);
}
// token uri
function _setBaseTokenURI(string memory uri_) internal virtual {
baseTokenURI = uri_;
}
function _setBaseTokenURI_EXT(string memory ext_) internal virtual {
baseTokenURI_EXT = ext_;
}
// // Internal View Functions
// Embedded Libraries
function _toString(uint256 value_) internal pure returns (string memory) {
if (value_ == 0) { return "0"; }
uint256 _iterate = value_; uint256 _digits;
while (_iterate != 0) { _digits++; _iterate /= 10; } // get digits in value_
bytes memory _buffer = new bytes(_digits);
while (value_ != 0) { _digits--; _buffer[_digits] = bytes1(uint8(
48 + uint256(value_ % 10 ))); value_ /= 10; } // create bytes of value_
return string(_buffer); // return string converted bytes of value_
}
// Functional Views
function _isApprovedOrOwner(address spender_, uint256 tokenId_) internal
view virtual returns (bool) {
require(ownerOf[tokenId_] != address(0x0),
"ERC721I: _isApprovedOrOwner() Owner is Zero Address!");
address _owner = ownerOf[tokenId_];
return (spender_ == _owner
|| spender_ == getApproved[tokenId_]
|| isApprovedForAll[_owner][spender_]);
}
function _exists(uint256 tokenId_) internal view virtual returns (bool) {
return ownerOf[tokenId_] != address(0x0);
}
// // public write functions
function approve(address to_, uint256 tokenId_) public virtual {
address _owner = ownerOf[tokenId_];
require(to_ != _owner,
"ERC721I: approve() Cannot approve yourself!");
require(msg.sender == _owner || isApprovedForAll[_owner][msg.sender],
"ERC721I: Caller not owner or Approved!");
_approve(to_, tokenId_);
}
function setApprovalForAll(address operator_, bool approved_) public virtual {
_setApprovalForAll(msg.sender, operator_, approved_);
}
function transferFrom(address from_, address to_, uint256 tokenId_)
public virtual {
require(_isApprovedOrOwner(msg.sender, tokenId_),
"ERC721I: transferFrom() _isApprovedOrOwner = false!");
_transfer(from_, to_, tokenId_);
}
function safeTransferFrom(address from_, address to_, uint256 tokenId_,
bytes memory data_) public virtual {
transferFrom(from_, to_, tokenId_);
if (to_.code.length != 0) {
(, bytes memory _returned) = to_.staticcall(abi.encodeWithSelector(
0x150b7a02, msg.sender, from_, tokenId_, data_));
bytes4 _selector = abi.decode(_returned, (bytes4));
require(_selector == 0x150b7a02,
"ERC721I: safeTransferFrom() to_ not ERC721Receivable!");
}
}
function safeTransferFrom(address from_, address to_, uint256 tokenId_)
public virtual {
safeTransferFrom(from_, to_, tokenId_, "");
}
// 0xInuarashi Custom Functions
function multiTransferFrom(address from_, address to_, uint256[] memory tokenIds_)
public virtual {
for (uint256 i = 0; i < tokenIds_.length; i++) {
transferFrom(from_, to_, tokenIds_[i]);
}
}
function multiSafeTransferFrom(address from_, address to_,
uint256[] memory tokenIds_, bytes memory data_) public virtual {
for (uint256 i = 0; i < tokenIds_.length; i++) {
safeTransferFrom(from_, to_, tokenIds_[i], data_);
}
}
// OZ Standard Stuff
function supportsInterface(bytes4 interfaceId_) public pure returns (bool) {
return (interfaceId_ == 0x80ac58cd || interfaceId_ == 0x5b5e139f);
}
function tokenURI(uint256 tokenId_) public view virtual returns (string memory) {
require(ownerOf[tokenId_] != address(0x0),
"ERC721I: tokenURI() Token does not exist!");
return string(abi.encodePacked(
baseTokenURI, _toString(tokenId_), baseTokenURI_EXT));
}
// // public view functions
// never use these for functions ever, they are expensive af and for view only
function walletOfOwner(address address_) public virtual view
returns (uint256[] memory) {
uint256 _balance = balanceOf[address_];
uint256[] memory _tokens = new uint256[] (_balance);
uint256 _index;
uint256 _loopThrough = totalSupply;
for (uint256 i = 0; i < _loopThrough; i++) {
if (ownerOf[i] == address(0x0) && _tokens[_balance - 1] == 0) {
_loopThrough++;
}
if (ownerOf[i] == address_) {
_tokens[_index] = i; _index++;
}
}
return _tokens;
}
// not sure when this will ever be needed but it conforms to erc721 enumerable
function tokenOfOwnerByIndex(address address_, uint256 index_) public
virtual view returns (uint256) {
uint256[] memory _wallet = walletOfOwner(address_);
return _wallet[index_];
}
}
| 12,881 |
88 | // If there has already been a record for the upcoming epoch, no need to deduct the unlocks | if (prevCkpt.epochStart == upcomingEpoch) {
ckpts[ckpts.length - 1] = DelegateeCheckpoint({
votes: (prevCkpt.votes + _upcomingAddition - _upcomingDeduction).to224(),
epochStart: upcomingEpoch.to32()
});
| if (prevCkpt.epochStart == upcomingEpoch) {
ckpts[ckpts.length - 1] = DelegateeCheckpoint({
votes: (prevCkpt.votes + _upcomingAddition - _upcomingDeduction).to224(),
epochStart: upcomingEpoch.to32()
});
| 33,178 |
87 | // Reserve the memory. 32 for the length , the input bytes and 32 extra bytes at the end for word manipulation | mstore(0x40, add(add(inputBytes, 0x40), inputBytesLength))
| mstore(0x40, add(add(inputBytes, 0x40), inputBytesLength))
| 3,646 |
31 | // Calculate MIT purchased directly in this transaction. | uint MIT = msg.value * 10; // $1 / MIT based on $10 / ETH value
| uint MIT = msg.value * 10; // $1 / MIT based on $10 / ETH value
| 50,585 |
14 | // Multiplies two exponentials given their mantissas, returning a new exponential. / | function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
| function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
| 12,357 |
14 | // Total number of tokens to be disbursed for a given tranch. Used when Alias of founderTimelocks.length for legibility | uint tranches = _founderTimelocks.length;
| uint tranches = _founderTimelocks.length;
| 36,866 |
20 | // buy for DAI using DApp, need approve first! | function buyDai(uint256 amt) external guarded {
// accept DAI token
require(
IERC20(DAI).transferFrom(msg.sender, address(this), amt),
"DAI transfer failed"
);
// dai uses 18 decimals, we need only 6
uint256 refund = _buy(amt / (10**12));
if (refund > 0) {
require(
IERC20(DAI).transfer(msg.sender, refund * 10**12),
"Refund failed"
);
}
}
| function buyDai(uint256 amt) external guarded {
// accept DAI token
require(
IERC20(DAI).transferFrom(msg.sender, address(this), amt),
"DAI transfer failed"
);
// dai uses 18 decimals, we need only 6
uint256 refund = _buy(amt / (10**12));
if (refund > 0) {
require(
IERC20(DAI).transfer(msg.sender, refund * 10**12),
"Refund failed"
);
}
}
| 47,011 |
4 | // Structure for the сreateLimitOrder with parameters necessary to create limit order bucket The bucket, from which the loan will be taken depositAsset The address of the deposit token (collateral for margin trade orlocked funds for spot) depositAmount The amount of deposit funds for deal positionAsset The address output token for exchange deadline Unix timestamp after which the order will not be filled takeDepositFromWallet Bool, add a collateral deposit within the current transaction leverage leverage for trading shouldOpenPosition Bool, indicate whether position should be opened openingManagerAddresses Array of contract addresses that will be called in canBeFilled openingManagerParams Array of bytes representing | struct CreateLimitOrderParams {
string bucket;
uint256 depositAmount;
address depositAsset;
address positionAsset;
uint256 deadline;
bool takeDepositFromWallet;
bool payFeeFromWallet;
uint256 leverage;
bool shouldOpenPosition;
Condition[] openConditions;
Condition[] closeConditions;
bool isProtocolFeeInPmx;
}
| struct CreateLimitOrderParams {
string bucket;
uint256 depositAmount;
address depositAsset;
address positionAsset;
uint256 deadline;
bool takeDepositFromWallet;
bool payFeeFromWallet;
uint256 leverage;
bool shouldOpenPosition;
Condition[] openConditions;
Condition[] closeConditions;
bool isProtocolFeeInPmx;
}
| 16,470 |
8 | // Whether we should store the @BlockInfo for this block on-chain. | bool storeBlockInfoOnchain;
| bool storeBlockInfoOnchain;
| 27,371 |
33 | // Guard against transfers where the contract attempts to transfer more CHI tokens than it has available. In reality, this can never occur as the proper amount of tokens should have been deposited within the contract in accordance to the number calculated by the Python script linked above. This is simply a guard against human error. | if (tokenBalance < tokensToBuy + bonusTokens) {
chiContract.transfer(msg.sender, tokenBalance);
} else {
| if (tokenBalance < tokensToBuy + bonusTokens) {
chiContract.transfer(msg.sender, tokenBalance);
} else {
| 25,582 |
47 | // Emit BuyPlatinum event | emit BuyPlatinum(msg.sender, _PlatinumPrice, msg.value);
| emit BuyPlatinum(msg.sender, _PlatinumPrice, msg.value);
| 24,866 |
6 | // Other errors | error LCDBackstopEndInTheFuture();
error LCDCannotAssignStakingLocks();
error LCDInvalidPaidPrice();
| error LCDBackstopEndInTheFuture();
error LCDCannotAssignStakingLocks();
error LCDInvalidPaidPrice();
| 43,386 |
626 | // Call multiple functions in the current contract and return the data from all of them if they all succeed/The `msg.value` should not be trusted for any method callable from multicall./data The encoded function data for each of the calls to make to this contract/ return results The results from each of the calls passed in via data | function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
| function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
| 61,767 |
182 | // Calculate earning and withdraw it from Vesper Grow. _totalDebt Total collateral debt of this strategyreturn profit in collateral token / | function _realizeProfit(uint256 _totalDebt) internal virtual override returns (uint256) {
_claimRewardsAndConvertTo(address(collateralToken));
uint256 _collateralBalance = _getCollateralBalance();
if (_collateralBalance > _totalDebt) {
_withdrawHere(_collateralBalance - _totalDebt);
}
return collateralToken.balanceOf(address(this));
}
| function _realizeProfit(uint256 _totalDebt) internal virtual override returns (uint256) {
_claimRewardsAndConvertTo(address(collateralToken));
uint256 _collateralBalance = _getCollateralBalance();
if (_collateralBalance > _totalDebt) {
_withdrawHere(_collateralBalance - _totalDebt);
}
return collateralToken.balanceOf(address(this));
}
| 64,896 |
126 | // Calculate the amount of transferred PTokens | uint256 pTokenAmount = getDecimalConversion(_underlyingTokenAddress, amount - fee, address(0x0));
require(pTokenAmount > 0, "Log:InsurancePool:!pTokenAmount");
| uint256 pTokenAmount = getDecimalConversion(_underlyingTokenAddress, amount - fee, address(0x0));
require(pTokenAmount > 0, "Log:InsurancePool:!pTokenAmount");
| 44,554 |
0 | // uint256 public unitMultiplier;will be used to convert feed price units to token price units |
modifier onlyComdexAdmin() {
_onlyCommdexOwner();
_;
}
|
modifier onlyComdexAdmin() {
_onlyCommdexOwner();
_;
}
| 36,689 |
7 | // Keep record of registered account | mapping(address => bool) registered;
Member[] members; // Organization members
| mapping(address => bool) registered;
Member[] members; // Organization members
| 19,440 |
8 | // Start Presale, only whitelisted addresses can mint (up to `presaleMintMaxAmount` tokens). / | function startPresale() external onlyOwner {
currentStage = Stage.Presale;
}
| function startPresale() external onlyOwner {
currentStage = Stage.Presale;
}
| 44,356 |
52 | // See {IAbridgedMintVector-updateAbridgedVector} / | function updateAbridgedVector(
uint256 vectorId,
AbridgedVector calldata _newVector,
UpdateAbridgedVectorConfig calldata updateConfig
) external {
address contractAddress = address(_abridgedVectors[vectorId].contractAddress);
address msgSender = _msgSender();
| function updateAbridgedVector(
uint256 vectorId,
AbridgedVector calldata _newVector,
UpdateAbridgedVectorConfig calldata updateConfig
) external {
address contractAddress = address(_abridgedVectors[vectorId].contractAddress);
address msgSender = _msgSender();
| 18,491 |
7 | // Sets the extended duration, in seconds, of the auction Sets the extended duration, in seconds, of the auction _extendedDuration The new extended duration, in seconds, of the auction / | function setExtendedDuration(uint _extendedDuration) external onlyOwner {
extendedDuration = _extendedDuration;
}
| function setExtendedDuration(uint _extendedDuration) external onlyOwner {
extendedDuration = _extendedDuration;
}
| 23,197 |
946 | // Execute the Open operation | DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2);
| DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2);
| 13,185 |
89 | // Adds an inscription on-chain to the specified NFT. This is mainly used to sign your own NFTs or forother smart contracts to add inscription functionality. nftAddressThe NFT contract address tokenId The tokenId of the NFT that is being signed contentHash A hash of the content. This hash will not change and will be used to verify the contents in the frontend.This hash must be hosted by inscription operators at the baseURI in order to be considered a valid inscription. baseUriId The id of the inscription operatorRequirements: - `tokenId` The user calling this method must own the `tokenId` at `nftAddress` or | function addInscriptionWithNoSig(
| function addInscriptionWithNoSig(
| 788 |
29 | // Get the stake details information for the given Relay Manager. relayManager The address of a Relay Manager.return stakeInfo The `StakeInfo` structure.return isSenderAuthorizedHub `true` if the `msg.sender` for this call was a `RelayHub` that is authorized now.`false` if the `msg.sender` for this call is not authorized. / | function getStakeInfo(address relayManager) external view returns (StakeInfo memory stakeInfo, bool isSenderAuthorizedHub);
| function getStakeInfo(address relayManager) external view returns (StakeInfo memory stakeInfo, bool isSenderAuthorizedHub);
| 23,710 |
120 | // sets the contract registry to whichever address the current registry is pointing to / | function updateRegistry() public {
// require that upgrading is allowed or that the caller is the owner
require(allowRegistryUpdate || msg.sender == owner);
// get the address of whichever registry the current registry is pointing to
address newRegistry = registry.addressOf(ContractIds.CONTRACT_REGISTRY);
// if the new registry hasn't changed or is the zero address, revert
require(newRegistry != address(registry) && newRegistry != address(0));
// set the previous registry as current registry and current registry as newRegistry
prevRegistry = registry;
registry = IContractRegistry(newRegistry);
}
| function updateRegistry() public {
// require that upgrading is allowed or that the caller is the owner
require(allowRegistryUpdate || msg.sender == owner);
// get the address of whichever registry the current registry is pointing to
address newRegistry = registry.addressOf(ContractIds.CONTRACT_REGISTRY);
// if the new registry hasn't changed or is the zero address, revert
require(newRegistry != address(registry) && newRegistry != address(0));
// set the previous registry as current registry and current registry as newRegistry
prevRegistry = registry;
registry = IContractRegistry(newRegistry);
}
| 10,317 |
24 | // This abstract contract provides getters and event emitting update functions for _Available since v4.1._ @custom:oz-upgrades-unsafe-allow delegatecall / | abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT =
0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(
Address.isContract(newImplementation),
"ERC1967: new implementation is not a contract"
);
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (
bytes32 slot
) {
require(
slot == _IMPLEMENTATION_SLOT,
"ERC1967Upgrade: unsupported proxiableUUID"
);
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT =
0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
Address.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
| abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT =
0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(
Address.isContract(newImplementation),
"ERC1967: new implementation is not a contract"
);
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (
bytes32 slot
) {
require(
slot == _IMPLEMENTATION_SLOT,
"ERC1967Upgrade: unsupported proxiableUUID"
);
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT =
0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
Address.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
| 23,757 |
63 | // If no xUnic exists, mint it 1:1 to the amount put in | if (totalShares == 0 || totalUnic == 0) {
_mint(msg.sender, _amount);
}
| if (totalShares == 0 || totalUnic == 0) {
_mint(msg.sender, _amount);
}
| 29,060 |
6 | // Launch a new campaign. Only one campaign can be started per project./_projectId id of project./_goal Campaign goal./_startAt Campaign start timestamp./_endAt Campaign end timestamp. | function launchCampaign(uint _projectId, uint _goal, uint32 _startAt, uint32 _endAt) external {
require(_startAt > block.timestamp, "Campaign start time must be in the future");
require(_endAt > _startAt, "Campaign end time must be after start time");
require(_endAt < _startAt + maxDuration, "Campaign duration is too long");
require(projectToCampaign[_projectId] == 0, "Project already has a campaign");
campaignsCount++;
campaigns[campaignsCount] = Campaign(campaignsCount, _projectId, msg.sender, _goal, 0, _startAt, _endAt, 0);
projectToCampaign[_projectId] = campaignsCount;
ownerCampaigns[msg.sender].push(campaignsCount);
projectCampaigns[_projectId].push(campaignsCount);
emit CampaignLaunched(campaignsCount, _projectId, msg.sender, _goal, _startAt, _endAt);
}
| function launchCampaign(uint _projectId, uint _goal, uint32 _startAt, uint32 _endAt) external {
require(_startAt > block.timestamp, "Campaign start time must be in the future");
require(_endAt > _startAt, "Campaign end time must be after start time");
require(_endAt < _startAt + maxDuration, "Campaign duration is too long");
require(projectToCampaign[_projectId] == 0, "Project already has a campaign");
campaignsCount++;
campaigns[campaignsCount] = Campaign(campaignsCount, _projectId, msg.sender, _goal, 0, _startAt, _endAt, 0);
projectToCampaign[_projectId] = campaignsCount;
ownerCampaigns[msg.sender].push(campaignsCount);
projectCampaigns[_projectId].push(campaignsCount);
emit CampaignLaunched(campaignsCount, _projectId, msg.sender, _goal, _startAt, _endAt);
}
| 19,486 |
28 | // Event emitted when the start time of an auction changes (due to admin interaction ) | emit Auction_StartTimeUpdated(auctionId, getAuctionStartTime(auctionId));
| emit Auction_StartTimeUpdated(auctionId, getAuctionStartTime(auctionId));
| 19,369 |
15 | // ------------------------------------------------------------------------ Transfer tokens from the from account to the to account The calling account must already have sufficient tokens approve(...)-d for spending from the from account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------ | function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
| function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
| 1,089 |
38 | // calculate price | uint curPrice = currentPrice(index);
uint bidPrice = amount1.mul(1 ether).div(amount0);
require(bidPrice >= curPrice, "the bid price is lower than the current price");
if (lowestBidPrice[index] == 0 || lowestBidPrice[index] > bidPrice) {
lowestBidPrice[index] = bidPrice;
}
| uint curPrice = currentPrice(index);
uint bidPrice = amount1.mul(1 ether).div(amount0);
require(bidPrice >= curPrice, "the bid price is lower than the current price");
if (lowestBidPrice[index] == 0 || lowestBidPrice[index] > bidPrice) {
lowestBidPrice[index] = bidPrice;
}
| 14,392 |
20 | // Stakes serveral of a user's NFTs/tokenIds the tokenId of the NFT to be staked | function groupStake(uint64[] memory tokenIds) external;
| function groupStake(uint64[] memory tokenIds) external;
| 55,355 |
13 | // recommend function | function join(uint256 _refference)public payable onlyFirst(_refference) investAmount returns(bool){
require(users[msg.sender].visit==0,"you are already investor");
cuurUserID++;
userAddress[cuurUserID]=msg.sender;
invested[msg.sender]= msg.value;
user memory obj =user({recomendation:0,creationTime:now,total_Days:0,id:cuurUserID,
total_Amount:0,level:0,referBy:_refference,expirePeriod:false,visit:1,ref_Income:0,total_Withdraw:0,reffrals:new address[](0)});
userList.push(obj);
users[msg.sender]= obj;
isRecomended[msg.sender]=true;
commission=(msg.value.mul(10)).div(100);
Creators(commission);
address payable a=userAddress[_refference];
recomendators[msg.sender]=a;
users[a].reffrals.push(msg.sender);
users[a].recomendation+=1;
if(users[a].level<1){
users[a].level=1;
}
amount[msg.sender]=(invested[msg.sender].mul(1)).div(100);
return true;
}
| function join(uint256 _refference)public payable onlyFirst(_refference) investAmount returns(bool){
require(users[msg.sender].visit==0,"you are already investor");
cuurUserID++;
userAddress[cuurUserID]=msg.sender;
invested[msg.sender]= msg.value;
user memory obj =user({recomendation:0,creationTime:now,total_Days:0,id:cuurUserID,
total_Amount:0,level:0,referBy:_refference,expirePeriod:false,visit:1,ref_Income:0,total_Withdraw:0,reffrals:new address[](0)});
userList.push(obj);
users[msg.sender]= obj;
isRecomended[msg.sender]=true;
commission=(msg.value.mul(10)).div(100);
Creators(commission);
address payable a=userAddress[_refference];
recomendators[msg.sender]=a;
users[a].reffrals.push(msg.sender);
users[a].recomendation+=1;
if(users[a].level<1){
users[a].level=1;
}
amount[msg.sender]=(invested[msg.sender].mul(1)).div(100);
return true;
}
| 51,695 |
185 | // Searches a sorted `array` and returns the first index that containsa value greater or equal to `element`. If no such index exists (i.e. allvalues in the array are strictly less than `element`), the array length isreturned. Time complexity O(log n). `array` is expected to be sorted in ascending order, and to contain norepeated elements. / | function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = MathUpgradeable.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
| function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = MathUpgradeable.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
| 64,591 |
2 | // \ | contract DiamondCutFacet is IDiamondCut {
/// @notice Add/replace/remove any number of functions and optionally execute
/// a function with delegatecall
/// @param _diamondCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
/// _calldata is executed with delegatecall on _init
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external override {
LibDiamond.enforceIsContractOwner();
LibDiamond.diamondCut(_diamondCut, _init, _calldata);
}
}
| contract DiamondCutFacet is IDiamondCut {
/// @notice Add/replace/remove any number of functions and optionally execute
/// a function with delegatecall
/// @param _diamondCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
/// _calldata is executed with delegatecall on _init
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external override {
LibDiamond.enforceIsContractOwner();
LibDiamond.diamondCut(_diamondCut, _init, _calldata);
}
}
| 4,026 |
3 | // Throws if called by any account other than the owner./ | modifier onlyProxyOwner() {
require(msg.sender == proxyOwner());
_;
}
| modifier onlyProxyOwner() {
require(msg.sender == proxyOwner());
_;
}
| 11,062 |
40 | // And send them the PERI. | periFinance().transfer(msg.sender, periFinanceToSend);
emit Exchange("ETH", msg.value, "PERI", periFinanceToSend);
return periFinanceToSend;
| periFinance().transfer(msg.sender, periFinanceToSend);
emit Exchange("ETH", msg.value, "PERI", periFinanceToSend);
return periFinanceToSend;
| 7,288 |
75 | // Yoohoo someone contributed ! | event Contribute(address indexed _from, uint _amount);
| event Contribute(address indexed _from, uint _amount);
| 17,419 |
3 | // Registration of fifth and subsequent airlines requires multi-party consensus of 50% of registered airlines | uint256 constant REGISTER_AIRLINE_MULTI_CALL_THRESHOLD = 4;
uint256 constant REGISTER_AIRLINE_MULTI_CALL_CONSENSUS_DIVISOR = 2;
| uint256 constant REGISTER_AIRLINE_MULTI_CALL_THRESHOLD = 4;
uint256 constant REGISTER_AIRLINE_MULTI_CALL_CONSENSUS_DIVISOR = 2;
| 47,237 |
30 | // Maintains a sorted list of oracle exchange rates between CELO and other currencies. / | contract SortedOracles is ISortedOracles, ICeloVersionedContract, Ownable, Initializable {
using SafeMath for uint256;
using AddressSortedLinkedListWithMedian for SortedLinkedListWithMedian.List;
using FixidityLib for FixidityLib.Fraction;
uint256 private constant FIXED1_UINT = 1000000000000000000000000;
// Maps a token address to a sorted list of report values.
mapping(address => SortedLinkedListWithMedian.List) private rates;
// Maps a token address to a sorted list of report timestamps.
mapping(address => SortedLinkedListWithMedian.List) private timestamps;
mapping(address => mapping(address => bool)) public isOracle;
mapping(address => address[]) public oracles;
// `reportExpirySeconds` is the fallback value used to determine reporting
// frequency. Initially it was the _only_ value but we later introduced
// the per token mapping in `tokenReportExpirySeconds`. If a token
// doesn't have a value in the mapping (i.e. it's 0), the fallback is used.
// See: #getTokenReportExpirySeconds
uint256 public reportExpirySeconds;
mapping(address => uint256) public tokenReportExpirySeconds;
event OracleAdded(address indexed token, address indexed oracleAddress);
event OracleRemoved(address indexed token, address indexed oracleAddress);
event OracleReported(
address indexed token,
address indexed oracle,
uint256 timestamp,
uint256 value
);
event OracleReportRemoved(address indexed token, address indexed oracle);
event MedianUpdated(address indexed token, uint256 value);
event ReportExpirySet(uint256 reportExpiry);
event TokenReportExpirySet(address token, uint256 reportExpiry);
modifier onlyOracle(address token) {
require(isOracle[token][msg.sender], "sender was not an oracle for token addr");
_;
}
/**
* @notice Returns the storage, major, minor, and patch version of the contract.
* @return The storage, major, minor, and patch version of the contract.
*/
function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) {
return (1, 1, 2, 1);
}
/**
* @notice Sets initialized == true on implementation contracts
* @param test Set to true to skip implementation initialization
*/
constructor(bool test) public Initializable(test) {}
/**
* @notice Used in place of the constructor to allow the contract to be upgradable via proxy.
* @param _reportExpirySeconds The number of seconds before a report is considered expired.
*/
function initialize(uint256 _reportExpirySeconds) external initializer {
_transferOwnership(msg.sender);
setReportExpiry(_reportExpirySeconds);
}
/**
* @notice Sets the report expiry parameter.
* @param _reportExpirySeconds The number of seconds before a report is considered expired.
*/
function setReportExpiry(uint256 _reportExpirySeconds) public onlyOwner {
require(_reportExpirySeconds > 0, "report expiry seconds must be > 0");
require(_reportExpirySeconds != reportExpirySeconds, "reportExpirySeconds hasn't changed");
reportExpirySeconds = _reportExpirySeconds;
emit ReportExpirySet(_reportExpirySeconds);
}
/**
* @notice Sets the report expiry parameter for a token.
* @param _token The address of the token to set expiry for.
* @param _reportExpirySeconds The number of seconds before a report is considered expired.
*/
function setTokenReportExpiry(address _token, uint256 _reportExpirySeconds) external onlyOwner {
require(_reportExpirySeconds > 0, "report expiry seconds must be > 0");
require(
_reportExpirySeconds != tokenReportExpirySeconds[_token],
"token reportExpirySeconds hasn't changed"
);
tokenReportExpirySeconds[_token] = _reportExpirySeconds;
emit TokenReportExpirySet(_token, _reportExpirySeconds);
}
/**
* @notice Adds a new Oracle.
* @param token The address of the token.
* @param oracleAddress The address of the oracle.
*/
function addOracle(address token, address oracleAddress) external onlyOwner {
require(
token != address(0) && oracleAddress != address(0) && !isOracle[token][oracleAddress],
"token addr was null or oracle addr was null or oracle addr is not an oracle for token addr"
);
isOracle[token][oracleAddress] = true;
oracles[token].push(oracleAddress);
emit OracleAdded(token, oracleAddress);
}
/**
* @notice Removes an Oracle.
* @param token The address of the token.
* @param oracleAddress The address of the oracle.
* @param index The index of `oracleAddress` in the list of oracles.
*/
function removeOracle(address token, address oracleAddress, uint256 index) external onlyOwner {
require(
token != address(0) &&
oracleAddress != address(0) &&
oracles[token].length > index &&
oracles[token][index] == oracleAddress,
"token addr null or oracle addr null or index of token oracle not mapped to oracle addr"
);
isOracle[token][oracleAddress] = false;
oracles[token][index] = oracles[token][oracles[token].length.sub(1)];
oracles[token].length = oracles[token].length.sub(1);
if (reportExists(token, oracleAddress)) {
removeReport(token, oracleAddress);
}
emit OracleRemoved(token, oracleAddress);
}
/**
* @notice Removes a report that is expired.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @param n The number of expired reports to remove, at most (deterministic upper gas bound).
*/
function removeExpiredReports(address token, uint256 n) external {
require(
token != address(0) && n < timestamps[token].getNumElements(),
"token addr null or trying to remove too many reports"
);
for (uint256 i = 0; i < n; i = i.add(1)) {
(bool isExpired, address oldestAddress) = isOldestReportExpired(token);
if (isExpired) {
removeReport(token, oldestAddress);
} else {
break;
}
}
}
/**
* @notice Check if last report is expired.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @return bool isExpired and the address of the last report
*/
function isOldestReportExpired(address token) public view returns (bool, address) {
require(token != address(0));
address oldest = timestamps[token].getTail();
uint256 timestamp = timestamps[token].getValue(oldest);
// solhint-disable-next-line not-rely-on-time
if (now.sub(timestamp) >= getTokenReportExpirySeconds(token)) {
return (true, oldest);
}
return (false, oldest);
}
/**
* @notice Updates an oracle value and the median.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @param value The amount of `token` equal to one CELO, expressed as a fixidity value.
* @param lesserKey The element which should be just left of the new oracle value.
* @param greaterKey The element which should be just right of the new oracle value.
* @dev Note that only one of `lesserKey` or `greaterKey` needs to be correct to reduce friction.
*/
function report(address token, uint256 value, address lesserKey, address greaterKey)
external
onlyOracle(token)
{
uint256 originalMedian = rates[token].getMedianValue();
if (rates[token].contains(msg.sender)) {
rates[token].update(msg.sender, value, lesserKey, greaterKey);
// Rather than update the timestamp, we remove it and re-add it at the
// head of the list later. The reason for this is that we need to handle
// a few different cases:
// 1. This oracle is the only one to report so far. lesserKey = address(0)
// 2. Other oracles have reported since this one's last report. lesserKey = getHead()
// 3. Other oracles have reported, but the most recent is this one.
// lesserKey = key immediately after getHead()
//
// However, if we just remove this timestamp, timestamps[token].getHead()
// does the right thing in all cases.
timestamps[token].remove(msg.sender);
} else {
rates[token].insert(msg.sender, value, lesserKey, greaterKey);
}
timestamps[token].insert(
msg.sender,
// solhint-disable-next-line not-rely-on-time
now,
timestamps[token].getHead(),
address(0)
);
emit OracleReported(token, msg.sender, now, value);
uint256 newMedian = rates[token].getMedianValue();
if (newMedian != originalMedian) {
emit MedianUpdated(token, newMedian);
}
}
/**
* @notice Returns the number of rates.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @return The number of reported oracle rates for `token`.
*/
function numRates(address token) public view returns (uint256) {
return rates[token].getNumElements();
}
/**
* @notice Returns the median rate.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @return The median exchange rate for `token`.
*/
function medianRate(address token) external view returns (uint256, uint256) {
return (rates[token].getMedianValue(), numRates(token) == 0 ? 0 : FIXED1_UINT);
}
/**
* @notice Gets all elements from the doubly linked list.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @return An unpacked list of elements from largest to smallest.
*/
function getRates(address token)
external
view
returns (address[] memory, uint256[] memory, SortedLinkedListWithMedian.MedianRelation[] memory)
{
return rates[token].getElements();
}
/**
* @notice Returns the number of timestamps.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @return The number of oracle report timestamps for `token`.
*/
function numTimestamps(address token) public view returns (uint256) {
return timestamps[token].getNumElements();
}
/**
* @notice Returns the median timestamp.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @return The median report timestamp for `token`.
*/
function medianTimestamp(address token) external view returns (uint256) {
return timestamps[token].getMedianValue();
}
/**
* @notice Gets all elements from the doubly linked list.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @return An unpacked list of elements from largest to smallest.
*/
function getTimestamps(address token)
external
view
returns (address[] memory, uint256[] memory, SortedLinkedListWithMedian.MedianRelation[] memory)
{
return timestamps[token].getElements();
}
/**
* @notice Returns whether a report exists on token from oracle.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @param oracle The oracle whose report should be checked.
*/
function reportExists(address token, address oracle) internal view returns (bool) {
return rates[token].contains(oracle) && timestamps[token].contains(oracle);
}
/**
* @notice Returns the list of oracles for a particular token.
* @param token The address of the token whose oracles should be returned.
* @return The list of oracles for a particular token.
*/
function getOracles(address token) external view returns (address[] memory) {
return oracles[token];
}
/**
* @notice Returns the expiry for the token if exists, if not the default.
* @param token The address of the token.
* @return The report expiry in seconds.
*/
function getTokenReportExpirySeconds(address token) public view returns (uint256) {
if (tokenReportExpirySeconds[token] == 0) {
return reportExpirySeconds;
}
return tokenReportExpirySeconds[token];
}
/**
* @notice Removes an oracle value and updates the median.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @param oracle The oracle whose value should be removed.
* @dev This can be used to delete elements for oracles that have been removed.
* However, a > 1 elements reports list should always be maintained
*/
function removeReport(address token, address oracle) private {
if (numTimestamps(token) == 1 && reportExists(token, oracle)) return;
uint256 originalMedian = rates[token].getMedianValue();
rates[token].remove(oracle);
timestamps[token].remove(oracle);
emit OracleReportRemoved(token, oracle);
uint256 newMedian = rates[token].getMedianValue();
if (newMedian != originalMedian) {
emit MedianUpdated(token, newMedian);
}
}
}
| contract SortedOracles is ISortedOracles, ICeloVersionedContract, Ownable, Initializable {
using SafeMath for uint256;
using AddressSortedLinkedListWithMedian for SortedLinkedListWithMedian.List;
using FixidityLib for FixidityLib.Fraction;
uint256 private constant FIXED1_UINT = 1000000000000000000000000;
// Maps a token address to a sorted list of report values.
mapping(address => SortedLinkedListWithMedian.List) private rates;
// Maps a token address to a sorted list of report timestamps.
mapping(address => SortedLinkedListWithMedian.List) private timestamps;
mapping(address => mapping(address => bool)) public isOracle;
mapping(address => address[]) public oracles;
// `reportExpirySeconds` is the fallback value used to determine reporting
// frequency. Initially it was the _only_ value but we later introduced
// the per token mapping in `tokenReportExpirySeconds`. If a token
// doesn't have a value in the mapping (i.e. it's 0), the fallback is used.
// See: #getTokenReportExpirySeconds
uint256 public reportExpirySeconds;
mapping(address => uint256) public tokenReportExpirySeconds;
event OracleAdded(address indexed token, address indexed oracleAddress);
event OracleRemoved(address indexed token, address indexed oracleAddress);
event OracleReported(
address indexed token,
address indexed oracle,
uint256 timestamp,
uint256 value
);
event OracleReportRemoved(address indexed token, address indexed oracle);
event MedianUpdated(address indexed token, uint256 value);
event ReportExpirySet(uint256 reportExpiry);
event TokenReportExpirySet(address token, uint256 reportExpiry);
modifier onlyOracle(address token) {
require(isOracle[token][msg.sender], "sender was not an oracle for token addr");
_;
}
/**
* @notice Returns the storage, major, minor, and patch version of the contract.
* @return The storage, major, minor, and patch version of the contract.
*/
function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) {
return (1, 1, 2, 1);
}
/**
* @notice Sets initialized == true on implementation contracts
* @param test Set to true to skip implementation initialization
*/
constructor(bool test) public Initializable(test) {}
/**
* @notice Used in place of the constructor to allow the contract to be upgradable via proxy.
* @param _reportExpirySeconds The number of seconds before a report is considered expired.
*/
function initialize(uint256 _reportExpirySeconds) external initializer {
_transferOwnership(msg.sender);
setReportExpiry(_reportExpirySeconds);
}
/**
* @notice Sets the report expiry parameter.
* @param _reportExpirySeconds The number of seconds before a report is considered expired.
*/
function setReportExpiry(uint256 _reportExpirySeconds) public onlyOwner {
require(_reportExpirySeconds > 0, "report expiry seconds must be > 0");
require(_reportExpirySeconds != reportExpirySeconds, "reportExpirySeconds hasn't changed");
reportExpirySeconds = _reportExpirySeconds;
emit ReportExpirySet(_reportExpirySeconds);
}
/**
* @notice Sets the report expiry parameter for a token.
* @param _token The address of the token to set expiry for.
* @param _reportExpirySeconds The number of seconds before a report is considered expired.
*/
function setTokenReportExpiry(address _token, uint256 _reportExpirySeconds) external onlyOwner {
require(_reportExpirySeconds > 0, "report expiry seconds must be > 0");
require(
_reportExpirySeconds != tokenReportExpirySeconds[_token],
"token reportExpirySeconds hasn't changed"
);
tokenReportExpirySeconds[_token] = _reportExpirySeconds;
emit TokenReportExpirySet(_token, _reportExpirySeconds);
}
/**
* @notice Adds a new Oracle.
* @param token The address of the token.
* @param oracleAddress The address of the oracle.
*/
function addOracle(address token, address oracleAddress) external onlyOwner {
require(
token != address(0) && oracleAddress != address(0) && !isOracle[token][oracleAddress],
"token addr was null or oracle addr was null or oracle addr is not an oracle for token addr"
);
isOracle[token][oracleAddress] = true;
oracles[token].push(oracleAddress);
emit OracleAdded(token, oracleAddress);
}
/**
* @notice Removes an Oracle.
* @param token The address of the token.
* @param oracleAddress The address of the oracle.
* @param index The index of `oracleAddress` in the list of oracles.
*/
function removeOracle(address token, address oracleAddress, uint256 index) external onlyOwner {
require(
token != address(0) &&
oracleAddress != address(0) &&
oracles[token].length > index &&
oracles[token][index] == oracleAddress,
"token addr null or oracle addr null or index of token oracle not mapped to oracle addr"
);
isOracle[token][oracleAddress] = false;
oracles[token][index] = oracles[token][oracles[token].length.sub(1)];
oracles[token].length = oracles[token].length.sub(1);
if (reportExists(token, oracleAddress)) {
removeReport(token, oracleAddress);
}
emit OracleRemoved(token, oracleAddress);
}
/**
* @notice Removes a report that is expired.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @param n The number of expired reports to remove, at most (deterministic upper gas bound).
*/
function removeExpiredReports(address token, uint256 n) external {
require(
token != address(0) && n < timestamps[token].getNumElements(),
"token addr null or trying to remove too many reports"
);
for (uint256 i = 0; i < n; i = i.add(1)) {
(bool isExpired, address oldestAddress) = isOldestReportExpired(token);
if (isExpired) {
removeReport(token, oldestAddress);
} else {
break;
}
}
}
/**
* @notice Check if last report is expired.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @return bool isExpired and the address of the last report
*/
function isOldestReportExpired(address token) public view returns (bool, address) {
require(token != address(0));
address oldest = timestamps[token].getTail();
uint256 timestamp = timestamps[token].getValue(oldest);
// solhint-disable-next-line not-rely-on-time
if (now.sub(timestamp) >= getTokenReportExpirySeconds(token)) {
return (true, oldest);
}
return (false, oldest);
}
/**
* @notice Updates an oracle value and the median.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @param value The amount of `token` equal to one CELO, expressed as a fixidity value.
* @param lesserKey The element which should be just left of the new oracle value.
* @param greaterKey The element which should be just right of the new oracle value.
* @dev Note that only one of `lesserKey` or `greaterKey` needs to be correct to reduce friction.
*/
function report(address token, uint256 value, address lesserKey, address greaterKey)
external
onlyOracle(token)
{
uint256 originalMedian = rates[token].getMedianValue();
if (rates[token].contains(msg.sender)) {
rates[token].update(msg.sender, value, lesserKey, greaterKey);
// Rather than update the timestamp, we remove it and re-add it at the
// head of the list later. The reason for this is that we need to handle
// a few different cases:
// 1. This oracle is the only one to report so far. lesserKey = address(0)
// 2. Other oracles have reported since this one's last report. lesserKey = getHead()
// 3. Other oracles have reported, but the most recent is this one.
// lesserKey = key immediately after getHead()
//
// However, if we just remove this timestamp, timestamps[token].getHead()
// does the right thing in all cases.
timestamps[token].remove(msg.sender);
} else {
rates[token].insert(msg.sender, value, lesserKey, greaterKey);
}
timestamps[token].insert(
msg.sender,
// solhint-disable-next-line not-rely-on-time
now,
timestamps[token].getHead(),
address(0)
);
emit OracleReported(token, msg.sender, now, value);
uint256 newMedian = rates[token].getMedianValue();
if (newMedian != originalMedian) {
emit MedianUpdated(token, newMedian);
}
}
/**
* @notice Returns the number of rates.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @return The number of reported oracle rates for `token`.
*/
function numRates(address token) public view returns (uint256) {
return rates[token].getNumElements();
}
/**
* @notice Returns the median rate.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @return The median exchange rate for `token`.
*/
function medianRate(address token) external view returns (uint256, uint256) {
return (rates[token].getMedianValue(), numRates(token) == 0 ? 0 : FIXED1_UINT);
}
/**
* @notice Gets all elements from the doubly linked list.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @return An unpacked list of elements from largest to smallest.
*/
function getRates(address token)
external
view
returns (address[] memory, uint256[] memory, SortedLinkedListWithMedian.MedianRelation[] memory)
{
return rates[token].getElements();
}
/**
* @notice Returns the number of timestamps.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @return The number of oracle report timestamps for `token`.
*/
function numTimestamps(address token) public view returns (uint256) {
return timestamps[token].getNumElements();
}
/**
* @notice Returns the median timestamp.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @return The median report timestamp for `token`.
*/
function medianTimestamp(address token) external view returns (uint256) {
return timestamps[token].getMedianValue();
}
/**
* @notice Gets all elements from the doubly linked list.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @return An unpacked list of elements from largest to smallest.
*/
function getTimestamps(address token)
external
view
returns (address[] memory, uint256[] memory, SortedLinkedListWithMedian.MedianRelation[] memory)
{
return timestamps[token].getElements();
}
/**
* @notice Returns whether a report exists on token from oracle.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @param oracle The oracle whose report should be checked.
*/
function reportExists(address token, address oracle) internal view returns (bool) {
return rates[token].contains(oracle) && timestamps[token].contains(oracle);
}
/**
* @notice Returns the list of oracles for a particular token.
* @param token The address of the token whose oracles should be returned.
* @return The list of oracles for a particular token.
*/
function getOracles(address token) external view returns (address[] memory) {
return oracles[token];
}
/**
* @notice Returns the expiry for the token if exists, if not the default.
* @param token The address of the token.
* @return The report expiry in seconds.
*/
function getTokenReportExpirySeconds(address token) public view returns (uint256) {
if (tokenReportExpirySeconds[token] == 0) {
return reportExpirySeconds;
}
return tokenReportExpirySeconds[token];
}
/**
* @notice Removes an oracle value and updates the median.
* @param token The address of the token for which the CELO exchange rate is being reported.
* @param oracle The oracle whose value should be removed.
* @dev This can be used to delete elements for oracles that have been removed.
* However, a > 1 elements reports list should always be maintained
*/
function removeReport(address token, address oracle) private {
if (numTimestamps(token) == 1 && reportExists(token, oracle)) return;
uint256 originalMedian = rates[token].getMedianValue();
rates[token].remove(oracle);
timestamps[token].remove(oracle);
emit OracleReportRemoved(token, oracle);
uint256 newMedian = rates[token].getMedianValue();
if (newMedian != originalMedian) {
emit MedianUpdated(token, newMedian);
}
}
}
| 19,256 |
63 | // Internal function to quote an ACO token price. isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. acoToken Address of the ACO token. tokenAmount Amount of ACO tokens to swap.return The quote price, the protocol fee charged, the underlying price, and the collateral amount. / | function _internalQuote(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256, uint256, uint256) {
require(isPoolSelling || canBuy, "ACOPool:: The pool only sell");
require(tokenAmount > 0, "ACOPool:: Invalid token amount");
(uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken);
require(expiryTime > block.timestamp, "ACOPool:: ACO token expired");
(uint256 collateralAmount, uint256 collateralAvailable) = _getSizeData(isPoolSelling, acoToken, tokenAmount);
(uint256 price, uint256 underlyingPrice,) = _strategyQuote(acoToken, isPoolSelling, strikePrice, expiryTime, collateralAmount, collateralAvailable);
price = price.mul(tokenAmount).div(underlyingPrecision);
uint256 protocolFee = 0;
if (fee > 0) {
protocolFee = price.mul(fee).div(100000);
if (isPoolSelling) {
price = price.add(protocolFee);
} else {
price = price.sub(protocolFee);
}
}
require(price > 0, "ACOPool:: Invalid quote");
return (price, protocolFee, underlyingPrice, collateralAmount);
}
| function _internalQuote(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256, uint256, uint256) {
require(isPoolSelling || canBuy, "ACOPool:: The pool only sell");
require(tokenAmount > 0, "ACOPool:: Invalid token amount");
(uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken);
require(expiryTime > block.timestamp, "ACOPool:: ACO token expired");
(uint256 collateralAmount, uint256 collateralAvailable) = _getSizeData(isPoolSelling, acoToken, tokenAmount);
(uint256 price, uint256 underlyingPrice,) = _strategyQuote(acoToken, isPoolSelling, strikePrice, expiryTime, collateralAmount, collateralAvailable);
price = price.mul(tokenAmount).div(underlyingPrecision);
uint256 protocolFee = 0;
if (fee > 0) {
protocolFee = price.mul(fee).div(100000);
if (isPoolSelling) {
price = price.add(protocolFee);
} else {
price = price.sub(protocolFee);
}
}
require(price > 0, "ACOPool:: Invalid quote");
return (price, protocolFee, underlyingPrice, collateralAmount);
}
| 56,518 |
18 | // Contract utils / | function updateReward(address _address) internal {
rewards[_address] += getPendingReward(_address);
lastUpdate[_address] = block.timestamp;
}
| function updateReward(address _address) internal {
rewards[_address] += getPendingReward(_address);
lastUpdate[_address] = block.timestamp;
}
| 64,039 |
74 | // Sender redeems hTokens in exchange for the underlying asset Accrues interest whether or not the operation succeeds, unless reverted redeemTokens The number of hTokens to redeem into underlyingreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) / | function redeemInternal(uint256 redeemTokens) internal nonReentrant returns (uint256) {
uint256 error = accrueInterestInternal();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
| function redeemInternal(uint256 redeemTokens) internal nonReentrant returns (uint256) {
uint256 error = accrueInterestInternal();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
| 9,429 |
2 | // uint256 pos = users.length + 1; IERC20(_token).transferFrom(msg.sender, address(this), signupFee(pos)); | _new(msg.sender, _parent);
| _new(msg.sender, _parent);
| 40,874 |
62 | // essentially the same as buy, but instead of you sending etherfrom your wallet, it uses your unwithdrawn earnings.-functionhash- 0x349cdcac (using ID for affiliate)-functionhash- 0x82bfc739 (using address for affiliate)-functionhash- 0x079ce327 (using name for affiliate) _affCode the ID/address/name of the player who gets the affiliate fee _team what team is the player playing for? _eth amount of earnings to use (remainder returned to gen vault) / | function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
| function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
| 8,205 |
147 | // only called from within the this contract itself, will actually do the funding / | function doFunding(bytes32 _platform, string _platformId, address _token, uint256 _value, address _funder) internal returns (bool success) {
if (_token == ETHER_ADDRESS) {
//must check this, so we don't have people foefeling with the amounts
require(msg.value == _value);
}
require(!fundRepository.issueResolved(_platform, _platformId), "Can't fund tokens, platformId already claimed");
for (uint idx = 0; idx < preconditions.length; idx++) {
if (address(preconditions[idx]) != address(0)) {
require(preconditions[idx].isValid(_platform, _platformId, _token, _value, _funder));
}
}
require(_value > 0, "amount of tokens needs to be more than 0");
if (_token != ETHER_ADDRESS) {
require(ERC20(_token).transferFrom(_funder, address(this), _value), "Transfer of tokens to contract failed");
}
fundRepository.updateFunders(_funder, _platform, _platformId);
fundRepository.updateBalances(_funder, _platform, _platformId, _token, _value);
emit Funded(_funder, _platform, _platformId, _token, _value);
return true;
}
| function doFunding(bytes32 _platform, string _platformId, address _token, uint256 _value, address _funder) internal returns (bool success) {
if (_token == ETHER_ADDRESS) {
//must check this, so we don't have people foefeling with the amounts
require(msg.value == _value);
}
require(!fundRepository.issueResolved(_platform, _platformId), "Can't fund tokens, platformId already claimed");
for (uint idx = 0; idx < preconditions.length; idx++) {
if (address(preconditions[idx]) != address(0)) {
require(preconditions[idx].isValid(_platform, _platformId, _token, _value, _funder));
}
}
require(_value > 0, "amount of tokens needs to be more than 0");
if (_token != ETHER_ADDRESS) {
require(ERC20(_token).transferFrom(_funder, address(this), _value), "Transfer of tokens to contract failed");
}
fundRepository.updateFunders(_funder, _platform, _platformId);
fundRepository.updateBalances(_funder, _platform, _platformId, _token, _value);
emit Funded(_funder, _platform, _platformId, _token, _value);
return true;
}
| 76,393 |
70 | // Subtract the transferred amount from the sender's balance. | _tOwned[sender] -= tAmount;
_rOwned[sender] -= rAmount;
| _tOwned[sender] -= tAmount;
_rOwned[sender] -= rAmount;
| 26,438 |
15 | // Deposit LP tokens to BagBang for reward allocation. | function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accRewardPerShare).div(1e24).sub(user.rewardDebt);
safeRewardTransfer(msg.sender, pending);
}
if (_amount > 0) {
IERC20(pool.stakingToken).safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e24);
emit Deposit(msg.sender, _pid, _amount);
}
| function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accRewardPerShare).div(1e24).sub(user.rewardDebt);
safeRewardTransfer(msg.sender, pending);
}
if (_amount > 0) {
IERC20(pool.stakingToken).safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e24);
emit Deposit(msg.sender, _pid, _amount);
}
| 67,695 |
48 | // See {ERC20-transfer}. Requirements: - `recipient` cannot be the zero address.- the caller must have a balance of at least `amount`. / | function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
| function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
| 13,887 |
8 | // Retrieves the protocol fee for all streams created with the provided ERC-20 asset./asset The contract address of the ERC-20 asset to query./ return fee The protocol fee denoted as a fixed-point number where 1e18 is 100%. | function protocolFees(IERC20 asset) external view returns (UD60x18 fee);
/*//////////////////////////////////////////////////////////////////////////
NON-CONSTANT FUNCTIONS
| function protocolFees(IERC20 asset) external view returns (UD60x18 fee);
/*//////////////////////////////////////////////////////////////////////////
NON-CONSTANT FUNCTIONS
| 23,263 |
53 | // convert amount to match payout token decimals | value_ = _amount.mul( 10 ** IERC20( payoutToken ).decimals() ).div( 10 ** IERC20( _principleTokenAddress ).decimals() );
| value_ = _amount.mul( 10 ** IERC20( payoutToken ).decimals() ).div( 10 ** IERC20( _principleTokenAddress ).decimals() );
| 18,989 |
55 | // ISuperToken.upgradeTo implementation | function upgradeTo(address to, uint256 amount, bytes calldata data) external override {
_upgrade(msg.sender, msg.sender, to, amount, "", data);
}
| function upgradeTo(address to, uint256 amount, bytes calldata data) external override {
_upgrade(msg.sender, msg.sender, to, amount, "", data);
}
| 24,516 |
24 | // ConditionType[] decode function | function ConditionTypes(uint[] memory arr) internal pure returns (ConditionType[] memory t) {
t = new ConditionType[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = ConditionType(arr[i]); }
| function ConditionTypes(uint[] memory arr) internal pure returns (ConditionType[] memory t) {
t = new ConditionType[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = ConditionType(arr[i]); }
| 60,008 |
0 | // note: this method doesn't support sending ether to L1 together with a call | uint256 id = IArbSys(address(100)).sendTxToL1(to, data);
emit TxToL1(user, to, id, data);
return id;
| uint256 id = IArbSys(address(100)).sendTxToL1(to, data);
emit TxToL1(user, to, id, data);
return id;
| 17,112 |
40 | // Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it. | if (msg.value < 0.000001 ether || msg.value > 1000000 ether)
revert();
| if (msg.value < 0.000001 ether || msg.value > 1000000 ether)
revert();
| 45,423 |
2 | // Mints the given amount of LPToken to the recipient. only owner can call this mint function recipient address of account to receive the tokens amount amount of tokens to mint / | function mint(address recipient, uint256 amount) external onlyOwner {
require(amount != 0, "LPToken: cannot mint 0");
_mint(recipient, amount);
}
| function mint(address recipient, uint256 amount) external onlyOwner {
require(amount != 0, "LPToken: cannot mint 0");
_mint(recipient, amount);
}
| 26,716 |
173 | // The Dolphin TOKEN! | DolphinToken public Dolphin;
| DolphinToken public Dolphin;
| 8,413 |
3 | // Create a Chainlink request to retrieve API response, find the targetdata, then multiply by 1000000000000000000 (to remove decimal places from data). / | function requestSingleData(
address _address,
bytes32 _jobId,
string memory _id,
uint32 _jobtype
| function requestSingleData(
address _address,
bytes32 _jobId,
string memory _id,
uint32 _jobtype
| 9,330 |
20 | // creat a new software developer (struct) and pass in new values | SoftwareDeveloper memory newSoftwareDeveloper = SoftwareDeveloper(
cryptoBoyCounter,
_name,
_tokenURI,
msg.sender,
msg.sender,
address(0),
_price,
0,
true);
| SoftwareDeveloper memory newSoftwareDeveloper = SoftwareDeveloper(
cryptoBoyCounter,
_name,
_tokenURI,
msg.sender,
msg.sender,
address(0),
_price,
0,
true);
| 36,814 |
92 | // Interface for ERC20 token contract / | interface IERC20 {
function totalSupply() external view returns (uint);
function balanceOf(address) external view returns (uint);
function allowance(address, address) external view returns (uint);
function transfer(address, uint) external returns (bool);
function approve(address, uint) external returns (bool);
function transferFrom(address, address, uint) external returns (bool);
| interface IERC20 {
function totalSupply() external view returns (uint);
function balanceOf(address) external view returns (uint);
function allowance(address, address) external view returns (uint);
function transfer(address, uint) external returns (bool);
function approve(address, uint) external returns (bool);
function transferFrom(address, address, uint) external returns (bool);
| 41,109 |
0 | // define a struct- Transaction | struct Transaction{
address txSender;
address payable destination;
uint amount;
bool isExecuted;
uint noOfConfirmations;
uint txId;
bytes data;
}
| struct Transaction{
address txSender;
address payable destination;
uint amount;
bool isExecuted;
uint noOfConfirmations;
uint txId;
bytes data;
}
| 3,581 |
146 | // To recieve ETH from uniswapV2Router when swapping | receive() external payable {}
function transferForeignToken(address _token, address _to) public onlyOwner returns(bool _sent){
require(_token != address(this), "Can't let you take all native token");
uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
_sent = IERC20(_token).transfer(_to, _contractBalance);
}
| receive() external payable {}
function transferForeignToken(address _token, address _to) public onlyOwner returns(bool _sent){
require(_token != address(this), "Can't let you take all native token");
uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
_sent = IERC20(_token).transfer(_to, _contractBalance);
}
| 48,919 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.