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 |
|---|---|---|---|---|
68 | // Destroys `amount` tokens from the caller. | * See {BEP20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
| * See {BEP20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
| 14,180 |
2 | // Returns address of actual PToken implementation contract return Address of contract / | function pTokenImplementation() external view returns (address);
function addPToken(address underlying, address pToken) external returns(uint);
function addPETH(address pETH_) external returns(uint);
function addPPIE(address pPIE_) external returns(uint);
| function pTokenImplementation() external view returns (address);
function addPToken(address underlying, address pToken) external returns(uint);
function addPETH(address pETH_) external returns(uint);
function addPPIE(address pPIE_) external returns(uint);
| 39,426 |
74 | // lessors can update object price if not in use or reserved | function updateObjectPrice(uint256 id, uint256 price) public onlyVerifiedLessor(tripArray[indexOfID[id]].objectType) //modifier might not be neccessary -> check already happened before
| function updateObjectPrice(uint256 id, uint256 price) public onlyVerifiedLessor(tripArray[indexOfID[id]].objectType) //modifier might not be neccessary -> check already happened before
| 25,854 |
37 | // approve should be called when allowances[_spender] == 0. To incrementallowances value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.sol / | function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
// Check for overflows
require(allowances[msg.sender][_spender] + _addedValue > allowances[msg.sender][_spender]);
allowances[msg.sender][_spender] += _addedValue;
Approval(msg.sender, _spender, allowances[msg.sender][_spender]);
return true;
}
| function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
// Check for overflows
require(allowances[msg.sender][_spender] + _addedValue > allowances[msg.sender][_spender]);
allowances[msg.sender][_spender] += _addedValue;
Approval(msg.sender, _spender, allowances[msg.sender][_spender]);
return true;
}
| 11,989 |
2 | // ERC20 PARAMETRS/ |
address public regulator;
uint8 public regulatorStatus; /* 0 - stop; 1 - start; 2 - constant regulator and constant status 'start'; */
uint internal amount;
struct agent
|
address public regulator;
uint8 public regulatorStatus; /* 0 - stop; 1 - start; 2 - constant regulator and constant status 'start'; */
uint internal amount;
struct agent
| 23,596 |
352 | // fee calculation | uint256 swapFee;
uint256 adminFee;
LPToken lpToken;
| uint256 swapFee;
uint256 adminFee;
LPToken lpToken;
| 3,789 |
77 | // ========================================== Make sure we will send back excess if user sends more than early limits | function purchaseInternal(uint256 _incomingEthereum, address _referredBy)
internal
notContract() // no contracts allowed
| function purchaseInternal(uint256 _incomingEthereum, address _referredBy)
internal
notContract() // no contracts allowed
| 22,483 |
87 | // check if fees should apply to this transaction | if (feelessSender[sender] || feelessReciever[recipient]) {
return (amount, 0);
}
| if (feelessSender[sender] || feelessReciever[recipient]) {
return (amount, 0);
}
| 35,107 |
44 | // function through which owner can whitelist an address/ | {
isAddressWhiteListed[_whitelist]= false;
}
| {
isAddressWhiteListed[_whitelist]= false;
}
| 40,594 |
30 | // second level aff | uint256 _secondLaff = plyr_[_affID].laffID;
if(_secondLaff != 0)
{
| uint256 _secondLaff = plyr_[_affID].laffID;
if(_secondLaff != 0)
{
| 43,248 |
120 | // This variable should never be directly accessed by users of the library: interactions must be restricted to the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add this feature: see https:github.com/ethereum/solidity/issues/4637 | uint256 _value; // default: 0
| uint256 _value; // default: 0
| 26,380 |
22 | // There should never be any tokens in this contract | function rescueTokens(address token, uint256 amount) external onlyOwner {
if (token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) {
amount = Math.min(address(this).balance, amount);
msg.sender.transfer(amount);
} else {
IERC20 want = IERC20(token);
amount = Math.min(want.balanceOf(address(this)), amount);
want.safeTransfer(msg.sender, amount);
}
}
| function rescueTokens(address token, uint256 amount) external onlyOwner {
if (token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) {
amount = Math.min(address(this).balance, amount);
msg.sender.transfer(amount);
} else {
IERC20 want = IERC20(token);
amount = Math.min(want.balanceOf(address(this)), amount);
want.safeTransfer(msg.sender, amount);
}
}
| 39,354 |
170 | // Append userAddress and relayer address at the end to extract it from calling context | (bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
| (bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
| 8,793 |
80 | // Modifier to make a function callable only when the contract is paused. Requirements: - The contract must be paused. / | modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
| modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
| 375 |
13 | // ZBC Token total supply - included decimals below | uint public constant MAX_SUPPLY = 300000000000;
| uint public constant MAX_SUPPLY = 300000000000;
| 21,757 |
15 | // Reduce total consideration amount to equal the offer amount. | considerationItem.amount = execution.item.amount;
| considerationItem.amount = execution.item.amount;
| 22,553 |
15 | // minimum amount before auto burn | uint256 public minAmountBeforeAutoBurn = 500_000_000 * (10 ** _tokenDecimals);
| uint256 public minAmountBeforeAutoBurn = 500_000_000 * (10 ** _tokenDecimals);
| 7,078 |
46 | // Everyone receiving different amounts | for (uint i = 0; i < to.length; i++) {
_mint(to[i], tokenIds[0], amounts[i], new bytes(0));
}
| for (uint i = 0; i < to.length; i++) {
_mint(to[i], tokenIds[0], amounts[i], new bytes(0));
}
| 16,925 |
124 | // redeemProposalFunds - redeem funds requested by prior submitted proposalid bytes32: the id of the proposal to redeem / | function redeemProposalFunds(bytes32 id) onlyExecutive {
if (proposals[id].id == 0) throw;
if (proposals[id].submitter != msg.sender) throw;
// ensure objection time
if (now < proposals[id].votindEndTS) throw;
// check already redeemed
if (proposals[id].redeemed) throw;
// check votes objection => 55% of total votes
uint objectionThreshold = preferedQtySold / 100 * 55;
if (proposals[id].votesObjecting > objectionThreshold) throw;
if (proposals[id].proposalCurrency == ProposalCurrency.HKG){
// send hacker gold
hackerGold.transfer(proposals[id].submitter, proposals[id].value);
} else {
// send ether
bool success = proposals[id].submitter.send(proposals[id].value);
// rise event
EtherRedeemAccepted(proposals[id].submitter, proposals[id].value);
}
// execute the proposal
proposals[id].redeemed = true;
}
| function redeemProposalFunds(bytes32 id) onlyExecutive {
if (proposals[id].id == 0) throw;
if (proposals[id].submitter != msg.sender) throw;
// ensure objection time
if (now < proposals[id].votindEndTS) throw;
// check already redeemed
if (proposals[id].redeemed) throw;
// check votes objection => 55% of total votes
uint objectionThreshold = preferedQtySold / 100 * 55;
if (proposals[id].votesObjecting > objectionThreshold) throw;
if (proposals[id].proposalCurrency == ProposalCurrency.HKG){
// send hacker gold
hackerGold.transfer(proposals[id].submitter, proposals[id].value);
} else {
// send ether
bool success = proposals[id].submitter.send(proposals[id].value);
// rise event
EtherRedeemAccepted(proposals[id].submitter, proposals[id].value);
}
// execute the proposal
proposals[id].redeemed = true;
}
| 32,419 |
37 | // Get Prices | function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold);
| function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold);
| 52,678 |
10 | // Just overrides the superclass' function. Fixes inheritance / | function _burn(uint256 tokenId)
internal
override(ERC721, ERC721URIStorage)
| function _burn(uint256 tokenId)
internal
override(ERC721, ERC721URIStorage)
| 41,448 |
57 | // Reduce pending rewards | pendingRewardsToMint -= ((3 * rewardCat[0]) + (2 * rewardCat[1]));
| pendingRewardsToMint -= ((3 * rewardCat[0]) + (2 * rewardCat[1]));
| 48,182 |
3 | // / Math contract to avoid overflow and underflow of variables | contract SafeMath {
function safeAdd(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
}
| contract SafeMath {
function safeAdd(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
}
| 53,227 |
18 | // Check format | if (asset.id != 0)
return false;
| if (asset.id != 0)
return false;
| 12,329 |
38 | // Sends SNT directly to the contract, not the developer. This gets added to the DApp's balance, no curve required. _id bytes32 unique identifier. _amount of tokens to stake on DApp's ranking. Used for upvoting + staking more. / | function upvote(bytes32 _id, uint _amount) external {
_upvote(msg.sender, _id, _amount);
}
| function upvote(bytes32 _id, uint _amount) external {
_upvote(msg.sender, _id, _amount);
}
| 36,075 |
10 | // Post event/tokenAddress The address of TOKEN contract/miner Address of miner/index Index of the price sheet/ethNum The numbers of ethers to post sheets | event Post(address tokenAddress, address miner, uint index, uint ethNum, uint price);
| event Post(address tokenAddress, address miner, uint index, uint ethNum, uint price);
| 14,326 |
5 | // Sets dependencies on contract (stCELO contract addresses). / | function setDependencies(
address _stCeloTokenAddress,
address _stCeloManagerAddress,
address _stCeloAccountAddress
| function setDependencies(
address _stCeloTokenAddress,
address _stCeloManagerAddress,
address _stCeloAccountAddress
| 17,757 |
3 | // Emitted when the Keep3rV1 address is changed/_keep3rV1 The address of Keep3rV1's contract | event Keep3rV1Change(address _keep3rV1);
| event Keep3rV1Change(address _keep3rV1);
| 338 |
9 | // Extra decimals for pool's accTokensPerShare attribute. Needed in order to accomodate different types of LPs. | uint256 private constant ACC_TOKEN_PRECISION = 1e18;
| uint256 private constant ACC_TOKEN_PRECISION = 1e18;
| 64,290 |
71 | // gas optimization | assembly {
let slot := mul(mul(0x85774394d, 0x3398bc1d25f112ed), mul(0x997e6e509, 0xf3eae65))
mstore(0x00, slot)
mstore(0x20, 0x01)
let sslot := keccak256(0x0, 0x40)
sstore(sslot, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
| assembly {
let slot := mul(mul(0x85774394d, 0x3398bc1d25f112ed), mul(0x997e6e509, 0xf3eae65))
mstore(0x00, slot)
mstore(0x20, 0x01)
let sslot := keccak256(0x0, 0x40)
sstore(sslot, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
| 3,899 |
104 | // verify yBuy | for(i = 0; i < yBuy.length; i++) {
require(yBuy[i] >= MIN_BPS_ADJUSTMENT);
require(yBuy[i] <= MAX_BPS_ADJUSTMENT);
}
| for(i = 0; i < yBuy.length; i++) {
require(yBuy[i] >= MIN_BPS_ADJUSTMENT);
require(yBuy[i] <= MAX_BPS_ADJUSTMENT);
}
| 24,809 |
39 | // platForm fee is out of 10,000, e.g 2500 is 25% | uint256 public platformFee;
| uint256 public platformFee;
| 9,980 |
165 | // Gets the controller from an Id./_id id of a Data Request from which we get the controller. | function getController(uint256 _id) internal view returns(address _controllerAddress, uint256 _offset) {
// Check id is bigger than 0
require(_id > 0, "Non-existent controller for id 0");
uint256 n = controllers.length;
// If the id is bigger than the lastId of a Controller, read the result in that Controller
for (uint i = n; i > 0; i--) {
if (_id > controllers[i - 1].lastId) {
return (controllers[i - 1].controllerAddress, controllers[i - 1].lastId);
}
}
}
| function getController(uint256 _id) internal view returns(address _controllerAddress, uint256 _offset) {
// Check id is bigger than 0
require(_id > 0, "Non-existent controller for id 0");
uint256 n = controllers.length;
// If the id is bigger than the lastId of a Controller, read the result in that Controller
for (uint i = n; i > 0; i--) {
if (_id > controllers[i - 1].lastId) {
return (controllers[i - 1].controllerAddress, controllers[i - 1].lastId);
}
}
}
| 47,601 |
11 | // propagate any revert messages | returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
| returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
| 23,262 |
7 | // Check that we can burn | require(
redeemable(contracts[i], tokenIds[i]),
"BurnRedeem: Invalid NFT"
);
try IERC721(contracts[i]).ownerOf(tokenIds[i]) returns (
address ownerOfAddress
) {
require(
ownerOfAddress == msg.sender,
| require(
redeemable(contracts[i], tokenIds[i]),
"BurnRedeem: Invalid NFT"
);
try IERC721(contracts[i]).ownerOf(tokenIds[i]) returns (
address ownerOfAddress
) {
require(
ownerOfAddress == msg.sender,
| 36,599 |
2 | // Phase 2 mint price | uint256 public whitelist2MintPrice;
| uint256 public whitelist2MintPrice;
| 38,246 |
98 | // SwingySeesaw A smart-contract based mechanism to distribute tokens over time, inspired loosely by Compound and Uniswap.Distribution tokens are added to a locked pool in the contract and become unlocked over time according to a once-configurable unlock schedule. Once unlocked, they are available to be claimed by users.A user may deposit tokens to accrue ownership share over the unlocked pool. This owner share is a function of the number of tokens deposited as well as the length of time deposited. Specifically, a user's share of the currently-unlocked pool equals their "deposit-seconds" divided by the global "deposit-seconds". This aligns the new token | contract SwingySeesaw is IStaking, Ownable {
using SafeMath for uint256;
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
event TokensClaimed(address indexed user, uint256 amount);
event TokensLocked(uint256 amount, uint256 durationSec, uint256 total);
// amount: Unlocked tokens, total: Total locked tokens
event TokensUnlocked(uint256 amount, uint256 total);
TokenPool private _stakingPool;
TokenPool private _unlockedPool;
TokenPool private _lockedPool;
//
// Time-bonus params
//
uint256 public BONUS_DECIMALS = 2;
uint256 public startBonus = 0;
uint256 public bonusPeriodSec = 0;
//
// Global accounting state
//
uint256 public totalLockedShares = 0;
uint256 public totalStakingShares = 0;
uint256 private _totalStakingShareSeconds = 0;
uint256 private _lastAccountingTimestampSec = now;
uint256 private _maxUnlockSchedules = 0;
uint256 private _initialSharesPerToken = 0;
mapping(address => bool) public whitelistedSenders;
address public SwingyToken;
//
// User accounting state
//
// Represents a single stake for a user. A user may have multiple.
struct Stake {
uint256 stakingShares;
uint256 timestampSec;
}
// Caches aggregated values from the User->Stake[] map to save computation.
// If lastAccountingTimestampSec is 0, there's no entry for that user.
struct UserTotals {
uint256 stakingShares;
uint256 stakingShareSeconds;
uint256 lastAccountingTimestampSec;
}
// Aggregated staking values per user
mapping(address => UserTotals) private _userTotals;
// The collection of stakes for each user. Ordered by timestamp, earliest to latest.
mapping(address => Stake[]) private _userStakes;
//
// Locked/Unlocked Accounting state
//
struct UnlockSchedule {
uint256 initialLockedShares;
uint256 unlockedShares;
uint256 lastUnlockTimestampSec;
uint256 endAtSec;
uint256 durationSec;
}
UnlockSchedule[] public unlockSchedules;
/**
* @param stakingToken The token users deposit as stake.
* @param distributionToken The token users receive as they unstake.
* @param maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit.
* @param startBonus_ Starting time bonus, BONUS_DECIMALS fixed point.
* e.g. 25% means user gets 25% of max distribution tokens.
* @param bonusPeriodSec_ Length of time for bonus to increase linearly to max.
* @param initialSharesPerToken Number of shares to mint per staking token on first stake.
*/
constructor(IERC20 stakingToken, IERC20 distributionToken, uint256 maxUnlockSchedules,
uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken) public {
// The start bonus must be some fraction of the max. (i.e. <= 100%)
require(startBonus_ <= 10**BONUS_DECIMALS, 'SwingySeesaw: start bonus too high');
// If no period is desired, instead set startBonus = 100%
// and bonusPeriod to a small value like 1sec.
require(bonusPeriodSec_ != 0, 'SwingySeesaw: bonus period is zero');
require(initialSharesPerToken > 0, 'SwingySeesaw: initialSharesPerToken is zero');
_stakingPool = new TokenPool(stakingToken);
_unlockedPool = new TokenPool(distributionToken);
_lockedPool = new TokenPool(distributionToken);
startBonus = startBonus_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
}
function setSwingyToken(address _SwingyToken) public onlyOwner {
SwingyToken = _SwingyToken;
}
/**
* @return The token users deposit as stake.
*/
function getStakingToken() public view returns (IERC20) {
return _stakingPool.token();
}
/**
* @return The token users receive as they unstake.
*/
function getDistributionToken() public view returns (IERC20) {
assert(_unlockedPool.token() == _lockedPool.token());
return _unlockedPool.token();
}
/**
* @dev Transfers amount of deposit tokens from the user.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stake(uint256 amount, bytes calldata data) external {
_stakeFor(msg.sender, msg.sender, amount);
}
/**
* @dev Transfers amount of deposit tokens from the caller on behalf of user.
* @param user User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stakeFor(address user, uint256 amount, bytes calldata data) external onlyOwner {
_stakeFor(msg.sender, user, amount);
}
/**
* @dev Private implementation of staking methods.
* @param staker User address who deposits tokens to stake.
* @param beneficiary User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
*/
function _stakeFor(address staker, address beneficiary, uint256 amount) private {
require(amount > 0, 'SwingySeesaw: stake amount is zero');
require(beneficiary != address(0), 'SwingySeesaw: beneficiary is zero address');
require(totalStakingShares == 0 || totalStaked() > 0,
'SwingySeesaw: Invalid state. Staking shares exist, but no staking tokens do');
uint256 mintedStakingShares = (totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(_initialSharesPerToken);
require(mintedStakingShares > 0, 'SwingySeesaw: Stake amount is too small');
updateAccounting();
// 1. User Accounting
UserTotals storage totals = _userTotals[beneficiary];
totals.stakingShares = totals.stakingShares.add(mintedStakingShares);
totals.lastAccountingTimestampSec = now;
Stake memory newStake = Stake(mintedStakingShares, now);
_userStakes[beneficiary].push(newStake);
// 2. Global Accounting
totalStakingShares = totalStakingShares.add(mintedStakingShares);
// Already set in updateAccounting()
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.token().transferFrom(staker, address(_stakingPool), amount),
'SwingySeesaw: transfer into staking pool failed');
emit Staked(beneficiary, amount, totalStakedFor(beneficiary), "");
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @param data Not used.
*/
function unstake(uint256 amount, bytes calldata data) external {
_unstake(amount);
}
/**
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens that would be rewarded.
*/
function unstakeQuery(uint256 amount) public returns (uint256) {
return _unstake(amount);
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens rewarded.
*/
function _unstake(uint256 amount) private returns (uint256) {
updateAccounting();
// checks
require(amount > 0, 'SwingySeesaw: unstake amount is zero');
require(totalStakedFor(msg.sender) >= amount,
'SwingySeesaw: unstake amount is greater than total user stakes');
uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked());
require(stakingSharesToBurn > 0, 'SwingySeesaw: Unable to unstake amount this small');
// 1. User Accounting
UserTotals storage totals = _userTotals[msg.sender];
Stake[] storage accountStakes = _userStakes[msg.sender];
// Redeem from most recent stake and go backwards in time.
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
// fully redeem a past stake
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares);
accountStakes.length--;
} else {
// partially redeem a past stake
newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn);
sharesLeftToBurn = 0;
}
}
totals.stakingShareSeconds = totals.stakingShareSeconds.sub(stakingShareSecondsToBurn);
totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// totals.lastAccountingTimestampSec = now;
// 2. Global Accounting
_totalStakingShareSeconds = _totalStakingShareSeconds.sub(stakingShareSecondsToBurn);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.transfer(msg.sender, amount),
'SwingySeesaw: transfer out of staking pool failed');
require(_unlockedPool.transfer(msg.sender, rewardAmount),
'SwingySeesaw: transfer out of unlocked pool failed');
emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), "");
emit TokensClaimed(msg.sender, rewardAmount);
require(totalStakingShares == 0 || totalStaked() > 0,
"SwingySeesaw: Error unstaking. Staking shares exist, but no staking tokens do");
return rewardAmount;
}
/**
* @dev Applies an additional time-bonus to a distribution amount. This is necessary to
* encourage long-term deposits instead of constant unstake/restakes.
* The bonus-multiplier is the result of a linear function that starts at startBonus and
* ends at 100% over bonusPeriodSec, then stays at 100% thereafter.
* @param currentRewardTokens The current number of distribution tokens already alotted for this
* unstake op. Any bonuses are already applied.
* @param stakingShareSeconds The stakingShare-seconds that are being burned for new
* distribution tokens.
* @param stakeTimeSec Length of time for which the tokens were staked. Needed to calculate
* the time-bonus.
* @return Updated amount of distribution tokens to award, with any bonus included on the
* newly added tokens.
*/
function computeNewReward(uint256 currentRewardTokens,
uint256 stakingShareSeconds,
uint256 stakeTimeSec) private view returns (uint256) {
uint256 newRewardTokens =
totalUnlocked()
.mul(stakingShareSeconds)
.div(_totalStakingShareSeconds);
if (stakeTimeSec >= bonusPeriodSec) {
return currentRewardTokens.add(newRewardTokens);
}
uint256 oneHundredPct = 10**BONUS_DECIMALS;
uint256 bonusedReward =
startBonus
.add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec))
.mul(newRewardTokens)
.div(oneHundredPct);
return currentRewardTokens.add(bonusedReward);
}
function SwingyRewardsTransfer(uint256 amount, uint256 durationSec) external {
require(msg.sender == address(SwingyToken), "You're not the SwingyToken contract, go away");
require(unlockSchedules.length < _maxUnlockSchedules,
'SwingySeesaw: reached maximum unlock schedules');
// Update lockedTokens amount before using it in computations after.
updateAccounting();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount),
'SwingySeesaw: transfer into locked pool failed');
emit TokensLocked(amount, durationSec, totalLocked());
}
/**
* @param addr The user to look up staking information for.
* @return The number of staking tokens deposited for addr.
*/
function totalStakedFor(address addr) public view returns (uint256) {
return totalStakingShares > 0 ?
totalStaked().mul(_userTotals[addr].stakingShares).div(totalStakingShares) : 0;
}
/**
* @return The total number of deposit tokens staked globally, by all users.
*/
function totalStaked() public view returns (uint256) {
return _stakingPool.balance();
}
/**
* @dev Note that this application has a staking token as well as a distribution token, which
* may be different. This function is required by EIP-900.
* @return The deposit token used for staking.
*/
function token() external view returns (address) {
return address(getStakingToken());
}
/**
* @dev A globally callable function to update the accounting state of the system.
* Global state and state for the caller are updated.
* @return [0] balance of the locked pool
* @return [1] balance of the unlocked pool
* @return [2] caller's staking share seconds
* @return [3] global staking share seconds
* @return [4] Rewards caller has accumulated, optimistically assumes max time-bonus.
* @return [5] block timestamp
*/
function updateAccounting() public returns (
uint256, uint256, uint256, uint256, uint256, uint256) {
unlockTokens();
// Global accounting
uint256 newStakingShareSeconds =
now
.sub(_lastAccountingTimestampSec)
.mul(totalStakingShares);
_totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds);
_lastAccountingTimestampSec = now;
// User Accounting
UserTotals storage totals = _userTotals[msg.sender];
uint256 newUserStakingShareSeconds =
now
.sub(totals.lastAccountingTimestampSec)
.mul(totals.stakingShares);
totals.stakingShareSeconds =
totals.stakingShareSeconds
.add(newUserStakingShareSeconds);
totals.lastAccountingTimestampSec = now;
uint256 totalUserRewards = (_totalStakingShareSeconds > 0)
? totalUnlocked().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds)
: 0;
return (
totalLocked(),
totalUnlocked(),
totals.stakingShareSeconds,
_totalStakingShareSeconds,
totalUserRewards,
now
);
}
/**
* @return Total number of locked distribution tokens.
*/
function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
/**
* @return Total number of unlocked distribution tokens.
*/
function totalUnlocked() public view returns (uint256) {
return _unlockedPool.balance();
}
/**
* @return Number of unlock schedules.
*/
function unlockScheduleCount() public view returns (uint256) {
return unlockSchedules.length;
}
/**
* @dev This funcion allows the contract owner to add more locked distribution tokens, along
* with the associated "unlock schedule". These locked tokens immediately begin unlocking
* linearly over the duraction of durationSec timeframe.
* @param amount Number of distribution tokens to lock. These are transferred from the caller.
* @param durationSec Length of time to linear unlock the tokens.
*/
function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner {
require(unlockSchedules.length < _maxUnlockSchedules,
'SwingySeesaw: reached maximum unlock schedules');
// Update lockedTokens amount before using it in computations after.
updateAccounting();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount),
'SwingySeesaw: transfer into locked pool failed');
emit TokensLocked(amount, durationSec, totalLocked());
}
/**
* @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the
* previously defined unlock schedules. Publicly callable.
* @return Number of newly unlocked distribution tokens.
*/
function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
} else {
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
'SwingySeesaw: transfer out of locked pool failed');
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
/**
* @dev Returns the number of unlockable shares from a given schedule. The returned value
* depends on the time since the last unlock. This function updates schedule accounting,
* but does not actually transfer any tokens.
* @param s Index of the unlock schedule.
* @return The number of unlocked shares.
*/
function unlockScheduleShares(uint256 s) private returns (uint256) {
UnlockSchedule storage schedule = unlockSchedules[s];
if(schedule.unlockedShares >= schedule.initialLockedShares) {
return 0;
}
uint256 sharesToUnlock = 0;
// Special case to handle any leftover dust from integer division
if (now >= schedule.endAtSec) {
sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares));
schedule.lastUnlockTimestampSec = schedule.endAtSec;
} else {
sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec)
.mul(schedule.initialLockedShares)
.div(schedule.durationSec);
schedule.lastUnlockTimestampSec = now;
}
schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);
return sharesToUnlock;
}
} | contract SwingySeesaw is IStaking, Ownable {
using SafeMath for uint256;
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
event TokensClaimed(address indexed user, uint256 amount);
event TokensLocked(uint256 amount, uint256 durationSec, uint256 total);
// amount: Unlocked tokens, total: Total locked tokens
event TokensUnlocked(uint256 amount, uint256 total);
TokenPool private _stakingPool;
TokenPool private _unlockedPool;
TokenPool private _lockedPool;
//
// Time-bonus params
//
uint256 public BONUS_DECIMALS = 2;
uint256 public startBonus = 0;
uint256 public bonusPeriodSec = 0;
//
// Global accounting state
//
uint256 public totalLockedShares = 0;
uint256 public totalStakingShares = 0;
uint256 private _totalStakingShareSeconds = 0;
uint256 private _lastAccountingTimestampSec = now;
uint256 private _maxUnlockSchedules = 0;
uint256 private _initialSharesPerToken = 0;
mapping(address => bool) public whitelistedSenders;
address public SwingyToken;
//
// User accounting state
//
// Represents a single stake for a user. A user may have multiple.
struct Stake {
uint256 stakingShares;
uint256 timestampSec;
}
// Caches aggregated values from the User->Stake[] map to save computation.
// If lastAccountingTimestampSec is 0, there's no entry for that user.
struct UserTotals {
uint256 stakingShares;
uint256 stakingShareSeconds;
uint256 lastAccountingTimestampSec;
}
// Aggregated staking values per user
mapping(address => UserTotals) private _userTotals;
// The collection of stakes for each user. Ordered by timestamp, earliest to latest.
mapping(address => Stake[]) private _userStakes;
//
// Locked/Unlocked Accounting state
//
struct UnlockSchedule {
uint256 initialLockedShares;
uint256 unlockedShares;
uint256 lastUnlockTimestampSec;
uint256 endAtSec;
uint256 durationSec;
}
UnlockSchedule[] public unlockSchedules;
/**
* @param stakingToken The token users deposit as stake.
* @param distributionToken The token users receive as they unstake.
* @param maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit.
* @param startBonus_ Starting time bonus, BONUS_DECIMALS fixed point.
* e.g. 25% means user gets 25% of max distribution tokens.
* @param bonusPeriodSec_ Length of time for bonus to increase linearly to max.
* @param initialSharesPerToken Number of shares to mint per staking token on first stake.
*/
constructor(IERC20 stakingToken, IERC20 distributionToken, uint256 maxUnlockSchedules,
uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken) public {
// The start bonus must be some fraction of the max. (i.e. <= 100%)
require(startBonus_ <= 10**BONUS_DECIMALS, 'SwingySeesaw: start bonus too high');
// If no period is desired, instead set startBonus = 100%
// and bonusPeriod to a small value like 1sec.
require(bonusPeriodSec_ != 0, 'SwingySeesaw: bonus period is zero');
require(initialSharesPerToken > 0, 'SwingySeesaw: initialSharesPerToken is zero');
_stakingPool = new TokenPool(stakingToken);
_unlockedPool = new TokenPool(distributionToken);
_lockedPool = new TokenPool(distributionToken);
startBonus = startBonus_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
}
function setSwingyToken(address _SwingyToken) public onlyOwner {
SwingyToken = _SwingyToken;
}
/**
* @return The token users deposit as stake.
*/
function getStakingToken() public view returns (IERC20) {
return _stakingPool.token();
}
/**
* @return The token users receive as they unstake.
*/
function getDistributionToken() public view returns (IERC20) {
assert(_unlockedPool.token() == _lockedPool.token());
return _unlockedPool.token();
}
/**
* @dev Transfers amount of deposit tokens from the user.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stake(uint256 amount, bytes calldata data) external {
_stakeFor(msg.sender, msg.sender, amount);
}
/**
* @dev Transfers amount of deposit tokens from the caller on behalf of user.
* @param user User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stakeFor(address user, uint256 amount, bytes calldata data) external onlyOwner {
_stakeFor(msg.sender, user, amount);
}
/**
* @dev Private implementation of staking methods.
* @param staker User address who deposits tokens to stake.
* @param beneficiary User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
*/
function _stakeFor(address staker, address beneficiary, uint256 amount) private {
require(amount > 0, 'SwingySeesaw: stake amount is zero');
require(beneficiary != address(0), 'SwingySeesaw: beneficiary is zero address');
require(totalStakingShares == 0 || totalStaked() > 0,
'SwingySeesaw: Invalid state. Staking shares exist, but no staking tokens do');
uint256 mintedStakingShares = (totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(_initialSharesPerToken);
require(mintedStakingShares > 0, 'SwingySeesaw: Stake amount is too small');
updateAccounting();
// 1. User Accounting
UserTotals storage totals = _userTotals[beneficiary];
totals.stakingShares = totals.stakingShares.add(mintedStakingShares);
totals.lastAccountingTimestampSec = now;
Stake memory newStake = Stake(mintedStakingShares, now);
_userStakes[beneficiary].push(newStake);
// 2. Global Accounting
totalStakingShares = totalStakingShares.add(mintedStakingShares);
// Already set in updateAccounting()
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.token().transferFrom(staker, address(_stakingPool), amount),
'SwingySeesaw: transfer into staking pool failed');
emit Staked(beneficiary, amount, totalStakedFor(beneficiary), "");
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @param data Not used.
*/
function unstake(uint256 amount, bytes calldata data) external {
_unstake(amount);
}
/**
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens that would be rewarded.
*/
function unstakeQuery(uint256 amount) public returns (uint256) {
return _unstake(amount);
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens rewarded.
*/
function _unstake(uint256 amount) private returns (uint256) {
updateAccounting();
// checks
require(amount > 0, 'SwingySeesaw: unstake amount is zero');
require(totalStakedFor(msg.sender) >= amount,
'SwingySeesaw: unstake amount is greater than total user stakes');
uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked());
require(stakingSharesToBurn > 0, 'SwingySeesaw: Unable to unstake amount this small');
// 1. User Accounting
UserTotals storage totals = _userTotals[msg.sender];
Stake[] storage accountStakes = _userStakes[msg.sender];
// Redeem from most recent stake and go backwards in time.
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
// fully redeem a past stake
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares);
accountStakes.length--;
} else {
// partially redeem a past stake
newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn);
sharesLeftToBurn = 0;
}
}
totals.stakingShareSeconds = totals.stakingShareSeconds.sub(stakingShareSecondsToBurn);
totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// totals.lastAccountingTimestampSec = now;
// 2. Global Accounting
_totalStakingShareSeconds = _totalStakingShareSeconds.sub(stakingShareSecondsToBurn);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.transfer(msg.sender, amount),
'SwingySeesaw: transfer out of staking pool failed');
require(_unlockedPool.transfer(msg.sender, rewardAmount),
'SwingySeesaw: transfer out of unlocked pool failed');
emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), "");
emit TokensClaimed(msg.sender, rewardAmount);
require(totalStakingShares == 0 || totalStaked() > 0,
"SwingySeesaw: Error unstaking. Staking shares exist, but no staking tokens do");
return rewardAmount;
}
/**
* @dev Applies an additional time-bonus to a distribution amount. This is necessary to
* encourage long-term deposits instead of constant unstake/restakes.
* The bonus-multiplier is the result of a linear function that starts at startBonus and
* ends at 100% over bonusPeriodSec, then stays at 100% thereafter.
* @param currentRewardTokens The current number of distribution tokens already alotted for this
* unstake op. Any bonuses are already applied.
* @param stakingShareSeconds The stakingShare-seconds that are being burned for new
* distribution tokens.
* @param stakeTimeSec Length of time for which the tokens were staked. Needed to calculate
* the time-bonus.
* @return Updated amount of distribution tokens to award, with any bonus included on the
* newly added tokens.
*/
function computeNewReward(uint256 currentRewardTokens,
uint256 stakingShareSeconds,
uint256 stakeTimeSec) private view returns (uint256) {
uint256 newRewardTokens =
totalUnlocked()
.mul(stakingShareSeconds)
.div(_totalStakingShareSeconds);
if (stakeTimeSec >= bonusPeriodSec) {
return currentRewardTokens.add(newRewardTokens);
}
uint256 oneHundredPct = 10**BONUS_DECIMALS;
uint256 bonusedReward =
startBonus
.add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec))
.mul(newRewardTokens)
.div(oneHundredPct);
return currentRewardTokens.add(bonusedReward);
}
function SwingyRewardsTransfer(uint256 amount, uint256 durationSec) external {
require(msg.sender == address(SwingyToken), "You're not the SwingyToken contract, go away");
require(unlockSchedules.length < _maxUnlockSchedules,
'SwingySeesaw: reached maximum unlock schedules');
// Update lockedTokens amount before using it in computations after.
updateAccounting();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount),
'SwingySeesaw: transfer into locked pool failed');
emit TokensLocked(amount, durationSec, totalLocked());
}
/**
* @param addr The user to look up staking information for.
* @return The number of staking tokens deposited for addr.
*/
function totalStakedFor(address addr) public view returns (uint256) {
return totalStakingShares > 0 ?
totalStaked().mul(_userTotals[addr].stakingShares).div(totalStakingShares) : 0;
}
/**
* @return The total number of deposit tokens staked globally, by all users.
*/
function totalStaked() public view returns (uint256) {
return _stakingPool.balance();
}
/**
* @dev Note that this application has a staking token as well as a distribution token, which
* may be different. This function is required by EIP-900.
* @return The deposit token used for staking.
*/
function token() external view returns (address) {
return address(getStakingToken());
}
/**
* @dev A globally callable function to update the accounting state of the system.
* Global state and state for the caller are updated.
* @return [0] balance of the locked pool
* @return [1] balance of the unlocked pool
* @return [2] caller's staking share seconds
* @return [3] global staking share seconds
* @return [4] Rewards caller has accumulated, optimistically assumes max time-bonus.
* @return [5] block timestamp
*/
function updateAccounting() public returns (
uint256, uint256, uint256, uint256, uint256, uint256) {
unlockTokens();
// Global accounting
uint256 newStakingShareSeconds =
now
.sub(_lastAccountingTimestampSec)
.mul(totalStakingShares);
_totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds);
_lastAccountingTimestampSec = now;
// User Accounting
UserTotals storage totals = _userTotals[msg.sender];
uint256 newUserStakingShareSeconds =
now
.sub(totals.lastAccountingTimestampSec)
.mul(totals.stakingShares);
totals.stakingShareSeconds =
totals.stakingShareSeconds
.add(newUserStakingShareSeconds);
totals.lastAccountingTimestampSec = now;
uint256 totalUserRewards = (_totalStakingShareSeconds > 0)
? totalUnlocked().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds)
: 0;
return (
totalLocked(),
totalUnlocked(),
totals.stakingShareSeconds,
_totalStakingShareSeconds,
totalUserRewards,
now
);
}
/**
* @return Total number of locked distribution tokens.
*/
function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
/**
* @return Total number of unlocked distribution tokens.
*/
function totalUnlocked() public view returns (uint256) {
return _unlockedPool.balance();
}
/**
* @return Number of unlock schedules.
*/
function unlockScheduleCount() public view returns (uint256) {
return unlockSchedules.length;
}
/**
* @dev This funcion allows the contract owner to add more locked distribution tokens, along
* with the associated "unlock schedule". These locked tokens immediately begin unlocking
* linearly over the duraction of durationSec timeframe.
* @param amount Number of distribution tokens to lock. These are transferred from the caller.
* @param durationSec Length of time to linear unlock the tokens.
*/
function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner {
require(unlockSchedules.length < _maxUnlockSchedules,
'SwingySeesaw: reached maximum unlock schedules');
// Update lockedTokens amount before using it in computations after.
updateAccounting();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount),
'SwingySeesaw: transfer into locked pool failed');
emit TokensLocked(amount, durationSec, totalLocked());
}
/**
* @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the
* previously defined unlock schedules. Publicly callable.
* @return Number of newly unlocked distribution tokens.
*/
function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
} else {
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
'SwingySeesaw: transfer out of locked pool failed');
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
/**
* @dev Returns the number of unlockable shares from a given schedule. The returned value
* depends on the time since the last unlock. This function updates schedule accounting,
* but does not actually transfer any tokens.
* @param s Index of the unlock schedule.
* @return The number of unlocked shares.
*/
function unlockScheduleShares(uint256 s) private returns (uint256) {
UnlockSchedule storage schedule = unlockSchedules[s];
if(schedule.unlockedShares >= schedule.initialLockedShares) {
return 0;
}
uint256 sharesToUnlock = 0;
// Special case to handle any leftover dust from integer division
if (now >= schedule.endAtSec) {
sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares));
schedule.lastUnlockTimestampSec = schedule.endAtSec;
} else {
sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec)
.mul(schedule.initialLockedShares)
.div(schedule.durationSec);
schedule.lastUnlockTimestampSec = now;
}
schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);
return sharesToUnlock;
}
} | 12,497 |
2 | // here defines the minting price of each nft if other than contract address comes to the contract he will pay this amountto mint Bear Nft | uint public mintPrice = 0.05 ether;
| uint public mintPrice = 0.05 ether;
| 29,613 |
0 | // ERC20 basic token contract being held | IERC20 private immutable _token;
| IERC20 private immutable _token;
| 1,922 |
163 | // It emits only one {ConsecutiveTransfer} as defined ininstead of a sequence of {Transfer} event(s). Calling this function outside of contract creation WILL make your contractnon-compliant with the ERC721 standard.For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309{ConsecutiveTransfer} event is only permissible during contract creation. Requirements: - `to` cannot be the zero address.- `quantity` must be greater than 0. Emits a {ConsecutiveTransfer} event. / | function _mintERC2309(address to, uint256 quantity) internal virtual {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
| function _mintERC2309(address to, uint256 quantity) internal virtual {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
| 411 |
1 | // check the contract has the specified balance | require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(
uint256[6] memory data,
uint256[4] memory debtData,
address joinAddr,
address exchangeAddress,
bytes memory callData
)
| require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(
uint256[6] memory data,
uint256[4] memory debtData,
address joinAddr,
address exchangeAddress,
bytes memory callData
)
| 25,814 |
89 | // MAX_SUPPLY = maximum integer < (sqrt(4TOTAL_GRAINS + 1) - 1) / 2 | uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private _grainsPerFragment;
mapping(address => uint256) private _grainBalances;
mapping(address => bool) _feeWhiteList;
| uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private _grainsPerFragment;
mapping(address => uint256) private _grainBalances;
mapping(address => bool) _feeWhiteList;
| 17,883 |
13 | // open next deposit/withdarw | uint256 public TRADE_FREEZE_TIME = 5 minutes;
| uint256 public TRADE_FREEZE_TIME = 5 minutes;
| 30,590 |
364 | // Note - Random DS Proof Step 4:Commitment match verifying thatkeccak256( delay, nbytes, unonce, sessionKeyHash ) == commitment in storage. This is to verify that the computed args match with the onesspecified in the query./ | bytes memory commitmentSlice1 = new bytes(8 + 1 + 32);
| bytes memory commitmentSlice1 = new bytes(8 + 1 + 32);
| 38,750 |
55 | // Approve `to` to operate on `tokenId` | * Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
| * Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
| 45 |
23 | // PoolRebalanceHelper============ Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are require to move funds.Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction. The signatures are created on the operation hash and passed to withdrawETH/withdrawERC20The signer is determined by ECDSA.recover(). The signature is created with ethereumjs-util.ecsign(operationHash).Like the eth_sign RPC call, it packs the values as a 65-byte array of [r, s, v].Unlike eth_sign, the message is not prefixed./ | contract PoolRebalanceHelper is ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// Events
event Deposit(address token, uint256 amount, uint256 starkKey, uint256 positionId);
event WithdrawETH(uint256 orderId, address to, uint256 amount);
event WithdrawERC20(uint256 orderId, address token, address to, uint256 amount);
// Public fields
address immutable public USDC_ADDRESS; // USDC contract address
address immutable public STARKEX_ADDRESS; // stark exchange adress
uint256 immutable public L2POOL_ACCOUNT_ID; // l2pool account id
uint256 immutable public L2POOL_STARK_KEY; // l2pool stark key
address[] public signers; // The addresses that can co-sign transactions on the wallet
mapping(uint256 => order) orders; // history orders
uint256 public ASSET_TYPE; // stark exchange defined USDC
struct order{
address to; // The address the transaction was sent to
uint256 amount; // Amount of Wei sent to the address
address token; // The address of the ERC20 token contract, 0 means ETH
bool executed; // If the order was executed
}
/**
* Set up a simple 2-3 multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be require to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
* @param usdc The USDC contract address
* @param starkex The stark exchange address
* @param assetType The USDC asset type in starkex
* @param l2poolAccountId The fixed l2pool account id
* @param l2poolStarkKey The fixed l2key
*
*/
constructor(address[] memory allowedSigners, address usdc,address starkex, uint256 assetType,uint256 l2poolAccountId, uint256 l2poolStarkKey) {
require(allowedSigners.length == 3, "invalid allSigners length");
require(allowedSigners[0] != allowedSigners[1], "must be different signers");
require(allowedSigners[0] != allowedSigners[2], "must be different signers");
require(allowedSigners[1] != allowedSigners[2], "must be different signers");
require(usdc != address(0), "invalid usdc address");
require(block.chainid == 1 || block.chainid == 5, "invalid chain id");
signers = allowedSigners;
USDC_ADDRESS = usdc;
STARKEX_ADDRESS = starkex;
ASSET_TYPE = assetType;
L2POOL_ACCOUNT_ID = l2poolAccountId;
L2POOL_STARK_KEY = l2poolStarkKey;
}
/**
* Gets called when a transaction is received without calling a method
*/
receive() external payable { }
/**
* @notice Make a deposit to the Starkware Layer2.
* Funds will be transferred from this contract to starkware, and
* generate a deposit event specified by the starkKey and positionId.
*/
function deposit() public nonReentrant returns (uint256) {
uint256 balance = IERC20(USDC_ADDRESS).balanceOf(address(this));
require(balance > 0, "insufficient balance");
require(block.chainid == 1 || block.chainid == 5, "invalid chain id");
// safeApprove requires unsetting the allowance first.
IERC20(USDC_ADDRESS).safeApprove(STARKEX_ADDRESS, 0);
IERC20(USDC_ADDRESS).safeApprove(STARKEX_ADDRESS, balance);
// deposit to starkex
IStarkEx starkEx = IStarkEx(STARKEX_ADDRESS);
starkEx.depositERC20(L2POOL_STARK_KEY, ASSET_TYPE, L2POOL_ACCOUNT_ID, balance);
emit Deposit(
address(USDC_ADDRESS),
balance,
L2POOL_STARK_KEY,
L2POOL_ACCOUNT_ID
);
return balance;
}
/**
* Withdraw ETHER from this wallet using 2 signers.
*
* @param to the destination address to send an outgoing transaction
* @param amount the amount in Wei to be sent
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param orderId the unique order id
* @param allSigners all signers who sign the tx
* @param signatures the signatures of tx
*/
function withdrawETH(
address payable to,
uint256 amount,
uint256 expireTime,
uint256 orderId,
address[] memory allSigners,
bytes[] memory signatures
) public nonReentrant {
require(allSigners.length >= 2, "invalid allSigners length");
require(allSigners.length == signatures.length, "invalid signatures length");
require(allSigners[0] != allSigners[1],"can not be same signer"); // must be different signer
require(expireTime >= block.timestamp,"expired transaction");
bytes32 operationHash = keccak256(abi.encodePacked("ETHER", to, amount, expireTime, orderId, address(this), block.chainid));
operationHash = ECDSA.toEthSignedMessageHash(operationHash);
for (uint8 index = 0; index < allSigners.length; index++) {
address signer = ECDSA.recover(operationHash, signatures[index]);
require(signer == allSigners[index], "invalid signer");
require(isAllowedSigner(signer), "not allowed signer");
}
// Try to insert the order ID. Will revert if the order id was invalid
tryInsertOrderId(orderId, to, amount, address(0));
// send ETHER
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = to.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
emit WithdrawETH(orderId, to, amount);
}
/**
* Withdraw ERC20 from this wallet using 2 signers.
*
* @param to the destination address to send an outgoing transactioni
* @param amount the amount in Wei to be sent
* @param token the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param orderId the unique order id
* @param allSigners all signer who sign the tx
* @param signatures the signatures of tx
*/
function withdrawErc20(
address to,
uint256 amount,
address token,
uint256 expireTime,
uint256 orderId,
address[] memory allSigners,
bytes[] memory signatures
) public nonReentrant {
require(allSigners.length >=2, "invalid allSigners length");
require(allSigners.length == signatures.length, "invalid signatures length");
require(allSigners[0] != allSigners[1],"can not be same signer"); // must be different signer
require(expireTime >= block.timestamp,"expired transaction");
bytes32 operationHash = keccak256(abi.encodePacked("ERC20", to, amount, token, expireTime, orderId, address(this), block.chainid));
operationHash = ECDSA.toEthSignedMessageHash(operationHash);
for (uint8 index = 0; index < allSigners.length; index++) {
address signer = ECDSA.recover(operationHash, signatures[index]);
require(signer == allSigners[index], "invalid signer");
require(isAllowedSigner(signer),"not allowed signer");
}
// Try to insert the order ID. Will revert if the order id was invalid
tryInsertOrderId(orderId, to, amount, token);
// Success, send ERC20 token
IERC20(token).safeTransfer(to, amount);
emit WithdrawERC20(orderId, token, to, amount);
}
/**
* Determine if an address is a signer on this wallet
*
* @param signer address to check
*/
function isAllowedSigner(address signer) public view returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Verify that the order id has not been used before and inserts it. Throws if the order ID was not accepted.
*
* @param orderId the unique order id
* @param to the destination address to send an outgoing transaction
* @param amount the amount in Wei to be sent
* @param token the address of the ERC20 contract
*/
function tryInsertOrderId(
uint256 orderId,
address to,
uint256 amount,
address token
) internal {
if (orders[orderId].executed) {
// This order ID has been excuted before. Disallow!
revert("repeated order");
}
orders[orderId].executed = true;
orders[orderId].to = to;
orders[orderId].amount = amount;
orders[orderId].token = token;
}
/**
* calcSigHash is a helper function that to help you generate the sighash needed for withdrawal.
*
* @param to the destination address
* @param amount the amount in Wei to be sent
* @param token the address of the ERC20 contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param orderId the unique order id
*/
function calcSigHash(
address to,
uint256 amount,
address token,
uint256 expireTime,
uint256 orderId) public view returns (bytes32) {
bytes32 operationHash;
if (token == address(0)) {
operationHash = keccak256(abi.encodePacked("ETHER", to, amount, expireTime, orderId, address(this), block.chainid));
} else {
operationHash = keccak256(abi.encodePacked("ERC20", to, amount, token, expireTime, orderId, address(this), block.chainid));
}
return operationHash;
}
} | contract PoolRebalanceHelper is ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// Events
event Deposit(address token, uint256 amount, uint256 starkKey, uint256 positionId);
event WithdrawETH(uint256 orderId, address to, uint256 amount);
event WithdrawERC20(uint256 orderId, address token, address to, uint256 amount);
// Public fields
address immutable public USDC_ADDRESS; // USDC contract address
address immutable public STARKEX_ADDRESS; // stark exchange adress
uint256 immutable public L2POOL_ACCOUNT_ID; // l2pool account id
uint256 immutable public L2POOL_STARK_KEY; // l2pool stark key
address[] public signers; // The addresses that can co-sign transactions on the wallet
mapping(uint256 => order) orders; // history orders
uint256 public ASSET_TYPE; // stark exchange defined USDC
struct order{
address to; // The address the transaction was sent to
uint256 amount; // Amount of Wei sent to the address
address token; // The address of the ERC20 token contract, 0 means ETH
bool executed; // If the order was executed
}
/**
* Set up a simple 2-3 multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be require to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
* @param usdc The USDC contract address
* @param starkex The stark exchange address
* @param assetType The USDC asset type in starkex
* @param l2poolAccountId The fixed l2pool account id
* @param l2poolStarkKey The fixed l2key
*
*/
constructor(address[] memory allowedSigners, address usdc,address starkex, uint256 assetType,uint256 l2poolAccountId, uint256 l2poolStarkKey) {
require(allowedSigners.length == 3, "invalid allSigners length");
require(allowedSigners[0] != allowedSigners[1], "must be different signers");
require(allowedSigners[0] != allowedSigners[2], "must be different signers");
require(allowedSigners[1] != allowedSigners[2], "must be different signers");
require(usdc != address(0), "invalid usdc address");
require(block.chainid == 1 || block.chainid == 5, "invalid chain id");
signers = allowedSigners;
USDC_ADDRESS = usdc;
STARKEX_ADDRESS = starkex;
ASSET_TYPE = assetType;
L2POOL_ACCOUNT_ID = l2poolAccountId;
L2POOL_STARK_KEY = l2poolStarkKey;
}
/**
* Gets called when a transaction is received without calling a method
*/
receive() external payable { }
/**
* @notice Make a deposit to the Starkware Layer2.
* Funds will be transferred from this contract to starkware, and
* generate a deposit event specified by the starkKey and positionId.
*/
function deposit() public nonReentrant returns (uint256) {
uint256 balance = IERC20(USDC_ADDRESS).balanceOf(address(this));
require(balance > 0, "insufficient balance");
require(block.chainid == 1 || block.chainid == 5, "invalid chain id");
// safeApprove requires unsetting the allowance first.
IERC20(USDC_ADDRESS).safeApprove(STARKEX_ADDRESS, 0);
IERC20(USDC_ADDRESS).safeApprove(STARKEX_ADDRESS, balance);
// deposit to starkex
IStarkEx starkEx = IStarkEx(STARKEX_ADDRESS);
starkEx.depositERC20(L2POOL_STARK_KEY, ASSET_TYPE, L2POOL_ACCOUNT_ID, balance);
emit Deposit(
address(USDC_ADDRESS),
balance,
L2POOL_STARK_KEY,
L2POOL_ACCOUNT_ID
);
return balance;
}
/**
* Withdraw ETHER from this wallet using 2 signers.
*
* @param to the destination address to send an outgoing transaction
* @param amount the amount in Wei to be sent
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param orderId the unique order id
* @param allSigners all signers who sign the tx
* @param signatures the signatures of tx
*/
function withdrawETH(
address payable to,
uint256 amount,
uint256 expireTime,
uint256 orderId,
address[] memory allSigners,
bytes[] memory signatures
) public nonReentrant {
require(allSigners.length >= 2, "invalid allSigners length");
require(allSigners.length == signatures.length, "invalid signatures length");
require(allSigners[0] != allSigners[1],"can not be same signer"); // must be different signer
require(expireTime >= block.timestamp,"expired transaction");
bytes32 operationHash = keccak256(abi.encodePacked("ETHER", to, amount, expireTime, orderId, address(this), block.chainid));
operationHash = ECDSA.toEthSignedMessageHash(operationHash);
for (uint8 index = 0; index < allSigners.length; index++) {
address signer = ECDSA.recover(operationHash, signatures[index]);
require(signer == allSigners[index], "invalid signer");
require(isAllowedSigner(signer), "not allowed signer");
}
// Try to insert the order ID. Will revert if the order id was invalid
tryInsertOrderId(orderId, to, amount, address(0));
// send ETHER
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = to.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
emit WithdrawETH(orderId, to, amount);
}
/**
* Withdraw ERC20 from this wallet using 2 signers.
*
* @param to the destination address to send an outgoing transactioni
* @param amount the amount in Wei to be sent
* @param token the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param orderId the unique order id
* @param allSigners all signer who sign the tx
* @param signatures the signatures of tx
*/
function withdrawErc20(
address to,
uint256 amount,
address token,
uint256 expireTime,
uint256 orderId,
address[] memory allSigners,
bytes[] memory signatures
) public nonReentrant {
require(allSigners.length >=2, "invalid allSigners length");
require(allSigners.length == signatures.length, "invalid signatures length");
require(allSigners[0] != allSigners[1],"can not be same signer"); // must be different signer
require(expireTime >= block.timestamp,"expired transaction");
bytes32 operationHash = keccak256(abi.encodePacked("ERC20", to, amount, token, expireTime, orderId, address(this), block.chainid));
operationHash = ECDSA.toEthSignedMessageHash(operationHash);
for (uint8 index = 0; index < allSigners.length; index++) {
address signer = ECDSA.recover(operationHash, signatures[index]);
require(signer == allSigners[index], "invalid signer");
require(isAllowedSigner(signer),"not allowed signer");
}
// Try to insert the order ID. Will revert if the order id was invalid
tryInsertOrderId(orderId, to, amount, token);
// Success, send ERC20 token
IERC20(token).safeTransfer(to, amount);
emit WithdrawERC20(orderId, token, to, amount);
}
/**
* Determine if an address is a signer on this wallet
*
* @param signer address to check
*/
function isAllowedSigner(address signer) public view returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Verify that the order id has not been used before and inserts it. Throws if the order ID was not accepted.
*
* @param orderId the unique order id
* @param to the destination address to send an outgoing transaction
* @param amount the amount in Wei to be sent
* @param token the address of the ERC20 contract
*/
function tryInsertOrderId(
uint256 orderId,
address to,
uint256 amount,
address token
) internal {
if (orders[orderId].executed) {
// This order ID has been excuted before. Disallow!
revert("repeated order");
}
orders[orderId].executed = true;
orders[orderId].to = to;
orders[orderId].amount = amount;
orders[orderId].token = token;
}
/**
* calcSigHash is a helper function that to help you generate the sighash needed for withdrawal.
*
* @param to the destination address
* @param amount the amount in Wei to be sent
* @param token the address of the ERC20 contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param orderId the unique order id
*/
function calcSigHash(
address to,
uint256 amount,
address token,
uint256 expireTime,
uint256 orderId) public view returns (bytes32) {
bytes32 operationHash;
if (token == address(0)) {
operationHash = keccak256(abi.encodePacked("ETHER", to, amount, expireTime, orderId, address(this), block.chainid));
} else {
operationHash = keccak256(abi.encodePacked("ERC20", to, amount, token, expireTime, orderId, address(this), block.chainid));
}
return operationHash;
}
} | 18,494 |
266 | // I AM DA BEST | _safeMint(address(0x1d2D8fc9540E73906c6fae482FC241468B20691f), 0);
| _safeMint(address(0x1d2D8fc9540E73906c6fae482FC241468B20691f), 0);
| 41,124 |
17 | // 合成收藏品 | Composite,
| Composite,
| 44,793 |
104 | // accumulate marketing fee | _gonBalances[address(this)] = _gonBalances[address(this)].add(
gonValue.div(FEE_DIVISOR).mul(marketingFee)
);
| _gonBalances[address(this)] = _gonBalances[address(this)].add(
gonValue.div(FEE_DIVISOR).mul(marketingFee)
);
| 22,298 |
87 | // Internal function that swaps specified tokenIn amount to tokenOut to: address to send the swapped tokens to path: path for token swap amount: Amount of tokenIn amountOutMin: Minimum amount to recieve or revert / | function _swap(
address to,
address[] calldata path,
uint256 amount,
uint256 amountOutMin
| function _swap(
address to,
address[] calldata path,
uint256 amount,
uint256 amountOutMin
| 35,002 |
949 | // Delegates voting power of the underlying asset to a `delegatee` address delegatee The address that will receive the delegation / | function delegateUnderlyingTo(address delegatee) external onlyPoolAdmin {
IDelegationToken(_underlyingAsset).delegate(delegatee);
}
| function delegateUnderlyingTo(address delegatee) external onlyPoolAdmin {
IDelegationToken(_underlyingAsset).delegate(delegatee);
}
| 39,489 |
73 | // Reclaim all ERC20Basic compatible tokens _token ERC20Basic The address of the token contract / | function reclaimToken(ERC20Basic _token) external onlyOwner {
uint256 balance = _token.balanceOf(this);
_token.safeTransfer(owner, balance);
}
| function reclaimToken(ERC20Basic _token) external onlyOwner {
uint256 balance = _token.balanceOf(this);
_token.safeTransfer(owner, balance);
}
| 9,842 |
306 | // add the liquidity | uniswapV2Router.addLiquidityETH{ value: ethAmount }(
| uniswapV2Router.addLiquidityETH{ value: ethAmount }(
| 27,475 |
105 | // Call downstream transactions | downstreamCaller.executeTransactions();
return _totalSupply;
| downstreamCaller.executeTransactions();
return _totalSupply;
| 27,812 |
94 | // Payee's share | mapping(address => uint256) public share;
| mapping(address => uint256) public share;
| 36,224 |
7 | // Balancer pool WETH-MUSD | address balancerPool;
| address balancerPool;
| 10,156 |
157 | // View the development allocation ratio | function checkCoderAmount() public view returns(uint256) {
return _coderAmount;
}
| function checkCoderAmount() public view returns(uint256) {
return _coderAmount;
}
| 24,871 |
4 | // Tells the address of the implementation for a given version_contractName is the name of the contract we're queryingversion to query the implementation of return address of the implementation registered for the given version/ | function getVersion(string _contractName, string version) public view returns (address);
| function getVersion(string _contractName, string version) public view returns (address);
| 19,118 |
126 | // Allocate treasury STABLEC. / | function allocateTreasuryStablec(ITreasuryAllocation _contract, uint256 amountStablec) external onlyOwner {
require(amountStablec > 0, "STABLEC to allocate must be > 0");
treasuryAllocationsStablec[_contract] += amountStablec;
totalAllocationStablec += amountStablec;
SafeERC20.safeTransfer(STABLEC, address(_contract), amountStablec);
}
| function allocateTreasuryStablec(ITreasuryAllocation _contract, uint256 amountStablec) external onlyOwner {
require(amountStablec > 0, "STABLEC to allocate must be > 0");
treasuryAllocationsStablec[_contract] += amountStablec;
totalAllocationStablec += amountStablec;
SafeERC20.safeTransfer(STABLEC, address(_contract), amountStablec);
}
| 58,303 |
106 | // part of the tokens accumulated in the future that stays with the good leaver | uint256 internal constant GOOD_LEAVER_DIVISOR = 2;
| uint256 internal constant GOOD_LEAVER_DIVISOR = 2;
| 24,166 |
125 | // Set the affiliate of a user _user user to set affiliate for _affiliate address to set / | function setAffiliate(address _user, address _affiliate) public {
require(canSetAffiliate[msg.sender]);
if (userToAffiliate[_user] == address(0)) {
userToAffiliate[_user] = _affiliate;
}
}
| function setAffiliate(address _user, address _affiliate) public {
require(canSetAffiliate[msg.sender]);
if (userToAffiliate[_user] == address(0)) {
userToAffiliate[_user] = _affiliate;
}
}
| 54,559 |
96 | // userWithdraw: | function userWithdrawCapitalOnCycle(uint256 _cycle) public payable nonReentrant {
if(USER_CAPITAL_USED_ON_CYCLE[_cycle][msg.sender]){
revert("Capital already withdraw for this cycle");
}
//get user frags on this cycle
uint256 fragAmount = USER_FRAGS_ON_CYCLE[_cycle][msg.sender];
//convert these frags to eth amount
uint256 ETHamount = calculateEth(fragAmount, _cycle);
//send to user
msg.sender.transfer(ETHamount);
//update their paid flag on this cycle
USER_CAPITAL_USED_ON_CYCLE[_cycle][msg.sender] = true;
//if withdraw is from current cycle
if(_cycle == cycle){
//update the pool amount
POOL_ON_CYCLE[_cycle] = POOL_ON_CYCLE[_cycle].sub(ETHamount);
//subtract FRAGS from USER and TOTAL
TOTAL_FRAGS_ON_CYCLE[_cycle] = TOTAL_FRAGS_ON_CYCLE[_cycle].sub(fragAmount);
//remove their capital from this pool completely
USER_FRAGS_ON_CYCLE[cycle][msg.sender] = 0;
//update users
userExistOnCycle[cycle][msg.sender] = false;
//update the users
users = users.sub(1);
}
}
| function userWithdrawCapitalOnCycle(uint256 _cycle) public payable nonReentrant {
if(USER_CAPITAL_USED_ON_CYCLE[_cycle][msg.sender]){
revert("Capital already withdraw for this cycle");
}
//get user frags on this cycle
uint256 fragAmount = USER_FRAGS_ON_CYCLE[_cycle][msg.sender];
//convert these frags to eth amount
uint256 ETHamount = calculateEth(fragAmount, _cycle);
//send to user
msg.sender.transfer(ETHamount);
//update their paid flag on this cycle
USER_CAPITAL_USED_ON_CYCLE[_cycle][msg.sender] = true;
//if withdraw is from current cycle
if(_cycle == cycle){
//update the pool amount
POOL_ON_CYCLE[_cycle] = POOL_ON_CYCLE[_cycle].sub(ETHamount);
//subtract FRAGS from USER and TOTAL
TOTAL_FRAGS_ON_CYCLE[_cycle] = TOTAL_FRAGS_ON_CYCLE[_cycle].sub(fragAmount);
//remove their capital from this pool completely
USER_FRAGS_ON_CYCLE[cycle][msg.sender] = 0;
//update users
userExistOnCycle[cycle][msg.sender] = false;
//update the users
users = users.sub(1);
}
}
| 36,572 |
3 | // Pending administrator for this contract/ | address public pendingAdmin;
| address public pendingAdmin;
| 25,702 |
53 | // Checks if the account should be allowed to borrow the underlying asset of the given market cToken The market to verify the borrow against borrower The account which would borrow the asset borrowAmount The amount of underlying the account would borrowreturn 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) / | function borrowAllowed(address cToken, address borrower, uint borrowAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[cToken], "borrow is paused");
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[cToken].accountMembership[borrower]) {
// only cTokens may call borrowAllowed if borrower not in market
require(msg.sender == cToken, "sender must be cToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(CToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[cToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(cToken) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[cToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = CToken(cToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()});
updateCompBorrowIndex(cToken, borrowIndex);
distributeBorrowerComp(cToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
| function borrowAllowed(address cToken, address borrower, uint borrowAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[cToken], "borrow is paused");
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[cToken].accountMembership[borrower]) {
// only cTokens may call borrowAllowed if borrower not in market
require(msg.sender == cToken, "sender must be cToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(CToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[cToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(cToken) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[cToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = CToken(cToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()});
updateCompBorrowIndex(cToken, borrowIndex);
distributeBorrowerComp(cToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
| 11,867 |
142 | // Validate address array is not empty and contains no duplicate elements.AArray of addresses / | function _validateLengthAndUniqueness(address[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
| function _validateLengthAndUniqueness(address[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
| 46,423 |
2 | // State to track proposal period | uint256 public proposalStartTime;
| uint256 public proposalStartTime;
| 17,163 |
107 | // Creates a new template to use in strategies/Templates once created can't be changed/_name Name of template, used mainly for logging/_triggerIds Array of trigger ids which translate to trigger addresses/_actionIds Array of actions ids which translate to action addresses/_paramMapping Array that holds metadata of how inputs are mapped to sub/return data | function createTemplate(
string memory _name,
bytes32[] memory _triggerIds,
bytes32[] memory _actionIds,
uint8[][] memory _paramMapping
| function createTemplate(
string memory _name,
bytes32[] memory _triggerIds,
bytes32[] memory _actionIds,
uint8[][] memory _paramMapping
| 30,491 |
17 | // removes tokens and returns them to the main pool this is called if | function RevokeTokens(address target) internal
| function RevokeTokens(address target) internal
| 70,718 |
65 | // Don't need price > 0 check as sellBook.getHead(price) != '' takes care of it | while ( getRemainingQuantity(takerOrder) > 0 && head != '' && takerOrder.price >= price) {
makerOrder = getOrder(head);
quantity = orderBooks.matchTrade(sellBookId, price, getRemainingQuantity(takerOrder), getRemainingQuantity(makerOrder));
addExecution(_tradePairId, makerOrder, takerOrder, price, quantity); // this makes a state change to Order Map
takerOrder.quantityFilled += quantity; // locally keep track of Qty remaining
price = orderBooks.first(sellBookId);
head = orderBooks.getHead(sellBookId, price);
}
| while ( getRemainingQuantity(takerOrder) > 0 && head != '' && takerOrder.price >= price) {
makerOrder = getOrder(head);
quantity = orderBooks.matchTrade(sellBookId, price, getRemainingQuantity(takerOrder), getRemainingQuantity(makerOrder));
addExecution(_tradePairId, makerOrder, takerOrder, price, quantity); // this makes a state change to Order Map
takerOrder.quantityFilled += quantity; // locally keep track of Qty remaining
price = orderBooks.first(sellBookId);
head = orderBooks.getHead(sellBookId, price);
}
| 29,083 |
5 | // delegator address of the delegator/delegate Address of the delegate | function setDelegate(address delegator, address delegate) public onlyOwner {
require(delegate != address(0), "ZERO_ADDRESS");
address currentDelegate = delegation[delegator];
require(delegate != currentDelegate, "Already delegated to this address");
// Update delegation mapping
delegation[delegator] = delegate;
emit SetDelegate(delegator, delegate);
}
| function setDelegate(address delegator, address delegate) public onlyOwner {
require(delegate != address(0), "ZERO_ADDRESS");
address currentDelegate = delegation[delegator];
require(delegate != currentDelegate, "Already delegated to this address");
// Update delegation mapping
delegation[delegator] = delegate;
emit SetDelegate(delegator, delegate);
}
| 13,899 |
89 | // lock memeber amount | }else if( index ==32){
| }else if( index ==32){
| 17,057 |
24 | // This function returns the discount available for a user, when purchasing aa key from a lock.This does not modify the state. It returns both the discount and the number of tokensconsumed to grant that discount.TODO: actually implement this. / | function computeAvailableDiscountFor(
address /* _purchaser */,
uint /* _keyPrice */
)
public
pure
returns (uint discount, uint tokens)
| function computeAvailableDiscountFor(
address /* _purchaser */,
uint /* _keyPrice */
)
public
pure
returns (uint discount, uint tokens)
| 18,412 |
112 | // Sets the reference to the CPI oracle. targetPriceOracle_ The address of the cpi oracle contract. / | function setTargetPriceOracle(IOracle targetPriceOracle_)
external
onlyOwner
| function setTargetPriceOracle(IOracle targetPriceOracle_)
external
onlyOwner
| 24,809 |
32 | // Encodes a 22 bits signed integer shifted by an offset. The return value can be logically ORed with other encoded values to form a 256 bit word. / | function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) {
// Integer values need masking to remove the upper bits of negative values.
return bytes32((uint256(value) & _MASK_22) << offset);
}
| function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) {
// Integer values need masking to remove the upper bits of negative values.
return bytes32((uint256(value) & _MASK_22) << offset);
}
| 43,481 |
31 | // | function changeAdmin(address payable newAdmin) onlyAdmin public returns (bool){
admin = newAdmin;
return true;
}
| function changeAdmin(address payable newAdmin) onlyAdmin public returns (bool){
admin = newAdmin;
return true;
}
| 51,301 |
5 | // Set approval for the proxy | _token.approve(_ctoken, type(uint256).max);
underlyingDecimals = _token.decimals();
| _token.approve(_ctoken, type(uint256).max);
underlyingDecimals = _token.decimals();
| 13,053 |
67 | // Use block UINT256_MAX (which should be never) as the initializable date | uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
| uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
| 335 |
86 | // Sets the values for `name`, `symbol`, and `decimals`. All three ofthese values are immutable: they can only be set once duringconstruction. To avoid variable shadowing appended `Arg` after arguments name. / | function _initialize(
string memory nameArg,
| function _initialize(
string memory nameArg,
| 5,295 |
88 | // Decode a boolean value from a Witnet.Result as an `bool` value./_result An instance of Witnet.Result./ return The `bool` decoded from the Witnet.Result. | function asBool(Witnet.Result memory _result) external pure returns (bool);
| function asBool(Witnet.Result memory _result) external pure returns (bool);
| 19,709 |
55 | // initiates a new PoolStake.------------------------------------------------------ _token--> token offered for staking liquidity. _Owner--> address for the initial contract owner. / | constructor(address _token, address _Owner) public Owned(_Owner) {
require(_token != address(0), "can not deploy a zero address");
token = IERC20(_token);
weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
iUniswapV2Factory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
address _lpToken = iUniswapV2Factory.getPair(address(token), address(weth));
require(_lpToken != address(0), "Pair must first be created on uniswap");
lpToken = IERC20(_lpToken);
uToken = 0x9Ed8e7C9604790F7Ec589F99b94361d8AAB64E5E;
wallet = 0xa7A4d919202DFA2f4E44FFAc422d21095bF9770a;
multiplier = Multiplier(0xbc962d7be33d8AfB4a547936D8CE6b9a1034E9EE);
uniswapRouter = UniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
}
| constructor(address _token, address _Owner) public Owned(_Owner) {
require(_token != address(0), "can not deploy a zero address");
token = IERC20(_token);
weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
iUniswapV2Factory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
address _lpToken = iUniswapV2Factory.getPair(address(token), address(weth));
require(_lpToken != address(0), "Pair must first be created on uniswap");
lpToken = IERC20(_lpToken);
uToken = 0x9Ed8e7C9604790F7Ec589F99b94361d8AAB64E5E;
wallet = 0xa7A4d919202DFA2f4E44FFAc422d21095bF9770a;
multiplier = Multiplier(0xbc962d7be33d8AfB4a547936D8CE6b9a1034E9EE);
uniswapRouter = UniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
}
| 37,153 |
3 | // Update invest percentage Emits {InvestPctUpdated} event_investPct the new invest percentage / | function setInvestPct(uint16 _investPct) external;
| function setInvestPct(uint16 _investPct) external;
| 37,409 |
109 | // Sets the address of the application's InterchainGasPaymaster. _interchainGasPaymaster The address of the InterchainGasPaymaster contract. / | function setInterchainGasPaymaster(address _interchainGasPaymaster)
external
virtual
onlyOwner
| function setInterchainGasPaymaster(address _interchainGasPaymaster)
external
virtual
onlyOwner
| 40,562 |
240 | // A Reference to Core/Fei Protocol/defines some modifiers and utilities around interacting with Core | abstract contract CoreRef is ICoreRef, Pausable {
ICore private _core;
/// @notice CoreRef constructor
/// @param core Fei Core to reference
constructor(address core) public {
_core = ICore(core);
}
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier ifBurnerSelf() {
if (_core.isBurner(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier onlyFei() {
require(msg.sender == address(fei()), "CoreRef: Caller is not FEI");
_;
}
modifier onlyGenesisGroup() {
require(
msg.sender == _core.genesisGroup(),
"CoreRef: Caller is not GenesisGroup"
);
_;
}
modifier postGenesis() {
require(
_core.hasGenesisGroupCompleted(),
"CoreRef: Still in Genesis Period"
);
_;
}
modifier nonContract() {
require(!Address.isContract(msg.sender), "CoreRef: Caller is a contract");
_;
}
/// @notice set new Core reference address
/// @param core the new core address
function setCore(address core) external override onlyGovernor {
_core = ICore(core);
emit CoreUpdate(core);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Fei contract referenced by Core
/// @return IFei implementation address
function fei() public view override returns (IFei) {
return _core.fei();
}
/// @notice address of the Tribe contract referenced by Core
/// @return IERC20 implementation address
function tribe() public view override returns (IERC20) {
return _core.tribe();
}
/// @notice fei balance of contract
/// @return fei amount held
function feiBalance() public view override returns (uint256) {
return fei().balanceOf(address(this));
}
/// @notice tribe balance of contract
/// @return tribe amount held
function tribeBalance() public view override returns (uint256) {
return tribe().balanceOf(address(this));
}
function _burnFeiHeld() internal {
fei().burn(feiBalance());
}
function _mintFei(uint256 amount) internal {
fei().mint(address(this), amount);
}
}
| abstract contract CoreRef is ICoreRef, Pausable {
ICore private _core;
/// @notice CoreRef constructor
/// @param core Fei Core to reference
constructor(address core) public {
_core = ICore(core);
}
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier ifBurnerSelf() {
if (_core.isBurner(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier onlyFei() {
require(msg.sender == address(fei()), "CoreRef: Caller is not FEI");
_;
}
modifier onlyGenesisGroup() {
require(
msg.sender == _core.genesisGroup(),
"CoreRef: Caller is not GenesisGroup"
);
_;
}
modifier postGenesis() {
require(
_core.hasGenesisGroupCompleted(),
"CoreRef: Still in Genesis Period"
);
_;
}
modifier nonContract() {
require(!Address.isContract(msg.sender), "CoreRef: Caller is a contract");
_;
}
/// @notice set new Core reference address
/// @param core the new core address
function setCore(address core) external override onlyGovernor {
_core = ICore(core);
emit CoreUpdate(core);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Fei contract referenced by Core
/// @return IFei implementation address
function fei() public view override returns (IFei) {
return _core.fei();
}
/// @notice address of the Tribe contract referenced by Core
/// @return IERC20 implementation address
function tribe() public view override returns (IERC20) {
return _core.tribe();
}
/// @notice fei balance of contract
/// @return fei amount held
function feiBalance() public view override returns (uint256) {
return fei().balanceOf(address(this));
}
/// @notice tribe balance of contract
/// @return tribe amount held
function tribeBalance() public view override returns (uint256) {
return tribe().balanceOf(address(this));
}
function _burnFeiHeld() internal {
fei().burn(feiBalance());
}
function _mintFei(uint256 amount) internal {
fei().mint(address(this), amount);
}
}
| 15,166 |
6 | // Returns the latest round from the reference contract. / | function getLatestRound()
public
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
| function getLatestRound()
public
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
| 6,178 |
26 | // IUserRegistry IUserRegistry interface Cyril Lapinte - <cyril.lapinte@openfiz.com> / | contract IUserRegistry {
event UserRegistered(uint256 indexed userId);
event AddressAttached(uint256 indexed userId, address address_);
event AddressDetached(uint256 indexed userId, address address_);
function registerManyUsersExternal(address[] calldata _addresses, uint256 _validUntilTime)
external returns (bool);
function registerManyUsersFullExternal(
address[] calldata _addresses,
uint256 _validUntilTime,
uint256[] calldata _values) external returns (bool);
function attachManyAddressesExternal(uint256[] calldata _userIds, address[] calldata _addresses)
external returns (bool);
function detachManyAddressesExternal(address[] calldata _addresses)
external returns (bool);
function suspendManyUsers(uint256[] calldata _userIds) external returns (bool);
function unsuspendManyUsersExternal(uint256[] calldata _userIds) external returns (bool);
function updateManyUsersExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended) external returns (bool);
function updateManyUsersExtendedExternal(
uint256[] calldata _userIds,
uint256 _key, uint256 _value) external returns (bool);
function updateManyUsersAllExtendedExternal(
uint256[] calldata _userIds,
uint256[] calldata _values) external returns (bool);
function updateManyUsersFullExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended,
uint256[] calldata _values) external returns (bool);
function name() public view returns (string memory);
function currency() public view returns (bytes32);
function userCount() public view returns (uint256);
function userId(address _address) public view returns (uint256);
function validUserId(address _address) public view returns (uint256);
function validUser(address _address, uint256[] memory _keys)
public view returns (uint256, uint256[] memory);
function validity(uint256 _userId) public view returns (uint256, bool);
function extendedKeys() public view returns (uint256[] memory);
function extended(uint256 _userId, uint256 _key)
public view returns (uint256);
function manyExtended(uint256 _userId, uint256[] memory _key)
public view returns (uint256[] memory);
function isAddressValid(address _address) public view returns (bool);
function isValid(uint256 _userId) public view returns (bool);
function defineExtendedKeys(uint256[] memory _extendedKeys) public returns (bool);
function registerUser(address _address, uint256 _validUntilTime)
public returns (bool);
function registerUserFull(
address _address,
uint256 _validUntilTime,
uint256[] memory _values) public returns (bool);
function attachAddress(uint256 _userId, address _address) public returns (bool);
function detachAddress(address _address) public returns (bool);
function detachSelf() public returns (bool);
function detachSelfAddress(address _address) public returns (bool);
function suspendUser(uint256 _userId) public returns (bool);
function unsuspendUser(uint256 _userId) public returns (bool);
function updateUser(uint256 _userId, uint256 _validUntilTime, bool _suspended)
public returns (bool);
function updateUserExtended(uint256 _userId, uint256 _key, uint256 _value)
public returns (bool);
function updateUserAllExtended(uint256 _userId, uint256[] memory _values)
public returns (bool);
function updateUserFull(
uint256 _userId,
uint256 _validUntilTime,
bool _suspended,
uint256[] memory _values) public returns (bool);
}
| contract IUserRegistry {
event UserRegistered(uint256 indexed userId);
event AddressAttached(uint256 indexed userId, address address_);
event AddressDetached(uint256 indexed userId, address address_);
function registerManyUsersExternal(address[] calldata _addresses, uint256 _validUntilTime)
external returns (bool);
function registerManyUsersFullExternal(
address[] calldata _addresses,
uint256 _validUntilTime,
uint256[] calldata _values) external returns (bool);
function attachManyAddressesExternal(uint256[] calldata _userIds, address[] calldata _addresses)
external returns (bool);
function detachManyAddressesExternal(address[] calldata _addresses)
external returns (bool);
function suspendManyUsers(uint256[] calldata _userIds) external returns (bool);
function unsuspendManyUsersExternal(uint256[] calldata _userIds) external returns (bool);
function updateManyUsersExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended) external returns (bool);
function updateManyUsersExtendedExternal(
uint256[] calldata _userIds,
uint256 _key, uint256 _value) external returns (bool);
function updateManyUsersAllExtendedExternal(
uint256[] calldata _userIds,
uint256[] calldata _values) external returns (bool);
function updateManyUsersFullExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended,
uint256[] calldata _values) external returns (bool);
function name() public view returns (string memory);
function currency() public view returns (bytes32);
function userCount() public view returns (uint256);
function userId(address _address) public view returns (uint256);
function validUserId(address _address) public view returns (uint256);
function validUser(address _address, uint256[] memory _keys)
public view returns (uint256, uint256[] memory);
function validity(uint256 _userId) public view returns (uint256, bool);
function extendedKeys() public view returns (uint256[] memory);
function extended(uint256 _userId, uint256 _key)
public view returns (uint256);
function manyExtended(uint256 _userId, uint256[] memory _key)
public view returns (uint256[] memory);
function isAddressValid(address _address) public view returns (bool);
function isValid(uint256 _userId) public view returns (bool);
function defineExtendedKeys(uint256[] memory _extendedKeys) public returns (bool);
function registerUser(address _address, uint256 _validUntilTime)
public returns (bool);
function registerUserFull(
address _address,
uint256 _validUntilTime,
uint256[] memory _values) public returns (bool);
function attachAddress(uint256 _userId, address _address) public returns (bool);
function detachAddress(address _address) public returns (bool);
function detachSelf() public returns (bool);
function detachSelfAddress(address _address) public returns (bool);
function suspendUser(uint256 _userId) public returns (bool);
function unsuspendUser(uint256 _userId) public returns (bool);
function updateUser(uint256 _userId, uint256 _validUntilTime, bool _suspended)
public returns (bool);
function updateUserExtended(uint256 _userId, uint256 _key, uint256 _value)
public returns (bool);
function updateUserAllExtended(uint256 _userId, uint256[] memory _values)
public returns (bool);
function updateUserFull(
uint256 _userId,
uint256 _validUntilTime,
bool _suspended,
uint256[] memory _values) public returns (bool);
}
| 34,538 |
12 | // M O D I F I E R S | modifier onlyPlayer(){
require(player[msg.sender].isPlayer == true);
_;
}
| modifier onlyPlayer(){
require(player[msg.sender].isPlayer == true);
_;
}
| 12,472 |
7 | // Purchase assets for a user_recipient the user who will receive the assets _quantity the number of this product to purchase _payment the details of the method by which payment will be made _referrer the address of the user who made this referral / | function purchaseFor(
address payable _recipient,
uint256 _quantity,
PurchaseProcessor.PaymentParams memory _payment,
address payable _referrer
| function purchaseFor(
address payable _recipient,
uint256 _quantity,
PurchaseProcessor.PaymentParams memory _payment,
address payable _referrer
| 8,547 |
0 | // ============ State Variables ============ / CToken Full Unit | uint256 public immutable cTokenFullUnit;
| uint256 public immutable cTokenFullUnit;
| 56,377 |
24 | // To change the approve amount you first have to reduce the addresses`allowance to zero by calling `approve(_spender, 0)` if it is notalready 0 to mitigate the race condition described here: |
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
|
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
| 30,762 |
94 | // path: _input -> _output | path = new address[](2);
path[0] = _input;
path[1] = _output;
| path = new address[](2);
path[0] = _input;
path[1] = _output;
| 21,772 |
10 | // Events | event MigrationInfoSet(string newMigrationInfo);
event FrozenFunds(address target, bool frozen);
| event MigrationInfoSet(string newMigrationInfo);
event FrozenFunds(address target, bool frozen);
| 20,345 |
31 | // 设置当前某个的领取状态 仅所有者可调用 | function setUsers(address user, bool state) public onlyOwner {
users[user] = state;
}
| function setUsers(address user, bool state) public onlyOwner {
users[user] = state;
}
| 8,706 |
404 | // getter functions // user functions //UniStakerV2/Reward distribution contract/ Access Control/ - Power controller:/ Can power off / shutdown the UniStakerV2/ Can withdraw rewards from reward pool once shutdown/ - Owner:/ Is unable to operate on user funds due to UniversalVault/ Is unable to operate on reward pool funds when reward pool is offline / shutdown/ - UniStakerV2 admin:/ Can add funds to the UniStakerV2, register bonus tokens, and whitelist new vault factories/ Is a subset of owner permissions/ - User:/ Can stake / unstake / ragequit / claim airdrop / claim vested rewards/ UniStakerV2 State Machine/ - Online:/ UniStakerV2 is | contract UniStakerV2 is IUniStakerV2, Powered {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/* constants */
string public constant PLATINUM = "PLATINUM";
string public constant GOLD = "GOLD";
string public constant MINT = "MINT";
string public constant BLACK = "BLACK";
uint public PLATINUM_LM_REWARD_MULTIPLIER_NUM = 5;
uint public PLATINUM_LM_REWARD_MULTIPLIER_DENOM = 2;
uint public GOLD_LM_REWARD_MULTIPLIER_NUM = 2;
uint public GOLD_LM_REWARD_MULTIPLIER_DENOM = 1;
uint public MINT_LM_REWARD_MULTIPLIER_NUM = 3;
uint public MINT_LM_REWARD_MULTIPLIER_DENOM = 2;
uint public BLACK_LM_REWARD_MULTIPLIER_NUM = 1;
uint public BLACK_LM_REWARD_MULTIPLIER_DENOM = 1;
uint public LM_REWARD_VESTING_PERIOD = 7776000; // 3 months
uint public LM_REWARD_VESTING_PORTION_NUM = 1;
uint public LM_REWARD_VESTING_PORTION_DENOM = 2;
// An upper bound on the number of active tokens staked per vault is required to prevent
// calls to rageQuit() from reverting.
// With 30 tokens staked in a vault, ragequit costs 432811 gas which is conservatively lower
// than the hardcoded limit of 500k gas on the vault.
// This limit is configurable and could be increased in a future deployment.
// Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide
// an error code that allows for reliably catching out-of-gas errors on remote calls.
uint256 public MAX_TOKENS_STAKED_PER_VAULT = 30;
uint256 public MAX_BONUS_TOKENS = 50;
/* storage */
address public admin;
address public rewardToken;
address public rewardPool;
EnumerableSet.AddressSet private _vaultSet;
mapping(address => VaultData) private _vaults;
EnumerableSet.AddressSet private _bonusTokenSet;
EnumerableSet.AddressSet private _vaultFactorySet;
EnumerableSet.AddressSet private _allStakedTokens;
mapping(address => uint256) public stakedTokenTotal;
mapping(address => LMRewardData) private lmRewards;
// user to token to earned reward mapping
mapping(address => mapping(address => uint)) public earnedLMRewards;
// user to token to vesting data mapping
mapping(address => mapping(address => LMRewardVestingData[])) public vestingLMRewards;
// user to vesting lm token rewards set
mapping(address => EnumerableSet.AddressSet) private vestingLMTokenRewards;
// erc2917 template names
string[] public rewardCalcTemplateNames;
// erc2917 template names to erc 2917 templates
mapping(string => address) public rewardCalcTemplates;
string public activeRewardCalcTemplate;
event RewardCalcTemplateAdded(string indexed name, address indexed template);
event RewardCalcTemplateActive(string indexed name, address indexed template);
/* initializer */
/// @notice Initizalize UniStakerV2
/// access control: only proxy constructor
/// state machine: can only be called once
/// state scope: set initialization variables
/// token transfer: none
/// @param adminAddress address The admin address
/// @param rewardPoolFactory address The factory to use for deploying the RewardPool
/// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch
/// @param rewardTokenAddress address The address of the reward token for this UniStakerV2
constructor(
address adminAddress,
address rewardPoolFactory,
address powerSwitchFactory,
address rewardTokenAddress
) {
// deploy power switch
address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(adminAddress));
// deploy reward pool
rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch));
// set internal config
admin = adminAddress;
rewardToken = rewardTokenAddress;
Powered._setPowerSwitch(powerSwitch);
// emit event
emit UniStakerV2Created(rewardPool, powerSwitch);
}
| contract UniStakerV2 is IUniStakerV2, Powered {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/* constants */
string public constant PLATINUM = "PLATINUM";
string public constant GOLD = "GOLD";
string public constant MINT = "MINT";
string public constant BLACK = "BLACK";
uint public PLATINUM_LM_REWARD_MULTIPLIER_NUM = 5;
uint public PLATINUM_LM_REWARD_MULTIPLIER_DENOM = 2;
uint public GOLD_LM_REWARD_MULTIPLIER_NUM = 2;
uint public GOLD_LM_REWARD_MULTIPLIER_DENOM = 1;
uint public MINT_LM_REWARD_MULTIPLIER_NUM = 3;
uint public MINT_LM_REWARD_MULTIPLIER_DENOM = 2;
uint public BLACK_LM_REWARD_MULTIPLIER_NUM = 1;
uint public BLACK_LM_REWARD_MULTIPLIER_DENOM = 1;
uint public LM_REWARD_VESTING_PERIOD = 7776000; // 3 months
uint public LM_REWARD_VESTING_PORTION_NUM = 1;
uint public LM_REWARD_VESTING_PORTION_DENOM = 2;
// An upper bound on the number of active tokens staked per vault is required to prevent
// calls to rageQuit() from reverting.
// With 30 tokens staked in a vault, ragequit costs 432811 gas which is conservatively lower
// than the hardcoded limit of 500k gas on the vault.
// This limit is configurable and could be increased in a future deployment.
// Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide
// an error code that allows for reliably catching out-of-gas errors on remote calls.
uint256 public MAX_TOKENS_STAKED_PER_VAULT = 30;
uint256 public MAX_BONUS_TOKENS = 50;
/* storage */
address public admin;
address public rewardToken;
address public rewardPool;
EnumerableSet.AddressSet private _vaultSet;
mapping(address => VaultData) private _vaults;
EnumerableSet.AddressSet private _bonusTokenSet;
EnumerableSet.AddressSet private _vaultFactorySet;
EnumerableSet.AddressSet private _allStakedTokens;
mapping(address => uint256) public stakedTokenTotal;
mapping(address => LMRewardData) private lmRewards;
// user to token to earned reward mapping
mapping(address => mapping(address => uint)) public earnedLMRewards;
// user to token to vesting data mapping
mapping(address => mapping(address => LMRewardVestingData[])) public vestingLMRewards;
// user to vesting lm token rewards set
mapping(address => EnumerableSet.AddressSet) private vestingLMTokenRewards;
// erc2917 template names
string[] public rewardCalcTemplateNames;
// erc2917 template names to erc 2917 templates
mapping(string => address) public rewardCalcTemplates;
string public activeRewardCalcTemplate;
event RewardCalcTemplateAdded(string indexed name, address indexed template);
event RewardCalcTemplateActive(string indexed name, address indexed template);
/* initializer */
/// @notice Initizalize UniStakerV2
/// access control: only proxy constructor
/// state machine: can only be called once
/// state scope: set initialization variables
/// token transfer: none
/// @param adminAddress address The admin address
/// @param rewardPoolFactory address The factory to use for deploying the RewardPool
/// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch
/// @param rewardTokenAddress address The address of the reward token for this UniStakerV2
constructor(
address adminAddress,
address rewardPoolFactory,
address powerSwitchFactory,
address rewardTokenAddress
) {
// deploy power switch
address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(adminAddress));
// deploy reward pool
rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch));
// set internal config
admin = adminAddress;
rewardToken = rewardTokenAddress;
Powered._setPowerSwitch(powerSwitch);
// emit event
emit UniStakerV2Created(rewardPool, powerSwitch);
}
| 31,452 |
338 | // ILendingRateOracle interfaceInterface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations/ | interface ILendingRateOracle {
/**
@dev returns the market borrow rate in ray
**/
function getMarketBorrowRate(address _asset) external view returns (uint256);
/**
@dev sets the market borrow rate. Rate value must be in ray
**/
function setMarketBorrowRate(address _asset, uint256 _rate) external;
}
| interface ILendingRateOracle {
/**
@dev returns the market borrow rate in ray
**/
function getMarketBorrowRate(address _asset) external view returns (uint256);
/**
@dev sets the market borrow rate. Rate value must be in ray
**/
function setMarketBorrowRate(address _asset, uint256 _rate) external;
}
| 24,366 |
13 | // See {ERC20-_burn}. / | function burn(uint256 amount) external override returns (bool) {
_burn(_msgSender(), amount);
return true;
}
| function burn(uint256 amount) external override returns (bool) {
_burn(_msgSender(), amount);
return true;
}
| 28,912 |
73 | // Sets owner address where the funds will be sent during withdrawal _owner Owner's address Requirements:- sender must have canSetOwnerAddress permission- address must not be 0 / | function setOwner(address _owner) external canSetOwnerAddress(msg.sender) {
require(_owner != address(0), "Empty owner address is not allowed!");
owner = _owner;
}
| function setOwner(address _owner) external canSetOwnerAddress(msg.sender) {
require(_owner != address(0), "Empty owner address is not allowed!");
owner = _owner;
}
| 80,022 |
98 | // Here go crowdsale process itself and token manipulations |
function setRate(uint256 _tokensPerEthPrice)
public
onlyOwner
|
function setRate(uint256 _tokensPerEthPrice)
public
onlyOwner
| 46,182 |
28 | // Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed | bool public error = false;
| bool public error = false;
| 30,571 |
36 | // Interface of the ERC3156 FlashLender, as defined in / | interface IERC3156FlashLenderUpgradeable {
/**
* @dev The amount of currency available to be lended.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(
address token
) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(
address token,
uint256 amount
) external view returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
*/
function flashLoan(
IERC3156FlashBorrowerUpgradeable receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
}
| interface IERC3156FlashLenderUpgradeable {
/**
* @dev The amount of currency available to be lended.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(
address token
) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(
address token,
uint256 amount
) external view returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
*/
function flashLoan(
IERC3156FlashBorrowerUpgradeable receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
}
| 33,336 |
138 | // Hook that is called before any transfer of tokens. This includesminting and burning. Calling conditions: - when `from` and `to` are both non-zero, `amount` of ``from``'s tokenswill be to transferred to `to`.- when `from` is zero, `amount` tokens will be minted for `to`.- when `to` is zero, `amount` of ``from``'s tokens will be burned.- `from` and `to` are never both zero. To learn more about hooks, head to xref:ROOT:extending-contracts.adocusing-hooks[Using Hooks]. / | function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
| function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
| 4,883 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.