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
|
---|---|---|---|---|
71 | // If the ruling is "0" the reserved funds of this session become expendable. | reservedETH = reservedETH.subCap(session.sumDeposit);
session.sumDeposit = 0;
shadowWinner = NO_SHADOW_WINNER;
lastApprovalTime = now;
session.status = Status.Resolved;
session.ruling = _ruling;
sessions.length++;
| reservedETH = reservedETH.subCap(session.sumDeposit);
session.sumDeposit = 0;
shadowWinner = NO_SHADOW_WINNER;
lastApprovalTime = now;
session.status = Status.Resolved;
session.ruling = _ruling;
sessions.length++;
| 10,407 |
19 | // get all user todo uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. | /* function getUserList() public view returns(address[]) {
address[] lists;
uint userLength = users.length();
for (uint i = 0; i < userLength; i++) {
address user = users.at(i);
lists.push(user);
}
return lists;
}*/
| /* function getUserList() public view returns(address[]) {
address[] lists;
uint userLength = users.length();
for (uint i = 0; i < userLength; i++) {
address user = users.at(i);
lists.push(user);
}
return lists;
}*/
| 5,003 |
40 | // Swap ERC20 for specific NFTs cost <= maxCost = outputAmount - minOutput, so outputAmount' = outputAmount - cost >= minOutput input tokens are taken directly from msg.sender | outputAmount =
_swapERC20ForSpecificNFTs(
trade.tokenToNFTTrades,
outputAmount - minOutput,
nftRecipient
) +
minOutput;
| outputAmount =
_swapERC20ForSpecificNFTs(
trade.tokenToNFTTrades,
outputAmount - minOutput,
nftRecipient
) +
minOutput;
| 20,876 |
27 | // Implementation of a vault to deposit funds for yield optimizing.This is the contract that receives funds and that users interface with.The yield optimizing strategy itself is implemented in a separate 'Strategy.sol' contract. / | contract BeefyVaultV7 is ERC20Upgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
struct StratCandidate {
address implementation;
uint proposedTime;
}
// The last proposed strategy to switch to.
StratCandidate public stratCandidate;
// The strategy currently in use by the vault.
IStrategyV7 public strategy;
// The minimum time it has to pass before a strat candidate can be approved.
uint256 public approvalDelay;
// The address of the migrator contract
address public migrator;
event NewStratCandidate(address implementation);
event UpgradeStrat(address implementation);
/**
* @dev Sets the value of {token} to the token that the vault will
* hold as underlying value. It initializes the vault's own 'moo' token.
* This token is minted when someone does a deposit. It is burned in order
* to withdraw the corresponding portion of the underlying assets.
* @param _strategy the address of the strategy.
* @param _name the name of the vault token.
* @param _symbol the symbol of the vault token.
* @param _approvalDelay the delay before a new strat can be approved.
* @param _migrator the address of the migrataor contract.
*/
function initialize(
IStrategyV7 _strategy,
string memory _name,
string memory _symbol,
uint256 _approvalDelay,
address _migrator
) public initializer {
__ERC20_init(_name, _symbol);
__Ownable_init();
__ReentrancyGuard_init();
strategy = _strategy;
approvalDelay = _approvalDelay;
migrator = _migrator;
}
function want() public view returns (IERC20Upgradeable) {
return IERC20Upgradeable(strategy.want());
}
/**
* @dev It calculates the total underlying value of {token} held by the system.
* It takes into account the vault contract balance, the strategy contract balance
* and the balance deployed in other contracts as part of the strategy.
*/
function balance() public view returns (uint) {
return want().balanceOf(address(this)) + IStrategyV7(strategy).balanceOf();
}
function balancePrecise() public returns (uint) {
return want().balanceOf(address(this)) + IStrategyV7(strategy).balanceOfPrecise();
}
/**
* @dev Custom logic in here for how much the vault allows to be borrowed.
* We return 100% of tokens for now. Under certain conditions we might
* want to keep some of the system funds at hand in the vault, instead
* of putting them to work.
*/
function available() public view returns (uint256) {
return want().balanceOf(address(this));
}
/**
* @dev Function for various UIs to display the current value of one of our yield tokens.
* Returns an uint256 with 18 decimals of how much underlying asset one vault share represents.
*/
function getPricePerFullShare() public view returns (uint256) {
return totalSupply() == 0 ? 1e18 : balance() * 1e18 / totalSupply();
}
/**
* @dev A helper function to call deposit() with all the sender's funds.
*/
function depositAll() external {
deposit(want().balanceOf(msg.sender));
}
/**
* @dev The entrypoint of funds into the system. People deposit with this function
* into the vault. The vault is then in charge of sending funds into the strategy.
*/
function deposit(uint _amount) public nonReentrant {
_deposit(_amount, msg.sender, msg.sender);
}
/**
* @dev The entrypoint of funds into the system from Migrator contract.
* This is for users who want to migrate funds from one vault to another vault
*/
function migrationDeposit(uint _amount, address _owner) public nonReentrant {
require(msg.sender == migrator, "Only migrator");
_deposit(_amount, migrator, _owner);
}
function _deposit(uint _amount, address _from, address _to) internal {
strategy.beforeDeposit();
uint256 _pool = balancePrecise();
want().safeTransferFrom(_from, address(this), _amount);
earn();
uint256 _after = balancePrecise();
_amount = _after - _pool; // Additional check for deflationary tokens
uint256 shares = 0;
if (totalSupply() == 0) {
shares = _amount;
} else {
shares = (_amount * totalSupply()) / _pool;
}
_mint(_to, shares);
}
/**
* @dev Function to send funds into the strategy and put them to work. It's primarily called
* by the vault's deposit() function.
*/
function earn() public {
uint _bal = available();
want().safeTransfer(address(strategy), _bal);
strategy.deposit();
}
/**
* @dev A helper function to call withdraw() with all the sender's funds.
*/
function withdrawAll() external {
withdraw(balanceOf(msg.sender));
}
/**
* @dev Function to exit the system. The vault will withdraw the required tokens
* from the strategy and pay up the token holder. A proportional number of IOU
* tokens are burned in the process.
*/
function withdraw(uint256 _shares) public {
_withdraw(_shares, msg.sender, msg.sender);
}
/**
* @dev Function to exit the system from Migrator contract.
* This is for users who want to migrate funds from one vault to another vault
*/
function migrationWithdraw(uint256 _shares, address _owner) public returns(uint256 r) {
require(msg.sender == migrator, "Only migrator");
r = _withdraw(_shares, _owner, migrator);
}
function _withdraw(uint256 _shares, address _from, address _to) internal returns(uint256 r) {
r = (balancePrecise() * _shares) / totalSupply();
_burn(_from, _shares);
uint b = want().balanceOf(address(this));
if (b < r) {
uint _withdrawAmount = r - b;
strategy.withdraw(_withdrawAmount);
uint _after = want().balanceOf(address(this));
uint _diff = _after - b;
if (_diff < _withdrawAmount) {
r = b + _diff;
}
}
want().safeTransfer(_to, r);
}
/**
* @dev Sets the candidate for the new strat to use with this vault.
* @param _implementation The address of the candidate strategy.
*/
function proposeStrat(address _implementation) public onlyOwner {
require(address(this) == IStrategyV7(_implementation).vault(), "Proposal not valid for this Vault");
require(want() == IStrategyV7(_implementation).want(), "Different want");
stratCandidate = StratCandidate({
implementation: _implementation,
proposedTime: block.timestamp
});
emit NewStratCandidate(_implementation);
}
/**
* @dev It switches the active strat for the strat candidate. After upgrading, the
* candidate implementation is set to the 0x00 address, and proposedTime to a time
* happening in +100 years for safety.
*/
function upgradeStrat() public onlyOwner {
require(stratCandidate.implementation != address(0), "There is no candidate");
require(stratCandidate.proposedTime + approvalDelay < block.timestamp, "Delay has not passed");
emit UpgradeStrat(stratCandidate.implementation);
strategy.retireStrat();
strategy = IStrategyV7(stratCandidate.implementation);
stratCandidate.implementation = address(0);
stratCandidate.proposedTime = 5000000000;
earn();
}
/**
* @dev Rescues random funds stuck that the strat can't handle.
* @param _token address of the token to rescue.
*/
function inCaseTokensGetStuck(address _token) external onlyOwner {
require(_token != address(want()), "!token");
uint256 amount = IERC20Upgradeable(_token).balanceOf(address(this));
IERC20Upgradeable(_token).safeTransfer(msg.sender, amount);
}
/**
* @dev Changes the address of the migrator contract in case it is upgraded.
* @param _migrator address of the new migrator contract.
*/
function upgradeMigrator(address _migrator) external onlyOwner {
require(_migrator != migrator, "This is the current migrator");
migrator = _migrator;
}
}
| contract BeefyVaultV7 is ERC20Upgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
struct StratCandidate {
address implementation;
uint proposedTime;
}
// The last proposed strategy to switch to.
StratCandidate public stratCandidate;
// The strategy currently in use by the vault.
IStrategyV7 public strategy;
// The minimum time it has to pass before a strat candidate can be approved.
uint256 public approvalDelay;
// The address of the migrator contract
address public migrator;
event NewStratCandidate(address implementation);
event UpgradeStrat(address implementation);
/**
* @dev Sets the value of {token} to the token that the vault will
* hold as underlying value. It initializes the vault's own 'moo' token.
* This token is minted when someone does a deposit. It is burned in order
* to withdraw the corresponding portion of the underlying assets.
* @param _strategy the address of the strategy.
* @param _name the name of the vault token.
* @param _symbol the symbol of the vault token.
* @param _approvalDelay the delay before a new strat can be approved.
* @param _migrator the address of the migrataor contract.
*/
function initialize(
IStrategyV7 _strategy,
string memory _name,
string memory _symbol,
uint256 _approvalDelay,
address _migrator
) public initializer {
__ERC20_init(_name, _symbol);
__Ownable_init();
__ReentrancyGuard_init();
strategy = _strategy;
approvalDelay = _approvalDelay;
migrator = _migrator;
}
function want() public view returns (IERC20Upgradeable) {
return IERC20Upgradeable(strategy.want());
}
/**
* @dev It calculates the total underlying value of {token} held by the system.
* It takes into account the vault contract balance, the strategy contract balance
* and the balance deployed in other contracts as part of the strategy.
*/
function balance() public view returns (uint) {
return want().balanceOf(address(this)) + IStrategyV7(strategy).balanceOf();
}
function balancePrecise() public returns (uint) {
return want().balanceOf(address(this)) + IStrategyV7(strategy).balanceOfPrecise();
}
/**
* @dev Custom logic in here for how much the vault allows to be borrowed.
* We return 100% of tokens for now. Under certain conditions we might
* want to keep some of the system funds at hand in the vault, instead
* of putting them to work.
*/
function available() public view returns (uint256) {
return want().balanceOf(address(this));
}
/**
* @dev Function for various UIs to display the current value of one of our yield tokens.
* Returns an uint256 with 18 decimals of how much underlying asset one vault share represents.
*/
function getPricePerFullShare() public view returns (uint256) {
return totalSupply() == 0 ? 1e18 : balance() * 1e18 / totalSupply();
}
/**
* @dev A helper function to call deposit() with all the sender's funds.
*/
function depositAll() external {
deposit(want().balanceOf(msg.sender));
}
/**
* @dev The entrypoint of funds into the system. People deposit with this function
* into the vault. The vault is then in charge of sending funds into the strategy.
*/
function deposit(uint _amount) public nonReentrant {
_deposit(_amount, msg.sender, msg.sender);
}
/**
* @dev The entrypoint of funds into the system from Migrator contract.
* This is for users who want to migrate funds from one vault to another vault
*/
function migrationDeposit(uint _amount, address _owner) public nonReentrant {
require(msg.sender == migrator, "Only migrator");
_deposit(_amount, migrator, _owner);
}
function _deposit(uint _amount, address _from, address _to) internal {
strategy.beforeDeposit();
uint256 _pool = balancePrecise();
want().safeTransferFrom(_from, address(this), _amount);
earn();
uint256 _after = balancePrecise();
_amount = _after - _pool; // Additional check for deflationary tokens
uint256 shares = 0;
if (totalSupply() == 0) {
shares = _amount;
} else {
shares = (_amount * totalSupply()) / _pool;
}
_mint(_to, shares);
}
/**
* @dev Function to send funds into the strategy and put them to work. It's primarily called
* by the vault's deposit() function.
*/
function earn() public {
uint _bal = available();
want().safeTransfer(address(strategy), _bal);
strategy.deposit();
}
/**
* @dev A helper function to call withdraw() with all the sender's funds.
*/
function withdrawAll() external {
withdraw(balanceOf(msg.sender));
}
/**
* @dev Function to exit the system. The vault will withdraw the required tokens
* from the strategy and pay up the token holder. A proportional number of IOU
* tokens are burned in the process.
*/
function withdraw(uint256 _shares) public {
_withdraw(_shares, msg.sender, msg.sender);
}
/**
* @dev Function to exit the system from Migrator contract.
* This is for users who want to migrate funds from one vault to another vault
*/
function migrationWithdraw(uint256 _shares, address _owner) public returns(uint256 r) {
require(msg.sender == migrator, "Only migrator");
r = _withdraw(_shares, _owner, migrator);
}
function _withdraw(uint256 _shares, address _from, address _to) internal returns(uint256 r) {
r = (balancePrecise() * _shares) / totalSupply();
_burn(_from, _shares);
uint b = want().balanceOf(address(this));
if (b < r) {
uint _withdrawAmount = r - b;
strategy.withdraw(_withdrawAmount);
uint _after = want().balanceOf(address(this));
uint _diff = _after - b;
if (_diff < _withdrawAmount) {
r = b + _diff;
}
}
want().safeTransfer(_to, r);
}
/**
* @dev Sets the candidate for the new strat to use with this vault.
* @param _implementation The address of the candidate strategy.
*/
function proposeStrat(address _implementation) public onlyOwner {
require(address(this) == IStrategyV7(_implementation).vault(), "Proposal not valid for this Vault");
require(want() == IStrategyV7(_implementation).want(), "Different want");
stratCandidate = StratCandidate({
implementation: _implementation,
proposedTime: block.timestamp
});
emit NewStratCandidate(_implementation);
}
/**
* @dev It switches the active strat for the strat candidate. After upgrading, the
* candidate implementation is set to the 0x00 address, and proposedTime to a time
* happening in +100 years for safety.
*/
function upgradeStrat() public onlyOwner {
require(stratCandidate.implementation != address(0), "There is no candidate");
require(stratCandidate.proposedTime + approvalDelay < block.timestamp, "Delay has not passed");
emit UpgradeStrat(stratCandidate.implementation);
strategy.retireStrat();
strategy = IStrategyV7(stratCandidate.implementation);
stratCandidate.implementation = address(0);
stratCandidate.proposedTime = 5000000000;
earn();
}
/**
* @dev Rescues random funds stuck that the strat can't handle.
* @param _token address of the token to rescue.
*/
function inCaseTokensGetStuck(address _token) external onlyOwner {
require(_token != address(want()), "!token");
uint256 amount = IERC20Upgradeable(_token).balanceOf(address(this));
IERC20Upgradeable(_token).safeTransfer(msg.sender, amount);
}
/**
* @dev Changes the address of the migrator contract in case it is upgraded.
* @param _migrator address of the new migrator contract.
*/
function upgradeMigrator(address _migrator) external onlyOwner {
require(_migrator != migrator, "This is the current migrator");
migrator = _migrator;
}
}
| 20,048 |
4 | // Auto-generated via 'PrintWeightFactors.py' | uint256 private constant MAX_UNF_WEIGHT = 0x10c6f7a0b5ed8d36b4c7f34938583621fafc8b0079a2834d26fa3fcc9ea9;
| uint256 private constant MAX_UNF_WEIGHT = 0x10c6f7a0b5ed8d36b4c7f34938583621fafc8b0079a2834d26fa3fcc9ea9;
| 10,490 |
383 | // Opens compound positions with a leverage | contract CompoundCreateTaker is ProxyPermission {
using SafeERC20 for ERC20;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateInfo {
address cCollAddress;
address cBorrowAddress;
uint depositAmount;
}
/// @notice Main function which will take a FL and open a leverage position
/// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy
/// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount]
/// @param _exchangeData Exchange data struct
function openLeveragedLoan(
CreateInfo memory _createInfo,
DFSExchangeData.ExchangeData memory _exchangeData,
address payable _compReceiver
) public payable {
uint loanAmount = _exchangeData.srcAmount;
// Pull tokens from user
if (_exchangeData.destAddr != ETH_ADDRESS) {
ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount);
} else {
require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth");
}
// Send tokens to FL receiver
sendDeposit(_compReceiver, _exchangeData.destAddr);
bytes memory paramsData = abi.encode(_createInfo, _exchangeData, address(this));
givePermission(_compReceiver);
lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData);
removePermission(_compReceiver);
logger.Log(address(this), msg.sender, "CompoundLeveragedLoan",
abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount));
}
function sendDeposit(address payable _compoundReceiver, address _token) internal {
if (_token != ETH_ADDRESS) {
ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this)));
}
_compoundReceiver.transfer(address(this).balance);
}
}
| contract CompoundCreateTaker is ProxyPermission {
using SafeERC20 for ERC20;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateInfo {
address cCollAddress;
address cBorrowAddress;
uint depositAmount;
}
/// @notice Main function which will take a FL and open a leverage position
/// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy
/// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount]
/// @param _exchangeData Exchange data struct
function openLeveragedLoan(
CreateInfo memory _createInfo,
DFSExchangeData.ExchangeData memory _exchangeData,
address payable _compReceiver
) public payable {
uint loanAmount = _exchangeData.srcAmount;
// Pull tokens from user
if (_exchangeData.destAddr != ETH_ADDRESS) {
ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount);
} else {
require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth");
}
// Send tokens to FL receiver
sendDeposit(_compReceiver, _exchangeData.destAddr);
bytes memory paramsData = abi.encode(_createInfo, _exchangeData, address(this));
givePermission(_compReceiver);
lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData);
removePermission(_compReceiver);
logger.Log(address(this), msg.sender, "CompoundLeveragedLoan",
abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount));
}
function sendDeposit(address payable _compoundReceiver, address _token) internal {
if (_token != ETH_ADDRESS) {
ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this)));
}
_compoundReceiver.transfer(address(this).balance);
}
}
| 63,277 |
117 | // cancelEscape(): for _point, stop the current escape request, if any | function cancelEscape(uint32 _point)
onlyOwner
external
| function cancelEscape(uint32 _point)
onlyOwner
external
| 19,541 |
45 | // allows resolvers to send withdrawal amounts 'to' addresses via arbitrary smart contracts | function withdrawSnowflakeBalanceFromVia(
uint einFrom, address via, address payable to, uint amount, bytes memory _bytes
)
public
| function withdrawSnowflakeBalanceFromVia(
uint einFrom, address via, address payable to, uint amount, bytes memory _bytes
)
public
| 13,209 |
261 | // Emitted when a new MOAR speed is set for a contributor | event ContributorMoarSpeedUpdated(address indexed contributor, uint newSpeed);
| event ContributorMoarSpeedUpdated(address indexed contributor, uint newSpeed);
| 32,631 |
186 | // oracle query builder/ | string constant private queryString1 = "[identity] ";
| string constant private queryString1 = "[identity] ";
| 42,042 |
237 | // Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} isused, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1. Calling conditions: - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.- When `from` is zero, the tokens will be minted for `to`.- When `to` is zero, ``from``'s tokens will be burned.- `from` and `to` are never both zero.- `batchSize` is non-zero. To learn more about hooks, head to xref:ROOT:extending-contracts.adocusing-hooks[Using Hooks]. / | function _beforeTokenTransfer(
address from,
address to,
uint256 /* firstTokenId */,
uint256 batchSize
) internal virtual {
if (batchSize > 1) {
if (from != address(0)) {
_balances[from] -= batchSize;
}
| function _beforeTokenTransfer(
address from,
address to,
uint256 /* firstTokenId */,
uint256 batchSize
) internal virtual {
if (batchSize > 1) {
if (from != address(0)) {
_balances[from] -= batchSize;
}
| 29,699 |
139 | // transfer money to the owner! | function _transferOrderMoney(uint _price, address _owner)
| function _transferOrderMoney(uint _price, address _owner)
| 43,048 |
204 | // GB HOLDERS EARLY ACCESS TOKENS | uint256 public constant gbHoldersMaxMint = 900;
mapping(address => bool) public gbholders;
address public GB_erc20_contract;
uint256[] private _gbTokenSupply;
| uint256 public constant gbHoldersMaxMint = 900;
mapping(address => bool) public gbholders;
address public GB_erc20_contract;
uint256[] private _gbTokenSupply;
| 23,195 |
78 | // function createERC721Offer( address _tokenContract, uint256 _tokenId, uint256 _price, bool _isNative | // ) external nonReentrant {
// require(_price > 0, "Price must be greater than 0");
// require(
// IERC721(_tokenContract).ownerOf(_tokenId) != msg.sender,
// "Can't make offer on your own token"
// );
// require(
// IERC721(_tokenContract).getApproved(_tokenId) == address(this),
// "Contract must be approved to transfer token"
// );
// offers[nextOfferId] = Offer(nextOfferId, msg.sender, true, _isNative);
// if (_isNative) {
// // transfer _price from msg.sender to the contract
// require(
// address(msg.sender).balance >= _price,
// "Not enough balance to make offer"
// );
// payable(address(this)).transfer(_price);
// } else {
// // transfer _price from msg.sender to the contract
// require(
// IERC20(MTVT).balanceOf(msg.sender) >= _price,
// "Not enough balance to make offer"
// );
// require(
// IERC20(MTVT).allowance(msg.sender, address(this)) >= _price,
// "Not enough allowance to make offer"
// );
// IERC20(MTVT).transferFrom(msg.sender, address(this), _price);
// }
// erc721Offers[nextOfferId] = ERC721Offer(
// nextOfferId,
// IERC721(_tokenContract).ownerOf(_tokenId),
// msg.sender,
// _tokenContract,
// _tokenId,
// _price,
// _isNative
// );
// emit ERC721OfferCreated(
// nextOfferId,
// IERC721(_tokenContract).ownerOf(_tokenId),
// msg.sender,
// _tokenContract,
// _tokenId,
// _price,
// _isNative
// );
// nextOfferId = nextOfferId.add(1);
// }
| // ) external nonReentrant {
// require(_price > 0, "Price must be greater than 0");
// require(
// IERC721(_tokenContract).ownerOf(_tokenId) != msg.sender,
// "Can't make offer on your own token"
// );
// require(
// IERC721(_tokenContract).getApproved(_tokenId) == address(this),
// "Contract must be approved to transfer token"
// );
// offers[nextOfferId] = Offer(nextOfferId, msg.sender, true, _isNative);
// if (_isNative) {
// // transfer _price from msg.sender to the contract
// require(
// address(msg.sender).balance >= _price,
// "Not enough balance to make offer"
// );
// payable(address(this)).transfer(_price);
// } else {
// // transfer _price from msg.sender to the contract
// require(
// IERC20(MTVT).balanceOf(msg.sender) >= _price,
// "Not enough balance to make offer"
// );
// require(
// IERC20(MTVT).allowance(msg.sender, address(this)) >= _price,
// "Not enough allowance to make offer"
// );
// IERC20(MTVT).transferFrom(msg.sender, address(this), _price);
// }
// erc721Offers[nextOfferId] = ERC721Offer(
// nextOfferId,
// IERC721(_tokenContract).ownerOf(_tokenId),
// msg.sender,
// _tokenContract,
// _tokenId,
// _price,
// _isNative
// );
// emit ERC721OfferCreated(
// nextOfferId,
// IERC721(_tokenContract).ownerOf(_tokenId),
// msg.sender,
// _tokenContract,
// _tokenId,
// _price,
// _isNative
// );
// nextOfferId = nextOfferId.add(1);
// }
| 3,919 |
153 | // Remaining tokens third party spender has to send/self Stored token from token contract/_owner Address of token holder/_spender Address of authorized spender/ return remaining Number of tokens spender has left in owner's account | function allowance(TokenStorage storage self, address _owner, address _spender)
public
view
| function allowance(TokenStorage storage self, address _owner, address _spender)
public
view
| 65,326 |
71 | // conduct transfer from Luxarity to address | transferFrom(msg.sender, _buyerAddress, _tokenId);
| transferFrom(msg.sender, _buyerAddress, _tokenId);
| 39,974 |
40 | // EXCHANGES | address private m_UniswapV2Pair;
IUniswapV2Router02 private m_UniswapV2Router;
| address private m_UniswapV2Pair;
IUniswapV2Router02 private m_UniswapV2Router;
| 22,146 |
22 | // add new stake | _newDeposit(address(little), _amount);
| _newDeposit(address(little), _amount);
| 65,279 |
103 | // Ensure the sEUR synth can write to its TokenState; | tokenstateseur_i.setAssociatedContract(new_SynthsEUR_contract);
| tokenstateseur_i.setAssociatedContract(new_SynthsEUR_contract);
| 22,597 |
91 | // function that allows a token owner to claim tokens for himselfif there is some free tokens they will be sent out of the vesting contract to the owner wallet / | function claim() external override {
claimFor(msg.sender);
}
| function claim() external override {
claimFor(msg.sender);
}
| 44,381 |
5 | // Function to access decimals of token. | function decimals() constant public returns (uint8 _decimals) {
return decimals;
}
| function decimals() constant public returns (uint8 _decimals) {
return decimals;
}
| 75,454 |
194 | // Then scale that accumulated interest by the old interest index to get the new interest index | (Error err3, Exp memory newInterestIndexExp) = mulScalar(
onePlusBlocksTimesRate,
startingInterestIndex
);
if (err3 != Error.NO_ERROR) {
return (err3, 0);
}
| (Error err3, Exp memory newInterestIndexExp) = mulScalar(
onePlusBlocksTimesRate,
startingInterestIndex
);
if (err3 != Error.NO_ERROR) {
return (err3, 0);
}
| 74,046 |
116 | // Override unpause so it requires all external contract addresses/to be set before contract can be unpaused. Also, we can't have/newContractAddress set either, because then the contract was upgraded./This is public rather than external so we can call super.unpause/without using an expensive CALL. | function unpause() public onlyCEO whenPaused {
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
| function unpause() public onlyCEO whenPaused {
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
| 30,790 |
94 | // Emitted if total supply exceeds maximum expected supply / | event WarningMaxExpectedSupplyExceeded(uint256 totalSupply, uint256 totalShares);
address public supplyController;
uint256 private MAX_UINT256;
| event WarningMaxExpectedSupplyExceeded(uint256 totalSupply, uint256 totalShares);
address public supplyController;
uint256 private MAX_UINT256;
| 51,360 |
13 | // – unlocks a user's bonded deposits from a claim.superblockHash – claim id.account – user's address. return – user's deposit which was unbonded from the claim. | function unbondDeposit(bytes32 superblockHash, address account) internal returns (uint, uint) {
SuperblockClaim storage claim = claims[superblockHash];
if (!claimExists(claim)) {
return (ERR_SUPERBLOCK_BAD_CLAIM, 0);
}
if (!claim.decided) {
return (ERR_SUPERBLOCK_BAD_STATUS, 0);
}
uint bondedDeposit = claim.bondedDeposits[account];
delete claim.bondedDeposits[account];
deposits[account] = deposits[account].add(bondedDeposit);
emit DepositUnbonded(superblockHash, account, bondedDeposit);
return (ERR_SUPERBLOCK_OK, bondedDeposit);
}
| function unbondDeposit(bytes32 superblockHash, address account) internal returns (uint, uint) {
SuperblockClaim storage claim = claims[superblockHash];
if (!claimExists(claim)) {
return (ERR_SUPERBLOCK_BAD_CLAIM, 0);
}
if (!claim.decided) {
return (ERR_SUPERBLOCK_BAD_STATUS, 0);
}
uint bondedDeposit = claim.bondedDeposits[account];
delete claim.bondedDeposits[account];
deposits[account] = deposits[account].add(bondedDeposit);
emit DepositUnbonded(superblockHash, account, bondedDeposit);
return (ERR_SUPERBLOCK_OK, bondedDeposit);
}
| 36,586 |
11 | // True if deposit is enabled. | bool public vaultDepositEnabled;
| bool public vaultDepositEnabled;
| 8,392 |
97 | // Emit the event | emit RegisterCreator(account, resultAssets[i]);
| emit RegisterCreator(account, resultAssets[i]);
| 75,555 |
44 | // overriding CrowdsalebuyTokens to add partial refund logic | function buyTokens(address beneficiary) public payable {
uint256 weiToCap = cap.sub(weiRaised);
uint256 weiAmount = weiToCap < msg.value ? weiToCap : msg.value;
buyTokens(beneficiary, weiAmount);
uint256 refund = msg.value.sub(weiAmount);
if (refund > 0) {
msg.sender.transfer(refund);
}
}
| function buyTokens(address beneficiary) public payable {
uint256 weiToCap = cap.sub(weiRaised);
uint256 weiAmount = weiToCap < msg.value ? weiToCap : msg.value;
buyTokens(beneficiary, weiAmount);
uint256 refund = msg.value.sub(weiAmount);
if (refund > 0) {
msg.sender.transfer(refund);
}
}
| 42,026 |
835 | // Ensure the Exchanger contract can suspend synths - see SIP-65; | systemstatus_i.updateAccessControl("Synth", new_Exchanger_contract, true, false);
| systemstatus_i.updateAccessControl("Synth", new_Exchanger_contract, true, false);
| 29,653 |
6 | // Used by asset plugins to price their collateral | library OracleLib {
/// @dev Use for on-the-fly calculations that should revert
/// @param timeout The number of seconds after which oracle values should be considered stale
/// @return {UoA/tok}
function price(AggregatorV3Interface chainlinkFeed, uint48 timeout)
internal
view
returns (uint192)
{
(uint80 roundId, int256 p, , uint256 updateTime, uint80 answeredInRound) = chainlinkFeed
.latestRoundData();
if (updateTime == 0 || answeredInRound < roundId) {
revert StalePrice();
}
// Downcast is safe: uint256(-) reverts on underflow; block.timestamp assumed < 2^48
uint48 secondsSince = uint48(block.timestamp - updateTime);
if (secondsSince > timeout) revert StalePrice();
// {UoA/tok}
uint192 scaledPrice = shiftl_toFix(uint256(p), -int8(chainlinkFeed.decimals()));
if (scaledPrice == 0) revert PriceOutsideRange();
return scaledPrice;
}
/// @dev Use when a try-catch is necessary
/// @param timeout The number of seconds after which oracle values should be considered stale
/// @return {UoA/tok}
function price_(AggregatorV3Interface chainlinkFeed, uint48 timeout)
external
view
returns (uint192)
{
return price(chainlinkFeed, timeout);
}
}
| library OracleLib {
/// @dev Use for on-the-fly calculations that should revert
/// @param timeout The number of seconds after which oracle values should be considered stale
/// @return {UoA/tok}
function price(AggregatorV3Interface chainlinkFeed, uint48 timeout)
internal
view
returns (uint192)
{
(uint80 roundId, int256 p, , uint256 updateTime, uint80 answeredInRound) = chainlinkFeed
.latestRoundData();
if (updateTime == 0 || answeredInRound < roundId) {
revert StalePrice();
}
// Downcast is safe: uint256(-) reverts on underflow; block.timestamp assumed < 2^48
uint48 secondsSince = uint48(block.timestamp - updateTime);
if (secondsSince > timeout) revert StalePrice();
// {UoA/tok}
uint192 scaledPrice = shiftl_toFix(uint256(p), -int8(chainlinkFeed.decimals()));
if (scaledPrice == 0) revert PriceOutsideRange();
return scaledPrice;
}
/// @dev Use when a try-catch is necessary
/// @param timeout The number of seconds after which oracle values should be considered stale
/// @return {UoA/tok}
function price_(AggregatorV3Interface chainlinkFeed, uint48 timeout)
external
view
returns (uint192)
{
return price(chainlinkFeed, timeout);
}
}
| 38,694 |
72 | // The accrued but not yet transferred to account | uint accruedAmount;
| uint accruedAmount;
| 38,926 |
10 | // Adds `newAdmin` as an admin of the contract Can only be called by the current owner or an admin newAdmin A new admin of the contract / | function addAdmin(address newAdmin) public virtual onlyOwnerOrAdmin {
admins[newAdmin] = true;
emit AdminAdded(msg.sender, newAdmin);
}
| function addAdmin(address newAdmin) public virtual onlyOwnerOrAdmin {
admins[newAdmin] = true;
emit AdminAdded(msg.sender, newAdmin);
}
| 2,371 |
3 | // Process meta txs batch / | function processMetaBatch(address[] memory senders,
address[] memory recipients,
uint256[] memory amounts,
uint256[] memory relayerFees,
uint256[] memory blocks,
uint8[] memory sigV,
bytes32[] memory sigR,
| function processMetaBatch(address[] memory senders,
address[] memory recipients,
uint256[] memory amounts,
uint256[] memory relayerFees,
uint256[] memory blocks,
uint8[] memory sigV,
bytes32[] memory sigR,
| 50,924 |
35 | // withdraw released multiplier balance.---------------------------------------- amount --> the amount to be withdrawn.-------------------------------------------returns whether successfully withdrawn or not. / | function withdraw(uint256 amount) external returns (bool) {
require(amount > 0, "amount must be larger than zero");
require(getUserMultiplierBalance(msg.sender) >= amount, "must have a sufficient balance");
require(checkForReleasedBalance(now, msg.sender), "balance must be released");
_users[msg.sender].multiplierBalance = getUserMultiplierBalance(msg.sender).sub(amount);
require(_token.transfer(msg.sender, amount), "token transfer failed");
emit Withdrawn(msg.sender, amount, now);
return true;
}
| function withdraw(uint256 amount) external returns (bool) {
require(amount > 0, "amount must be larger than zero");
require(getUserMultiplierBalance(msg.sender) >= amount, "must have a sufficient balance");
require(checkForReleasedBalance(now, msg.sender), "balance must be released");
_users[msg.sender].multiplierBalance = getUserMultiplierBalance(msg.sender).sub(amount);
require(_token.transfer(msg.sender, amount), "token transfer failed");
emit Withdrawn(msg.sender, amount, now);
return true;
}
| 3,559 |
216 | // credit founder developer fee |
propertyBalanceLedger_[0x676c6f62616c0000000000000000000000000000000000000000000000000000][_commissionFounderDeveloper]
+= (_amountOfTokens * 1000) / _founderDeveloperFee;
tokenBalanceLedger_[_commissionFounderDeveloper]
= tokenBalanceLedger_[_commissionFounderDeveloper] + (_amountOfTokens * 1000) / _founderDeveloperFee;
|
propertyBalanceLedger_[0x676c6f62616c0000000000000000000000000000000000000000000000000000][_commissionFounderDeveloper]
+= (_amountOfTokens * 1000) / _founderDeveloperFee;
tokenBalanceLedger_[_commissionFounderDeveloper]
= tokenBalanceLedger_[_commissionFounderDeveloper] + (_amountOfTokens * 1000) / _founderDeveloperFee;
| 15,247 |
52 | // The baselineGrossCLBalance represents the expected growth of our validators balance in the new period given no slashings, no rewards, etc. It's used as the baseline in our upper (growth) and lower (loss) bounds calculations. | uint256 baselineGrossCLBalance = prevRecord.currentTotalValidatorBalance
+ (newRecord.cumulativeProcessedDepositAmount - prevRecord.cumulativeProcessedDepositAmount);
| uint256 baselineGrossCLBalance = prevRecord.currentTotalValidatorBalance
+ (newRecord.cumulativeProcessedDepositAmount - prevRecord.cumulativeProcessedDepositAmount);
| 35,585 |
13 | // All dice Dice 1 | if (_diceMetadata.amount >= 1) {
attributes = string(
abi.encodePacked(
attributes,
'{"trait_type":"dice ',
"1",
' type","value":"',
DiceBitmapUtil.getDiceType(_diceMetadata.bitmap, 0).toString(),
'"},{"trait_type":"dice ',
| if (_diceMetadata.amount >= 1) {
attributes = string(
abi.encodePacked(
attributes,
'{"trait_type":"dice ',
"1",
' type","value":"',
DiceBitmapUtil.getDiceType(_diceMetadata.bitmap, 0).toString(),
'"},{"trait_type":"dice ',
| 9,171 |
9 | // eth variables | address constant wbnb= 0xd00ae08403B9bbb9124bB305C09058E32C39A48c;
address constant cakeFactory = 0xE4A575550C2b460d2307b82dCd7aFe84AD1484dd;
address payable private administrator;
address private sandwichRouter = 0xE046C03b6C39149F2e9811Ee567A4e2a47010278;
uint private wbnbIn;
uint private minTknOut;
address private tokenToBuy;
address private tokenPaired;
bool private snipeLock;
| address constant wbnb= 0xd00ae08403B9bbb9124bB305C09058E32C39A48c;
address constant cakeFactory = 0xE4A575550C2b460d2307b82dCd7aFe84AD1484dd;
address payable private administrator;
address private sandwichRouter = 0xE046C03b6C39149F2e9811Ee567A4e2a47010278;
uint private wbnbIn;
uint private minTknOut;
address private tokenToBuy;
address private tokenPaired;
bool private snipeLock;
| 748 |
2 | // increase nonce | randNonce++;
return uint(keccak256(abi.encodePacked(now,
msg.sender,
randNonce))) % _modulus;
| randNonce++;
return uint(keccak256(abi.encodePacked(now,
msg.sender,
randNonce))) % _modulus;
| 17,583 |
79 | // stop destroy | if(_tFeeTotal >= _maxDestroyAmount) return;
_balances[deadAddress] = _balances[deadAddress].add(tAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
emit Transfer(sender, deadAddress, tAmount);
| if(_tFeeTotal >= _maxDestroyAmount) return;
_balances[deadAddress] = _balances[deadAddress].add(tAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
emit Transfer(sender, deadAddress, tAmount);
| 32,022 |
173 | // UNITS | modifier contains (string memory what, string memory where) {
bytes memory whatBytes = bytes (what);
bytes memory whereBytes = bytes (where);
uint256 found = 0;
for (uint i = 0; i < whereBytes.length - whatBytes.length; i++) {
bool flag = true;
for (uint j = 0; j < whatBytes.length; j++)
if (whereBytes [i + j] != whatBytes [j]) {
flag = false;
break;
}
if (flag) {
found = 1;
break;
}
}
require (found == 1);
_;
}
| modifier contains (string memory what, string memory where) {
bytes memory whatBytes = bytes (what);
bytes memory whereBytes = bytes (where);
uint256 found = 0;
for (uint i = 0; i < whereBytes.length - whatBytes.length; i++) {
bool flag = true;
for (uint j = 0; j < whatBytes.length; j++)
if (whereBytes [i + j] != whatBytes [j]) {
flag = false;
break;
}
if (flag) {
found = 1;
break;
}
}
require (found == 1);
_;
}
| 40,920 |
18 | // Check if recipient is frozen | require(!frozenAccount[_to]);
| require(!frozenAccount[_to]);
| 2,596 |
8 | // TODO: add to check that allowance is enough | stakingToken.transferFrom(msg.sender, address(this), _amount);
| stakingToken.transferFrom(msg.sender, address(this), _amount);
| 25,300 |
3 | // uint _id = KryptoBirdz.push(_kpyptoBird);only works in complier version 4 because push no longer return length | kryptoBirdz.push(_kpyptoBird);
uint _id = kryptoBirdz.length - 1;
_mint(msg.sender, _id);
| kryptoBirdz.push(_kpyptoBird);
uint _id = kryptoBirdz.length - 1;
_mint(msg.sender, _id);
| 6,996 |
17 | // Minimium amount of collateral that user wants to redeem (anti-slippage) | uint256 minCollateral;
| uint256 minCollateral;
| 45,572 |
15 | // Interest rate state of each position | mapping(address position => PositionIRS) private _positionIRS;
/*//////////////////////////////////////////////////////////////
EVENTS
| mapping(address position => PositionIRS) private _positionIRS;
/*//////////////////////////////////////////////////////////////
EVENTS
| 26,530 |
104 | // Removed the subscriber from the whitelist. subscriber The subscriber to remove from the whitelist. / | function removeFromWhitelist(address subscriber) external onlyOwner beforeEnd {
removeFromWhitelistInternal(subscriber, balanceOf[subscriber]);
}
| function removeFromWhitelist(address subscriber) external onlyOwner beforeEnd {
removeFromWhitelistInternal(subscriber, balanceOf[subscriber]);
}
| 19,233 |
26 | // totalSupply : Display total supply of token / | function totalSupply()
public
virtual
override
view
returns (uint)
| function totalSupply()
public
virtual
override
view
returns (uint)
| 47,935 |
34 | // Used for getting the actual options prices amountIn Option amount amountOut Strike price of the option currentOut current price of the optionreturn total Total price to be paid / | function fees(uint amountIn, uint amountOut, uint currentOut) external pure returns (uint) {
return getPeriodFee(amountIn, amountOut, currentOut)
.add(getStrikeFee(amountIn, amountOut, currentOut))
.add(getSettlementFee(amountIn));
}
| function fees(uint amountIn, uint amountOut, uint currentOut) external pure returns (uint) {
return getPeriodFee(amountIn, amountOut, currentOut)
.add(getStrikeFee(amountIn, amountOut, currentOut))
.add(getSettlementFee(amountIn));
}
| 45,021 |
49 | // Return the contract which implements the IModelCalculator interface. / | function getModelCalculator() public view returns (IModelCalculator) {
return IModelCalculator(getContractAddress(_IModelCalculator_));
}
| function getModelCalculator() public view returns (IModelCalculator) {
return IModelCalculator(getContractAddress(_IModelCalculator_));
}
| 13,607 |
36 | // add bonus to community tokens | communityTokenAmount = communityTokenAmount.add(bonusTokenAmount);
| communityTokenAmount = communityTokenAmount.add(bonusTokenAmount);
| 4,368 |
200 | // Standard functions to be overridden | function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721,
| function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721,
| 19,430 |
0 | // use safemath | using SafeMath for uint256;
using SafeMath32 for uint32;
using SafeMath16 for uint16;
| using SafeMath for uint256;
using SafeMath32 for uint32;
using SafeMath16 for uint16;
| 52,075 |
1 | // Mint tokens / | function _curvedMint() internal returns (uint256) {
require(msg.value > 0);
super._curvedMint(msg.value);
poolBalance_ = poolBalance_.add(msg.value);
}
| function _curvedMint() internal returns (uint256) {
require(msg.value > 0);
super._curvedMint(msg.value);
poolBalance_ = poolBalance_.add(msg.value);
}
| 13,898 |
52 | // Transfer token for a specified addressesfrom The address to transfer from.to The address to transfer to.value The amount to be transferred./ | function _transfer(address from, address to, uint256 value) internal {
require(from != address(0));
require(to != address(0));
require(value <= _balances[from]);
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
| function _transfer(address from, address to, uint256 value) internal {
require(from != address(0));
require(to != address(0));
require(value <= _balances[from]);
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
| 8,668 |
8 | // Pool specification library. Library for defining, querying, and encoding the specifications of theparameters of a pool type. / | library PoolSpecs {
/* @notice Specifcations of the parameters of a single pool type. Any given pair
* may have many different pool types, each of which may operate as segmented
* markets with different underlying behavior to the AMM.
*
* @param schema_ Placeholder that defines the structure of the poolSpecs object in
* in storage. Because slots initialize zero, 0 is used for an
* unitialized or disabled pool. 1 is the only currently used schema
* (for the below struct), but allows for upgradeability in the future
*
* @param feeRate_ The overall fee (liquidity fees + protocol fees inclusive) that
* swappers pay to the pool as a fraction of notional. Represented as an
* integer representing hundredths of a basis point. I.e. a 0.25% fee
* would be 2500
*
* @param protocolTake_ The fraction of the fee rate that goes to the protocol fee
* (the rest accumulates as a liquidity fee to LPs). Represented in units
* of 1/256. Since uint8 can represent up to 255, protocol could take
* as much as 99.6% of liquidity fees. However currently the protocol
* set function prohibits values above 128, i.e. 50% of liquidity fees.
* (See set ProtocolTakeRate in PoolRegistry.sol)
*
* @param tickSize The minimum granularity of price ticks defining a grid, on which
* range orders may be placed. (Outside off-grid price improvement facility.)
* For example a value of 50 would mean that range order bounds could only
* be placed on every 50th price tick, guaranteeing a minimum separation of
* 0.005% (50 one basis point ticks) between bump points.
*
* @param jitThresh_ Sets the minimum TTL for concentrated LP positions in the pool.
* Represented in units of 10 seconds (as measured by block time)
* E.g. a value of 5 equates to a minimum TTL of 50 seconds.
* Attempts to burn or partially burn an LP position in less than
* N seconds (as measured in block.timestamp) after a position was
* minted (or had its liquidity increased) will revert. If set to
* 0, atomically flashed liquidity that mints->burns in the same
* block is enabled.
*
* @param knockoutBits_ Defines the parameters for where and how knockout liquidity
* is allowed in the pool. (See KnockoutLiq library for a full
* description of the bit field.)
*
* @param oracleFlags_ Bitmap flags to indicate the pool's oracle permission
* requirements. Current implementation only uses the least
* significant bit, which if on checks oracle permission on every
* pool related call. Otherwise pool is permissionless. */
struct Pool {
uint8 schema_;
uint16 feeRate_;
uint8 protocolTake_;
uint16 tickSize_;
uint8 jitThresh_;
uint8 knockoutBits_;
uint8 oracleFlags_;
}
uint8 constant BASE_SCHEMA = 1;
uint8 constant DISABLED_SCHEMA = 0;
/* @notice Convenience struct that's used to gather all useful context about on a
* specific pool.
* @param head_ The full specification for the pool. (See struct Pool comments above.)
* @param hash_ The keccak256 hash used to encode the full pool location.
* @param oracle_ The permission oracle associated with this pool (0 if pool is
* permissionless.) */
struct PoolCursor {
Pool head_;
bytes32 hash_;
address oracle_;
}
/* @notice Given a mapping of pools, a base/quote token pair and a pool type index,
* copies the pool specification to memory. */
function queryPool (mapping(bytes32 => Pool) storage pools,
address tokenX, address tokenY, uint256 poolIdx)
internal view returns (PoolCursor memory specs) {
bytes32 key = encodeKey(tokenX, tokenY, poolIdx);
Pool memory pool = pools[key];
address oracle = oracleForPool(poolIdx, pool.oracleFlags_);
return PoolCursor ({head_: pool, hash_: key, oracle_: oracle});
}
/* @notice Given a mapping of pools, a base/quote token pair and a pool type index,
* retrieves a storage reference to the pool specification. */
function selectPool (mapping(bytes32 => Pool) storage pools,
address tokenX, address tokenY, uint256 poolIdx)
internal view returns (Pool storage specs) {
bytes32 key = encodeKey(tokenX, tokenY, poolIdx);
return pools[key];
}
/* @notice Writes a pool specification for a pair and pool type combination. */
function writePool (mapping(bytes32 => Pool) storage pools,
address tokenX, address tokenY, uint256 poolIdx,
Pool memory val) internal {
bytes32 key = encodeKey(tokenX, tokenY, poolIdx);
pools[key] = val;
}
/* @notice Hashes the key associated with a pool for a base/quote asset pair and
* a specific pool type index. */
function encodeKey (address tokenX, address tokenY, uint256 poolIdx)
internal pure returns (bytes32) {
require(tokenX < tokenY);
return keccak256(abi.encode(tokenX, tokenY, poolIdx));
}
/* @notice Returns the permission oracle associated with the pool (or 0 if pool is
* permissionless.
*
* @dev The oracle (if enabled on pool settings) is always deterministically based
* on the first 160-bits of the pool type value. This means users can know
* ahead of time if a pool can be oracled by checking the bits in the pool
* index. */
function oracleForPool (uint256 poolIdx, uint8 oracleFlags)
internal pure returns (address) {
uint8 ORACLE_ENABLED_MASK = 0x1;
bool oracleEnabled = (oracleFlags & ORACLE_ENABLED_MASK == 1);
return oracleEnabled ?
address(uint160(poolIdx >> 96)) :
address(0);
}
/* @notice Constructs a cryptographically unique virtual address based off a base
* address (either virtual or real), and a salt unique to the base address.
* Can be used to create synthetic tokens, users, etc.
*
* @param base The address of the base root.
* @param salt A salt unique to the base token tracker contract.
*
* @return A synthetic token address corresponding to the specific virtual address. */
function virtualizeAddress (address base, uint256 salt) internal
pure returns (address) {
bytes32 hash = keccak256(abi.encode(base, salt));
uint160 hashTrail = uint160((uint256(hash) << 96) >> 96);
return address(hashTrail);
}
}
| library PoolSpecs {
/* @notice Specifcations of the parameters of a single pool type. Any given pair
* may have many different pool types, each of which may operate as segmented
* markets with different underlying behavior to the AMM.
*
* @param schema_ Placeholder that defines the structure of the poolSpecs object in
* in storage. Because slots initialize zero, 0 is used for an
* unitialized or disabled pool. 1 is the only currently used schema
* (for the below struct), but allows for upgradeability in the future
*
* @param feeRate_ The overall fee (liquidity fees + protocol fees inclusive) that
* swappers pay to the pool as a fraction of notional. Represented as an
* integer representing hundredths of a basis point. I.e. a 0.25% fee
* would be 2500
*
* @param protocolTake_ The fraction of the fee rate that goes to the protocol fee
* (the rest accumulates as a liquidity fee to LPs). Represented in units
* of 1/256. Since uint8 can represent up to 255, protocol could take
* as much as 99.6% of liquidity fees. However currently the protocol
* set function prohibits values above 128, i.e. 50% of liquidity fees.
* (See set ProtocolTakeRate in PoolRegistry.sol)
*
* @param tickSize The minimum granularity of price ticks defining a grid, on which
* range orders may be placed. (Outside off-grid price improvement facility.)
* For example a value of 50 would mean that range order bounds could only
* be placed on every 50th price tick, guaranteeing a minimum separation of
* 0.005% (50 one basis point ticks) between bump points.
*
* @param jitThresh_ Sets the minimum TTL for concentrated LP positions in the pool.
* Represented in units of 10 seconds (as measured by block time)
* E.g. a value of 5 equates to a minimum TTL of 50 seconds.
* Attempts to burn or partially burn an LP position in less than
* N seconds (as measured in block.timestamp) after a position was
* minted (or had its liquidity increased) will revert. If set to
* 0, atomically flashed liquidity that mints->burns in the same
* block is enabled.
*
* @param knockoutBits_ Defines the parameters for where and how knockout liquidity
* is allowed in the pool. (See KnockoutLiq library for a full
* description of the bit field.)
*
* @param oracleFlags_ Bitmap flags to indicate the pool's oracle permission
* requirements. Current implementation only uses the least
* significant bit, which if on checks oracle permission on every
* pool related call. Otherwise pool is permissionless. */
struct Pool {
uint8 schema_;
uint16 feeRate_;
uint8 protocolTake_;
uint16 tickSize_;
uint8 jitThresh_;
uint8 knockoutBits_;
uint8 oracleFlags_;
}
uint8 constant BASE_SCHEMA = 1;
uint8 constant DISABLED_SCHEMA = 0;
/* @notice Convenience struct that's used to gather all useful context about on a
* specific pool.
* @param head_ The full specification for the pool. (See struct Pool comments above.)
* @param hash_ The keccak256 hash used to encode the full pool location.
* @param oracle_ The permission oracle associated with this pool (0 if pool is
* permissionless.) */
struct PoolCursor {
Pool head_;
bytes32 hash_;
address oracle_;
}
/* @notice Given a mapping of pools, a base/quote token pair and a pool type index,
* copies the pool specification to memory. */
function queryPool (mapping(bytes32 => Pool) storage pools,
address tokenX, address tokenY, uint256 poolIdx)
internal view returns (PoolCursor memory specs) {
bytes32 key = encodeKey(tokenX, tokenY, poolIdx);
Pool memory pool = pools[key];
address oracle = oracleForPool(poolIdx, pool.oracleFlags_);
return PoolCursor ({head_: pool, hash_: key, oracle_: oracle});
}
/* @notice Given a mapping of pools, a base/quote token pair and a pool type index,
* retrieves a storage reference to the pool specification. */
function selectPool (mapping(bytes32 => Pool) storage pools,
address tokenX, address tokenY, uint256 poolIdx)
internal view returns (Pool storage specs) {
bytes32 key = encodeKey(tokenX, tokenY, poolIdx);
return pools[key];
}
/* @notice Writes a pool specification for a pair and pool type combination. */
function writePool (mapping(bytes32 => Pool) storage pools,
address tokenX, address tokenY, uint256 poolIdx,
Pool memory val) internal {
bytes32 key = encodeKey(tokenX, tokenY, poolIdx);
pools[key] = val;
}
/* @notice Hashes the key associated with a pool for a base/quote asset pair and
* a specific pool type index. */
function encodeKey (address tokenX, address tokenY, uint256 poolIdx)
internal pure returns (bytes32) {
require(tokenX < tokenY);
return keccak256(abi.encode(tokenX, tokenY, poolIdx));
}
/* @notice Returns the permission oracle associated with the pool (or 0 if pool is
* permissionless.
*
* @dev The oracle (if enabled on pool settings) is always deterministically based
* on the first 160-bits of the pool type value. This means users can know
* ahead of time if a pool can be oracled by checking the bits in the pool
* index. */
function oracleForPool (uint256 poolIdx, uint8 oracleFlags)
internal pure returns (address) {
uint8 ORACLE_ENABLED_MASK = 0x1;
bool oracleEnabled = (oracleFlags & ORACLE_ENABLED_MASK == 1);
return oracleEnabled ?
address(uint160(poolIdx >> 96)) :
address(0);
}
/* @notice Constructs a cryptographically unique virtual address based off a base
* address (either virtual or real), and a salt unique to the base address.
* Can be used to create synthetic tokens, users, etc.
*
* @param base The address of the base root.
* @param salt A salt unique to the base token tracker contract.
*
* @return A synthetic token address corresponding to the specific virtual address. */
function virtualizeAddress (address base, uint256 salt) internal
pure returns (address) {
bytes32 hash = keccak256(abi.encode(base, salt));
uint160 hashTrail = uint160((uint256(hash) << 96) >> 96);
return address(hashTrail);
}
}
| 13,440 |
2 | // Set [addr] to be enabled on the precompile contract. | function setEnabled(address addr) external;
| function setEnabled(address addr) external;
| 16,339 |
312 | // Bootstrap Treasury | incentivize(Constants.getTreasuryAddress(), 5e23);
| incentivize(Constants.getTreasuryAddress(), 5e23);
| 19,107 |
14 | // _userData | ); // note _tokenBorrow == _tokenPay
IUniswapV2Pair iswap_instance = IUniswapV2Pair(uni_pair);
iswap_instance.swap (amount0, amount1, address(this), data);
| ); // note _tokenBorrow == _tokenPay
IUniswapV2Pair iswap_instance = IUniswapV2Pair(uni_pair);
iswap_instance.swap (amount0, amount1, address(this), data);
| 5,626 |
31 | // current total underlying balance, as measured by pool, without fees | function underlyingBalance()
external virtual override
returns (uint256)
| function underlyingBalance()
external virtual override
returns (uint256)
| 32,669 |
10 | // get balance | uint256 balance = IERC20(token).balanceOf(address(this));
| uint256 balance = IERC20(token).balanceOf(address(this));
| 10,746 |
1 | // flags | bool public migrated = false;
| bool public migrated = false;
| 1,987 |
72 | // assert(feed != address(0)); |
feedIndex = _feeds[feed];
|
feedIndex = _feeds[feed];
| 28,290 |
68 | // Add the subscriber to the whitelist. _subscriber The subscriber to add to the whitelist. / | function addToWhitelist(address _subscriber) external onlyOwner beforeEnd whenReserving {
addToWhitelistInternal(_subscriber);
}
| function addToWhitelist(address _subscriber) external onlyOwner beforeEnd whenReserving {
addToWhitelistInternal(_subscriber);
}
| 33,900 |
84 | // - to withdraw any ETH balance sitting in the contract | function withdraw() external onlyOwner {
_owner.transfer(address(this).balance);
}
| function withdraw() external onlyOwner {
_owner.transfer(address(this).balance);
}
| 35,383 |
29 | // Top up your stake once you've given approval to transfer funds._amount is how much you would like to withdraw._tokenAddress token for which to stake for./ | function topUpStake(uint _amount, address _tokenAddress)
public
returns (bool success)
| function topUpStake(uint _amount, address _tokenAddress)
public
returns (bool success)
| 52,842 |
73 | // median of report from given aggregator round (NOT OCR round) _roundId the aggregator round of the target report / | function getAnswer(uint256 _roundId)
public
override
view
virtual
returns (int256)
| function getAnswer(uint256 _roundId)
public
override
view
virtual
returns (int256)
| 11,605 |
104 | // Returns the token name. / | function name() public override view returns (string memory) {
return _name;
}
| function name() public override view returns (string memory) {
return _name;
}
| 1,317 |
13 | // Withdraw entire balance of a given ERC20 token from the vault.The vault must be in a "withdrawEnabled" state (non-transferrable),and the caller must be the owner.token The ERC20 token to withdraw. toThe recipient of the withdrawn funds. / | function withdrawERC20(address token, address to) external override onlyOwner onlyWithdrawEnabled {
uint256 balance = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(to, balance);
emit WithdrawERC20(msg.sender, token, to, balance);
}
| function withdrawERC20(address token, address to) external override onlyOwner onlyWithdrawEnabled {
uint256 balance = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(to, balance);
emit WithdrawERC20(msg.sender, token, to, balance);
}
| 36,247 |
14 | // Returns if the `operator` is allowed to manage all of the assets of `owner`. See {setApprovalForAll}/ | function isApprovedForAll(address owner, address operator) external view returns (bool);
| function isApprovedForAll(address owner, address operator) external view returns (bool);
| 35,070 |
79 | // Function: purchase() / |
function purchase(address purchaser, uint256 purchaseTokens)
|
function purchase(address purchaser, uint256 purchaseTokens)
| 50,025 |
61 | // Creates `amount` tokens and assigns them to `msg.sender`, increasingthe total supply. Requirements - `msg.sender` must be the token owner / | function mint(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
| function mint(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
| 1,808 |
117 | // Get fee recipients and fees in a single call.The data is the same as when calling getFeeRecipients and getFeeBps separately. / | function getFees(uint256 tokenId)
public
view
returns (address payable[2] memory recipients, uint256[2] memory feesInBasisPoints)
| function getFees(uint256 tokenId)
public
view
returns (address payable[2] memory recipients, uint256[2] memory feesInBasisPoints)
| 67,088 |
19 | // new proposal | Proposal memory p = Proposal({
tunnelKey: _tunnelKey,
to: to,
txid: _txid,
amount: _amount,
creater: trustee,
voteCount: 1,
finished: false,
isExist: true
});
| Proposal memory p = Proposal({
tunnelKey: _tunnelKey,
to: to,
txid: _txid,
amount: _amount,
creater: trustee,
voteCount: 1,
finished: false,
isExist: true
});
| 7,612 |
9 | // trigger voted event | emit votedEvent(_candidateId);
| emit votedEvent(_candidateId);
| 21,946 |
8 | // long call finished in the money | liquidityPool.sendReservedQuote(receiver, (priceAtExpiry - strike).multiplyDecimal(amount));
| liquidityPool.sendReservedQuote(receiver, (priceAtExpiry - strike).multiplyDecimal(amount));
| 16,730 |
261 | // uriSuffix | string public uriSuffix;
constructor(
string memory name,
string memory symbol,
string memory baseURI_,
string memory uriSuffix_
| string public uriSuffix;
constructor(
string memory name,
string memory symbol,
string memory baseURI_,
string memory uriSuffix_
| 19,848 |
13 | // Here be the core logic of WL Vending | struct ProjectInfo {
string projectName;
string tokenImageUri;
}
| struct ProjectInfo {
string projectName;
string tokenImageUri;
}
| 50,903 |
138 | // IRC20Protocol(tokenScAddr).transfer(to, value); | tokenScAddr.call(bytes4(keccak256("transfer(address,uint256)")), to, value);
afterBalance = IRC20Protocol(tokenScAddr).balanceOf(to);
return afterBalance == beforeBalance.add(value);
| tokenScAddr.call(bytes4(keccak256("transfer(address,uint256)")), to, value);
afterBalance = IRC20Protocol(tokenScAddr).balanceOf(to);
return afterBalance == beforeBalance.add(value);
| 2,232 |
23 | // fee portion reserved for Lyra DAO | uint feePortionReserved;
| uint feePortionReserved;
| 15,884 |
32 | // FixidityLib Gadi Guy, Alberto Cuesta Canada This library provides fixed point arithmetic with protection againstoverflow.All operations are done with uint256 and the operands must have been createdwith any of the newFrom functions, which shift the comma digits() to theright and check for limits, or with wrap() which expects a number alreadyin the internal representation of a fraction.When using this library be sure to use maxNewFixed() as the upper limit forcreation of fixed point numbers. Use maxFixedMul(), maxFixedDividend() andmaxFixedAdd() if you want to be certain that those operations don'toverflow. / | library FixidityLib {
struct Fraction {
uint256 value;
}
/**
* @notice Number of positions that the comma is shifted to the right.
*/
function digits() internal pure returns (uint8) {
return 24;
}
uint256 private constant FIXED1_UINT = 1000000000000000000000000;
/**
* @notice This is 1 in the fixed point units used in this library.
* @dev Test fixed1() equals 10^digits()
* Hardcoded to 24 digits.
*/
function fixed1() internal pure returns (Fraction memory) {
return Fraction(FIXED1_UINT);
}
/**
* @notice Wrap a uint256 that represents a 24-decimal fraction in a Fraction
* struct.
* @param x Number that already represents a 24-decimal fraction.
* @return A Fraction struct with contents x.
*/
function wrap(uint256 x) internal pure returns (Fraction memory) {
return Fraction(x);
}
/**
* @notice Unwraps the uint256 inside of a Fraction struct.
*/
function unwrap(Fraction memory x) internal pure returns (uint256) {
return x.value;
}
/**
* @notice The amount of decimals lost on each multiplication operand.
* @dev Test mulPrecision() equals sqrt(fixed1)
*/
function mulPrecision() internal pure returns (uint256) {
return 1000000000000;
}
/**
* @notice Maximum value that can be represented in a uint256
* @dev Test maxUint256() equals 2^256 -1
*/
function maxUint256() internal pure returns (uint256) {
return 115792089237316195423570985008687907853269984665640564039457584007913129639935;
}
/**
* @notice Maximum value that can be converted to fixed point. Optimize for
* deployment.
* @dev
* Test maxNewFixed() equals maxUint256() / fixed1()
*/
function maxNewFixed() internal pure returns (uint256) {
return 115792089237316195423570985008687907853269984665640564;
}
/**
* @notice Maximum value that can be safely used as an addition operator.
* @dev Test maxFixedAdd() equals maxUint256()-1 / 2
* Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd()
* Test add(maxFixedAdd()+1,maxFixedAdd()+1) throws
*/
function maxFixedAdd() internal pure returns (uint256) {
return 57896044618658097711785492504343953926634992332820282019728792003956564819967;
}
/**
* @notice Maximum value that can be safely used as a multiplication operator.
* @dev Calculated as sqrt(maxUint256()*fixed1()).
* Test multiply(maxFixedMul(),maxFixedMul()) is around maxFixedMul() * maxFixedMul()
* Test multiply(maxFixedMul(),maxFixedMul()+1) throws
*/
function maxFixedMul() internal pure returns (uint256) {
return 340282366920938463463374607431768211455999999999999;
}
/**
* @notice Maximum value that can be safely used as a dividend.
* @dev divide(maxFixedDividend,newFixedFraction(1,fixed1())) is around maxUint256().
* Test maxFixedDividend() equals maxUint256()/fixed1()
* Test divide(maxFixedDividend(),1) equals maxFixedDividend()*(fixed1)
* Test divide(maxFixedDividend()+1,multiply(mulPrecision(),mulPrecision())) throws
*/
function maxFixedDividend() internal pure returns (uint256) {
return 115792089237316195423570985008687907853269984665640564;
}
/**
* @notice Converts a uint256 to fixed point Fraction
* @dev Test newFixed(0) returns 0
* Test newFixed(1) returns fixed1()
* Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1()
* Test newFixed(maxNewFixed()+1) fails
*/
function newFixed(uint256 x) internal pure returns (Fraction memory) {
require(x <= maxNewFixed());
return Fraction(x * FIXED1_UINT);
}
/**
* @notice Converts a uint256 in the fixed point representation of this
* library to a non decimal. All decimal digits will be truncated.
*/
function fromFixed(Fraction memory x) internal pure returns (uint256) {
return x.value / FIXED1_UINT;
}
/**
* @notice Converts two uint256 representing a fraction to fixed point units,
* equivalent to multiplying dividend and divisor by 10^digits().
* @dev
* Test newFixedFraction(maxFixedDividend()+1,1) fails
* Test newFixedFraction(1,maxFixedDividend()+1) fails
* Test newFixedFraction(1,0) fails
* Test newFixedFraction(0,1) returns 0
* Test newFixedFraction(1,1) returns fixed1()
* Test newFixedFraction(maxFixedDividend(),1) returns maxFixedDividend()*fixed1()
* Test newFixedFraction(1,fixed1()) returns 1
*/
function newFixedFraction(uint256 numerator, uint256 denominator)
internal
pure
returns (Fraction memory)
{
require(numerator <= maxNewFixed());
require(denominator <= maxNewFixed());
require(denominator != 0);
Fraction memory convertedNumerator = newFixed(numerator);
Fraction memory convertedDenominator = newFixed(denominator);
return divide(convertedNumerator, convertedDenominator);
}
/**
* @notice Returns the integer part of a fixed point number.
* @dev
* Test integer(0) returns 0
* Test integer(fixed1()) returns fixed1()
* Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1()
*/
function integer(Fraction memory x) internal pure returns (Fraction memory) {
return Fraction((x.value / FIXED1_UINT) * FIXED1_UINT); // Can't overflow
}
/**
* @notice Returns the fractional part of a fixed point number.
* In the case of a negative number the fractional is also negative.
* @dev
* Test fractional(0) returns 0
* Test fractional(fixed1()) returns 0
* Test fractional(fixed1()-1) returns 10^24-1
*/
function fractional(Fraction memory x) internal pure returns (Fraction memory) {
return Fraction(x.value - (x.value / FIXED1_UINT) * FIXED1_UINT); // Can't overflow
}
/**
* @notice x+y. If any operator is higher than maxFixedAdd() it
* might overflow.
* @dev
* Test add(maxFixedAdd(),maxFixedAdd()) returns maxUint256()-1
* Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails
* Test add(maxUint256(),maxUint256()) fails
*/
function add(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) {
uint256 z = x.value + y.value;
require(z >= x.value);
return Fraction(z);
}
/**
* @notice x-y.
* @dev
* Test subtract(6, 10) fails
*/
function subtract(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) {
require(x.value >= y.value);
return Fraction(x.value - y.value);
}
/**
* @notice x*y. If any of the operators is higher than maxFixedMul() it
* might overflow.
* @dev
* Test multiply(0,0) returns 0
* Test multiply(maxFixedMul(),0) returns 0
* Test multiply(0,maxFixedMul()) returns 0
* Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision())
* Test multiply(maxFixedMul(),maxFixedMul()) is around maxUint256()
* Test multiply(maxFixedMul()+1,maxFixedMul()+1) fails
*/
function multiply(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) {
if (x.value == 0 || y.value == 0) return Fraction(0);
if (y.value == FIXED1_UINT) return x;
if (x.value == FIXED1_UINT) return y;
// Separate into integer and fractional parts
// x = x1 + x2, y = y1 + y2
uint256 x1 = integer(x).value / FIXED1_UINT;
uint256 x2 = fractional(x).value;
uint256 y1 = integer(y).value / FIXED1_UINT;
uint256 y2 = fractional(y).value;
// (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2)
uint256 x1y1 = x1 * y1;
if (x1 != 0) require(x1y1 / x1 == y1); // Overflow x1y1
// x1y1 needs to be multiplied back by fixed1
// solium-disable-next-line mixedcase
uint256 fixed_x1y1 = x1y1 * FIXED1_UINT;
if (x1y1 != 0) require(fixed_x1y1 / x1y1 == FIXED1_UINT); // Overflow x1y1 * fixed1
x1y1 = fixed_x1y1;
uint256 x2y1 = x2 * y1;
if (x2 != 0) require(x2y1 / x2 == y1); // Overflow x2y1
uint256 x1y2 = x1 * y2;
if (x1 != 0) require(x1y2 / x1 == y2); // Overflow x1y2
x2 = x2 / mulPrecision();
y2 = y2 / mulPrecision();
uint256 x2y2 = x2 * y2;
if (x2 != 0) require(x2y2 / x2 == y2); // Overflow x2y2
// result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1();
Fraction memory result = Fraction(x1y1);
result = add(result, Fraction(x2y1)); // Add checks for overflow
result = add(result, Fraction(x1y2)); // Add checks for overflow
result = add(result, Fraction(x2y2)); // Add checks for overflow
return result;
}
/**
* @notice 1/x
* @dev
* Test reciprocal(0) fails
* Test reciprocal(fixed1()) returns fixed1()
* Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated
* Test reciprocal(1+fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated
*/
function reciprocal(Fraction memory x) internal pure returns (Fraction memory) {
require(x.value != 0);
return Fraction((FIXED1_UINT * FIXED1_UINT) / x.value); // Can't overflow
}
/**
* @notice x/y. If the dividend is higher than maxFixedDividend() it
* might overflow. You can use multiply(x,reciprocal(y)) instead.
* @dev
* Test divide(fixed1(),0) fails
* Test divide(maxFixedDividend(),1) = maxFixedDividend()*(10^digits())
* Test divide(maxFixedDividend()+1,1) throws
*/
function divide(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) {
require(y.value != 0);
uint256 X = x.value * FIXED1_UINT;
require(X / FIXED1_UINT == x.value);
return Fraction(X / y.value);
}
/**
* @notice x > y
*/
function gt(Fraction memory x, Fraction memory y) internal pure returns (bool) {
return x.value > y.value;
}
/**
* @notice x >= y
*/
function gte(Fraction memory x, Fraction memory y) internal pure returns (bool) {
return x.value >= y.value;
}
/**
* @notice x < y
*/
function lt(Fraction memory x, Fraction memory y) internal pure returns (bool) {
return x.value < y.value;
}
/**
* @notice x <= y
*/
function lte(Fraction memory x, Fraction memory y) internal pure returns (bool) {
return x.value <= y.value;
}
/**
* @notice x == y
*/
function equals(Fraction memory x, Fraction memory y) internal pure returns (bool) {
return x.value == y.value;
}
/**
* @notice x <= 1
*/
function isProperFraction(Fraction memory x) internal pure returns (bool) {
return lte(x, fixed1());
}
}
| library FixidityLib {
struct Fraction {
uint256 value;
}
/**
* @notice Number of positions that the comma is shifted to the right.
*/
function digits() internal pure returns (uint8) {
return 24;
}
uint256 private constant FIXED1_UINT = 1000000000000000000000000;
/**
* @notice This is 1 in the fixed point units used in this library.
* @dev Test fixed1() equals 10^digits()
* Hardcoded to 24 digits.
*/
function fixed1() internal pure returns (Fraction memory) {
return Fraction(FIXED1_UINT);
}
/**
* @notice Wrap a uint256 that represents a 24-decimal fraction in a Fraction
* struct.
* @param x Number that already represents a 24-decimal fraction.
* @return A Fraction struct with contents x.
*/
function wrap(uint256 x) internal pure returns (Fraction memory) {
return Fraction(x);
}
/**
* @notice Unwraps the uint256 inside of a Fraction struct.
*/
function unwrap(Fraction memory x) internal pure returns (uint256) {
return x.value;
}
/**
* @notice The amount of decimals lost on each multiplication operand.
* @dev Test mulPrecision() equals sqrt(fixed1)
*/
function mulPrecision() internal pure returns (uint256) {
return 1000000000000;
}
/**
* @notice Maximum value that can be represented in a uint256
* @dev Test maxUint256() equals 2^256 -1
*/
function maxUint256() internal pure returns (uint256) {
return 115792089237316195423570985008687907853269984665640564039457584007913129639935;
}
/**
* @notice Maximum value that can be converted to fixed point. Optimize for
* deployment.
* @dev
* Test maxNewFixed() equals maxUint256() / fixed1()
*/
function maxNewFixed() internal pure returns (uint256) {
return 115792089237316195423570985008687907853269984665640564;
}
/**
* @notice Maximum value that can be safely used as an addition operator.
* @dev Test maxFixedAdd() equals maxUint256()-1 / 2
* Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd()
* Test add(maxFixedAdd()+1,maxFixedAdd()+1) throws
*/
function maxFixedAdd() internal pure returns (uint256) {
return 57896044618658097711785492504343953926634992332820282019728792003956564819967;
}
/**
* @notice Maximum value that can be safely used as a multiplication operator.
* @dev Calculated as sqrt(maxUint256()*fixed1()).
* Test multiply(maxFixedMul(),maxFixedMul()) is around maxFixedMul() * maxFixedMul()
* Test multiply(maxFixedMul(),maxFixedMul()+1) throws
*/
function maxFixedMul() internal pure returns (uint256) {
return 340282366920938463463374607431768211455999999999999;
}
/**
* @notice Maximum value that can be safely used as a dividend.
* @dev divide(maxFixedDividend,newFixedFraction(1,fixed1())) is around maxUint256().
* Test maxFixedDividend() equals maxUint256()/fixed1()
* Test divide(maxFixedDividend(),1) equals maxFixedDividend()*(fixed1)
* Test divide(maxFixedDividend()+1,multiply(mulPrecision(),mulPrecision())) throws
*/
function maxFixedDividend() internal pure returns (uint256) {
return 115792089237316195423570985008687907853269984665640564;
}
/**
* @notice Converts a uint256 to fixed point Fraction
* @dev Test newFixed(0) returns 0
* Test newFixed(1) returns fixed1()
* Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1()
* Test newFixed(maxNewFixed()+1) fails
*/
function newFixed(uint256 x) internal pure returns (Fraction memory) {
require(x <= maxNewFixed());
return Fraction(x * FIXED1_UINT);
}
/**
* @notice Converts a uint256 in the fixed point representation of this
* library to a non decimal. All decimal digits will be truncated.
*/
function fromFixed(Fraction memory x) internal pure returns (uint256) {
return x.value / FIXED1_UINT;
}
/**
* @notice Converts two uint256 representing a fraction to fixed point units,
* equivalent to multiplying dividend and divisor by 10^digits().
* @dev
* Test newFixedFraction(maxFixedDividend()+1,1) fails
* Test newFixedFraction(1,maxFixedDividend()+1) fails
* Test newFixedFraction(1,0) fails
* Test newFixedFraction(0,1) returns 0
* Test newFixedFraction(1,1) returns fixed1()
* Test newFixedFraction(maxFixedDividend(),1) returns maxFixedDividend()*fixed1()
* Test newFixedFraction(1,fixed1()) returns 1
*/
function newFixedFraction(uint256 numerator, uint256 denominator)
internal
pure
returns (Fraction memory)
{
require(numerator <= maxNewFixed());
require(denominator <= maxNewFixed());
require(denominator != 0);
Fraction memory convertedNumerator = newFixed(numerator);
Fraction memory convertedDenominator = newFixed(denominator);
return divide(convertedNumerator, convertedDenominator);
}
/**
* @notice Returns the integer part of a fixed point number.
* @dev
* Test integer(0) returns 0
* Test integer(fixed1()) returns fixed1()
* Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1()
*/
function integer(Fraction memory x) internal pure returns (Fraction memory) {
return Fraction((x.value / FIXED1_UINT) * FIXED1_UINT); // Can't overflow
}
/**
* @notice Returns the fractional part of a fixed point number.
* In the case of a negative number the fractional is also negative.
* @dev
* Test fractional(0) returns 0
* Test fractional(fixed1()) returns 0
* Test fractional(fixed1()-1) returns 10^24-1
*/
function fractional(Fraction memory x) internal pure returns (Fraction memory) {
return Fraction(x.value - (x.value / FIXED1_UINT) * FIXED1_UINT); // Can't overflow
}
/**
* @notice x+y. If any operator is higher than maxFixedAdd() it
* might overflow.
* @dev
* Test add(maxFixedAdd(),maxFixedAdd()) returns maxUint256()-1
* Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails
* Test add(maxUint256(),maxUint256()) fails
*/
function add(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) {
uint256 z = x.value + y.value;
require(z >= x.value);
return Fraction(z);
}
/**
* @notice x-y.
* @dev
* Test subtract(6, 10) fails
*/
function subtract(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) {
require(x.value >= y.value);
return Fraction(x.value - y.value);
}
/**
* @notice x*y. If any of the operators is higher than maxFixedMul() it
* might overflow.
* @dev
* Test multiply(0,0) returns 0
* Test multiply(maxFixedMul(),0) returns 0
* Test multiply(0,maxFixedMul()) returns 0
* Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision())
* Test multiply(maxFixedMul(),maxFixedMul()) is around maxUint256()
* Test multiply(maxFixedMul()+1,maxFixedMul()+1) fails
*/
function multiply(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) {
if (x.value == 0 || y.value == 0) return Fraction(0);
if (y.value == FIXED1_UINT) return x;
if (x.value == FIXED1_UINT) return y;
// Separate into integer and fractional parts
// x = x1 + x2, y = y1 + y2
uint256 x1 = integer(x).value / FIXED1_UINT;
uint256 x2 = fractional(x).value;
uint256 y1 = integer(y).value / FIXED1_UINT;
uint256 y2 = fractional(y).value;
// (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2)
uint256 x1y1 = x1 * y1;
if (x1 != 0) require(x1y1 / x1 == y1); // Overflow x1y1
// x1y1 needs to be multiplied back by fixed1
// solium-disable-next-line mixedcase
uint256 fixed_x1y1 = x1y1 * FIXED1_UINT;
if (x1y1 != 0) require(fixed_x1y1 / x1y1 == FIXED1_UINT); // Overflow x1y1 * fixed1
x1y1 = fixed_x1y1;
uint256 x2y1 = x2 * y1;
if (x2 != 0) require(x2y1 / x2 == y1); // Overflow x2y1
uint256 x1y2 = x1 * y2;
if (x1 != 0) require(x1y2 / x1 == y2); // Overflow x1y2
x2 = x2 / mulPrecision();
y2 = y2 / mulPrecision();
uint256 x2y2 = x2 * y2;
if (x2 != 0) require(x2y2 / x2 == y2); // Overflow x2y2
// result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1();
Fraction memory result = Fraction(x1y1);
result = add(result, Fraction(x2y1)); // Add checks for overflow
result = add(result, Fraction(x1y2)); // Add checks for overflow
result = add(result, Fraction(x2y2)); // Add checks for overflow
return result;
}
/**
* @notice 1/x
* @dev
* Test reciprocal(0) fails
* Test reciprocal(fixed1()) returns fixed1()
* Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated
* Test reciprocal(1+fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated
*/
function reciprocal(Fraction memory x) internal pure returns (Fraction memory) {
require(x.value != 0);
return Fraction((FIXED1_UINT * FIXED1_UINT) / x.value); // Can't overflow
}
/**
* @notice x/y. If the dividend is higher than maxFixedDividend() it
* might overflow. You can use multiply(x,reciprocal(y)) instead.
* @dev
* Test divide(fixed1(),0) fails
* Test divide(maxFixedDividend(),1) = maxFixedDividend()*(10^digits())
* Test divide(maxFixedDividend()+1,1) throws
*/
function divide(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) {
require(y.value != 0);
uint256 X = x.value * FIXED1_UINT;
require(X / FIXED1_UINT == x.value);
return Fraction(X / y.value);
}
/**
* @notice x > y
*/
function gt(Fraction memory x, Fraction memory y) internal pure returns (bool) {
return x.value > y.value;
}
/**
* @notice x >= y
*/
function gte(Fraction memory x, Fraction memory y) internal pure returns (bool) {
return x.value >= y.value;
}
/**
* @notice x < y
*/
function lt(Fraction memory x, Fraction memory y) internal pure returns (bool) {
return x.value < y.value;
}
/**
* @notice x <= y
*/
function lte(Fraction memory x, Fraction memory y) internal pure returns (bool) {
return x.value <= y.value;
}
/**
* @notice x == y
*/
function equals(Fraction memory x, Fraction memory y) internal pure returns (bool) {
return x.value == y.value;
}
/**
* @notice x <= 1
*/
function isProperFraction(Fraction memory x) internal pure returns (bool) {
return lte(x, fixed1());
}
}
| 26,334 |
7 | // If address is blacklisted, it can't update backup address | require(!backupBlacklist[msg.sender], "ERC20_BLACKLISTED_ADDRESS");
require(msg.sender != _to, "ERC20_SAME_ADDRESS");
backupAddresses[msg.sender] = _to;
emit BackupAddressSet(msg.sender, _to);
return true;
| require(!backupBlacklist[msg.sender], "ERC20_BLACKLISTED_ADDRESS");
require(msg.sender != _to, "ERC20_SAME_ADDRESS");
backupAddresses[msg.sender] = _to;
emit BackupAddressSet(msg.sender, _to);
return true;
| 23,472 |
212 | // Modifier that requires the sender to have been whitelistedbefore or on the given date date The time sender must have been added before / | modifier onlyAddedBefore(uint256 date) {
require(
identity.lastAuthenticated(msg.sender) <= date,
"Was not added within period"
);
_;
}
| modifier onlyAddedBefore(uint256 date) {
require(
identity.lastAuthenticated(msg.sender) <= date,
"Was not added within period"
);
_;
}
| 15,412 |
38 | // Calculate the amount "owed" to the account, in units of (wei / token) S Subtract Wei already credited to the account (per token) from the total Wei per token | uint256 owed = scaledDividendPerToken.sub(scaledDividendCreditedTo[account]);
| uint256 owed = scaledDividendPerToken.sub(scaledDividendCreditedTo[account]);
| 33,769 |
4 | // used to store list of contracts MNY holds tokens in | mapping(uint256 => address) public exchangePartners;
mapping(address => uint256) public exchangeRates;
uint tierLevel = 1;
uint maxTier = 30;
uint256 totalSupply = 1.698846726062230000E25;
uint256 public mineableTokens = totalSupply;
uint256 public swappedTokens = 0;
uint256 circulatingSupply = 0;
| mapping(uint256 => address) public exchangePartners;
mapping(address => uint256) public exchangeRates;
uint tierLevel = 1;
uint maxTier = 30;
uint256 totalSupply = 1.698846726062230000E25;
uint256 public mineableTokens = totalSupply;
uint256 public swappedTokens = 0;
uint256 circulatingSupply = 0;
| 50,017 |
7 | // require(upkeepNeeded, "Upkeep not needed"); | if (!upkeepNeeded) {
revert Raffle__UpkeepNotNeeded(s_raffleBalance, s_playersCount, uint256(s_raffleState));
}
| if (!upkeepNeeded) {
revert Raffle__UpkeepNotNeeded(s_raffleBalance, s_playersCount, uint256(s_raffleState));
}
| 21,186 |
0 | // 6/9/23 v.12.7 prep error "Stack too deep, try removing local variables", changed patient_address from address to string and removed it as param in _createScripts address patient_address; | struct Script {
bytes patient_wallet_address;
string patient_name;
string sig_description;
string medication;
string dob;
string patient_physical_address;
uint256 per_diem_max;
uint256 rxId;
uint256 date_prescribed;
string doctor_name;
string doctor_dea;
}
| struct Script {
bytes patient_wallet_address;
string patient_name;
string sig_description;
string medication;
string dob;
string patient_physical_address;
uint256 per_diem_max;
uint256 rxId;
uint256 date_prescribed;
string doctor_name;
string doctor_dea;
}
| 4,636 |
2 | // Protected function suppossedly not accessible by smart contracts | function protected() external returns (bool) {
require(!isContract(msg.sender), "no smart contract access");
bool accessed = true;
accessCount++;
return accessed;
}
| function protected() external returns (bool) {
require(!isContract(msg.sender), "no smart contract access");
bool accessed = true;
accessCount++;
return accessed;
}
| 11,921 |
14 | // get single token total royalties/ return single token royalties | function getTokenTotalRoyalties() public view returns (uint256) {
uint256 _communityRoyalties = (communityRoyalties * 100) /
getTotalRoyalties();
return
((getTotalCollected() * _communityRoyalties) / 100) /
collectionSize;
}
| function getTokenTotalRoyalties() public view returns (uint256) {
uint256 _communityRoyalties = (communityRoyalties * 100) /
getTotalRoyalties();
return
((getTotalCollected() * _communityRoyalties) / 100) /
collectionSize;
}
| 45,755 |
28 | // Execute a request after the time for challenging it has passed. Can be called by anyone._tokenID The tokenID of the item with the request to execute. / | function executeRequest(bytes32 _tokenID) external {
Item storage item = items[_tokenID];
bytes32 agreementID = item.latestAgreementID;
Agreement storage agreement = agreements[agreementID];
require(now - item.lastAction > timeToChallenge, "The time to challenge has not passed yet.");
require(agreement.creator != address(0), "The specified agreement does not exist.");
require(!agreement.executed, "The specified agreement has already been executed.");
require(!agreement.disputed, "The specified agreement is disputed.");
if (item.status == ItemStatus.Resubmitted || item.status == ItemStatus.Submitted)
item.status = ItemStatus.Registered;
else if (item.status == ItemStatus.ClearingRequested || item.status == ItemStatus.PreventiveClearingRequested)
item.status = ItemStatus.Cleared;
else
revert("Item in wrong status for executing request.");
agreement.parties[0].send(item.balance); // Deliberate use of send in order to not block the contract in case of reverting fallback.
agreement.executed = true;
item.lastAction = now;
item.challengeReward = 0; // Clear challengeReward once a request has been executed.
item.balance = 0;
emit ItemStatusChange(agreement.parties[0], address(0), _tokenID, item.status, agreement.disputed);
}
| function executeRequest(bytes32 _tokenID) external {
Item storage item = items[_tokenID];
bytes32 agreementID = item.latestAgreementID;
Agreement storage agreement = agreements[agreementID];
require(now - item.lastAction > timeToChallenge, "The time to challenge has not passed yet.");
require(agreement.creator != address(0), "The specified agreement does not exist.");
require(!agreement.executed, "The specified agreement has already been executed.");
require(!agreement.disputed, "The specified agreement is disputed.");
if (item.status == ItemStatus.Resubmitted || item.status == ItemStatus.Submitted)
item.status = ItemStatus.Registered;
else if (item.status == ItemStatus.ClearingRequested || item.status == ItemStatus.PreventiveClearingRequested)
item.status = ItemStatus.Cleared;
else
revert("Item in wrong status for executing request.");
agreement.parties[0].send(item.balance); // Deliberate use of send in order to not block the contract in case of reverting fallback.
agreement.executed = true;
item.lastAction = now;
item.challengeReward = 0; // Clear challengeReward once a request has been executed.
item.balance = 0;
emit ItemStatusChange(agreement.parties[0], address(0), _tokenID, item.status, agreement.disputed);
}
| 1,495 |
57 | // distributes the effective balance to different actions the manager can keep a reserve in the vault by not distributing all the funds. / | function _distribute(uint256[] memory _percentages) internal nonReentrant {
uint256 totalBalance = _effectiveBalance();
currentRoundStartingAmount = totalBalance;
// keep track of total percentage to make sure we're summing up to 100%
uint256 sumPercentage;
for (uint8 i = 0; i < actions.length; i = i + 1) {
sumPercentage = sumPercentage.add(_percentages[i]);
require(sumPercentage <= BASE, "PERCENTAGE_SUM_EXCEED_MAX");
uint256 newAmount = totalBalance.mul(_percentages[i]).div(BASE);
if (newAmount > 0) {
IERC20(asset).safeTransfer(actions[i], newAmount);
IAction(actions[i]).rolloverPosition();
}
}
require(sumPercentage == BASE, "PERCENTAGE_DOESNT_ADD_UP");
}
| function _distribute(uint256[] memory _percentages) internal nonReentrant {
uint256 totalBalance = _effectiveBalance();
currentRoundStartingAmount = totalBalance;
// keep track of total percentage to make sure we're summing up to 100%
uint256 sumPercentage;
for (uint8 i = 0; i < actions.length; i = i + 1) {
sumPercentage = sumPercentage.add(_percentages[i]);
require(sumPercentage <= BASE, "PERCENTAGE_SUM_EXCEED_MAX");
uint256 newAmount = totalBalance.mul(_percentages[i]).div(BASE);
if (newAmount > 0) {
IERC20(asset).safeTransfer(actions[i], newAmount);
IAction(actions[i]).rolloverPosition();
}
}
require(sumPercentage == BASE, "PERCENTAGE_DOESNT_ADD_UP");
}
| 27,545 |
43 | // IDS / | function _validateId(string memory _id) internal pure {
require(bytes(_id).length > 0, ERROR_INVALID_ID);
}
| function _validateId(string memory _id) internal pure {
require(bytes(_id).length > 0, ERROR_INVALID_ID);
}
| 19,048 |
191 | // Changes the references to contracts from this protocol with which this collateral `PoolManager` interacts/ and propagates some references to the `perpetualManager` and `feeManager` contracts/governorList List of the governor addresses of protocol/guardian Address of the guardian of the protocol (it can be revoked)/_perpetualManager New reference to the `PerpetualManager` contract containing all the logic for HAs/_feeManager Reference to the `FeeManager` contract that will serve for the `PerpetualManager` contract/_oracle Reference to the `Oracle` contract that will serve for the `PerpetualManager` contract | function deployCollateral(
address[] memory governorList,
address guardian,
IPerpetualManager _perpetualManager,
IFeeManager _feeManager,
IOracle _oracle
) external override onlyRole(STABLEMASTER_ROLE) {
| function deployCollateral(
address[] memory governorList,
address guardian,
IPerpetualManager _perpetualManager,
IFeeManager _feeManager,
IOracle _oracle
) external override onlyRole(STABLEMASTER_ROLE) {
| 48,352 |
132 | // if player is winner | if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
| if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
| 15,809 |
23 | // update liquidity providing state | providingLiquidity = state;
| providingLiquidity = state;
| 29,407 |
132 | // uint token0BalanceBefore = _token0.balanceOf(address(this)); _token0.safeTransferFrom(pool.creator, address(this), pool.amountTotal0); require( _token0.balanceOf(address(this)).sub(token0BalanceBefore) == pool.amountTotal0, "DON'T SUPPORT DEFLATIONARY TOKEN" ); reset allowance to 0 | _token0.safeApprove(address(this), 0);
uint index = getPoolCount();
super._setEnableWhiteList(index, false);
super._addWhitelist(index, whitelist_);
super._setPoolToken(pool.creator, pool.token0, pool.token1, pool.amountTotal0, pool.amountTotal1, pool.maxAllocToken1);
super._setPoolTime(index, pool.openAt, pool.closeAt, pool.claimAt);
emit Created(index, msg.sender, pool);
| _token0.safeApprove(address(this), 0);
uint index = getPoolCount();
super._setEnableWhiteList(index, false);
super._addWhitelist(index, whitelist_);
super._setPoolToken(pool.creator, pool.token0, pool.token1, pool.amountTotal0, pool.amountTotal1, pool.maxAllocToken1);
super._setPoolTime(index, pool.openAt, pool.closeAt, pool.claimAt);
emit Created(index, msg.sender, pool);
| 31,218 |
44 | // roles | bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
bytes32 public constant FEE_WITHDRAWER_ROLE = keccak256("FEE_WITHDRAWER_ROLE");
bytes32 public constant COLLATERAL_WITHDRAWER_ROLE = keccak256("COLLATERAL_WITHDRAWER_ROLE");
bytes32 public constant REMAINING_DOLLAR_CAP_SETTER_ROLE = keccak256("REMAINING_DOLLAR_CAP_SETTER_ROLE");
| bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
bytes32 public constant FEE_WITHDRAWER_ROLE = keccak256("FEE_WITHDRAWER_ROLE");
bytes32 public constant COLLATERAL_WITHDRAWER_ROLE = keccak256("COLLATERAL_WITHDRAWER_ROLE");
bytes32 public constant REMAINING_DOLLAR_CAP_SETTER_ROLE = keccak256("REMAINING_DOLLAR_CAP_SETTER_ROLE");
| 31,148 |
9 | // SPDX-License-Identifier: MIT// Publius Bean Silo/ | contract BeanSilo is LPSilo {
using SafeMath for uint256;
using SafeMath for uint32;
event BeanDeposit(address indexed account, uint256 season, uint256 beans);
event BeanRemove(address indexed account, uint32[] crates, uint256[] crateBeans, uint256 beans);
event BeanWithdraw(address indexed account, uint256 season, uint256 beans);
/**
* Getters
**/
function totalDepositedBeans() public view returns (uint256) {
return s.bean.deposited;
}
function totalWithdrawnBeans() public view returns (uint256) {
return s.bean.withdrawn;
}
function beanDeposit(address account, uint32 id) public view returns (uint256) {
return s.a[account].bean.deposits[id];
}
function beanWithdrawal(address account, uint32 i) public view returns (uint256) {
return s.a[account].bean.withdrawals[i];
}
/**
* Internal
**/
function _depositBeans(uint256 amount) internal {
require(amount > 0, "Silo: No beans.");
updateSilo(msg.sender);
LibBeanSilo.incrementDepositedBeans(amount);
LibSilo.depositSiloAssets(msg.sender, amount.mul(C.getSeedsPerBean()), amount.mul(C.getStalkPerBean()));
LibBeanSilo.addBeanDeposit(msg.sender, season(), amount);
}
function _withdrawBeans(
uint32[] calldata crates,
uint256[] calldata amounts
)
internal
{
updateSilo(msg.sender);
require(crates.length == amounts.length, "Silo: Crates, amounts are diff lengths.");
(uint256 beansRemoved, uint256 stalkRemoved) = removeBeanDeposits(crates, amounts);
addBeanWithdrawal(msg.sender, season()+s.season.withdrawSeasons, beansRemoved);
LibBeanSilo.decrementDepositedBeans(beansRemoved);
LibSilo.withdrawSiloAssets(msg.sender, beansRemoved.mul(C.getSeedsPerBean()), stalkRemoved);
LibSilo.updateBalanceOfRainStalk(msg.sender);
LibCheck.beanBalanceCheck();
}
function removeBeanDeposits(uint32[] calldata crates, uint256[] calldata amounts)
private
returns (uint256 beansRemoved, uint256 stalkRemoved)
{
for (uint256 i = 0; i < crates.length; i++) {
uint256 crateBeans = LibBeanSilo.removeBeanDeposit(msg.sender, crates[i], amounts[i]);
beansRemoved = beansRemoved.add(crateBeans);
stalkRemoved = stalkRemoved.add(crateBeans.mul(C.getStalkPerBean()).add(
LibSilo.stalkReward(crateBeans.mul(C.getSeedsPerBean()), season()-crates[i]))
);
}
emit BeanRemove(msg.sender, crates, amounts, beansRemoved);
}
function addBeanWithdrawal(address account, uint32 arrivalSeason, uint256 amount) private {
s.a[account].bean.withdrawals[arrivalSeason] = s.a[account].bean.withdrawals[arrivalSeason].add(amount);
s.bean.withdrawn = s.bean.withdrawn.add(amount);
emit BeanWithdraw(msg.sender, arrivalSeason, amount);
}
function bean() internal view returns (IBean) {
return IBean(s.c.bean);
}
}
| contract BeanSilo is LPSilo {
using SafeMath for uint256;
using SafeMath for uint32;
event BeanDeposit(address indexed account, uint256 season, uint256 beans);
event BeanRemove(address indexed account, uint32[] crates, uint256[] crateBeans, uint256 beans);
event BeanWithdraw(address indexed account, uint256 season, uint256 beans);
/**
* Getters
**/
function totalDepositedBeans() public view returns (uint256) {
return s.bean.deposited;
}
function totalWithdrawnBeans() public view returns (uint256) {
return s.bean.withdrawn;
}
function beanDeposit(address account, uint32 id) public view returns (uint256) {
return s.a[account].bean.deposits[id];
}
function beanWithdrawal(address account, uint32 i) public view returns (uint256) {
return s.a[account].bean.withdrawals[i];
}
/**
* Internal
**/
function _depositBeans(uint256 amount) internal {
require(amount > 0, "Silo: No beans.");
updateSilo(msg.sender);
LibBeanSilo.incrementDepositedBeans(amount);
LibSilo.depositSiloAssets(msg.sender, amount.mul(C.getSeedsPerBean()), amount.mul(C.getStalkPerBean()));
LibBeanSilo.addBeanDeposit(msg.sender, season(), amount);
}
function _withdrawBeans(
uint32[] calldata crates,
uint256[] calldata amounts
)
internal
{
updateSilo(msg.sender);
require(crates.length == amounts.length, "Silo: Crates, amounts are diff lengths.");
(uint256 beansRemoved, uint256 stalkRemoved) = removeBeanDeposits(crates, amounts);
addBeanWithdrawal(msg.sender, season()+s.season.withdrawSeasons, beansRemoved);
LibBeanSilo.decrementDepositedBeans(beansRemoved);
LibSilo.withdrawSiloAssets(msg.sender, beansRemoved.mul(C.getSeedsPerBean()), stalkRemoved);
LibSilo.updateBalanceOfRainStalk(msg.sender);
LibCheck.beanBalanceCheck();
}
function removeBeanDeposits(uint32[] calldata crates, uint256[] calldata amounts)
private
returns (uint256 beansRemoved, uint256 stalkRemoved)
{
for (uint256 i = 0; i < crates.length; i++) {
uint256 crateBeans = LibBeanSilo.removeBeanDeposit(msg.sender, crates[i], amounts[i]);
beansRemoved = beansRemoved.add(crateBeans);
stalkRemoved = stalkRemoved.add(crateBeans.mul(C.getStalkPerBean()).add(
LibSilo.stalkReward(crateBeans.mul(C.getSeedsPerBean()), season()-crates[i]))
);
}
emit BeanRemove(msg.sender, crates, amounts, beansRemoved);
}
function addBeanWithdrawal(address account, uint32 arrivalSeason, uint256 amount) private {
s.a[account].bean.withdrawals[arrivalSeason] = s.a[account].bean.withdrawals[arrivalSeason].add(amount);
s.bean.withdrawn = s.bean.withdrawn.add(amount);
emit BeanWithdraw(msg.sender, arrivalSeason, amount);
}
function bean() internal view returns (IBean) {
return IBean(s.c.bean);
}
}
| 763 |
2 | // bytes4(keccak256("isValidSignature(bytes,bytes)") | bytes4 constant internal EIP1271_MAGIC_VALUE = 0x20c13b0b;
address owner;
bytes32 public domainSeparator;
IERC20 public cash;
| bytes4 constant internal EIP1271_MAGIC_VALUE = 0x20c13b0b;
address owner;
bytes32 public domainSeparator;
IERC20 public cash;
| 24,711 |
132 | // Given the values of stETH smart contract slots, calculates the amount of stETH owned by the Curve pool by reproducing calculations performed in the stETH contract. / | function _getStethBalanceByShares(
uint256 _shares,
uint256 _totalShares,
uint256 _beaconBalance,
uint256 _bufferedEther,
uint256 _depositedValidators,
uint256 _beaconValidators
)
internal pure returns (uint256)
| function _getStethBalanceByShares(
uint256 _shares,
uint256 _totalShares,
uint256 _beaconBalance,
uint256 _bufferedEther,
uint256 _depositedValidators,
uint256 _beaconValidators
)
internal pure returns (uint256)
| 15,405 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.