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 |
|---|---|---|---|---|
114 | // Updates the fee amount and it's split ratio between the relayer and feeSplitRecipient | function updateFee(uint256 _feeNumerator, uint256 _feeSplitNumerator) public onlyOwner {
feeNumerator = _feeNumerator;
feeSplitNumerator = _feeSplitNumerator;
}
| function updateFee(uint256 _feeNumerator, uint256 _feeSplitNumerator) public onlyOwner {
feeNumerator = _feeNumerator;
feeSplitNumerator = _feeSplitNumerator;
}
| 36,313 |
129 | // Modifier to only allow the execution of certain functions restricted to the creator | modifier onlyCreatorLevel() {
require(
creator == msg.sender
);
_;
}
| modifier onlyCreatorLevel() {
require(
creator == msg.sender
);
_;
}
| 39,330 |
23 | // overrides safeTransferFrom to prevent transfer if token is staked / | function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
| function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
| 16,019 |
198 | // microLinkPerEth is 1e-6LINK/ETH units, gasCostEthWei is 1e-18ETH units (ETH-wei), product is 1e-24LINK-wei units, dividing by 1e6 gives 1e-18LINK units, i.e. LINK-wei units Safe from over/underflow, since all components are non-negative, gasCostEthWei will always fit into uint128 and microLinkPerEth is a uint32 (128+32 < 256!). | uint256 gasCostLinkWei = (gasCostEthWei * billing.microLinkPerEth)/ 1e6;
| uint256 gasCostLinkWei = (gasCostEthWei * billing.microLinkPerEth)/ 1e6;
| 26,003 |
225 | // See {setApprovalForAll}. / | function isApprovedForAll(address account, address operator) public view returns (bool) {
return everRiseToken.isApprovedForAll(account, operator);
}
| function isApprovedForAll(address account, address operator) public view returns (bool) {
return everRiseToken.isApprovedForAll(account, operator);
}
| 26,755 |
8 | // Do not collect after birthday time | if (block.timestamp >= birthday) throw;
| if (block.timestamp >= birthday) throw;
| 11,027 |
18 | // Gets a metaverse registry at a given index/_metaverseId The target metaverse/_index The target index | function registryAt(uint256 _metaverseId, uint256 _index)
external
view
returns (address)
| function registryAt(uint256 _metaverseId, uint256 _index)
external
view
returns (address)
| 74,514 |
9 | // Multiplier used to offset small percentage values to fit within a uint256/ e.g. 5% is internally represented as (0.05mul). The final result/ after calculations is divided by mul again to retrieve a real value | uint256 internal constant MUL = 1e10;
| uint256 internal constant MUL = 1e10;
| 28,594 |
126 | // Chooses the best strategy and re-invests. If the strategy did not change, it just calls doHardWork on the current strategy. Call this through controller to claim hard rewards./ | function doHardWork() whenStrategyDefined onlyControllerOrGovernance external {
// ensure that new funds are invested too
invest();
strategy.doHardWork();
}
| function doHardWork() whenStrategyDefined onlyControllerOrGovernance external {
// ensure that new funds are invested too
invest();
strategy.doHardWork();
}
| 45,462 |
14 | // A contract attempts to get the coins / | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
return true;
}
| function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
return true;
}
| 15,297 |
32 | // The address that will receive the commission for each transaction to or from the owner | address public tokenCommissionReceiver = 0xEa8867Ce34CC66318D4A055f43Cac6a88966C43f;
string public name = "ATON";
string public symbol = "ATL";
| address public tokenCommissionReceiver = 0xEa8867Ce34CC66318D4A055f43Cac6a88966C43f;
string public name = "ATON";
string public symbol = "ATL";
| 21,573 |
29 | // Allows the owner to change the broker. _broker The broker address / | function changeBroker(address _broker) public onlyOwner {
emit BrokerChanged(broker, _broker);
broker = _broker;
}
| function changeBroker(address _broker) public onlyOwner {
emit BrokerChanged(broker, _broker);
broker = _broker;
}
| 56,205 |
400 | // Calculate denominator for row 204: x - g^204z. | let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x880)))
mstore(add(productsPtr, 0x5e0), partialProduct)
mstore(add(valuesPtr, 0x5e0), denominator)
partialProduct := mulmod(partialProduct, denominator, PRIME)
| let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x880)))
mstore(add(productsPtr, 0x5e0), partialProduct)
mstore(add(valuesPtr, 0x5e0), denominator)
partialProduct := mulmod(partialProduct, denominator, PRIME)
| 47,263 |
3 | // Sets or upgrades the RariGovernanceTokenDistributor of the RariFundToken. Caller must have the {MinterRole}. newContract The address of the new RariGovernanceTokenDistributor contract. force Boolean indicating if we should not revert on validation error. / | function setGovernanceTokenDistributor(address payable newContract, bool force) external onlyMinter {
if (!force && address(rariGovernanceTokenDistributor) != address(0)) {
require(rariGovernanceTokenDistributor.disabled(), "The old governance token distributor contract has not been disabled. (Set `force` to true to avoid this error.)");
require(newContract != address(0), "By default, the governance token distributor cannot be set to the zero address. (Set `force` to true to avoid this error.)");
}
| function setGovernanceTokenDistributor(address payable newContract, bool force) external onlyMinter {
if (!force && address(rariGovernanceTokenDistributor) != address(0)) {
require(rariGovernanceTokenDistributor.disabled(), "The old governance token distributor contract has not been disabled. (Set `force` to true to avoid this error.)");
require(newContract != address(0), "By default, the governance token distributor cannot be set to the zero address. (Set `force` to true to avoid this error.)");
}
| 6,502 |
15 | // Withdraws all from IDLE/ | function withdrawAll() internal {
uint256 balance = IERC20(idleUnderlying).balanceOf(address(this));
// this automatically claims the crops
IIdleTokenV3_1(idleUnderlying).redeemIdleToken(balance);
liquidateRewards();
}
| function withdrawAll() internal {
uint256 balance = IERC20(idleUnderlying).balanceOf(address(this));
// this automatically claims the crops
IIdleTokenV3_1(idleUnderlying).redeemIdleToken(balance);
liquidateRewards();
}
| 44,907 |
13 | // A record of states for signing / validating signatures | mapping (address => uint) public nonces;
| mapping (address => uint) public nonces;
| 6,502 |
141 | // Grants `role` to `account`. Internal function without access restriction. / | function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
| function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
| 2,669 |
38 | // _______ __________ _____ _ __ _______ |__ __| |__ ||_| | ___|| | / /| | |__ __| | || __ _|| |_| | | | | |/ / __| || | | || |\ \ |_| | |__ | |\ \|__| | || | |_||_| \_\|_| |_| |____|| | \_\|_||_| / | contract TRACK {
/// @notice EIP-20 token name for this token
string public constant name = "TRACK-IT Token";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "TRACK";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 50000000e18;
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 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 The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comp token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
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) public {
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), "Comp::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce");
require(now <= expiry, "Comp::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 (uint96) {
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) public view returns (uint96) {
require(blockNumber < block.number, "Comp::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];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comp::_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 safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | contract TRACK {
/// @notice EIP-20 token name for this token
string public constant name = "TRACK-IT Token";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "TRACK";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 50000000e18;
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 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 The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comp token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
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) public {
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), "Comp::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce");
require(now <= expiry, "Comp::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 (uint96) {
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) public view returns (uint96) {
require(blockNumber < block.number, "Comp::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];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comp::_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 safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | 40,670 |
40 | // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires division by ONE_20. | int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
| int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
| 12,763 |
82 | // / | function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x >= y ? x : y;
}
| function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x >= y ? x : y;
}
| 11,145 |
18 | // Configure the max amount of passes that can be redeemed in a txn for a specific pass index id of tokenuri to point the token to/ | function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){
require(_exists(id), "ERC721Metadata: Token does not exist");
tokenData[id].tokenURI = uri;
tokenData[id].exists = true;
}
| function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){
require(_exists(id), "ERC721Metadata: Token does not exist");
tokenData[id].tokenURI = uri;
tokenData[id].exists = true;
}
| 19,470 |
42 | // Element Finance/Yearn Vault v1 Asset Proxy | contract YVaultAssetProxy is WrappedPosition, Authorizable {
// The addresses of the current yearn vault
IYearnVault public vault;
// 18 decimal fractional form of the multiplier which is applied after
// a vault upgrade. 0 when no upgrade has happened
uint88 public conversionRate;
// Bool packed into the same storage slot as vault and conversion rate
bool public paused;
uint8 public immutable vaultDecimals;
/// @notice Constructs this contract and stores needed data
/// @param vault_ The yearn v2 vault
/// @param _token The underlying token.
/// This token should revert in the event of a transfer failure.
/// @param _name The name of the token created
/// @param _symbol The symbol of the token created
/// @param _governance The address which can upgrade the yearn vault
/// @param _pauser address which can pause this contract
constructor(
address vault_,
IERC20 _token,
string memory _name,
string memory _symbol,
address _governance,
address _pauser
) WrappedPosition(_token, _name, _symbol) Authorizable() {
// Authorize the pauser
_authorize(_pauser);
// set the owner
setOwner(_governance);
// Set the vault
vault = IYearnVault(vault_);
// Approve the vault so it can pull tokens from this address
_token.approve(vault_, type(uint256).max);
// Load the decimals and set them as an immutable
uint8 localVaultDecimals = IERC20(vault_).decimals();
vaultDecimals = localVaultDecimals;
require(
uint8(_token.decimals()) == localVaultDecimals,
"Inconsistent decimals"
);
}
/// @notice Checks that the contract has not been paused
modifier notPaused() {
require(!paused, "Paused");
_;
}
/// @notice Makes the actual deposit into the yearn vault
/// @return Tuple (the shares minted, amount underlying used)
function _deposit() internal override notPaused returns (uint256, uint256) {
// Get the amount deposited
uint256 amount = token.balanceOf(address(this));
// Deposit and get the shares that were minted to this
uint256 shares = vault.deposit(amount, address(this));
// If we have migrated our shares are no longer 1 - 1 with the vault shares
if (conversionRate != 0) {
// conversionRate is the fraction of yearnSharePrice1/yearnSharePrices2 at time of migration
// and so this multiplication will convert between yearn shares in the new vault and
// those in the old vault
shares = (shares * conversionRate) / 1e18;
}
// Return the amount of shares the user has produced, and the amount used for it.
return (shares, amount);
}
/// @notice Withdraw the number of shares
/// @param _shares The number of wrapped position shares to withdraw
/// @param _destination The address to send the output funds
// @param _underlyingPerShare The possibly precomputed underlying per share
/// @return returns the amount of funds freed by doing a yearn withdraw
function _withdraw(
uint256 _shares,
address _destination,
uint256
) internal override notPaused returns (uint256) {
// If the conversion rate is non-zero we have upgraded and so our wrapped shares are
// not one to one with the original shares.
if (conversionRate != 0) {
// Then since conversion rate is yearnSharePrice1/yearnSharePrices2 we divide the
// wrapped position shares by it because they are equivalent to the first yearn vault shares
_shares = (_shares * 1e18) / conversionRate;
}
// Withdraws shares from the vault. Max loss is set at 100% as
// the minimum output value is enforced by the calling
// function in the WrappedPosition contract.
uint256 amountReceived = vault.withdraw(_shares, _destination, 10000);
// Return the amount of underlying
return amountReceived;
}
/// @notice Get the underlying amount of tokens per shares given
/// @param _amount The amount of shares you want to know the value of
/// @return Value of shares in underlying token
function _underlying(uint256 _amount)
internal
view
override
returns (uint256)
{
// We may have to convert before using the vault price per share
if (conversionRate != 0) {
// Imitate the _withdraw logic and convert this amount to yearn vault2 shares
_amount = (_amount * 1e18) / conversionRate;
}
return (_amount * _pricePerShare()) / (10**vaultDecimals);
}
/// @notice Get the price per share in the vault
/// @return The price per share in units of underlying;
function _pricePerShare() internal view returns (uint256) {
return vault.pricePerShare();
}
/// @notice Function to reset approvals for the proxy
function approve() external {
token.approve(address(vault), 0);
token.approve(address(vault), type(uint256).max);
}
/// @notice Allows an authorized address or the owner to pause this contract
/// @param pauseStatus true for paused, false for not paused
/// @dev the caller must be authorized
function pause(bool pauseStatus) external onlyAuthorized {
paused = pauseStatus;
}
/// @notice Function to transition between two yearn vaults
/// @param newVault The address of the new vault
/// @param minOutputShares The min of the new yearn vault's shares the wp will receive
/// @dev WARNING - This function has the capacity to steal all user funds from this
/// contract and so it should be ensured that the owner is a high quorum
/// governance vote through the time lock.
function transition(IYearnVault newVault, uint256 minOutputShares)
external
onlyOwner
{
// Load the current vault's price per share
uint256 currentPricePerShare = _pricePerShare();
// Load the new vault's price per share
uint256 newPricePerShare = newVault.pricePerShare();
// Load the current conversion rate or set it to 1
uint256 newConversionRate = conversionRate == 0 ? 1e18 : conversionRate;
// Calculate the new conversion rate, note by multiplying by the old
// conversion rate here we implicitly support more than 1 upgrade
newConversionRate =
(newConversionRate * newPricePerShare) /
currentPricePerShare;
// We now withdraw from the old yearn vault using max shares
// Note - Vaults should be checked in the future that they still have this behavior
vault.withdraw(type(uint256).max, address(this), 10000);
// Approve the new vault
token.approve(address(newVault), type(uint256).max);
// Then we deposit into the new vault
uint256 currentBalance = token.balanceOf(address(this));
uint256 outputShares = newVault.deposit(currentBalance, address(this));
// We enforce a min output
require(outputShares >= minOutputShares, "Not enough output");
// Change the stored variables
vault = newVault;
// because of the truncation yearn vaults can't have a larger diff than ~ billion
// times larger
conversionRate = uint88(newConversionRate);
}
}
| contract YVaultAssetProxy is WrappedPosition, Authorizable {
// The addresses of the current yearn vault
IYearnVault public vault;
// 18 decimal fractional form of the multiplier which is applied after
// a vault upgrade. 0 when no upgrade has happened
uint88 public conversionRate;
// Bool packed into the same storage slot as vault and conversion rate
bool public paused;
uint8 public immutable vaultDecimals;
/// @notice Constructs this contract and stores needed data
/// @param vault_ The yearn v2 vault
/// @param _token The underlying token.
/// This token should revert in the event of a transfer failure.
/// @param _name The name of the token created
/// @param _symbol The symbol of the token created
/// @param _governance The address which can upgrade the yearn vault
/// @param _pauser address which can pause this contract
constructor(
address vault_,
IERC20 _token,
string memory _name,
string memory _symbol,
address _governance,
address _pauser
) WrappedPosition(_token, _name, _symbol) Authorizable() {
// Authorize the pauser
_authorize(_pauser);
// set the owner
setOwner(_governance);
// Set the vault
vault = IYearnVault(vault_);
// Approve the vault so it can pull tokens from this address
_token.approve(vault_, type(uint256).max);
// Load the decimals and set them as an immutable
uint8 localVaultDecimals = IERC20(vault_).decimals();
vaultDecimals = localVaultDecimals;
require(
uint8(_token.decimals()) == localVaultDecimals,
"Inconsistent decimals"
);
}
/// @notice Checks that the contract has not been paused
modifier notPaused() {
require(!paused, "Paused");
_;
}
/// @notice Makes the actual deposit into the yearn vault
/// @return Tuple (the shares minted, amount underlying used)
function _deposit() internal override notPaused returns (uint256, uint256) {
// Get the amount deposited
uint256 amount = token.balanceOf(address(this));
// Deposit and get the shares that were minted to this
uint256 shares = vault.deposit(amount, address(this));
// If we have migrated our shares are no longer 1 - 1 with the vault shares
if (conversionRate != 0) {
// conversionRate is the fraction of yearnSharePrice1/yearnSharePrices2 at time of migration
// and so this multiplication will convert between yearn shares in the new vault and
// those in the old vault
shares = (shares * conversionRate) / 1e18;
}
// Return the amount of shares the user has produced, and the amount used for it.
return (shares, amount);
}
/// @notice Withdraw the number of shares
/// @param _shares The number of wrapped position shares to withdraw
/// @param _destination The address to send the output funds
// @param _underlyingPerShare The possibly precomputed underlying per share
/// @return returns the amount of funds freed by doing a yearn withdraw
function _withdraw(
uint256 _shares,
address _destination,
uint256
) internal override notPaused returns (uint256) {
// If the conversion rate is non-zero we have upgraded and so our wrapped shares are
// not one to one with the original shares.
if (conversionRate != 0) {
// Then since conversion rate is yearnSharePrice1/yearnSharePrices2 we divide the
// wrapped position shares by it because they are equivalent to the first yearn vault shares
_shares = (_shares * 1e18) / conversionRate;
}
// Withdraws shares from the vault. Max loss is set at 100% as
// the minimum output value is enforced by the calling
// function in the WrappedPosition contract.
uint256 amountReceived = vault.withdraw(_shares, _destination, 10000);
// Return the amount of underlying
return amountReceived;
}
/// @notice Get the underlying amount of tokens per shares given
/// @param _amount The amount of shares you want to know the value of
/// @return Value of shares in underlying token
function _underlying(uint256 _amount)
internal
view
override
returns (uint256)
{
// We may have to convert before using the vault price per share
if (conversionRate != 0) {
// Imitate the _withdraw logic and convert this amount to yearn vault2 shares
_amount = (_amount * 1e18) / conversionRate;
}
return (_amount * _pricePerShare()) / (10**vaultDecimals);
}
/// @notice Get the price per share in the vault
/// @return The price per share in units of underlying;
function _pricePerShare() internal view returns (uint256) {
return vault.pricePerShare();
}
/// @notice Function to reset approvals for the proxy
function approve() external {
token.approve(address(vault), 0);
token.approve(address(vault), type(uint256).max);
}
/// @notice Allows an authorized address or the owner to pause this contract
/// @param pauseStatus true for paused, false for not paused
/// @dev the caller must be authorized
function pause(bool pauseStatus) external onlyAuthorized {
paused = pauseStatus;
}
/// @notice Function to transition between two yearn vaults
/// @param newVault The address of the new vault
/// @param minOutputShares The min of the new yearn vault's shares the wp will receive
/// @dev WARNING - This function has the capacity to steal all user funds from this
/// contract and so it should be ensured that the owner is a high quorum
/// governance vote through the time lock.
function transition(IYearnVault newVault, uint256 minOutputShares)
external
onlyOwner
{
// Load the current vault's price per share
uint256 currentPricePerShare = _pricePerShare();
// Load the new vault's price per share
uint256 newPricePerShare = newVault.pricePerShare();
// Load the current conversion rate or set it to 1
uint256 newConversionRate = conversionRate == 0 ? 1e18 : conversionRate;
// Calculate the new conversion rate, note by multiplying by the old
// conversion rate here we implicitly support more than 1 upgrade
newConversionRate =
(newConversionRate * newPricePerShare) /
currentPricePerShare;
// We now withdraw from the old yearn vault using max shares
// Note - Vaults should be checked in the future that they still have this behavior
vault.withdraw(type(uint256).max, address(this), 10000);
// Approve the new vault
token.approve(address(newVault), type(uint256).max);
// Then we deposit into the new vault
uint256 currentBalance = token.balanceOf(address(this));
uint256 outputShares = newVault.deposit(currentBalance, address(this));
// We enforce a min output
require(outputShares >= minOutputShares, "Not enough output");
// Change the stored variables
vault = newVault;
// because of the truncation yearn vaults can't have a larger diff than ~ billion
// times larger
conversionRate = uint88(newConversionRate);
}
}
| 27,897 |
177 | // make owner to the owner of that contract | dbot.transferOwnership(dbot.owner());
| dbot.transferOwnership(dbot.owner());
| 16,041 |
116 | // Base contract of nest | contract NestBase {
// Address of nest token contract
address constant NEST_TOKEN_ADDRESS = 0x04abEdA201850aC0124161F037Efd70c74ddC74C;
// Genesis block number of nest
// NEST token contract is created at block height 6913517. However, because the mining algorithm of nest1.0
// is different from that at present, a new mining algorithm is adopted from nest2.0. The new algorithm
// includes the attenuation logic according to the block. Therefore, it is necessary to trace the block
// where the nest begins to decay. According to the circulation when nest2.0 is online, the new mining
// algorithm is used to deduce and convert the nest, and the new algorithm is used to mine the nest2.0
// on-line flow, the actual block is 5120000
uint constant NEST_GENESIS_BLOCK = 5120000;
/// @dev To support open-zeppelin/upgrades
/// @param nestGovernanceAddress INestGovernance implementation contract address
function initialize(address nestGovernanceAddress) virtual public {
require(_governance == address(0), 'NEST:!initialize');
_governance = nestGovernanceAddress;
}
/// @dev INestGovernance implementation contract address
address public _governance;
/// @dev Rewritten in the implementation contract, for load other contract addresses. Call
/// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance
/// @param nestGovernanceAddress INestGovernance implementation contract address
function update(address nestGovernanceAddress) virtual public {
address governance = _governance;
require(governance == msg.sender || INestGovernance(governance).checkGovernance(msg.sender, 0), "NEST:!gov");
_governance = nestGovernanceAddress;
}
/// @dev Migrate funds from current contract to NestLedger
/// @param tokenAddress Destination token address.(0 means eth)
/// @param value Migrate amount
function migrate(address tokenAddress, uint value) external onlyGovernance {
address to = INestGovernance(_governance).getNestLedgerAddress();
if (tokenAddress == address(0)) {
INestLedger(to).addETHReward { value: value } (address(0));
} else {
TransferHelper.safeTransfer(tokenAddress, to, value);
}
}
//---------modifier------------
modifier onlyGovernance() {
require(INestGovernance(_governance).checkGovernance(msg.sender, 0), "NEST:!gov");
_;
}
modifier noContract() {
require(msg.sender == tx.origin, "NEST:!contract");
_;
}
}
| contract NestBase {
// Address of nest token contract
address constant NEST_TOKEN_ADDRESS = 0x04abEdA201850aC0124161F037Efd70c74ddC74C;
// Genesis block number of nest
// NEST token contract is created at block height 6913517. However, because the mining algorithm of nest1.0
// is different from that at present, a new mining algorithm is adopted from nest2.0. The new algorithm
// includes the attenuation logic according to the block. Therefore, it is necessary to trace the block
// where the nest begins to decay. According to the circulation when nest2.0 is online, the new mining
// algorithm is used to deduce and convert the nest, and the new algorithm is used to mine the nest2.0
// on-line flow, the actual block is 5120000
uint constant NEST_GENESIS_BLOCK = 5120000;
/// @dev To support open-zeppelin/upgrades
/// @param nestGovernanceAddress INestGovernance implementation contract address
function initialize(address nestGovernanceAddress) virtual public {
require(_governance == address(0), 'NEST:!initialize');
_governance = nestGovernanceAddress;
}
/// @dev INestGovernance implementation contract address
address public _governance;
/// @dev Rewritten in the implementation contract, for load other contract addresses. Call
/// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance
/// @param nestGovernanceAddress INestGovernance implementation contract address
function update(address nestGovernanceAddress) virtual public {
address governance = _governance;
require(governance == msg.sender || INestGovernance(governance).checkGovernance(msg.sender, 0), "NEST:!gov");
_governance = nestGovernanceAddress;
}
/// @dev Migrate funds from current contract to NestLedger
/// @param tokenAddress Destination token address.(0 means eth)
/// @param value Migrate amount
function migrate(address tokenAddress, uint value) external onlyGovernance {
address to = INestGovernance(_governance).getNestLedgerAddress();
if (tokenAddress == address(0)) {
INestLedger(to).addETHReward { value: value } (address(0));
} else {
TransferHelper.safeTransfer(tokenAddress, to, value);
}
}
//---------modifier------------
modifier onlyGovernance() {
require(INestGovernance(_governance).checkGovernance(msg.sender, 0), "NEST:!gov");
_;
}
modifier noContract() {
require(msg.sender == tx.origin, "NEST:!contract");
_;
}
}
| 19,833 |
262 | // 9. Assign the return variable. | withdraw = amount;
| withdraw = amount;
| 9,432 |
189 | // Current order tries to deal against the AMM pool. Returns whether current order fully deals. | function _tryDealInPool(Context memory ctx, bool isBuy, RatPrice memory price) private pure returns (bool) {
uint currTokenCanTrade = _intopoolAmountTillPrice(isBuy, ctx.reserveMoney, ctx.reserveStock, price);
require(currTokenCanTrade < uint(1<<112), "GraSwap: CURR_TOKEN_TOO_LARGE");
// all the below variables are less than 112 bits
if(!isBuy) {
currTokenCanTrade /= ctx.stockUnit; //to round
currTokenCanTrade *= ctx.stockUnit;
}
if(currTokenCanTrade > ctx.amountIntoPool) {
uint diffTokenCanTrade = currTokenCanTrade - ctx.amountIntoPool;
bool allDeal = diffTokenCanTrade >= ctx.remainAmount;
if(allDeal) {
diffTokenCanTrade = ctx.remainAmount;
}
ctx.amountIntoPool += diffTokenCanTrade;
ctx.remainAmount -= diffTokenCanTrade;
return allDeal;
}
return false;
}
| function _tryDealInPool(Context memory ctx, bool isBuy, RatPrice memory price) private pure returns (bool) {
uint currTokenCanTrade = _intopoolAmountTillPrice(isBuy, ctx.reserveMoney, ctx.reserveStock, price);
require(currTokenCanTrade < uint(1<<112), "GraSwap: CURR_TOKEN_TOO_LARGE");
// all the below variables are less than 112 bits
if(!isBuy) {
currTokenCanTrade /= ctx.stockUnit; //to round
currTokenCanTrade *= ctx.stockUnit;
}
if(currTokenCanTrade > ctx.amountIntoPool) {
uint diffTokenCanTrade = currTokenCanTrade - ctx.amountIntoPool;
bool allDeal = diffTokenCanTrade >= ctx.remainAmount;
if(allDeal) {
diffTokenCanTrade = ctx.remainAmount;
}
ctx.amountIntoPool += diffTokenCanTrade;
ctx.remainAmount -= diffTokenCanTrade;
return allDeal;
}
return false;
}
| 38,868 |
21 | // Unanimously agree to cancel a dispute/signatures Signatures by all signing keys of the currently latest disputed/ state; an indication of agreement of this state and valid to cancel a dispute/Note this function is only callable when the state channel is in a DISPUTE state | function cancelDispute(bytes signatures)
public
onlyWhenChannelDispute
| function cancelDispute(bytes signatures)
public
onlyWhenChannelDispute
| 4,126 |
84 | // return the current dividend accrual rate, in USD per secondreturn dividend in USD per second / | function getCurrentValue() external view returns (uint256);
| function getCurrentValue() external view returns (uint256);
| 24,354 |
17 | // Team allocation percentages (KEY, BBT) + (Pot , Referrals, Community) Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. | fees_[0] = BBTdatasets.TeamFee(45,20); //15% to pot, 10% to aff, 10% to air drop pot
fees_[1] = BBTdatasets.TeamFee(15,20); //45% to pot, 10% to aff, 10% to air drop pot
| fees_[0] = BBTdatasets.TeamFee(45,20); //15% to pot, 10% to aff, 10% to air drop pot
fees_[1] = BBTdatasets.TeamFee(15,20); //45% to pot, 10% to aff, 10% to air drop pot
| 19,907 |
34 | // the actual amounts collected are returned | (amount0, amount1) = pool.collect(
recipient,
position.tickLower,
position.tickUpper,
amount0Collect,
amount1Collect
);
| (amount0, amount1) = pool.collect(
recipient,
position.tickLower,
position.tickUpper,
amount0Collect,
amount1Collect
);
| 70,039 |
58 | // Insert the last asset into the position previously occupied by the asset to be removed | _assetsOf[from][assetIndex] = lastAssetId;
| _assetsOf[from][assetIndex] = lastAssetId;
| 3,218 |
175 | // Current additionally assignable reward (RNB) of the user (depositor), meaning what wasn't added to UserInfo, but will be upon the next addToTheUsersAssignedReward() call (read only, does not save/alter state) | function calculateUsersAssignableReward() public view returns(uint256) {
// ---
// --- similar to addToTheUsersAssignedReward(), but without the writes, plus few other modifications
// ---
uint256 currentStakingDayNumber = getCurrentStakingDayNumber();
uint256 currentStakingDayNumberMinusOne = SafeMath.sub(currentStakingDayNumber, 1);
if (currentStakingDayNumber == 0) {
return 0;
}
UserInfo storage user = userInfo[msg.sender];
if (user.lptAmount == 0) {
// user.rewardCountedUptoDay = currentStakingDayNumberMinusOne; // different from addToTheUsersAssignedReward
return 0; // different from addToTheUsersAssignedReward
}
// ---
uint256 rewardCountedUptoDay = user.rewardCountedUptoDay;
uint256 rewardCountedUptoDayNextDay = SafeMath.add(rewardCountedUptoDay, 1);
if (!(rewardCountedUptoDayNextDay <= currentStakingDayNumberMinusOne)) {
return 0; // different from addToTheUsersAssignedReward
}
// ---
uint256 usersRewardRecently = 0;
for (uint256 i = rewardCountedUptoDayNextDay; i <= currentStakingDayNumberMinusOne; i++) {
if (dailyTotalLptAmount[i] == 0) {
continue;
}
// logic used here is because of integer division, we improve precision (not perfect solution, good enough)
// (sample use 10^4 instead of 10^19 units)
// 49.5k = users stake, 80k = total stake, 2k = daily reward)
// correct value would be = 1237.5
// (49 500 / 80 000 = 0.61875 = 0) * 2000 = 0;
// ((49 500 * 100) / 80 000 = 61,875 = 61) * 2000 = 122000) / 100 = 1220 = 1220
// ((49 500 * 1000) / 80 000 = 618,75 = 618) * 2000 = 1236000) / 1000 = 1236 = 1236
// ((49 500 * 10000) / 80 000 = 6187.5 = 6187) * 2000 = 12374000) / 10000 = 1237.4 = 1237
uint256 raiser = 10000000000000000000; // 10^19
// uint256 rew = (((user.lptAmount.mul(raiser)).div(dailyTotalLptAmount[i])).mul(dailyPlannedErc20RewardAmounts[i])).div(raiser);
// with SafeMath:
uint256 rew = SafeMath.mul(user.lptAmount, raiser);
rew = SafeMath.div(rew, dailyTotalLptAmount[i]);
rew = SafeMath.mul(rew, dailyPlannedErc20RewardAmounts[i]);
rew = SafeMath.div(rew, raiser);
if (dailyErc20RewardAmounts[i] < rew) {
// the has to be added amount is less, than the remaining (global), can happen because of slight rounding issues at the very end
// not really... more likely the oposite (that some small residue gets left behind)
rew = dailyErc20RewardAmounts[i];
}
usersRewardRecently = SafeMath.add(usersRewardRecently, rew);
// dailyErc20RewardAmounts[i] = SafeMath.sub(dailyErc20RewardAmounts[i], rew); // different from addToTheUsersAssignedReward
}
// different from addToTheUsersAssignedReward
// user.currentlyAssignedRewardAmount = SafeMath.add(user.currentlyAssignedRewardAmount, usersRewardRecently);
// currentTotalErc20RewardAmount = SafeMath.sub(currentTotalErc20RewardAmount, usersRewardRecently);
// user.rewardCountedUptoDay = currentStakingDayNumberMinusOne;
// ---
// ---
// ---
return usersRewardRecently;
}
| function calculateUsersAssignableReward() public view returns(uint256) {
// ---
// --- similar to addToTheUsersAssignedReward(), but without the writes, plus few other modifications
// ---
uint256 currentStakingDayNumber = getCurrentStakingDayNumber();
uint256 currentStakingDayNumberMinusOne = SafeMath.sub(currentStakingDayNumber, 1);
if (currentStakingDayNumber == 0) {
return 0;
}
UserInfo storage user = userInfo[msg.sender];
if (user.lptAmount == 0) {
// user.rewardCountedUptoDay = currentStakingDayNumberMinusOne; // different from addToTheUsersAssignedReward
return 0; // different from addToTheUsersAssignedReward
}
// ---
uint256 rewardCountedUptoDay = user.rewardCountedUptoDay;
uint256 rewardCountedUptoDayNextDay = SafeMath.add(rewardCountedUptoDay, 1);
if (!(rewardCountedUptoDayNextDay <= currentStakingDayNumberMinusOne)) {
return 0; // different from addToTheUsersAssignedReward
}
// ---
uint256 usersRewardRecently = 0;
for (uint256 i = rewardCountedUptoDayNextDay; i <= currentStakingDayNumberMinusOne; i++) {
if (dailyTotalLptAmount[i] == 0) {
continue;
}
// logic used here is because of integer division, we improve precision (not perfect solution, good enough)
// (sample use 10^4 instead of 10^19 units)
// 49.5k = users stake, 80k = total stake, 2k = daily reward)
// correct value would be = 1237.5
// (49 500 / 80 000 = 0.61875 = 0) * 2000 = 0;
// ((49 500 * 100) / 80 000 = 61,875 = 61) * 2000 = 122000) / 100 = 1220 = 1220
// ((49 500 * 1000) / 80 000 = 618,75 = 618) * 2000 = 1236000) / 1000 = 1236 = 1236
// ((49 500 * 10000) / 80 000 = 6187.5 = 6187) * 2000 = 12374000) / 10000 = 1237.4 = 1237
uint256 raiser = 10000000000000000000; // 10^19
// uint256 rew = (((user.lptAmount.mul(raiser)).div(dailyTotalLptAmount[i])).mul(dailyPlannedErc20RewardAmounts[i])).div(raiser);
// with SafeMath:
uint256 rew = SafeMath.mul(user.lptAmount, raiser);
rew = SafeMath.div(rew, dailyTotalLptAmount[i]);
rew = SafeMath.mul(rew, dailyPlannedErc20RewardAmounts[i]);
rew = SafeMath.div(rew, raiser);
if (dailyErc20RewardAmounts[i] < rew) {
// the has to be added amount is less, than the remaining (global), can happen because of slight rounding issues at the very end
// not really... more likely the oposite (that some small residue gets left behind)
rew = dailyErc20RewardAmounts[i];
}
usersRewardRecently = SafeMath.add(usersRewardRecently, rew);
// dailyErc20RewardAmounts[i] = SafeMath.sub(dailyErc20RewardAmounts[i], rew); // different from addToTheUsersAssignedReward
}
// different from addToTheUsersAssignedReward
// user.currentlyAssignedRewardAmount = SafeMath.add(user.currentlyAssignedRewardAmount, usersRewardRecently);
// currentTotalErc20RewardAmount = SafeMath.sub(currentTotalErc20RewardAmount, usersRewardRecently);
// user.rewardCountedUptoDay = currentStakingDayNumberMinusOne;
// ---
// ---
// ---
return usersRewardRecently;
}
| 29,411 |
3 | // Emitted when contract has been deployed. destination Destination address reserve Strategy address strategy Reserve address/ | event Deployed(
address indexed destination,
IReserve indexed reserve,
IStrategy indexed strategy
);
| event Deployed(
address indexed destination,
IReserve indexed reserve,
IStrategy indexed strategy
);
| 24,888 |
7 | // Whitelisted contracts, set by an auth | mapping (address => uint256) public bud;
| mapping (address => uint256) public bud;
| 31,945 |
25 | // poster (receiver) is subject to backup withholding, so keep a running balance, transfer to contract address | payable(address(this)).transfer(msg.value);
balances[poster] += msg.value;
| payable(address(this)).transfer(msg.value);
balances[poster] += msg.value;
| 30,507 |
13 | // Payout creator earnings (funds from minting locked on dstChain).collectionAddress The address of the ERC721 collection. dstChainName Name of the remote chain. redirectFee Fee required to cover transaction fee on the redirectChain, if involved. OmnichainRouter-specific. Involved during cross-chain multi-protocol routing. For example, Optimism (LayerZero) to Moonbeam (Axelar). / | function getEarned(address collectionAddress, string memory dstChainName, uint256 gas, uint256 redirectFee) external payable nonReentrant {
IOmniERC721 collection = IOmniERC721(collectionAddress);
uint256 price = collection.mintPrice();
uint256 amount = mints[collectionAddress][dstChainName] * price;
require(price > 0 && amount > 0 && msg.sender == collection.creator());
mints[collectionAddress][dstChainName] = 0;
_omniAction(_getWithdrawPayload(collectionAddress, true, amount, collection.assetName()), dstChainName, gas, redirectFee);
}
| function getEarned(address collectionAddress, string memory dstChainName, uint256 gas, uint256 redirectFee) external payable nonReentrant {
IOmniERC721 collection = IOmniERC721(collectionAddress);
uint256 price = collection.mintPrice();
uint256 amount = mints[collectionAddress][dstChainName] * price;
require(price > 0 && amount > 0 && msg.sender == collection.creator());
mints[collectionAddress][dstChainName] = 0;
_omniAction(_getWithdrawPayload(collectionAddress, true, amount, collection.assetName()), dstChainName, gas, redirectFee);
}
| 10,500 |
62 | // Process member burn of `shares` and/or `loot` to claim 'fair share' of `guildTokens`./to Account that receives 'fair share'./lootToBurn Baal pure economic weight to burn./sharesToBurn Baal voting weight to burn. | function ragequit(
address to,
uint96 lootToBurn,
uint96 sharesToBurn
| function ragequit(
address to,
uint96 lootToBurn,
uint96 sharesToBurn
| 4,849 |
83 | // Executes the strategy. Does not use the config argument. vaultTokenIn_ the address of the YEarnV2 vault token to exit tokenInAmount_ amount of tokenOut config_ configreturn executeUniLikeFrom always USDC / | function getExecuteDataByAmountIn(
address vaultTokenIn_,
uint256 tokenInAmount_,
bytes memory config_
)
external
view
override
returns (
address executeUniLikeFrom,
| function getExecuteDataByAmountIn(
address vaultTokenIn_,
uint256 tokenInAmount_,
bytes memory config_
)
external
view
override
returns (
address executeUniLikeFrom,
| 33,639 |
7 | // Register `asset`/ If either the erc20 address or the asset was already registered, fail/ return true if the erc20 address was not already registered./ @custom:governance | function register(IAsset asset) external returns (bool);
| function register(IAsset asset) external returns (bool);
| 31,222 |
32 | // renderfunction |
function tokenURI(
uint256 tokenId
)
public
view
virtual
override(IERC721AUpgradeable, ERC721AUpgradeable)
returns (string memory)
|
function tokenURI(
uint256 tokenId
)
public
view
virtual
override(IERC721AUpgradeable, ERC721AUpgradeable)
returns (string memory)
| 25,656 |
65 | // the cliff period has not ended, no tokens to draw down | return 0;
| return 0;
| 2,913 |
31 | // mapping from a pixelId to the price of that pixel | mapping (uint => uint ) private pixelToPrice;
| mapping (uint => uint ) private pixelToPrice;
| 11,793 |
455 | // - Pay submitter with challenger deposits | function doPaySubmitter(bytes32 superblockHash, SuperblockClaim storage claim) internal {
address challenger;
uint bondedDeposit;
for (uint idx=0; idx < claim.challengers.length; ++idx) {
challenger = claim.challengers[idx];
bondedDeposit = claim.bondedDeposits[challenger];
claim.bondedDeposits[challenger] = 0;
claim.bondedDeposits[claim.submitter] = claim.bondedDeposits[claim.submitter].add(bondedDeposit);
}
unbondDeposit(superblockHash, claim.submitter);
}
| function doPaySubmitter(bytes32 superblockHash, SuperblockClaim storage claim) internal {
address challenger;
uint bondedDeposit;
for (uint idx=0; idx < claim.challengers.length; ++idx) {
challenger = claim.challengers[idx];
bondedDeposit = claim.bondedDeposits[challenger];
claim.bondedDeposits[challenger] = 0;
claim.bondedDeposits[claim.submitter] = claim.bondedDeposits[claim.submitter].add(bondedDeposit);
}
unbondDeposit(superblockHash, claim.submitter);
}
| 3,134 |
3 | // The hash of 'ALGEBRA_BASE_PLUGIN_FACTORY_ADMINISTRATOR' used as role/allows to change settings of BasePluginV1Factory | function ALGEBRA_BASE_PLUGIN_FACTORY_ADMINISTRATOR() external pure returns (bytes32);
| function ALGEBRA_BASE_PLUGIN_FACTORY_ADMINISTRATOR() external pure returns (bytes32);
| 27,102 |
140 | // Allows for depositing the underlying asset in exchange for shares assigned to the holder. This facilitates depositing for someone else (using DepositHelper)/ | function depositFor(uint256 amount, address holder) public defense {
_deposit(amount, msg.sender, holder);
}
| function depositFor(uint256 amount, address holder) public defense {
_deposit(amount, msg.sender, holder);
}
| 26,400 |
219 | // Withdraw tokens in unbalanced proportion amount_ amount of internal token to burn outAmountPCTs_ array of token amount percentages to withdrawreturn outAmounts_ array of tokens amounts that were withdrawn/ | function widthdrawUnbalanced (
uint256 amount_,
uint256[N_TOKENS] calldata outAmountPCTs_
)
external
nonReentrant
returns (uint256[N_TOKENS] memory outAmounts_)
| function widthdrawUnbalanced (
uint256 amount_,
uint256[N_TOKENS] calldata outAmountPCTs_
)
external
nonReentrant
returns (uint256[N_TOKENS] memory outAmounts_)
| 31,373 |
464 | // Mark the Vault as initialized. | isInitialized = true;
| isInitialized = true;
| 30,567 |
27 | // Update the time of the last staking action for the staker | staker.timeOfLastUpdate = block.timestamp;
| staker.timeOfLastUpdate = block.timestamp;
| 26,777 |
155 | // The User Contract enables the entering of a deployed swap along with the wrapping of Ether.Thiscontract was specifically made for drct.decentralizedderivatives.org to simplify user metamask calls/ | contract UserContract{
using SafeMath for uint256;
/*Variables*/
TokenToTokenSwap_Interface internal swap;
Wrapped_Ether internal baseToken;
Factory internal factory;
address public factory_address;
address internal owner;
/*Functions*/
constructor() public {
owner = msg.sender;
}
/**
*@dev Value must be sent with Initiate and enter the _amount(in wei)
*@param _swapadd is the address of the deployed contract created from the Factory contract
*@param _amount is the amount of the base tokens(short or long) in the
*swap. For wrapped Ether, this is wei.
*/
function Initiate(address _swapadd, uint _amount) payable public{
require(msg.value == _amount.mul(2));
swap = TokenToTokenSwap_Interface(_swapadd);
address token_address = factory.token();
baseToken = Wrapped_Ether(token_address);
baseToken.createToken.value(_amount.mul(2))();
baseToken.transfer(_swapadd,_amount.mul(2));
swap.createSwap(_amount, msg.sender);
}
/**
*@dev Set factory address
*@param _factory_address is the factory address to clone?
*/
function setFactory(address _factory_address) public {
require (msg.sender == owner);
factory_address = _factory_address;
factory = Factory(factory_address);
}
} | contract UserContract{
using SafeMath for uint256;
/*Variables*/
TokenToTokenSwap_Interface internal swap;
Wrapped_Ether internal baseToken;
Factory internal factory;
address public factory_address;
address internal owner;
/*Functions*/
constructor() public {
owner = msg.sender;
}
/**
*@dev Value must be sent with Initiate and enter the _amount(in wei)
*@param _swapadd is the address of the deployed contract created from the Factory contract
*@param _amount is the amount of the base tokens(short or long) in the
*swap. For wrapped Ether, this is wei.
*/
function Initiate(address _swapadd, uint _amount) payable public{
require(msg.value == _amount.mul(2));
swap = TokenToTokenSwap_Interface(_swapadd);
address token_address = factory.token();
baseToken = Wrapped_Ether(token_address);
baseToken.createToken.value(_amount.mul(2))();
baseToken.transfer(_swapadd,_amount.mul(2));
swap.createSwap(_amount, msg.sender);
}
/**
*@dev Set factory address
*@param _factory_address is the factory address to clone?
*/
function setFactory(address _factory_address) public {
require (msg.sender == owner);
factory_address = _factory_address;
factory = Factory(factory_address);
}
} | 72,704 |
90 | // vote expire (1 day) | if(block.number.sub(session.blockNo) > NUMBER_OF_BLOCK_FOR_SESSION_EXPIRE) return true;
return false;
| if(block.number.sub(session.blockNo) > NUMBER_OF_BLOCK_FOR_SESSION_EXPIRE) return true;
return false;
| 24,336 |
65 | // Convert back into 18 decimals (1e18) | debtBalance = highPrecisionBalance.preciseDecimalToDecimal();
| debtBalance = highPrecisionBalance.preciseDecimalToDecimal();
| 28,450 |
92 | // fallback to desired wrapper if 0x failed | if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
| if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
| 13,425 |
0 | // / | struct Contract{
bytes32 IdTransaction;
bytes32 amount;
bytes32 currency;
bool IsRecovered;
bool IsInDefault;
bool sellerGotPaid;
}
| struct Contract{
bytes32 IdTransaction;
bytes32 amount;
bytes32 currency;
bool IsRecovered;
bool IsInDefault;
bool sellerGotPaid;
}
| 25,809 |
17 | // Ensure that the caller owns the key | modifier onlyKeyOwner(
uint _tokenId
| modifier onlyKeyOwner(
uint _tokenId
| 47,088 |
12 | // -- 해당 후보자가 해당 투표장에 등록된 후보자가 맞는지 검출. 연달아 사용해서 해당 후보자가 해당 투표장에 존재하면 true를 리턴 | function getCandidateId(uint index) constant returns(uint, uint) {
return (candidateList[index].placeID, candidateList[index].candidateID);
}
| function getCandidateId(uint index) constant returns(uint, uint) {
return (candidateList[index].placeID, candidateList[index].candidateID);
}
| 44,924 |
134 | // How many SNX do they have, excluding escrow? Note: We're excluding escrow here because we're interested in their transferable amount and escrowed SNX are not transferable. | uint balance = tokenState.balanceOf(account);
| uint balance = tokenState.balanceOf(account);
| 8,650 |
246 | // Transition `loanState` to `Liquidated` | loanState = State.Liquidated;
emit Liquidation(
amountLiquidated, // Amount of Collateral Asset swapped.
amountRecovered, // Amount of Liquidity Asset recovered from swap.
liquidationExcess, // Amount of Liquidity Asset returned to borrower.
defaultSuffered // Remaining losses after the liquidation.
);
emit LoanStateChanged(State.Liquidated);
| loanState = State.Liquidated;
emit Liquidation(
amountLiquidated, // Amount of Collateral Asset swapped.
amountRecovered, // Amount of Liquidity Asset recovered from swap.
liquidationExcess, // Amount of Liquidity Asset returned to borrower.
defaultSuffered // Remaining losses after the liquidation.
);
emit LoanStateChanged(State.Liquidated);
| 14,757 |
16 | // return The token being used / | function buck() public view returns(Buck) {
return _buck;
}
| function buck() public view returns(Buck) {
return _buck;
}
| 10,521 |
23 | // Transfer all the funds to the crowdsale address. | sale.transfer(contract_eth_value);
| sale.transfer(contract_eth_value);
| 14,660 |
7 | // SaturatingMath/Sometimes we neither want math operations to error nor wrap around/ on an overflow or underflow. In the case of transferring assets an error/ may cause assets to be locked in an irretrievable state within the erroring/ contract, e.g. due to a tiny rounding/calculation error. We also can't have/ assets underflowing and attempting to approve/transfer "infinity" when we/ wanted "almost or exactly zero" but some calculation bug underflowed zero./ Ideally there are no calculation mistakes, but in guarding against bugs it/ may be safer pragmatically to saturate arithmatic at the numeric bounds./ Note that saturating div is not supported because | library SaturatingMath {
/// Saturating addition.
/// @param a_ First term.
/// @param b_ Second term.
/// @return Minimum of a_ + b_ and max uint256.
function saturatingAdd(uint256 a_, uint256 b_)
internal
pure
returns (uint256)
{
unchecked {
uint256 c_ = a_ + b_;
return c_ < a_ ? type(uint256).max : c_;
}
}
/// Saturating subtraction.
/// @param a_ Minuend.
/// @param b_ Subtrahend.
/// @return Maximum of a_ - b_ and 0.
function saturatingSub(uint256 a_, uint256 b_)
internal
pure
returns (uint256)
{
unchecked {
return a_ > b_ ? a_ - b_ : 0;
}
}
/// Saturating multiplication.
/// @param a_ First term.
/// @param b_ Second term.
/// @return Minimum of a_ * b_ and max uint256.
function saturatingMul(uint256 a_, uint256 b_)
internal
pure
returns (uint256)
{
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being
// zero, but the benefit is lost if 'b' is also tested.
// https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a_ == 0) return 0;
uint256 c_ = a_ * b_;
return c_ / a_ != b_ ? type(uint256).max : c_;
}
}
}
| library SaturatingMath {
/// Saturating addition.
/// @param a_ First term.
/// @param b_ Second term.
/// @return Minimum of a_ + b_ and max uint256.
function saturatingAdd(uint256 a_, uint256 b_)
internal
pure
returns (uint256)
{
unchecked {
uint256 c_ = a_ + b_;
return c_ < a_ ? type(uint256).max : c_;
}
}
/// Saturating subtraction.
/// @param a_ Minuend.
/// @param b_ Subtrahend.
/// @return Maximum of a_ - b_ and 0.
function saturatingSub(uint256 a_, uint256 b_)
internal
pure
returns (uint256)
{
unchecked {
return a_ > b_ ? a_ - b_ : 0;
}
}
/// Saturating multiplication.
/// @param a_ First term.
/// @param b_ Second term.
/// @return Minimum of a_ * b_ and max uint256.
function saturatingMul(uint256 a_, uint256 b_)
internal
pure
returns (uint256)
{
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being
// zero, but the benefit is lost if 'b' is also tested.
// https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a_ == 0) return 0;
uint256 c_ = a_ * b_;
return c_ / a_ != b_ ? type(uint256).max : c_;
}
}
}
| 21,030 |
22 | // a helper function which be used to prove a users tickets were included in the lottery | function checkMerkleProof (
address user,
uint256 first,
uint256 last,
bytes32 merkleRoot,
| function checkMerkleProof (
address user,
uint256 first,
uint256 last,
bytes32 merkleRoot,
| 32,910 |
148 | // debug function for testrpc | return this.balance;
| return this.balance;
| 34,863 |
5 | // how much should service get | uint256 serviceAmount = balance - clientAmount;
| uint256 serviceAmount = balance - clientAmount;
| 41,998 |
52 | // This updates the interest rate model for the risky tokeninterestRateModel The interest rate model for the risky token Requirements: - Only the Int Governance can update this value.- Interest rate model and token cannot be the address zero / | function setRiskyTokenInterestRateModel(address interestRateModel)
external
onlyOwner
| function setRiskyTokenInterestRateModel(address interestRateModel)
external
onlyOwner
| 1,588 |
3 | // mapping from alphaIndex to its score | string[4] _alphas = [
"8",
"7",
"6",
"5"
];
IWoolf public woolf;
| string[4] _alphas = [
"8",
"7",
"6",
"5"
];
IWoolf public woolf;
| 18,488 |
17 | // swap ETH -> LUSD | if (_ethAmount > 0) {
xrouter.functionCallWithValue(_ethSwapData, _ethAmount);
}
| if (_ethAmount > 0) {
xrouter.functionCallWithValue(_ethSwapData, _ethAmount);
}
| 13,731 |
1 | // Whether to allow this token into the bridge. | bool enabled;
| bool enabled;
| 25,245 |
49 | // Submit index-matching arrays that form Phase 0 DepositData objects./ Will create a deposit transaction per index of the arrays submitted./pubkeys - An array of BLS12-381 public keys./withdrawal_credentials - An array of public keys for withdrawals./signatures - An array of BLS12-381 signatures./deposit_data_roots - An array of the SHA-256 hash of the SSZ-encoded DepositData object./service_charge - Amount of service charge charged by the institution. | function batchDeposit(
bytes[] calldata pubkeys,
bytes[] calldata withdrawal_credentials,
bytes[] calldata signatures,
bytes32[] calldata deposit_data_roots,
uint256 service_charge
| function batchDeposit(
bytes[] calldata pubkeys,
bytes[] calldata withdrawal_credentials,
bytes[] calldata signatures,
bytes32[] calldata deposit_data_roots,
uint256 service_charge
| 4,597 |
135 | // A helper contract that provides a way to restrict callers of restricted functions/ to a single address. This allows for a trusted call chain,/ as described in :ref:`contracts' architecture <contracts-architecture>`. | contract RestrictedCalls is Ownable {
/// Maps caller chain IDs to tuples [caller, messenger].
///
/// For same-chain calls, the messenger address is 0x0.
mapping(uint256 => address[2]) public callers;
function _addCaller(
uint256 callerChainId,
address caller,
address messenger
) internal {
require(caller != address(0), "RestrictedCalls: caller cannot be 0");
require(
callers[callerChainId][0] == address(0),
"RestrictedCalls: caller already exists"
);
callers[callerChainId] = [caller, messenger];
}
/// Allow calls from an address on the same chain.
///
/// @param caller The caller.
function addCaller(address caller) external onlyOwner {
_addCaller(block.chainid, caller, address(0));
}
/// Allow calls from an address on another chain.
///
/// @param callerChainId The caller's chain ID.
/// @param caller The caller.
/// @param messenger The messenger.
function addCaller(
uint256 callerChainId,
address caller,
address messenger
) external onlyOwner {
_addCaller(callerChainId, caller, messenger);
}
/// Mark the function as restricted.
///
/// Calls to the restricted function can only come from an address that
/// was previously added by a call to :sol:func:`addCaller`.
///
/// Example usage::
///
/// restricted(block.chainid) // expecting calls from the same chain
/// restricted(otherChainId) // expecting calls from another chain
///
modifier restricted(uint256 callerChainId) {
address caller = callers[callerChainId][0];
if (callerChainId == block.chainid) {
require(msg.sender == caller, "RestrictedCalls: call disallowed");
} else {
address messenger = callers[callerChainId][1];
require(
messenger != address(0),
"RestrictedCalls: messenger not set"
);
require(
IMessenger(messenger).callAllowed(caller, msg.sender),
"RestrictedCalls: call disallowed"
);
}
_;
}
}
| contract RestrictedCalls is Ownable {
/// Maps caller chain IDs to tuples [caller, messenger].
///
/// For same-chain calls, the messenger address is 0x0.
mapping(uint256 => address[2]) public callers;
function _addCaller(
uint256 callerChainId,
address caller,
address messenger
) internal {
require(caller != address(0), "RestrictedCalls: caller cannot be 0");
require(
callers[callerChainId][0] == address(0),
"RestrictedCalls: caller already exists"
);
callers[callerChainId] = [caller, messenger];
}
/// Allow calls from an address on the same chain.
///
/// @param caller The caller.
function addCaller(address caller) external onlyOwner {
_addCaller(block.chainid, caller, address(0));
}
/// Allow calls from an address on another chain.
///
/// @param callerChainId The caller's chain ID.
/// @param caller The caller.
/// @param messenger The messenger.
function addCaller(
uint256 callerChainId,
address caller,
address messenger
) external onlyOwner {
_addCaller(callerChainId, caller, messenger);
}
/// Mark the function as restricted.
///
/// Calls to the restricted function can only come from an address that
/// was previously added by a call to :sol:func:`addCaller`.
///
/// Example usage::
///
/// restricted(block.chainid) // expecting calls from the same chain
/// restricted(otherChainId) // expecting calls from another chain
///
modifier restricted(uint256 callerChainId) {
address caller = callers[callerChainId][0];
if (callerChainId == block.chainid) {
require(msg.sender == caller, "RestrictedCalls: call disallowed");
} else {
address messenger = callers[callerChainId][1];
require(
messenger != address(0),
"RestrictedCalls: messenger not set"
);
require(
IMessenger(messenger).callAllowed(caller, msg.sender),
"RestrictedCalls: call disallowed"
);
}
_;
}
}
| 11,302 |
2 | // ============================== ERC20 | event onTransfer(
address indexed from,
address indexed to,
uint tokens
);
event receivedTokens(
address indexed _from,
uint _value
);
| event onTransfer(
address indexed from,
address indexed to,
uint tokens
);
event receivedTokens(
address indexed _from,
uint _value
);
| 14,182 |
6 | // Modifier checks if the request already is in emergencyState._paymentRef Reference of the payment related.It requires the requestMapping[_paymentRef].emergencyState to be false./ | modifier IsNotInEmergencyState(bytes memory _paymentRef) {
require(!requestMapping[_paymentRef].emergencyState, "In emergencyState");
_;
}
| modifier IsNotInEmergencyState(bytes memory _paymentRef) {
require(!requestMapping[_paymentRef].emergencyState, "In emergencyState");
_;
}
| 22,681 |
167 | // ensure account have escrow migration pending | require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0");
require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending");
| require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0");
require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending");
| 24,205 |
6 | // start with index 1 | activityOwners[numberOfActivity] = msg.sender;
emit ActivityCreated(_name, msg.sender, _limit, _date);
| activityOwners[numberOfActivity] = msg.sender;
emit ActivityCreated(_name, msg.sender, _limit, _date);
| 39,377 |
1 | // transfer / | function transferInternal(STransferData memory _transferData)
override internal returns (bool)
| function transferInternal(STransferData memory _transferData)
override internal returns (bool)
| 14,368 |
30 | // Return 1Split swap function sig / | function getOneSplitSig() internal pure returns (bytes4) {
return 0xf88309d7;
}
| function getOneSplitSig() internal pure returns (bytes4) {
return 0xf88309d7;
}
| 53,770 |
84 | // log event | emit Transfer(0x0, _account, _tokens);
emit TokensMinted(_mint_type, _account, _tokens, _term);
| emit Transfer(0x0, _account, _tokens);
emit TokensMinted(_mint_type, _account, _tokens, _term);
| 43,002 |
2 | // _reserve underlying token address | function getReserveData(address _reserve)
external virtual
view
returns (
uint256 totalLiquidity, // reserve total liquidity
uint256 availableLiquidity, // reserve available liquidity for borrowing
uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate
uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate
uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units.
uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units.
| function getReserveData(address _reserve)
external virtual
view
returns (
uint256 totalLiquidity, // reserve total liquidity
uint256 availableLiquidity, // reserve available liquidity for borrowing
uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate
uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate
uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units.
uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units.
| 19,799 |
10 | // Update storedTotalAssets on withdraw/redeem | function beforeWithdraw(uint256 amount, uint256 shares) internal virtual override {
super.beforeWithdraw(amount, shares);
storedTotalAssets -= amount;
}
| function beforeWithdraw(uint256 amount, uint256 shares) internal virtual override {
super.beforeWithdraw(amount, shares);
storedTotalAssets -= amount;
}
| 36,851 |
52 | // Edit the canvas by buying new pixels and changing price and color of ones already/ owned. The given buyer address must either be the sender or the sender must have been/ approved-for-all by the buyer address. Bought pixels will be transferred to the given/ buyer address. This function works for both existant and non-existant pixels. | function edit(
address buyerAddress,
PixelBuyArgs[] memory buyArgss,
SetColorArgs[] memory setColorArgss,
SetPriceArgs[] memory setPriceArgss
| function edit(
address buyerAddress,
PixelBuyArgs[] memory buyArgss,
SetColorArgs[] memory setColorArgss,
SetPriceArgs[] memory setPriceArgss
| 22,143 |
69 | // end the whole Sale after the current round | function endSale() onlyAdmin public {
saleActive = false;
endNum = roundNum.add(1);
emit EndingSale(msg.sender, roundNum, now);
}
| function endSale() onlyAdmin public {
saleActive = false;
endNum = roundNum.add(1);
emit EndingSale(msg.sender, roundNum, now);
}
| 9,844 |
76 | // Sets {decimals} to a value other than the default one of 18. WARNING: This function should only be called from the constructor. Mostapplications that interact with token contracts will not expect{decimals} to ever change, and may work incorrectly if it does. / | function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
| function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
| 1,618 |
41 | // get current C-Level, without accounting for pending adjustments l storage layout struct isCall whether query is for call or put poolreturn cLevel64x64 64x64 fixed point representation of C-Level / | function getRawCLevel64x64(Layout storage l, bool isCall)
internal
view
returns (int128 cLevel64x64)
| function getRawCLevel64x64(Layout storage l, bool isCall)
internal
view
returns (int128 cLevel64x64)
| 13,103 |
12 | // transfer token for a specified address _to The address to transfer to. _value The amount to be transferred. / | function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| 37,591 |
78 | // Tells whether an operator is approved by a given keyManager _owner owner address which you want to query the approval of _operator operator address which you want to query the approval ofreturn bool whether the given operator is approved by the given owner / | function isApprovedForAll(
address _owner,
address _operator
| function isApprovedForAll(
address _owner,
address _operator
| 2,284 |
19 | // This abstract contract provides a fallback function that delegates all calls to another contract using the EVMinstruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to | * be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
| * be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
| 222 |
89 | // transfer amount minus burn amount | return super.transfer(recipient, amount.sub(burnAmount));
| return super.transfer(recipient, amount.sub(burnAmount));
| 21,310 |
54 | // for views | function getKeys() public view returns(uint) {
return goldKeyRepo[msg.sender];
}
| function getKeys() public view returns(uint) {
return goldKeyRepo[msg.sender];
}
| 33,806 |
15 | // Remove sender from current position. | accountsLL[oldPrev] = accountsLL[msg.sender];
| accountsLL[oldPrev] = accountsLL[msg.sender];
| 21,288 |
290 | // Cancels the salary and transfers the tokens back on a pro rata basis. Throws if the id does not point to a valid salary. Throws if the caller is not the company or the employee. Throws if there is a token transfer failure. salaryId The id of the salary to cancel.return bool true=success, false otherwise. / | function cancelSalary(uint256 salaryId)
external
salaryExists(salaryId)
onlyCompanyOrEmployee(salaryId)
returns (bool success)
| function cancelSalary(uint256 salaryId)
external
salaryExists(salaryId)
onlyCompanyOrEmployee(salaryId)
returns (bool success)
| 43,603 |
26 | // Updates vote delegation stakeID - ID of the stake to delegate votes uber to - address to delegate to / | function delegate(uint256 stakeID, address to)
public
stakeExist(msg.sender, stakeID)
| function delegate(uint256 stakeID, address to)
public
stakeExist(msg.sender, stakeID)
| 42,014 |
1 | // Length of time where the withdrawal window is active | uint256 private constant withdrawalWindowLength = 1 days;
| uint256 private constant withdrawalWindowLength = 1 days;
| 35,001 |
13 | // uint256 _deviceHostIndex, | uint256 _rewardProportion
) public recordChainlinkFulfillment(_requestId)
| uint256 _rewardProportion
) public recordChainlinkFulfillment(_requestId)
| 51,142 |
26 | // Allows the pendingOwner address to finalize the transfer. / | function claimOwnership() onlyPendingOwner public {
OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
| function claimOwnership() onlyPendingOwner public {
OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
| 1,681 |
210 | // Set the insurance mine rate per block. (e.g. 1.189e18 ~ 5% liquidity mine (50mm tokens)) | dsInsuranceFund.mineRatePerBlock = _mineRatePerBlock;
| dsInsuranceFund.mineRatePerBlock = _mineRatePerBlock;
| 34,836 |
12 | // Signature type used by the Order: EOA, POLY_PROXY or POLY_GNOSIS_SAFE | SignatureType signatureType;
| SignatureType signatureType;
| 1,393 |
50 | // Percentage of global debt that should be covered by the buffer | uint256 public coveredDebt; // [thousand]
| uint256 public coveredDebt; // [thousand]
| 52,207 |
157 | // Then fill up the junior tranche with all the interest remaining, upto the principal share price | uint256 expectedInterestSharePrice = slice.juniorTranche.interestSharePrice.add(
usdcToSharePrice(interestRemaining, slice.juniorTranche.principalDeposited)
);
uint256 expectedPrincipalSharePrice = calculateExpectedSharePrice(
slice.juniorTranche,
sliceInfo.principalAccrued,
slice
);
uint256 oldInterestSharePrice = slice.juniorTranche.interestSharePrice;
uint256 oldPrincipalSharePrice = slice.juniorTranche.principalSharePrice;
| uint256 expectedInterestSharePrice = slice.juniorTranche.interestSharePrice.add(
usdcToSharePrice(interestRemaining, slice.juniorTranche.principalDeposited)
);
uint256 expectedPrincipalSharePrice = calculateExpectedSharePrice(
slice.juniorTranche,
sliceInfo.principalAccrued,
slice
);
uint256 oldInterestSharePrice = slice.juniorTranche.interestSharePrice;
uint256 oldPrincipalSharePrice = slice.juniorTranche.principalSharePrice;
| 26,882 |
120 | // calculate trading fee | function _getTradingFee(
uint256 feeTokenAmount)
internal
view
returns (uint256)
| function _getTradingFee(
uint256 feeTokenAmount)
internal
view
returns (uint256)
| 51,474 |
97 | // stddev calculates the standard deviation for an array of integers precision is the same as sqrt above meaning for higher precision the decimal place must be moved prior to passing the params numbers uint[] array of numbers to be used in calculation / | function stddev(uint[] memory numbers) public pure returns (uint256 sd) {
uint sum = 0;
for(uint i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
uint256 mean = sum / numbers.length; // Integral value; float not supported in Solidity
sum = 0;
uint i;
for(i = 0; i < numbers.length; i++) {
sum += (numbers[i] - mean) ** 2;
}
sd = sqrt(sum / (numbers.length - 1)); //Integral value; float not supported in Solidity
return sd;
}
| function stddev(uint[] memory numbers) public pure returns (uint256 sd) {
uint sum = 0;
for(uint i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
uint256 mean = sum / numbers.length; // Integral value; float not supported in Solidity
sum = 0;
uint i;
for(i = 0; i < numbers.length; i++) {
sum += (numbers[i] - mean) ** 2;
}
sd = sqrt(sum / (numbers.length - 1)); //Integral value; float not supported in Solidity
return sd;
}
| 16,799 |
8 | // Define an internal function '_removeRetailer' to remove this role, called by 'removeRetailer' | function _removeManufacturer(address account) internal {
revokeRole(MANUFACTURER_ROLE, account);
}
| function _removeManufacturer(address account) internal {
revokeRole(MANUFACTURER_ROLE, account);
}
| 19,472 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.