Unnamed: 0 int64 0 7.36k | comments stringlengths 3 35.2k | code_string stringlengths 1 527k | code stringlengths 1 527k | __index_level_0__ int64 0 88.6k |
|---|---|---|---|---|
23 | // You can't change crowdsale contract when migration is in progress. | require(currentState != State.Migrating);
crowdsaleManager = _mgr;
| require(currentState != State.Migrating);
crowdsaleManager = _mgr;
| 39,444 |
87 | // max nft count without being an NST is 16384 color must be < 49153 | require(nftTokenCount < 0x4000);
require(TransferrableToken(_token).supportsInterface(0x80ac58cd) == true, "Not an ERC721 token");
color = NFT_FIRST_COLOR + nftTokenCount; // NFT color namespace starts from 2^15 + 1
nftTokenCount += 1;
| require(nftTokenCount < 0x4000);
require(TransferrableToken(_token).supportsInterface(0x80ac58cd) == true, "Not an ERC721 token");
color = NFT_FIRST_COLOR + nftTokenCount; // NFT color namespace starts from 2^15 + 1
nftTokenCount += 1;
| 10,066 |
6 | // Gnosis Protocol v2 Trade Library./Gnosis Developers | library GPv2Trade {
using GPv2Order for GPv2Order.Data;
using GPv2Order for bytes;
/// @dev A struct representing a trade to be executed as part a batch
/// settlement.
struct Data {
uint256 sellTokenIndex;
uint256 buyTokenIndex;
address receiver;
uint256 sellAmount;
uint256 buyAmount;
uint32 validTo;
bytes32 appData;
uint256 feeAmount;
uint256 flags;
uint256 executedAmount;
bytes signature;
}
/// @dev Extracts the order data and signing scheme for the specified trade.
///
/// @param trade The trade.
/// @param tokens The list of tokens included in the settlement. The token
/// indices in the trade parameters map to tokens in this array.
/// @param order The memory location to extract the order data to.
function extractOrder(
Data calldata trade,
IERC20[] calldata tokens,
GPv2Order.Data memory order
) internal pure returns (GPv2Signing.Scheme signingScheme) {
order.sellToken = tokens[trade.sellTokenIndex];
order.buyToken = tokens[trade.buyTokenIndex];
order.receiver = trade.receiver;
order.sellAmount = trade.sellAmount;
order.buyAmount = trade.buyAmount;
order.validTo = trade.validTo;
order.appData = trade.appData;
order.feeAmount = trade.feeAmount;
(
order.kind,
order.partiallyFillable,
order.sellTokenBalance,
order.buyTokenBalance,
signingScheme
) = extractFlags(trade.flags);
}
/// @dev Decodes trade flags.
///
/// Trade flags are used to tightly encode information on how to decode
/// an order. Examples that directly affect the structure of an order are
/// the kind of order (either a sell or a buy order) as well as whether the
/// order is partially fillable or if it is a "fill-or-kill" order. It also
/// encodes the signature scheme used to validate the order. As the most
/// likely values are fill-or-kill sell orders by an externally owned
/// account, the flags are chosen such that `0x00` represents this kind of
/// order. The flags byte uses the following format:
///
/// ```
/// bit | 31 ... | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
/// ----+----------+---+---+-------+---+---+
/// | reserved | * * | * | * * | * | * |
/// | | | | | | |
/// | | | | | | +---- order kind bit, 0 for a sell order
/// | | | | | | and 1 for a buy order
/// | | | | | |
/// | | | | | +-------- order fill bit, 0 for fill-or-kill
/// | | | | | and 1 for a partially fillable order
/// | | | | |
/// | | | +---+------------ use internal sell token balance bit:
/// | | | 0x: ERC20 token balance
/// | | | 10: external Balancer Vault balance
/// | | | 11: internal Balancer Vault balance
/// | | |
/// | | +-------------------- use buy token balance bit
/// | | 0: ERC20 token balance
/// | | 1: internal Balancer Vault balance
/// | |
/// +---+------------------------ signature scheme bits:
/// 00: EIP-712
/// 01: eth_sign
/// 10: EIP-1271
/// 11: pre_sign
/// ```
function extractFlags(uint256 flags)
internal
pure
returns (
bytes32 kind,
bool partiallyFillable,
bytes32 sellTokenBalance,
bytes32 buyTokenBalance,
GPv2Signing.Scheme signingScheme
)
{
if (flags & 0x01 == 0) {
kind = GPv2Order.KIND_SELL;
} else {
kind = GPv2Order.KIND_BUY;
}
partiallyFillable = flags & 0x02 != 0;
if (flags & 0x08 == 0) {
sellTokenBalance = GPv2Order.BALANCE_ERC20;
} else if (flags & 0x04 == 0) {
sellTokenBalance = GPv2Order.BALANCE_EXTERNAL;
} else {
sellTokenBalance = GPv2Order.BALANCE_INTERNAL;
}
if (flags & 0x10 == 0) {
buyTokenBalance = GPv2Order.BALANCE_ERC20;
} else {
buyTokenBalance = GPv2Order.BALANCE_INTERNAL;
}
// NOTE: Take advantage of the fact that Solidity will revert if the
// following expression does not produce a valid enum value. This means
// we check here that the leading reserved bits must be 0.
signingScheme = GPv2Signing.Scheme(flags >> 5);
}
}
| library GPv2Trade {
using GPv2Order for GPv2Order.Data;
using GPv2Order for bytes;
/// @dev A struct representing a trade to be executed as part a batch
/// settlement.
struct Data {
uint256 sellTokenIndex;
uint256 buyTokenIndex;
address receiver;
uint256 sellAmount;
uint256 buyAmount;
uint32 validTo;
bytes32 appData;
uint256 feeAmount;
uint256 flags;
uint256 executedAmount;
bytes signature;
}
/// @dev Extracts the order data and signing scheme for the specified trade.
///
/// @param trade The trade.
/// @param tokens The list of tokens included in the settlement. The token
/// indices in the trade parameters map to tokens in this array.
/// @param order The memory location to extract the order data to.
function extractOrder(
Data calldata trade,
IERC20[] calldata tokens,
GPv2Order.Data memory order
) internal pure returns (GPv2Signing.Scheme signingScheme) {
order.sellToken = tokens[trade.sellTokenIndex];
order.buyToken = tokens[trade.buyTokenIndex];
order.receiver = trade.receiver;
order.sellAmount = trade.sellAmount;
order.buyAmount = trade.buyAmount;
order.validTo = trade.validTo;
order.appData = trade.appData;
order.feeAmount = trade.feeAmount;
(
order.kind,
order.partiallyFillable,
order.sellTokenBalance,
order.buyTokenBalance,
signingScheme
) = extractFlags(trade.flags);
}
/// @dev Decodes trade flags.
///
/// Trade flags are used to tightly encode information on how to decode
/// an order. Examples that directly affect the structure of an order are
/// the kind of order (either a sell or a buy order) as well as whether the
/// order is partially fillable or if it is a "fill-or-kill" order. It also
/// encodes the signature scheme used to validate the order. As the most
/// likely values are fill-or-kill sell orders by an externally owned
/// account, the flags are chosen such that `0x00` represents this kind of
/// order. The flags byte uses the following format:
///
/// ```
/// bit | 31 ... | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
/// ----+----------+---+---+-------+---+---+
/// | reserved | * * | * | * * | * | * |
/// | | | | | | |
/// | | | | | | +---- order kind bit, 0 for a sell order
/// | | | | | | and 1 for a buy order
/// | | | | | |
/// | | | | | +-------- order fill bit, 0 for fill-or-kill
/// | | | | | and 1 for a partially fillable order
/// | | | | |
/// | | | +---+------------ use internal sell token balance bit:
/// | | | 0x: ERC20 token balance
/// | | | 10: external Balancer Vault balance
/// | | | 11: internal Balancer Vault balance
/// | | |
/// | | +-------------------- use buy token balance bit
/// | | 0: ERC20 token balance
/// | | 1: internal Balancer Vault balance
/// | |
/// +---+------------------------ signature scheme bits:
/// 00: EIP-712
/// 01: eth_sign
/// 10: EIP-1271
/// 11: pre_sign
/// ```
function extractFlags(uint256 flags)
internal
pure
returns (
bytes32 kind,
bool partiallyFillable,
bytes32 sellTokenBalance,
bytes32 buyTokenBalance,
GPv2Signing.Scheme signingScheme
)
{
if (flags & 0x01 == 0) {
kind = GPv2Order.KIND_SELL;
} else {
kind = GPv2Order.KIND_BUY;
}
partiallyFillable = flags & 0x02 != 0;
if (flags & 0x08 == 0) {
sellTokenBalance = GPv2Order.BALANCE_ERC20;
} else if (flags & 0x04 == 0) {
sellTokenBalance = GPv2Order.BALANCE_EXTERNAL;
} else {
sellTokenBalance = GPv2Order.BALANCE_INTERNAL;
}
if (flags & 0x10 == 0) {
buyTokenBalance = GPv2Order.BALANCE_ERC20;
} else {
buyTokenBalance = GPv2Order.BALANCE_INTERNAL;
}
// NOTE: Take advantage of the fact that Solidity will revert if the
// following expression does not produce a valid enum value. This means
// we check here that the leading reserved bits must be 0.
signingScheme = GPv2Signing.Scheme(flags >> 5);
}
}
| 30,132 |
9 | // Bare amount | uint256 bareAmount = DFX.balanceOf(_voter);
uint256 votePower = getAmountFromSLP(_stakedSlpAmount) + getAmountFromSLP(pool2StakedAmount) + getAmountFromSLP(slpAmount) + bareAmount;
return votePower;
| uint256 bareAmount = DFX.balanceOf(_voter);
uint256 votePower = getAmountFromSLP(_stakedSlpAmount) + getAmountFromSLP(pool2StakedAmount) + getAmountFromSLP(slpAmount) + bareAmount;
return votePower;
| 72,519 |
60 | // grant only maxAmount rewards | fullReward = maxAmount;
| fullReward = maxAmount;
| 23,588 |
317 | // 4. Get the latest cumulative rate. F_n+1 = F_n + F_last | uint latestCumulative = lastRate.add(rate.multiplyDecimal(timeDelta));
| uint latestCumulative = lastRate.add(rate.multiplyDecimal(timeDelta));
| 18,243 |
248 | // burn tokens/ | function burn(address _wallet, uint _amount) public onlyOwner{
_burn(_wallet, _amount);
}
| function burn(address _wallet, uint _amount) public onlyOwner{
_burn(_wallet, _amount);
}
| 40,460 |
77 | // console.log('fee: %s from %s on %s', fee, amount, address(token)); | require(fee < amount, 'Fee exceeds amount');
if (ETHER_ERC20 == token) {
feeWalletAddress.transfer(fee);
} else {
| require(fee < amount, 'Fee exceeds amount');
if (ETHER_ERC20 == token) {
feeWalletAddress.transfer(fee);
} else {
| 15,007 |
8 | // Sets `_tokenURI` as the tokenURI of `tokenId`. | * Emits {MetadataUpdate}.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
if (!_exists(tokenId)) {
revert("ERC721: URI set of nonexistent token");
}
_tokenURIs[tokenId] = _tokenURI;
emit MetadataUpdate(tokenId);
}
| * Emits {MetadataUpdate}.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
if (!_exists(tokenId)) {
revert("ERC721: URI set of nonexistent token");
}
_tokenURIs[tokenId] = _tokenURI;
emit MetadataUpdate(tokenId);
}
| 16,800 |
48 | // Recall that ``N'' was not accounted for in the loop because we didn't look at index 0, so we draw it here. `x` is `32` for the same reason outlined in the previous comment. `y` is `173` because the character starts 3 lines below the first (`351 = 153`), and we have the same 20px overhead as before, so `153 + 20 = 173`. `width` is `536` for the same reason. Finally, `height` is `204` because the character is 4 lines tall, and each line is 51 pixels tall: `451 = 204`. | 'N</pre></foreignObject><foreignObject x="32" y="173" width="53'
'6" height="204"><pre',
hyphenGuy.inverted
? ""
: string.concat(
' class="',
string(
abi.encodePacked(COLOR_CLASSES[hyphenGuy.color])
),
'"'
| 'N</pre></foreignObject><foreignObject x="32" y="173" width="53'
'6" height="204"><pre',
hyphenGuy.inverted
? ""
: string.concat(
' class="',
string(
abi.encodePacked(COLOR_CLASSES[hyphenGuy.color])
),
'"'
| 11,976 |
59 | // Sets {storeAddress} to a value./ | function setStoreAddress(address storeAddress) external onlyOwner returns (bool) {
require(storeAddress != address(0), 'Should not be zero address');
require(storeAddress != address(this), 'Should not be token address');
_storeAddress = storeAddress;
return true;
}
| function setStoreAddress(address storeAddress) external onlyOwner returns (bool) {
require(storeAddress != address(0), 'Should not be zero address');
require(storeAddress != address(this), 'Should not be token address');
_storeAddress = storeAddress;
return true;
}
| 32,984 |
167 | // SashimiToken with Governance. | contract SashimiToken is ERC20("PokeToken", "POKE"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SASHIMI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SASHIMI::delegateBySig: invalid nonce");
require(now <= expiry, "SASHIMI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "SASHIMI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SASHIMIs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "SASHIMI::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
| contract SashimiToken is ERC20("PokeToken", "POKE"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SASHIMI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SASHIMI::delegateBySig: invalid nonce");
require(now <= expiry, "SASHIMI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "SASHIMI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SASHIMIs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "SASHIMI::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
| 17,365 |
313 | // Gets the user's borrow balance with the latest `borrowIndex`. / | function borrowBalanceCurrent(address _account)
| function borrowBalanceCurrent(address _account)
| 52,238 |
38 | // centralBanker의 권한을 넘겨 줄 수 있다. 단, superOwner만 실행할 수 있다.newBanker centralBanker는 일종의 중앙은행으로 거래가 불가능하다.지급 준비율과 통화량에 따라 묶여있는 금액이 결정되어진다. 돈을 꺼내기 위해서는 감사를 거쳐서 owner쪽으로 인출이 가능하다. / | function transferBankOwnership(address newBanker) public onlySuperOwner {
emit TMTG_RoleTransferred(Role.centralBanker, centralBanker, newBanker);
centralBanker = newBanker;
}
| function transferBankOwnership(address newBanker) public onlySuperOwner {
emit TMTG_RoleTransferred(Role.centralBanker, centralBanker, newBanker);
centralBanker = newBanker;
}
| 29,915 |
44 | // Registers an already deployed pool instance within the factoryCan be executed by the pool factory owner onlypoolAddr address of the already deployed pool instance / | function registerPool(address poolAddr) public onlyOwner {
// read pool information from the pool smart contract
// via the pool interface (IPool)
address poolToken = IPool(poolAddr).poolToken();
bool isFlashPool = IPool(poolAddr).isFlashPool();
uint32 weight = IPool(poolAddr).weight();
// ensure that the pool is not already registered within the factory
require(pools[poolToken] == address(0), "this pool is already registered");
// create pool structure, register it within the factory
pools[poolToken] = poolAddr;
poolExists[poolAddr] = true;
// update total pool weight of the factory
totalWeight += weight;
// emit an event
emit PoolRegistered(msg.sender, poolToken, poolAddr, weight, isFlashPool);
}
| function registerPool(address poolAddr) public onlyOwner {
// read pool information from the pool smart contract
// via the pool interface (IPool)
address poolToken = IPool(poolAddr).poolToken();
bool isFlashPool = IPool(poolAddr).isFlashPool();
uint32 weight = IPool(poolAddr).weight();
// ensure that the pool is not already registered within the factory
require(pools[poolToken] == address(0), "this pool is already registered");
// create pool structure, register it within the factory
pools[poolToken] = poolAddr;
poolExists[poolAddr] = true;
// update total pool weight of the factory
totalWeight += weight;
// emit an event
emit PoolRegistered(msg.sender, poolToken, poolAddr, weight, isFlashPool);
}
| 50,408 |
181 | // Internal function used to reduce bytecode size | _validateOnlyModule();
_;
| _validateOnlyModule();
_;
| 73,419 |
64 | // Returns the amount of tokens owned by an account (`owner`). / | function balanceOf(address owner) external view returns (uint256);
| function balanceOf(address owner) external view returns (uint256);
| 28,012 |
25 | // sales status id | uint8 private _tokensale_status;
address public currency_token_address;
TetherToken_interface private _currency_token;
address public project_token_address;
ProjectToken_interface private _project_token;
uint256 private _token_price;
| uint8 private _tokensale_status;
address public currency_token_address;
TetherToken_interface private _currency_token;
address public project_token_address;
ProjectToken_interface private _project_token;
uint256 private _token_price;
| 10,938 |
31 | // Update auditor&39;s states | auditors[msg.sender].stakedInAudit[_id] = true;
auditors[msg.sender].stakedAudits.push(_id);
emit AuditorStaked(_id, msg.sender, msg.value);
| auditors[msg.sender].stakedInAudit[_id] = true;
auditors[msg.sender].stakedAudits.push(_id);
emit AuditorStaked(_id, msg.sender, msg.value);
| 11,364 |
3 | // 获取最新的恒定乘积中两种资产的数量 | function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
| function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
| 13,644 |
122 | // Ideally, we would compare the requested Wizard index against the reserved range directly. However, it's a bit wasteful to spend storage on a reserved range variable when we can combine some known true facts instead: - nextWizardIndex is initialized to reservedRange + 1 when the Series was opend - nextWizardIndex is only incremented when a new Wizard is created - therefore, the only empty Wizard IDs less than nextWizardIndex are in the reserved range. - _conjureWizard() will abort if we try to reuse an ID. Combining all of the above, we know that, if the requested index is less than | require((currentId & indexMask) < nextWizardIndex, "Wizards not in reserved range");
_createWizard(currentId, owner, powers[i], affinities[i]);
| require((currentId & indexMask) < nextWizardIndex, "Wizards not in reserved range");
_createWizard(currentId, owner, powers[i], affinities[i]);
| 18,141 |
43 | // Make a copy of the latest generation so we can update it | uint8[4] memory newGeneration = genesis.generations[
genesis.generations.length - 1
];
| uint8[4] memory newGeneration = genesis.generations[
genesis.generations.length - 1
];
| 50,108 |
10 | // effects | routerContract.swapExactTokensForAVAX(
amountInUSDC,
amountOutMin,
path,
receiver,
block.timestamp
);
return payment;
| routerContract.swapExactTokensForAVAX(
amountInUSDC,
amountOutMin,
path,
receiver,
block.timestamp
);
return payment;
| 6,427 |
8 | // Mint card and keep it in contract | rmu.mint(address(this), _nftIds[0], 1, "");
emit RaffleAdded(raffles.length.sub(1));
| rmu.mint(address(this), _nftIds[0], 1, "");
emit RaffleAdded(raffles.length.sub(1));
| 15,825 |
39 | // Provides information about the current execution context, including thesender of the transaction and its data. While these are generally availablevia msg.sender and msg.data, they should not be accessed in such a directmanner, since when dealing with GSN meta-transactions the account sending andpaying for execution may not be the actual sender (as far as an applicationis concerned). This contract is only required for intermediate, library-like contracts. / | contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() {}
function _msgSender() internal view returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
| contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() {}
function _msgSender() internal view returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
| 53,281 |
55 | // Branch - storemanGroup unregistration | StoremanGroup storage _r = mapStoremanGroup[recipient];
| StoremanGroup storage _r = mapStoremanGroup[recipient];
| 43,174 |
196 | // Variant with withdrawal fee and verification of max loss. Used in withdraw functions. /Migrate functions use the variant from BaseWrapper without these features. | function _withdraw(
address receiver,
uint256 shares, // if `MAX_UINT256`, just withdraw everything
bool processWithdrawalFee, // If true, process withdrawal fee to affiliate
bool verifyMaxLoss // If true, ensure that the amount is within an expected range based on withdrawalMaxDeviationThreshold
| function _withdraw(
address receiver,
uint256 shares, // if `MAX_UINT256`, just withdraw everything
bool processWithdrawalFee, // If true, process withdrawal fee to affiliate
bool verifyMaxLoss // If true, ensure that the amount is within an expected range based on withdrawalMaxDeviationThreshold
| 41,423 |
126 | // We can directly increment and decrement the balances. | --_packedAddressData[from]; // Updates: `balance -= 1`.
++_packedAddressData[to]; // Updates: `balance += 1`.
| --_packedAddressData[from]; // Updates: `balance -= 1`.
++_packedAddressData[to]; // Updates: `balance += 1`.
| 27,126 |
71 | // transfer gift for new owner | _transfer(oldOwner, newOwner, _giftId);
delete ownerToApprovedAddsToGifIds[oldOwner][newOwner];
| _transfer(oldOwner, newOwner, _giftId);
delete ownerToApprovedAddsToGifIds[oldOwner][newOwner];
| 35,457 |
6 | // The owner address is maintained. | owner = msg.sender;
ercToken = _ercToken;
internalDistributionToken = _internalCirculationToken;
transferHistory = _transferHistory;
| owner = msg.sender;
ercToken = _ercToken;
internalDistributionToken = _internalCirculationToken;
transferHistory = _transferHistory;
| 25,013 |
5 | // we add this check for avoiding too much vesting | require(lockers[msg.sender], "only locker can lock");
if (_amount > 0) {
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
lockInfo[_addr].push(
LockInfo({
isWithdrawn: false,
token: _token,
unlockableAt: block.timestamp + _lockedTime,
amount: _amount
| require(lockers[msg.sender], "only locker can lock");
if (_amount > 0) {
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
lockInfo[_addr].push(
LockInfo({
isWithdrawn: false,
token: _token,
unlockableAt: block.timestamp + _lockedTime,
amount: _amount
| 1,801 |
241 | // Update the weighted multiplier of the recipient | ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value);
| ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value);
| 53,049 |
6 | // Encodes withdraw parameters from standard input to compact representation of 1 bytes32 Without a to parameter as the compact calls to L2Pool will use msg.sender as to asset The address of the underlying asset to withdraw amount The underlying amount to be withdrawnreturn compact representation of withdraw parameters / | function encodeWithdrawParams(address asset, uint256 amount) external view returns (bytes32) {
DataTypes.ReserveData memory data = POOL.getReserveData(asset);
uint16 assetId = data.id;
uint128 shortenedAmount = amount == type(uint256).max ? type(uint128).max : amount.toUint128();
bytes32 res;
assembly {
res := add(assetId, shl(16, shortenedAmount))
}
return res;
}
| function encodeWithdrawParams(address asset, uint256 amount) external view returns (bytes32) {
DataTypes.ReserveData memory data = POOL.getReserveData(asset);
uint16 assetId = data.id;
uint128 shortenedAmount = amount == type(uint256).max ? type(uint128).max : amount.toUint128();
bytes32 res;
assembly {
res := add(assetId, shl(16, shortenedAmount))
}
return res;
}
| 18,632 |
13 | // setLandOwner changes the owner of an land unit | function setLandOwner(uint _idx, address _newOwner) public override {
Land storage land = lands[_idx];
require(msg.sender == land.owner, "MetaHomepage: sender is not owner");
land.owner = _newOwner;
emit SetLandOwner(_idx, msg.sender, _newOwner);
}
| function setLandOwner(uint _idx, address _newOwner) public override {
Land storage land = lands[_idx];
require(msg.sender == land.owner, "MetaHomepage: sender is not owner");
land.owner = _newOwner;
emit SetLandOwner(_idx, msg.sender, _newOwner);
}
| 13,778 |
10 | // Returns the input amount needed for a desired output amount in a single-hop trade/amountOut The desired output amount/reserveIn The reserves available of the input token/reserveOut The reserves available of the output token/ return amountIn The input amount of the input token | function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut)
internal
pure
returns (uint256 amountIn)
| function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut)
internal
pure
returns (uint256 amountIn)
| 7,219 |
276 | // _changeDonationRecipient(nul); think what's the best logic for donations | fundsDon = 0;
| fundsDon = 0;
| 22,473 |
125 | // Kine's Controller Contract Kine / | contract Controller is ControllerStorage, KineControllerInterface, Exponential, ControllerErrorReporter {
/// @notice Emitted when an admin supports a market
event MarketListed(KToken kToken);
/// @notice Emitted when an account enters a market
event MarketEntered(KToken kToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(KToken kToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(KToken kToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when redemption params is changed by admin
event NewRedemptionInitialPunishment(uint oldRedemptionInitialPunishmentMantissa, uint newRedemptionInitialPunishmentMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(KineOracleInterface oldPriceOracle, KineOracleInterface newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(KToken kToken, string action, bool pauseState);
/// @notice Emitted when borrow cap for a kToken is changed
event NewBorrowCap(KToken indexed kToken, uint newBorrowCap);
/// @notice Emitted when supply cap for a kToken is changed
event NewSupplyCap(KToken indexed kToken, uint newSupplyCap);
/// @notice Emitted when borrow/supply cap guardian is changed
event NewCapGuardian(address oldCapGuardian, address newCapGuardian);
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
constructor() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin, "only admin can call this function");
_;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (KToken[] memory) {
KToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param kToken The kToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, KToken kToken) external view returns (bool) {
return markets[address(kToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param kTokens The list of addresses of the kToken markets to be enabled
* @dev will revert if any market entering failed
*/
function enterMarkets(address[] memory kTokens) public {
uint len = kTokens.length;
for (uint i = 0; i < len; i++) {
KToken kToken = KToken(kTokens[i]);
addToMarketInternal(kToken, msg.sender);
}
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param kToken The market to enter
* @param borrower The address of the account to modify
*/
function addToMarketInternal(KToken kToken, address borrower) internal {
Market storage marketToJoin = markets[address(kToken)];
require(marketToJoin.isListed, MARKET_NOT_LISTED);
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(kToken);
emit MarketEntered(kToken, borrower);
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param kTokenAddress The address of the asset to be removed
*/
function exitMarket(address kTokenAddress) external {
KToken kToken = KToken(kTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the kToken */
(uint tokensHeld, uint amountOwed) = kToken.getAccountSnapshot(msg.sender);
/* Fail if the sender has a borrow balance */
require(amountOwed == 0, EXIT_MARKET_BALANCE_OWED);
/* Fail if the sender is not permitted to redeem all of their tokens */
(bool allowed,) = redeemAllowedInternal(kTokenAddress, msg.sender, tokensHeld);
require(allowed, EXIT_MARKET_REJECTION);
Market storage marketToExit = markets[address(kToken)];
/* Succeed true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return;
}
/* Set kToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete kToken from the account’s list of assets */
// load into memory for faster iteration
KToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == kToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
require(assetIndex < len, "accountAssets array broken");
// copy last item in list to location of item to be removed, reduce length by 1
KToken[] storage storedList = accountAssets[msg.sender];
if (assetIndex != storedList.length - 1) {
storedList[assetIndex] = storedList[storedList.length - 1];
}
storedList.length--;
emit MarketExited(kToken, msg.sender);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param kToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return false and reason if mint not allowed, otherwise return true and empty string
*/
function mintAllowed(address kToken, address minter, uint mintAmount) external returns (bool allowed, string memory reason) {
if (mintGuardianPaused[kToken]) {
allowed = false;
reason = MINT_PAUSED;
return (allowed, reason);
}
uint supplyCap = supplyCaps[kToken];
// Supply cap of 0 corresponds to unlimited supplying
if (supplyCap != 0) {
uint totalSupply = KToken(kToken).totalSupply();
uint nextTotalSupply = totalSupply.add(mintAmount);
if (nextTotalSupply > supplyCap) {
allowed = false;
reason = MARKET_SUPPLY_CAP_REACHED;
return (allowed, reason);
}
}
// Shh - currently unused
minter;
if (!markets[kToken].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param kToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address kToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
kToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param kToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of kTokens to exchange for the underlying asset in the market
* @return false and reason if redeem not allowed, otherwise return true and empty string
*/
function redeemAllowed(address kToken, address redeemer, uint redeemTokens) external returns (bool allowed, string memory reason) {
return redeemAllowedInternal(kToken, redeemer, redeemTokens);
}
/**
* @param kToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of kTokens to exchange for the underlying asset in the market
* @return false and reason if redeem not allowed, otherwise return true and empty string
*/
function redeemAllowedInternal(address kToken, address redeemer, uint redeemTokens) internal view returns (bool allowed, string memory reason) {
if (!markets[kToken].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[kToken].accountMembership[redeemer]) {
allowed = true;
return (allowed, reason);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(, uint shortfall,,) = getHypotheticalAccountLiquidityInternal(redeemer, KToken(kToken), redeemTokens, 0);
if (shortfall > 0) {
allowed = false;
reason = INSUFFICIENT_LIQUIDITY;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param kToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address kToken, address redeemer, uint redeemTokens) external {
// Shh - currently unused
kToken;
redeemer;
require(redeemTokens != 0, REDEEM_TOKENS_ZERO);
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param kToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return false and reason if borrow not allowed, otherwise return true and empty string
*/
function borrowAllowed(address kToken, address borrower, uint borrowAmount) external returns (bool allowed, string memory reason) {
if (borrowGuardianPaused[kToken]) {
allowed = false;
reason = BORROW_PAUSED;
return (allowed, reason);
}
if (!markets[kToken].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
if (!markets[kToken].accountMembership[borrower]) {
// only kTokens may call borrowAllowed if borrower not in market
require(msg.sender == kToken, "sender must be kToken");
// attempt to add borrower to the market
addToMarketInternal(KToken(msg.sender), borrower);
// it should be impossible to break the important invariant
assert(markets[kToken].accountMembership[borrower]);
}
require(oracle.getUnderlyingPrice(kToken) != 0, "price error");
uint borrowCap = borrowCaps[kToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = KMCD(kToken).totalBorrows();
uint nextTotalBorrows = totalBorrows.add(borrowAmount);
if (nextTotalBorrows > borrowCap) {
allowed = false;
reason = MARKET_BORROW_CAP_REACHED;
return (allowed, reason);
}
}
(, uint shortfall,,) = getHypotheticalAccountLiquidityInternal(borrower, KToken(kToken), 0, borrowAmount);
if (shortfall > 0) {
allowed = false;
reason = INSUFFICIENT_LIQUIDITY;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param kToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address kToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
kToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param kToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return false and reason if repay borrow not allowed, otherwise return true and empty string
*/
function repayBorrowAllowed(
address kToken,
address payer,
address borrower,
uint repayAmount) external returns (bool allowed, string memory reason) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[kToken].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param kToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address kToken,
address payer,
address borrower,
uint actualRepayAmount) external {
// Shh - currently unused
kToken;
payer;
borrower;
actualRepayAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param kTokenBorrowed Asset which was borrowed by the borrower
* @param kTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
* @return false and reason if liquidate borrow not allowed, otherwise return true and empty string
*/
function liquidateBorrowAllowed(
address kTokenBorrowed,
address kTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (bool allowed, string memory reason) {
// Shh - currently unused
liquidator;
if (!markets[kTokenBorrowed].isListed || !markets[kTokenCollateral].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
if (KToken(kTokenCollateral).controller() != KToken(kTokenBorrowed).controller()) {
allowed = false;
reason = CONTROLLER_MISMATCH;
return (allowed, reason);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
/* Only KMCD has borrow related logics */
uint borrowBalance = KMCD(kTokenBorrowed).borrowBalance(borrower);
uint maxClose = mulScalarTruncate(Exp({mantissa : closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
allowed = false;
reason = TOO_MUCH_REPAY;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param kTokenBorrowed Asset which was borrowed by the borrower
* @param kTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address kTokenBorrowed,
address kTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
kTokenBorrowed;
kTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param kTokenCollateral Asset which was used as collateral and will be seized
* @param kTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
* @return false and reason if seize not allowed, otherwise return true and empty string
*/
function seizeAllowed(
address kTokenCollateral,
address kTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (bool allowed, string memory reason) {
if (seizeGuardianPaused) {
allowed = false;
reason = SEIZE_PAUSED;
return (allowed, reason);
}
// Shh - currently unused
seizeTokens;
liquidator;
borrower;
if (!markets[kTokenCollateral].isListed || !markets[kTokenBorrowed].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
if (KToken(kTokenCollateral).controller() != KToken(kTokenBorrowed).controller()) {
allowed = false;
reason = CONTROLLER_MISMATCH;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param kTokenCollateral Asset which was used as collateral and will be seized
* @param kTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address kTokenCollateral,
address kTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
kTokenCollateral;
kTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param kToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of kTokens to transfer
* @return false and reason if seize not allowed, otherwise return true and empty string
*/
function transferAllowed(address kToken, address src, address dst, uint transferTokens) external returns (bool allowed, string memory reason) {
if (transferGuardianPaused) {
allowed = false;
reason = TRANSFER_PAUSED;
return (allowed, reason);
}
// not used currently
dst;
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
return redeemAllowedInternal(kToken, src, transferTokens);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param kToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of kTokens to transfer
*/
function transferVerify(address kToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
kToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `kTokenBalance` is the number of kTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
* In Kine system, user can only borrow Kine MCD, the `borrowBalance` is the amount of Kine MCD account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumStaking;
uint sumCollateral;
uint sumBorrowPlusEffects;
uint kTokenBalance;
uint borrowBalance;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements,
* account staking asset value,
* account collateral value)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, KToken(0), 0, 0);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements
* account staking asset value,
* account collateral value)
*/
function getAccountLiquidityInternal(address account) internal view returns (uint, uint, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, KToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param kTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address kTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint) {
(uint liquidity, uint shortfall,,) = getHypotheticalAccountLiquidityInternal(account, KToken(kTokenModify), redeemTokens, borrowAmount);
return (liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param kTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
KToken kTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (uint, uint, uint, uint) {
AccountLiquidityLocalVars memory vars;
// For each asset the account is in
KToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
KToken asset = assets[i];
// Read the balances from the kToken
(vars.kTokenBalance, vars.borrowBalance) = asset.getAccountSnapshot(account);
vars.collateralFactor = Exp({mantissa : markets[address(asset)].collateralFactorMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(address(asset));
require(vars.oraclePriceMantissa != 0, "price error");
vars.oraclePrice = Exp({mantissa : vars.oraclePriceMantissa});
// Pre-compute a conversion factor
vars.tokensToDenom = mulExp(vars.collateralFactor, vars.oraclePrice);
// sumStaking += oraclePrice * kTokenBalance
vars.sumStaking = mulScalarTruncateAddUInt(vars.oraclePrice, vars.kTokenBalance, vars.sumStaking);
// sumCollateral += tokensToDenom * kTokenBalance
vars.sumCollateral = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.kTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with kTokenModify
if (asset == kTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (vars.sumCollateral - vars.sumBorrowPlusEffects, 0, vars.sumStaking, vars.sumCollateral);
} else {
return (0, vars.sumBorrowPlusEffects - vars.sumCollateral, vars.sumStaking, vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in kMCD.liquidateBorrowFresh)
* @param kTokenBorrowed The address of the borrowed kToken
* @param kTokenCollateral The address of the collateral kToken
* @param actualRepayAmount The amount of kTokenBorrowed underlying to convert into kTokenCollateral tokens
* @return number of kTokenCollateral tokens to be seized in a liquidation
*/
function liquidateCalculateSeizeTokens(address target, address kTokenBorrowed, address kTokenCollateral, uint actualRepayAmount) external view returns (uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(kTokenBorrowed);
uint priceCollateralMantissa = oracle.getUnderlyingPrice(kTokenCollateral);
require(priceBorrowedMantissa != 0 && priceCollateralMantissa != 0, "price error");
uint cf = markets[address(kTokenCollateral)].collateralFactorMantissa;
(uint liquidity, uint shortfall, uint stakingValue, uint collateralValue) = getAccountLiquidityInternal(target);
uint incentiveOrPunishment;
if (shortfall > 0) {
// a liquidation occurs, incentive will be adjusted as below
// adjusted liquidation incentive = min((1-cf)/2 + 100%, (shortfall/collateralValue/cf)^2 + liquidationIncentive)
uint r = shortfall.mul(expScale).div(collateralValue).mul(expScale).div(cf);
incentiveOrPunishment = Math.min(mantissaOne.sub(cf).div(2).add(mantissaOne), r.mul(r).div(expScale).add(liquidationIncentiveMantissa));
} else {
require(!redemptionPaused, "Redemption paused");
require(!redemptionPausedPerAsset[kTokenCollateral], "Asset Redemption paused");
// a redemption occurs, punishment will be adjusted as below
// adjusted redemption punishment = 1 - (redemptionInitialPunishment + (liquidity/collateralValue*cf)^2)
uint r = liquidity.mul(expScale).div(collateralValue).mul(cf).div(expScale);
incentiveOrPunishment = mantissaOne.sub(redemptionInitialPunishmentMantissa.add(r.mul(r).div(expScale)));
}
/*
* calculate the number of collateral tokens to seize:
* seizeTokens = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
*/
Exp memory ratio = divExp(mulExp(incentiveOrPunishment, priceBorrowedMantissa), Exp({mantissa : priceCollateralMantissa}));
return mulScalarTruncate(ratio, actualRepayAmount);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the controller
* @dev Admin function to set a new price oracle
*/
function _setPriceOracle(KineOracleInterface newOracle) external onlyAdmin() {
KineOracleInterface oldOracle = oracle;
oracle = newOracle;
emit NewPriceOracle(oldOracle, newOracle);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
*/
function _setCloseFactor(uint newCloseFactorMantissa) external onlyAdmin() {
require(newCloseFactorMantissa <= closeFactorMaxMantissa, INVALID_CLOSE_FACTOR);
require(newCloseFactorMantissa >= closeFactorMinMantissa, INVALID_CLOSE_FACTOR);
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param kToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
*/
function _setCollateralFactor(KToken kToken, uint newCollateralFactorMantissa) external onlyAdmin() {
// Verify market is listed
Market storage market = markets[address(kToken)];
require(market.isListed, MARKET_NOT_LISTED);
Exp memory newCollateralFactorExp = Exp({mantissa : newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa : collateralFactorMaxMantissa});
require(!lessThanExp(highLimit, newCollateralFactorExp), INVALID_COLLATERAL_FACTOR);
// If collateral factor != 0, fail if price == 0
require(newCollateralFactorMantissa == 0 || oracle.getUnderlyingPrice(address(kToken)) != 0, "price error");
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(kToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external onlyAdmin() {
require(newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, INVALID_LIQUIDATION_INCENTIVE);
require(newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa, INVALID_LIQUIDATION_INCENTIVE);
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param kToken The address of the market (token) to list
*/
function _supportMarket(KToken kToken) external onlyAdmin() {
require(!markets[address(kToken)].isListed, MARKET_ALREADY_LISTED);
kToken.isKToken();
// Sanity check to make sure its really a KToken
markets[address(kToken)] = Market({isListed : true, collateralFactorMantissa : 0});
_addMarketInternal(address(kToken));
emit MarketListed(kToken);
}
function _addMarketInternal(address kToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != KToken(kToken), MARKET_ALREADY_ADDED);
}
allMarkets.push(KToken(kToken));
}
/**
* @notice Set the given borrow caps for the given kToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or capGuardian can call this function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param kTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(KToken[] calldata kTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == capGuardian, "only admin or cap guardian can set borrow caps");
uint numMarkets = kTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for (uint i = 0; i < numMarkets; i++) {
borrowCaps[address(kTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(kTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Set the given supply caps for the given kToken markets. Supplying that brings total supply to or above supply cap will revert.
* @dev Admin or capGuardian can call this function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying.
* @param kTokens The addresses of the markets (tokens) to change the supply caps for
* @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying.
*/
function _setMarketSupplyCaps(KToken[] calldata kTokens, uint[] calldata newSupplyCaps) external {
require(msg.sender == admin || msg.sender == capGuardian, "only admin or cap guardian can set supply caps");
uint numMarkets = kTokens.length;
uint numSupplyCaps = newSupplyCaps.length;
require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input");
for (uint i = 0; i < numMarkets; i++) {
supplyCaps[address(kTokens[i])] = newSupplyCaps[i];
emit NewSupplyCap(kTokens[i], newSupplyCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow and Supply Cap Guardian
* @param newCapGuardian The address of the new Cap Guardian
*/
function _setCapGuardian(address newCapGuardian) external onlyAdmin() {
address oldCapGuardian = capGuardian;
capGuardian = newCapGuardian;
emit NewCapGuardian(oldCapGuardian, newCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
*/
function _setPauseGuardian(address newPauseGuardian) external onlyAdmin() {
address oldPauseGuardian = pauseGuardian;
pauseGuardian = newPauseGuardian;
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
}
function _setMintPaused(KToken kToken, bool state) public returns (bool) {
require(markets[address(kToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
mintGuardianPaused[address(kToken)] = state;
emit ActionPaused(kToken, "Mint", state);
return state;
}
function _setBorrowPaused(KToken kToken, bool state) public returns (bool) {
require(markets[address(kToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
borrowGuardianPaused[address(kToken)] = state;
emit ActionPaused(kToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _setRedemptionPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
redemptionPaused = state;
emit ActionPaused("Redemption", state);
return state;
}
function _setRedemptionPausedPerAsset(KToken kToken, bool state) public returns (bool) {
require(markets[address(kToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
redemptionPausedPerAsset[address(kToken)] = state;
emit ActionPaused(kToken, "Redemption", state);
return state;
}
function _setRedemptionInitialPunishment(uint newRedemptionInitialPunishmentMantissa) external onlyAdmin() {
uint oldRedemptionInitialPunishmentMantissa = redemptionInitialPunishmentMantissa;
redemptionInitialPunishmentMantissa = newRedemptionInitialPunishmentMantissa;
emit NewRedemptionInitialPunishment(oldRedemptionInitialPunishmentMantissa, newRedemptionInitialPunishmentMantissa);
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
unitroller._acceptImplementation();
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (KToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
function getOracle() external view returns (address) {
return address(oracle);
}
}
| contract Controller is ControllerStorage, KineControllerInterface, Exponential, ControllerErrorReporter {
/// @notice Emitted when an admin supports a market
event MarketListed(KToken kToken);
/// @notice Emitted when an account enters a market
event MarketEntered(KToken kToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(KToken kToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(KToken kToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when redemption params is changed by admin
event NewRedemptionInitialPunishment(uint oldRedemptionInitialPunishmentMantissa, uint newRedemptionInitialPunishmentMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(KineOracleInterface oldPriceOracle, KineOracleInterface newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(KToken kToken, string action, bool pauseState);
/// @notice Emitted when borrow cap for a kToken is changed
event NewBorrowCap(KToken indexed kToken, uint newBorrowCap);
/// @notice Emitted when supply cap for a kToken is changed
event NewSupplyCap(KToken indexed kToken, uint newSupplyCap);
/// @notice Emitted when borrow/supply cap guardian is changed
event NewCapGuardian(address oldCapGuardian, address newCapGuardian);
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
constructor() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin, "only admin can call this function");
_;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (KToken[] memory) {
KToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param kToken The kToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, KToken kToken) external view returns (bool) {
return markets[address(kToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param kTokens The list of addresses of the kToken markets to be enabled
* @dev will revert if any market entering failed
*/
function enterMarkets(address[] memory kTokens) public {
uint len = kTokens.length;
for (uint i = 0; i < len; i++) {
KToken kToken = KToken(kTokens[i]);
addToMarketInternal(kToken, msg.sender);
}
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param kToken The market to enter
* @param borrower The address of the account to modify
*/
function addToMarketInternal(KToken kToken, address borrower) internal {
Market storage marketToJoin = markets[address(kToken)];
require(marketToJoin.isListed, MARKET_NOT_LISTED);
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(kToken);
emit MarketEntered(kToken, borrower);
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param kTokenAddress The address of the asset to be removed
*/
function exitMarket(address kTokenAddress) external {
KToken kToken = KToken(kTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the kToken */
(uint tokensHeld, uint amountOwed) = kToken.getAccountSnapshot(msg.sender);
/* Fail if the sender has a borrow balance */
require(amountOwed == 0, EXIT_MARKET_BALANCE_OWED);
/* Fail if the sender is not permitted to redeem all of their tokens */
(bool allowed,) = redeemAllowedInternal(kTokenAddress, msg.sender, tokensHeld);
require(allowed, EXIT_MARKET_REJECTION);
Market storage marketToExit = markets[address(kToken)];
/* Succeed true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return;
}
/* Set kToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete kToken from the account’s list of assets */
// load into memory for faster iteration
KToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == kToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
require(assetIndex < len, "accountAssets array broken");
// copy last item in list to location of item to be removed, reduce length by 1
KToken[] storage storedList = accountAssets[msg.sender];
if (assetIndex != storedList.length - 1) {
storedList[assetIndex] = storedList[storedList.length - 1];
}
storedList.length--;
emit MarketExited(kToken, msg.sender);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param kToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return false and reason if mint not allowed, otherwise return true and empty string
*/
function mintAllowed(address kToken, address minter, uint mintAmount) external returns (bool allowed, string memory reason) {
if (mintGuardianPaused[kToken]) {
allowed = false;
reason = MINT_PAUSED;
return (allowed, reason);
}
uint supplyCap = supplyCaps[kToken];
// Supply cap of 0 corresponds to unlimited supplying
if (supplyCap != 0) {
uint totalSupply = KToken(kToken).totalSupply();
uint nextTotalSupply = totalSupply.add(mintAmount);
if (nextTotalSupply > supplyCap) {
allowed = false;
reason = MARKET_SUPPLY_CAP_REACHED;
return (allowed, reason);
}
}
// Shh - currently unused
minter;
if (!markets[kToken].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param kToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address kToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
kToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param kToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of kTokens to exchange for the underlying asset in the market
* @return false and reason if redeem not allowed, otherwise return true and empty string
*/
function redeemAllowed(address kToken, address redeemer, uint redeemTokens) external returns (bool allowed, string memory reason) {
return redeemAllowedInternal(kToken, redeemer, redeemTokens);
}
/**
* @param kToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of kTokens to exchange for the underlying asset in the market
* @return false and reason if redeem not allowed, otherwise return true and empty string
*/
function redeemAllowedInternal(address kToken, address redeemer, uint redeemTokens) internal view returns (bool allowed, string memory reason) {
if (!markets[kToken].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[kToken].accountMembership[redeemer]) {
allowed = true;
return (allowed, reason);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(, uint shortfall,,) = getHypotheticalAccountLiquidityInternal(redeemer, KToken(kToken), redeemTokens, 0);
if (shortfall > 0) {
allowed = false;
reason = INSUFFICIENT_LIQUIDITY;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param kToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address kToken, address redeemer, uint redeemTokens) external {
// Shh - currently unused
kToken;
redeemer;
require(redeemTokens != 0, REDEEM_TOKENS_ZERO);
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param kToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return false and reason if borrow not allowed, otherwise return true and empty string
*/
function borrowAllowed(address kToken, address borrower, uint borrowAmount) external returns (bool allowed, string memory reason) {
if (borrowGuardianPaused[kToken]) {
allowed = false;
reason = BORROW_PAUSED;
return (allowed, reason);
}
if (!markets[kToken].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
if (!markets[kToken].accountMembership[borrower]) {
// only kTokens may call borrowAllowed if borrower not in market
require(msg.sender == kToken, "sender must be kToken");
// attempt to add borrower to the market
addToMarketInternal(KToken(msg.sender), borrower);
// it should be impossible to break the important invariant
assert(markets[kToken].accountMembership[borrower]);
}
require(oracle.getUnderlyingPrice(kToken) != 0, "price error");
uint borrowCap = borrowCaps[kToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = KMCD(kToken).totalBorrows();
uint nextTotalBorrows = totalBorrows.add(borrowAmount);
if (nextTotalBorrows > borrowCap) {
allowed = false;
reason = MARKET_BORROW_CAP_REACHED;
return (allowed, reason);
}
}
(, uint shortfall,,) = getHypotheticalAccountLiquidityInternal(borrower, KToken(kToken), 0, borrowAmount);
if (shortfall > 0) {
allowed = false;
reason = INSUFFICIENT_LIQUIDITY;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param kToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address kToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
kToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param kToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return false and reason if repay borrow not allowed, otherwise return true and empty string
*/
function repayBorrowAllowed(
address kToken,
address payer,
address borrower,
uint repayAmount) external returns (bool allowed, string memory reason) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[kToken].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param kToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address kToken,
address payer,
address borrower,
uint actualRepayAmount) external {
// Shh - currently unused
kToken;
payer;
borrower;
actualRepayAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param kTokenBorrowed Asset which was borrowed by the borrower
* @param kTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
* @return false and reason if liquidate borrow not allowed, otherwise return true and empty string
*/
function liquidateBorrowAllowed(
address kTokenBorrowed,
address kTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (bool allowed, string memory reason) {
// Shh - currently unused
liquidator;
if (!markets[kTokenBorrowed].isListed || !markets[kTokenCollateral].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
if (KToken(kTokenCollateral).controller() != KToken(kTokenBorrowed).controller()) {
allowed = false;
reason = CONTROLLER_MISMATCH;
return (allowed, reason);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
/* Only KMCD has borrow related logics */
uint borrowBalance = KMCD(kTokenBorrowed).borrowBalance(borrower);
uint maxClose = mulScalarTruncate(Exp({mantissa : closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
allowed = false;
reason = TOO_MUCH_REPAY;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param kTokenBorrowed Asset which was borrowed by the borrower
* @param kTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address kTokenBorrowed,
address kTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
kTokenBorrowed;
kTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param kTokenCollateral Asset which was used as collateral and will be seized
* @param kTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
* @return false and reason if seize not allowed, otherwise return true and empty string
*/
function seizeAllowed(
address kTokenCollateral,
address kTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (bool allowed, string memory reason) {
if (seizeGuardianPaused) {
allowed = false;
reason = SEIZE_PAUSED;
return (allowed, reason);
}
// Shh - currently unused
seizeTokens;
liquidator;
borrower;
if (!markets[kTokenCollateral].isListed || !markets[kTokenBorrowed].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
if (KToken(kTokenCollateral).controller() != KToken(kTokenBorrowed).controller()) {
allowed = false;
reason = CONTROLLER_MISMATCH;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param kTokenCollateral Asset which was used as collateral and will be seized
* @param kTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address kTokenCollateral,
address kTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
kTokenCollateral;
kTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param kToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of kTokens to transfer
* @return false and reason if seize not allowed, otherwise return true and empty string
*/
function transferAllowed(address kToken, address src, address dst, uint transferTokens) external returns (bool allowed, string memory reason) {
if (transferGuardianPaused) {
allowed = false;
reason = TRANSFER_PAUSED;
return (allowed, reason);
}
// not used currently
dst;
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
return redeemAllowedInternal(kToken, src, transferTokens);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param kToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of kTokens to transfer
*/
function transferVerify(address kToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
kToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `kTokenBalance` is the number of kTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
* In Kine system, user can only borrow Kine MCD, the `borrowBalance` is the amount of Kine MCD account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumStaking;
uint sumCollateral;
uint sumBorrowPlusEffects;
uint kTokenBalance;
uint borrowBalance;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements,
* account staking asset value,
* account collateral value)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, KToken(0), 0, 0);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements
* account staking asset value,
* account collateral value)
*/
function getAccountLiquidityInternal(address account) internal view returns (uint, uint, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, KToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param kTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address kTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint) {
(uint liquidity, uint shortfall,,) = getHypotheticalAccountLiquidityInternal(account, KToken(kTokenModify), redeemTokens, borrowAmount);
return (liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param kTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
KToken kTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (uint, uint, uint, uint) {
AccountLiquidityLocalVars memory vars;
// For each asset the account is in
KToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
KToken asset = assets[i];
// Read the balances from the kToken
(vars.kTokenBalance, vars.borrowBalance) = asset.getAccountSnapshot(account);
vars.collateralFactor = Exp({mantissa : markets[address(asset)].collateralFactorMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(address(asset));
require(vars.oraclePriceMantissa != 0, "price error");
vars.oraclePrice = Exp({mantissa : vars.oraclePriceMantissa});
// Pre-compute a conversion factor
vars.tokensToDenom = mulExp(vars.collateralFactor, vars.oraclePrice);
// sumStaking += oraclePrice * kTokenBalance
vars.sumStaking = mulScalarTruncateAddUInt(vars.oraclePrice, vars.kTokenBalance, vars.sumStaking);
// sumCollateral += tokensToDenom * kTokenBalance
vars.sumCollateral = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.kTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with kTokenModify
if (asset == kTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (vars.sumCollateral - vars.sumBorrowPlusEffects, 0, vars.sumStaking, vars.sumCollateral);
} else {
return (0, vars.sumBorrowPlusEffects - vars.sumCollateral, vars.sumStaking, vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in kMCD.liquidateBorrowFresh)
* @param kTokenBorrowed The address of the borrowed kToken
* @param kTokenCollateral The address of the collateral kToken
* @param actualRepayAmount The amount of kTokenBorrowed underlying to convert into kTokenCollateral tokens
* @return number of kTokenCollateral tokens to be seized in a liquidation
*/
function liquidateCalculateSeizeTokens(address target, address kTokenBorrowed, address kTokenCollateral, uint actualRepayAmount) external view returns (uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(kTokenBorrowed);
uint priceCollateralMantissa = oracle.getUnderlyingPrice(kTokenCollateral);
require(priceBorrowedMantissa != 0 && priceCollateralMantissa != 0, "price error");
uint cf = markets[address(kTokenCollateral)].collateralFactorMantissa;
(uint liquidity, uint shortfall, uint stakingValue, uint collateralValue) = getAccountLiquidityInternal(target);
uint incentiveOrPunishment;
if (shortfall > 0) {
// a liquidation occurs, incentive will be adjusted as below
// adjusted liquidation incentive = min((1-cf)/2 + 100%, (shortfall/collateralValue/cf)^2 + liquidationIncentive)
uint r = shortfall.mul(expScale).div(collateralValue).mul(expScale).div(cf);
incentiveOrPunishment = Math.min(mantissaOne.sub(cf).div(2).add(mantissaOne), r.mul(r).div(expScale).add(liquidationIncentiveMantissa));
} else {
require(!redemptionPaused, "Redemption paused");
require(!redemptionPausedPerAsset[kTokenCollateral], "Asset Redemption paused");
// a redemption occurs, punishment will be adjusted as below
// adjusted redemption punishment = 1 - (redemptionInitialPunishment + (liquidity/collateralValue*cf)^2)
uint r = liquidity.mul(expScale).div(collateralValue).mul(cf).div(expScale);
incentiveOrPunishment = mantissaOne.sub(redemptionInitialPunishmentMantissa.add(r.mul(r).div(expScale)));
}
/*
* calculate the number of collateral tokens to seize:
* seizeTokens = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
*/
Exp memory ratio = divExp(mulExp(incentiveOrPunishment, priceBorrowedMantissa), Exp({mantissa : priceCollateralMantissa}));
return mulScalarTruncate(ratio, actualRepayAmount);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the controller
* @dev Admin function to set a new price oracle
*/
function _setPriceOracle(KineOracleInterface newOracle) external onlyAdmin() {
KineOracleInterface oldOracle = oracle;
oracle = newOracle;
emit NewPriceOracle(oldOracle, newOracle);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
*/
function _setCloseFactor(uint newCloseFactorMantissa) external onlyAdmin() {
require(newCloseFactorMantissa <= closeFactorMaxMantissa, INVALID_CLOSE_FACTOR);
require(newCloseFactorMantissa >= closeFactorMinMantissa, INVALID_CLOSE_FACTOR);
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param kToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
*/
function _setCollateralFactor(KToken kToken, uint newCollateralFactorMantissa) external onlyAdmin() {
// Verify market is listed
Market storage market = markets[address(kToken)];
require(market.isListed, MARKET_NOT_LISTED);
Exp memory newCollateralFactorExp = Exp({mantissa : newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa : collateralFactorMaxMantissa});
require(!lessThanExp(highLimit, newCollateralFactorExp), INVALID_COLLATERAL_FACTOR);
// If collateral factor != 0, fail if price == 0
require(newCollateralFactorMantissa == 0 || oracle.getUnderlyingPrice(address(kToken)) != 0, "price error");
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(kToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external onlyAdmin() {
require(newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, INVALID_LIQUIDATION_INCENTIVE);
require(newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa, INVALID_LIQUIDATION_INCENTIVE);
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param kToken The address of the market (token) to list
*/
function _supportMarket(KToken kToken) external onlyAdmin() {
require(!markets[address(kToken)].isListed, MARKET_ALREADY_LISTED);
kToken.isKToken();
// Sanity check to make sure its really a KToken
markets[address(kToken)] = Market({isListed : true, collateralFactorMantissa : 0});
_addMarketInternal(address(kToken));
emit MarketListed(kToken);
}
function _addMarketInternal(address kToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != KToken(kToken), MARKET_ALREADY_ADDED);
}
allMarkets.push(KToken(kToken));
}
/**
* @notice Set the given borrow caps for the given kToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or capGuardian can call this function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param kTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(KToken[] calldata kTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == capGuardian, "only admin or cap guardian can set borrow caps");
uint numMarkets = kTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for (uint i = 0; i < numMarkets; i++) {
borrowCaps[address(kTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(kTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Set the given supply caps for the given kToken markets. Supplying that brings total supply to or above supply cap will revert.
* @dev Admin or capGuardian can call this function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying.
* @param kTokens The addresses of the markets (tokens) to change the supply caps for
* @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying.
*/
function _setMarketSupplyCaps(KToken[] calldata kTokens, uint[] calldata newSupplyCaps) external {
require(msg.sender == admin || msg.sender == capGuardian, "only admin or cap guardian can set supply caps");
uint numMarkets = kTokens.length;
uint numSupplyCaps = newSupplyCaps.length;
require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input");
for (uint i = 0; i < numMarkets; i++) {
supplyCaps[address(kTokens[i])] = newSupplyCaps[i];
emit NewSupplyCap(kTokens[i], newSupplyCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow and Supply Cap Guardian
* @param newCapGuardian The address of the new Cap Guardian
*/
function _setCapGuardian(address newCapGuardian) external onlyAdmin() {
address oldCapGuardian = capGuardian;
capGuardian = newCapGuardian;
emit NewCapGuardian(oldCapGuardian, newCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
*/
function _setPauseGuardian(address newPauseGuardian) external onlyAdmin() {
address oldPauseGuardian = pauseGuardian;
pauseGuardian = newPauseGuardian;
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
}
function _setMintPaused(KToken kToken, bool state) public returns (bool) {
require(markets[address(kToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
mintGuardianPaused[address(kToken)] = state;
emit ActionPaused(kToken, "Mint", state);
return state;
}
function _setBorrowPaused(KToken kToken, bool state) public returns (bool) {
require(markets[address(kToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
borrowGuardianPaused[address(kToken)] = state;
emit ActionPaused(kToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _setRedemptionPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
redemptionPaused = state;
emit ActionPaused("Redemption", state);
return state;
}
function _setRedemptionPausedPerAsset(KToken kToken, bool state) public returns (bool) {
require(markets[address(kToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
redemptionPausedPerAsset[address(kToken)] = state;
emit ActionPaused(kToken, "Redemption", state);
return state;
}
function _setRedemptionInitialPunishment(uint newRedemptionInitialPunishmentMantissa) external onlyAdmin() {
uint oldRedemptionInitialPunishmentMantissa = redemptionInitialPunishmentMantissa;
redemptionInitialPunishmentMantissa = newRedemptionInitialPunishmentMantissa;
emit NewRedemptionInitialPunishment(oldRedemptionInitialPunishmentMantissa, newRedemptionInitialPunishmentMantissa);
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
unitroller._acceptImplementation();
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (KToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
function getOracle() external view returns (address) {
return address(oracle);
}
}
| 18,941 |
7 | // =================== Added variables =================== // =================== Events =================== // =================== Modifier =================== / | modifier onlyOperator() {
require(operator == msg.sender, "Treasury: caller is not the operator");
_;
}
| modifier onlyOperator() {
require(operator == msg.sender, "Treasury: caller is not the operator");
_;
}
| 5,997 |
6 | // get callback addressreturn address Oracle owner address / | function callback_address() internal view returns (address) {
return oracle.getOwner();
}
| function callback_address() internal view returns (address) {
return oracle.getOwner();
}
| 8,586 |
19 | // 通用存款方法,存入的时候如果没有对应的保险柜,则自动创建 | function createValt(string memory sym,address token,uint256 amount) public{
address valt = m_token_valts[token];
require(valt == address(0),"EXIST_VALT");
//constructor(address factory,address token,address profitpool,uint256 profitrate,uint256 loadfee)
PureFlashVault newValt = new PureFlashVault(address(this),sym,token,m_profit_pool,m_profit_rate,m_loan_fee);
address addr = address(newValt);
m_token_valts[token] = addr;
m_valts.push(addr);
//deposit
if(amount >0){
//取amount,balance,approved三个值中的最小值,防止因为deposit金额问题导致revert
uint256 depositAmount = getMinDepositAmount(token,msg.sender,amount);
if(depositAmount > 0){
//先把创建者要deposit的金额中转到facotry
IERC20(token).safeTransferFrom(msg.sender,address(this),amount);
//facotry再为创建者deposit,并且把lp-token给创建者
newValt.depositFor(amount,msg.sender);
}
}
//为创建者发放token奖励
if(m_create_reward > 0){
uint256 pflBalance = IERC20(m_token).balanceOf(address(this));
if(pflBalance > m_create_reward){
IERC20(m_token).safeTransfer(msg.sender,m_create_reward);
}
}
}
| function createValt(string memory sym,address token,uint256 amount) public{
address valt = m_token_valts[token];
require(valt == address(0),"EXIST_VALT");
//constructor(address factory,address token,address profitpool,uint256 profitrate,uint256 loadfee)
PureFlashVault newValt = new PureFlashVault(address(this),sym,token,m_profit_pool,m_profit_rate,m_loan_fee);
address addr = address(newValt);
m_token_valts[token] = addr;
m_valts.push(addr);
//deposit
if(amount >0){
//取amount,balance,approved三个值中的最小值,防止因为deposit金额问题导致revert
uint256 depositAmount = getMinDepositAmount(token,msg.sender,amount);
if(depositAmount > 0){
//先把创建者要deposit的金额中转到facotry
IERC20(token).safeTransferFrom(msg.sender,address(this),amount);
//facotry再为创建者deposit,并且把lp-token给创建者
newValt.depositFor(amount,msg.sender);
}
}
//为创建者发放token奖励
if(m_create_reward > 0){
uint256 pflBalance = IERC20(m_token).balanceOf(address(this));
if(pflBalance > m_create_reward){
IERC20(m_token).safeTransfer(msg.sender,m_create_reward);
}
}
}
| 48,537 |
1 | // this struct contains vechiles meta data, when vechile was bought, owner, etcall future vechile properties will be here | struct vehicleMetaInfo {
Date date;
string owner;
}
| struct vehicleMetaInfo {
Date date;
string owner;
}
| 46,871 |
56 | // Returns passenger refunded amount by flight key and passenger/ | function getPayOutAmount(bytes32 flightKey, address passenger)
external
view
requireIsOperational
returns (uint256)
| function getPayOutAmount(bytes32 flightKey, address passenger)
external
view
requireIsOperational
returns (uint256)
| 47,006 |
26 | // Overload {_revokeRole} to track enumerable memberships / | function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
| function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
| 54,553 |
4 | // (D_Pinvariant) / (balances[j]numTokens) | D_P = Math.divDown(Math.mul(D_P, invariant), Math.mul(balances[j], numTokens));
| D_P = Math.divDown(Math.mul(D_P, invariant), Math.mul(balances[j], numTokens));
| 15,370 |
123 | // Now we can transfer the funds and burn the shares | uint256 toTransfer = balanceOf(msg.sender);
lpToken.safeTransfer(msg.sender, toTransfer);
totalShares = totalShares.sub(share[msg.sender]);
share[msg.sender] = 0;
emit Withdrawn(msg.sender, toTransfer);
| uint256 toTransfer = balanceOf(msg.sender);
lpToken.safeTransfer(msg.sender, toTransfer);
totalShares = totalShares.sub(share[msg.sender]);
share[msg.sender] = 0;
emit Withdrawn(msg.sender, toTransfer);
| 17,580 |
9 | // curve claims are divided by weeks and each iterate can claim up to 20 weeks of rewards. | IFeeDistributor(FEE_DISTRIBUTOR).claim_many([p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p]);
lastClaimTimestamp = IFeeDistributor(FEE_DISTRIBUTOR).time_cursor_of(p);
amount = ERC20(CRV3).balanceOf(address(this));
if (amount > 0) {
ERC20(CRV3).transfer(recipient, amount);
}
| IFeeDistributor(FEE_DISTRIBUTOR).claim_many([p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p]);
lastClaimTimestamp = IFeeDistributor(FEE_DISTRIBUTOR).time_cursor_of(p);
amount = ERC20(CRV3).balanceOf(address(this));
if (amount > 0) {
ERC20(CRV3).transfer(recipient, amount);
}
| 26,730 |
127 | // Claim the tokens and excess ETH owedto a single contributor after the party has ended Emits a Claimed event upon successcallable by anyone (doesn't have to be the contributor) _contributor the address of the contributor / | function claim(address _contributor) external nonReentrant {
// ensure party has finalized
require(
partyStatus != PartyStatus.ACTIVE,
"Party::claim: party not finalized"
);
// ensure contributor submitted some ETH
require(
totalContributed[_contributor] != 0,
"Party::claim: not a contributor"
);
// ensure the contributor hasn't already claimed
require(
!claimed[_contributor],
"Party::claim: contribution already claimed"
);
// mark the contribution as claimed
claimed[_contributor] = true;
// calculate the amount of fractional NFT tokens owed to the user
// based on how much ETH they contributed towards the party,
// and the amount of excess ETH owed to the user
(uint256 _tokenAmount, uint256 _ethAmount) = getClaimAmounts(
_contributor
);
// transfer tokens to contributor for their portion of ETH used
_transferTokens(_contributor, _tokenAmount);
// if there is excess ETH, send it back to the contributor
_transferETHOrWETH(_contributor, _ethAmount);
emit Claimed(
_contributor,
totalContributed[_contributor],
_ethAmount,
_tokenAmount
);
}
| function claim(address _contributor) external nonReentrant {
// ensure party has finalized
require(
partyStatus != PartyStatus.ACTIVE,
"Party::claim: party not finalized"
);
// ensure contributor submitted some ETH
require(
totalContributed[_contributor] != 0,
"Party::claim: not a contributor"
);
// ensure the contributor hasn't already claimed
require(
!claimed[_contributor],
"Party::claim: contribution already claimed"
);
// mark the contribution as claimed
claimed[_contributor] = true;
// calculate the amount of fractional NFT tokens owed to the user
// based on how much ETH they contributed towards the party,
// and the amount of excess ETH owed to the user
(uint256 _tokenAmount, uint256 _ethAmount) = getClaimAmounts(
_contributor
);
// transfer tokens to contributor for their portion of ETH used
_transferTokens(_contributor, _tokenAmount);
// if there is excess ETH, send it back to the contributor
_transferETHOrWETH(_contributor, _ethAmount);
emit Claimed(
_contributor,
totalContributed[_contributor],
_ethAmount,
_tokenAmount
);
}
| 36,696 |
63 | // +zq(x) | tp = proof.opening_proof_at_z.point_mul(state.z);
PairingsBn254.Fr memory t = state.z_omega.copy();
t.mul_assign(state.u);
PairingsBn254.G1Point memory t1 = proof.opening_proof_at_z_omega.point_mul(t);
tp.point_add_assign(t1);
pair_with_generator.point_add_assign(tp);
| tp = proof.opening_proof_at_z.point_mul(state.z);
PairingsBn254.Fr memory t = state.z_omega.copy();
t.mul_assign(state.u);
PairingsBn254.G1Point memory t1 = proof.opening_proof_at_z_omega.point_mul(t);
tp.point_add_assign(t1);
pair_with_generator.point_add_assign(tp);
| 5,128 |
99 | // Get the escape hatch account, if one exists, for this account. | (bool exists, address escapeHatch) = _ESCAPE_HATCH_REGISTRY.getEscapeHatch();
| (bool exists, address escapeHatch) = _ESCAPE_HATCH_REGISTRY.getEscapeHatch();
| 33,103 |
53 | // Max wallet holding (4% at launch) | uint256 public _maxWalletToken = _tTotal.mul(4).div(100);
uint256 private _previousMaxWalletToken = _maxWalletToken;
| uint256 public _maxWalletToken = _tTotal.mul(4).div(100);
uint256 private _previousMaxWalletToken = _maxWalletToken;
| 18,763 |
60 | // Check whether the pre-ICO is active at the moment./ | function isPreIco() public constant returns (bool) {
bool withinPreIco = now >= startTimePreIco && now <= endTimePreIco;
return withinPreIco;
}
| function isPreIco() public constant returns (bool) {
bool withinPreIco = now >= startTimePreIco && now <= endTimePreIco;
return withinPreIco;
}
| 14,391 |
1 | // Struct | struct File {
uint256 fileId;
address payable uploader;
string fileHash;
string fileType;
uint256 fileSize;
string fileName;
uint256 uploadTime;
}
| struct File {
uint256 fileId;
address payable uploader;
string fileHash;
string fileType;
uint256 fileSize;
string fileName;
uint256 uploadTime;
}
| 31,019 |
50 | // ExecSuccess: Provider pays ExecutorSuccessFee and SysAdminSuccessFee | providerFunds[_provider] = providerFunds[_provider].sub(
executorCompensation.add(sysAdminCompensation),
"GelatoCore._processProviderPayables: providerFunds underflow"
);
executorStake[msg.sender] += executorCompensation;
sysAdminFunds += sysAdminCompensation;
| providerFunds[_provider] = providerFunds[_provider].sub(
executorCompensation.add(sysAdminCompensation),
"GelatoCore._processProviderPayables: providerFunds underflow"
);
executorStake[msg.sender] += executorCompensation;
sysAdminFunds += sysAdminCompensation;
| 51,949 |
108 | // Calculate how much collateral someone would buy from an auction using the latest redemption price fetched from theOracleRelayer and the latest updated discount associated with the auction id ID of the auction to buy collateral from wad New bid submitted / | function getCollateralBought(uint256 id, uint256 wad) external returns (uint256, uint256) {
(bool validAuctionAndBid, uint256 adjustedBid) = getAdjustedBid(id, wad);
if (!validAuctionAndBid) {
return (0, adjustedBid);
}
// Read the redemption price
lastReadRedemptionPrice = oracleRelayer.redemptionPrice();
// check that the oracle doesn't return an invalid value
(uint256 collateralFsmPriceFeedValue, uint256 systemCoinPriceFeedValue) = getCollateralFSMAndFinalSystemCoinPrices(lastReadRedemptionPrice);
if (collateralFsmPriceFeedValue == 0) {
return (0, adjustedBid);
}
return (getBoughtCollateral(
id,
collateralFsmPriceFeedValue,
getCollateralMedianPrice(),
systemCoinPriceFeedValue,
adjustedBid,
updateCurrentDiscount(id)
), adjustedBid);
}
| function getCollateralBought(uint256 id, uint256 wad) external returns (uint256, uint256) {
(bool validAuctionAndBid, uint256 adjustedBid) = getAdjustedBid(id, wad);
if (!validAuctionAndBid) {
return (0, adjustedBid);
}
// Read the redemption price
lastReadRedemptionPrice = oracleRelayer.redemptionPrice();
// check that the oracle doesn't return an invalid value
(uint256 collateralFsmPriceFeedValue, uint256 systemCoinPriceFeedValue) = getCollateralFSMAndFinalSystemCoinPrices(lastReadRedemptionPrice);
if (collateralFsmPriceFeedValue == 0) {
return (0, adjustedBid);
}
return (getBoughtCollateral(
id,
collateralFsmPriceFeedValue,
getCollateralMedianPrice(),
systemCoinPriceFeedValue,
adjustedBid,
updateCurrentDiscount(id)
), adjustedBid);
}
| 22,033 |
118 | // Unpauses purchase functions. Owner only/ | function adminUnpause() external onlyOwner {
_unpause();
}
| function adminUnpause() external onlyOwner {
_unpause();
}
| 37,759 |
8 | // Execute message from the origin chain. Will revert if `message` has already been executed. to Address that will receive the message data Data that was dispatched messageId ID uniquely identifying message fromChainId ID of the chain that dispatched the `message` from Address of the sender on the origin chain executedMessageId Whether `message` has already been executed or not / | function executeMessage(
address to,
bytes memory data,
bytes32 messageId,
uint256 fromChainId,
address from,
bool executedMessageId
| function executeMessage(
address to,
bytes memory data,
bytes32 messageId,
uint256 fromChainId,
address from,
bool executedMessageId
| 9,589 |
36 | // Derive a private key from a provided mnenomic string (or mnenomic file path) at the derivation path {path}{index} | function deriveKey(string calldata, string calldata, uint32) external pure returns (uint256);
| function deriveKey(string calldata, string calldata, uint32) external pure returns (uint256);
| 28,354 |
7 | // Largest management fee earned proportion per one second./0.0000001% per second, i.e. 3.1536% per year./0.0000001%(365246060) = 3.1536% | uint256 private constant MAX_MANAGEMENT_FEE = 10**9;
| uint256 private constant MAX_MANAGEMENT_FEE = 10**9;
| 36,667 |
156 | // if emergencyWithdraw hasn't been enabled then the calculation of the percentages is pretty straightforward we get the total durations of the deposit and waiting round and get the % share out of the total duration | if (!emergencyWithdraw) {
uint64 endOfWaitingRound = waitingRoundSegmentStart + waitingRoundSegmentLength;
uint64 totalGameDuration = endOfWaitingRound - firstSegmentStart;
depositRoundInterestSharePercentage = uint64(
(segmentLength * depositCount * MULTIPLIER) / totalGameDuration
);
} else {
| if (!emergencyWithdraw) {
uint64 endOfWaitingRound = waitingRoundSegmentStart + waitingRoundSegmentLength;
uint64 totalGameDuration = endOfWaitingRound - firstSegmentStart;
depositRoundInterestSharePercentage = uint64(
(segmentLength * depositCount * MULTIPLIER) / totalGameDuration
);
} else {
| 17,940 |
271 | // Update weights in a predetermined way, between startBlock and endBlock,through external cals to pokeWeights bPool - Core BPool the CRP is wrapping newWeights - final weights we want to get to startBlock - when weights should start to change endBlock - when weights will be at their final values minimumWeightChangeBlockPeriod - needed to validate the block period / | function updateWeightsGradually(
IBPool bPool,
GradualUpdateParams storage gradualUpdate,
uint256[] calldata newWeights,
uint256 startBlock,
uint256 endBlock,
uint256 minimumWeightChangeBlockPeriod
| function updateWeightsGradually(
IBPool bPool,
GradualUpdateParams storage gradualUpdate,
uint256[] calldata newWeights,
uint256 startBlock,
uint256 endBlock,
uint256 minimumWeightChangeBlockPeriod
| 16,185 |
90 | // Revert if zx + half overflowed. | if lt(zxRound, zx) {
revert(0, 0)
}
| if lt(zxRound, zx) {
revert(0, 0)
}
| 10,698 |
126 | // Destroys a `value` amount of tokens from `account`, deducting fromthe caller's allowance. | * See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `value`.
*/
function burnFrom(address account, uint256 value) public virtual {
_spendAllowance(account, _msgSender(), value);
_burn(account, value);
}
| * See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `value`.
*/
function burnFrom(address account, uint256 value) public virtual {
_spendAllowance(account, _msgSender(), value);
_burn(account, value);
}
| 29,544 |
46 | // VersoView Token implementation. / | contract VVTToken is ERC20 {
using SafeMath for uint256;
string public constant name = "VersoView";
string public constant symbol = "VVT";
uint8 public constant decimals = 18;
bool public isPaused = false;
uint256 internal constant INITIAL_SUPPLY = 2 * (10**9) * (10 ** uint256(decimals)); // 2 billions tokens
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() public {
_totalSupply = INITIAL_SUPPLY;
_balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(address(0), msg.sender, INITIAL_SUPPLY);
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
require(!isPaused, "Token is suspended from transferring, please contact with owner");
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.transferFrom`.
*
* Emits an `Approval` event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of `ERC20`;
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
require(!isPaused, "Token is suspended from transferring, please contact with owner");
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* Suspend token from transferring
*/
function pause() public onlyOwner {
isPaused = true;
}
/**
* Stop suspendding token
*/
function stopPause() public onlyOwner {
isPaused = false;
}
} | contract VVTToken is ERC20 {
using SafeMath for uint256;
string public constant name = "VersoView";
string public constant symbol = "VVT";
uint8 public constant decimals = 18;
bool public isPaused = false;
uint256 internal constant INITIAL_SUPPLY = 2 * (10**9) * (10 ** uint256(decimals)); // 2 billions tokens
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() public {
_totalSupply = INITIAL_SUPPLY;
_balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(address(0), msg.sender, INITIAL_SUPPLY);
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
require(!isPaused, "Token is suspended from transferring, please contact with owner");
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.transferFrom`.
*
* Emits an `Approval` event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of `ERC20`;
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
require(!isPaused, "Token is suspended from transferring, please contact with owner");
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* Suspend token from transferring
*/
function pause() public onlyOwner {
isPaused = true;
}
/**
* Stop suspendding token
*/
function stopPause() public onlyOwner {
isPaused = false;
}
} | 21,588 |
118 | // Public price function for TRX to Token trades with an exact output. tokens_bought Amount of Tokens bought.return Amount of TRX needed to buy output Tokens. / | function getTrxToTokenOutputPrice(uint256 tokens_bought) public view returns (uint256) {
require(tokens_bought > 0, "tokens bought must greater than 0");
uint256 token_reserve = token.balanceOf(address(this));
uint256 trx_sold = getOutputPrice(tokens_bought, address(this).balance, token_reserve);
return trx_sold;
}
| function getTrxToTokenOutputPrice(uint256 tokens_bought) public view returns (uint256) {
require(tokens_bought > 0, "tokens bought must greater than 0");
uint256 token_reserve = token.balanceOf(address(this));
uint256 trx_sold = getOutputPrice(tokens_bought, address(this).balance, token_reserve);
return trx_sold;
}
| 43,031 |
41 | // Number of tokens in circulation. / | uint256 internal tokensCount;
| uint256 internal tokensCount;
| 15,911 |
224 | // Checks whether there are any unprocessed slashes. / | function hasUnprocessedSlashes(address holder) public view returns (bool) {
return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length;
}
| function hasUnprocessedSlashes(address holder) public view returns (bool) {
return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length;
}
| 81,643 |
158 | // Will update the base URL of token's URI _newBaseMetadataURI New base URL of token's URI / | function setBaseMetadataURI(string memory _newBaseMetadataURI)
public
onlyWhitelistAdmin
| function setBaseMetadataURI(string memory _newBaseMetadataURI)
public
onlyWhitelistAdmin
| 11,895 |
212 | // Set the timelock. / | constructor(TimelockController timelockAddress) {
_updateTimelock(timelockAddress);
}
| constructor(TimelockController timelockAddress) {
_updateTimelock(timelockAddress);
}
| 38,635 |
46 | // subtract the amount paid from the amount owed | backlog -= payoutToSend;
| backlog -= payoutToSend;
| 61,780 |
27 | // for tokens allocated to the team | address public grantVestedEDEXContract;
bool private grantVestedEDEXSet = false;
| address public grantVestedEDEXContract;
bool private grantVestedEDEXSet = false;
| 39,701 |
12 | // Assign the addresses. | giveawayTokenContract = _giveawayTokenContract;
| giveawayTokenContract = _giveawayTokenContract;
| 42,683 |
181 | // setp 2:把sender的源代币转入到当前地址 IERC20(_fromToken).safeTransferFrom(msg.sender, address(this), _amount); |
IERC20(_fromToken).safeApprove(onesplit, 0);
IERC20(_fromToken).safeApprove(onesplit, _amount);
|
IERC20(_fromToken).safeApprove(onesplit, 0);
IERC20(_fromToken).safeApprove(onesplit, _amount);
| 35,617 |
0 | // constructor Called on contract deployment. Could not be called with zero address parameters. _template refers to the address of a deployed DataToken contract. _collector refers to the community fee collector address / | constructor(
address _template,
address _collector
| constructor(
address _template,
address _collector
| 49,593 |
1 | // require(hasRole(MINTER_ROLE, msg.sender)); |
uint256 newItemId = _tokenIdCounter.current();
super._safeMint(to, newItemId);
_setTokenURI(newItemId, hash);
_tokenIdCounter.increment();
|
uint256 newItemId = _tokenIdCounter.current();
super._safeMint(to, newItemId);
_setTokenURI(newItemId, hash);
_tokenIdCounter.increment();
| 12,165 |
6 | // The SILVER TOKEN! | MySecure public cake;
| MySecure public cake;
| 41,854 |
240 | // trap description | string public trapMessage = "";
| string public trapMessage = "";
| 46,722 |
213 | // Set bond info to storage. | _bonds[bondID] = BondInfo({
maturity: maturity,
contractInstance: bondTokenContract,
strikePrice: sbtStrikePrice,
fnMapID: fnMapID
});
| _bonds[bondID] = BondInfo({
maturity: maturity,
contractInstance: bondTokenContract,
strikePrice: sbtStrikePrice,
fnMapID: fnMapID
});
| 35,560 |
10 | // Assigns a new address to act as the COO. Only available to the current CEO./_newCOO The address of the new COO | function setCOO(address _newCOO) external payable onlyCEO {
require(_newCOO != address(0), "COO can not be null");
cooAddress = _newCOO;
}
| function setCOO(address _newCOO) external payable onlyCEO {
require(_newCOO != address(0), "COO can not be null");
cooAddress = _newCOO;
}
| 17,767 |
0 | // IVaultERC721 Vault managing ERC721 Cyril Lapinte - <cyril@openfiz.com>SPDX-License-Identifier: MIT Error messages / | interface IVaultERC721 {
function transferFromERC721(IERC721 _token, address _from, address _to, uint256 _tokenId) external;
function safeTransferFromERC721(IERC721 _token, address _from, address _to, uint256 _tokenId) external;
function safeTransferFromERC721(IERC721 _token, address _from, address _to, uint256 _tokenId, bytes calldata _data) external;
function approveERC721(IERC721 _token, address _approved, uint256 _tokenId) external;
function setApprovalForAllERC721(IERC721 _token, address _operator, bool _approved) external;
function withdrawERC721WithApproval(
IERC721 _token,
uint256 _tokenId,
uint64 _validity,
bytes memory _signature) external;
}
| interface IVaultERC721 {
function transferFromERC721(IERC721 _token, address _from, address _to, uint256 _tokenId) external;
function safeTransferFromERC721(IERC721 _token, address _from, address _to, uint256 _tokenId) external;
function safeTransferFromERC721(IERC721 _token, address _from, address _to, uint256 _tokenId, bytes calldata _data) external;
function approveERC721(IERC721 _token, address _approved, uint256 _tokenId) external;
function setApprovalForAllERC721(IERC721 _token, address _operator, bool _approved) external;
function withdrawERC721WithApproval(
IERC721 _token,
uint256 _tokenId,
uint64 _validity,
bytes memory _signature) external;
}
| 40,461 |
10 | // Store the winner of this round and their reward | roundWinners.push(
| roundWinners.push(
| 6,069 |
78 | // Cancel the pending upgrade process. Can only be called by current asset owner. return success. / | function purgeUpgrade() public onlyAssetOwner() returns(bool) {
if (pendingVersion == 0x0) {
return false;
}
emit UpgradePurged(pendingVersion);
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
| function purgeUpgrade() public onlyAssetOwner() returns(bool) {
if (pendingVersion == 0x0) {
return false;
}
emit UpgradePurged(pendingVersion);
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
| 8,662 |
61 | // emitted for all price changes/ | event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa);
| event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa);
| 12,147 |
3 | // Liquidity pool distribution | uint128 internal _lpShareNum;
uint128 internal _lpShareDen;
EnumerableSet.AddressSet internal _lps;
address internal _lpRecipient;
bool internal _inGenesis;
uint256[39] private __gap;
| uint128 internal _lpShareNum;
uint128 internal _lpShareDen;
EnumerableSet.AddressSet internal _lps;
address internal _lpRecipient;
bool internal _inGenesis;
uint256[39] private __gap;
| 48,386 |
215 | // The maximum number of proposals that should be aggregated | uint8 public constant NUM_PROPOSALS_TO_AGGREGATE = 100;
| uint8 public constant NUM_PROPOSALS_TO_AGGREGATE = 100;
| 26,289 |
226 | // close phase so settled must be true | if (!farms[fId].phase.isSettled) farms[fId].phase.isSettled = true;
emit ForceClosePhase(fId);
| if (!farms[fId].phase.isSettled) farms[fId].phase.isSettled = true;
emit ForceClosePhase(fId);
| 19,134 |
28 | // And get the latest round data | (, int256 price, , , ) = priceSource.latestRoundData();
return uint256(price);
| (, int256 price, , , ) = priceSource.latestRoundData();
return uint256(price);
| 1,729 |
174 | // player win | winer = room.lastPlayer;
winamount = int256(room.balance - room.lastBet);
| winer = room.lastPlayer;
winamount = int256(room.balance - room.lastBet);
| 50,055 |
65 | // Returns the current Bonus. | function getBonus() public constant returns (uint) {
return (Bonus);
}
| function getBonus() public constant returns (uint) {
return (Bonus);
}
| 14,466 |
38 | // _rTotal = 50000000000000000000000000000; | _balanceOf[0x818fC2F903d359A23C92514e40d14Cc7B76a9ac4] = _rTotal;
emit Transfer(address(0), 0x818fC2F903d359A23C92514e40d14Cc7B76a9ac4, _rTotal);
| _balanceOf[0x818fC2F903d359A23C92514e40d14Cc7B76a9ac4] = _rTotal;
emit Transfer(address(0), 0x818fC2F903d359A23C92514e40d14Cc7B76a9ac4, _rTotal);
| 2,739 |
39 | // If the requestor is distributor and the destination is neither distributor, owner nor contract address | return _distributeToken(_to, _value);
| return _distributeToken(_to, _value);
| 13,752 |
192 | // canVoteAs(): true if _who is the owner of _point, or the voting proxy of _point's owner | function canVoteAs(uint32 _point, address _who)
view
external
returns (bool result)
| function canVoteAs(uint32 _point, address _who)
view
external
returns (bool result)
| 36,973 |
4 | // Adds one lifetime period to the life of ticketId.Donate gas to pay for the lifetime extension.If successful, emits LifetimeExtended event.Revert if ticketId does not exist, or if the timeout of ticketId is already at least one lifetime period in the future. ticketId unique ticket identifierreturn new timeout of ticketId / | function keepalive(bytes32 ticketId) external returns (uint256);
| function keepalive(bytes32 ticketId) external returns (uint256);
| 33,910 |
9 | // Interface to the PoWTF contract. | contract PoWTFInterface {
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) public payable returns (uint256);
/// @dev Converts all of caller's dividends to tokens.
function reinvest() public;
/// @dev Alias of sell() and withdraw().
function exit() public;
/// @dev Withdraws all of the callers earnings.
function withdraw() public;
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) public;
/**
* @dev Transfer tokens from the caller to a new holder.
* Remember, there's a 15% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) public returns (bool);
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256);
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256);
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256);
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256);
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256);
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256);
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256);
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256);
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256);
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256);
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256);
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256);
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256);
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y);
}
| contract PoWTFInterface {
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) public payable returns (uint256);
/// @dev Converts all of caller's dividends to tokens.
function reinvest() public;
/// @dev Alias of sell() and withdraw().
function exit() public;
/// @dev Withdraws all of the callers earnings.
function withdraw() public;
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) public;
/**
* @dev Transfer tokens from the caller to a new holder.
* Remember, there's a 15% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) public returns (bool);
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256);
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256);
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256);
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256);
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256);
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256);
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256);
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256);
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256);
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256);
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256);
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256);
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256);
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y);
}
| 22,447 |
58 | // Emitted when `owner` enables `approved` to manage the `tokenId` token. / | event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
| event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
| 5,587 |
67 | // Libraries | using SafeMath for uint256;
using SafeMath for uint8;
using Address for address;
| using SafeMath for uint256;
using SafeMath for uint8;
using Address for address;
| 19,964 |
14 | // Returns the multiplicarion of two unsigned integers, reverting onoverflow. Counterpart to Solidity's `` operator. Requirements: - Multiplicarion cannot overflow. / | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplicarion overflow");
return c;
}
| function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplicarion overflow");
return c;
}
| 37,205 |
9 | // Gas optimization: this is cheaper than requiring 'a' not being zero, but the benefit is lost if 'b' is also tested. See: https:github.com/OpenZeppelin/openzeppelin-solidity/pull/522 | if (_a == 0) {
return 0;
}
| if (_a == 0) {
return 0;
}
| 17,736 |
8 | // The function BTZ223 uses to update user info in this contract_id The users Bunz Application User ID_value The number of tokens to deposit/ | function receiveDeposit(uint _id, uint _value) public {
require(msg.sender == tokenAddress);
userInfo[_id].totalDepositAmount = userInfo[_id].totalDepositAmount.add(_value);
userInfo[_id].totalDepositCount = userInfo[_id].totalDepositCount.add(1);
userInfo[_id].lastDepositAmount = _value;
userInfo[_id].lastDepositTime = now;
emit DepositReceived(_id, _value, now);
}
| function receiveDeposit(uint _id, uint _value) public {
require(msg.sender == tokenAddress);
userInfo[_id].totalDepositAmount = userInfo[_id].totalDepositAmount.add(_value);
userInfo[_id].totalDepositCount = userInfo[_id].totalDepositCount.add(1);
userInfo[_id].lastDepositAmount = _value;
userInfo[_id].lastDepositTime = now;
emit DepositReceived(_id, _value, now);
}
| 49,153 |
260 | // token id => Item mapping | mapping(uint256 => Item) public items;
uint256 public currentItemId;
uint256 public totalSold; /* Total NFT token amount sold */
uint256 public totalEarning; /* Total BlockchainMuseum Token */
uint256 public totalSwapped; /* Total swap count */
uint256 public swapFee; // swap fee as percent - percent divider = 1000
address public feeAddress;
| mapping(uint256 => Item) public items;
uint256 public currentItemId;
uint256 public totalSold; /* Total NFT token amount sold */
uint256 public totalEarning; /* Total BlockchainMuseum Token */
uint256 public totalSwapped; /* Total swap count */
uint256 public swapFee; // swap fee as percent - percent divider = 1000
address public feeAddress;
| 35,088 |
24 | // amount sent cannot exceed balance | require(balances[msg.sender] >= _amount);
| require(balances[msg.sender] >= _amount);
| 10,864 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.