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
|
---|---|---|---|---|
97 | // Rebase ERC20 token This is part of an implementation of the Rebase Ideal Money protocol. Rebase is a normal ERC20 token, but its supply can be adjusted by splitting and combining tokens proportionally across all wallets.Rebase balances are internally represented with a hidden denomination, 'gons'. We support splitting the currency in expansion and combining the currency on contraction by changing the exchange rate between the hidden 'gons' and the public 'fragments'. / | contract Rebase is ERC20Detailed, Ownable {
// PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH
// Anytime there is division, there is a risk of numerical instability from rounding errors. In
// order to minimize this risk, we adhere to the following guidelines:
// 1) The conversion rate adopted is the number of gons that equals 1 fragment.
// The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is
// always the denominator. (i.e. If you want to convert gons to fragments instead of
// multiplying by the inverse rate, you should divide by the normal rate)
// 2) Gon balances converted into Fragments are always rounded down (truncated).
//
// We make the following guarantees:
// - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will
// be decreased by precisely x Fragments, and B's external balance will be precisely
// increased by x Fragments.
//
// We do not guarantee that the sum of all balances equals the result of calling totalSupply().
// This is because, for any conversion function 'f()' that has non-zero rounding error,
// f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn).
using SafeMath for uint256;
using SafeMathInt for int256;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
event LogRebasePaused(bool paused);
event LogTokenPaused(bool paused);
event LogMonetaryPolicyUpdated(address monetaryPolicy);
// Used for authentication
address public monetaryPolicy;
modifier onlyMonetaryPolicy() {
require(msg.sender == monetaryPolicy);
_;
}
// Precautionary emergency controls.
bool public rebasePaused;
bool public tokenPaused;
modifier whenRebaseNotPaused() {
require(!rebasePaused);
_;
}
modifier whenTokenNotPaused() {
require(!tokenPaused);
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private constant DECIMALS = 9;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 3.025 * 10**6 * 10**DECIMALS;
// TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
// This is denominated in Fragments, because the gons-fragments conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedFragments;
// Percentile fee, when a transaction is done, the quotient by tx_fee is taken for future reward
// Default divisor is 10
uint16 public _txFee;
address public _rewardAddress;
// For reward, get the _rewardPercentage of the current sender balance. Default value is 10
uint16 public _rewardPercentage;
mapping(address => bool) private _hasRewarded;
address[] rewardedUsers;
bytes32 public currentBlockWinner;
event LogWinner(address addr, bool winner);
event LogClaimReward(address to, uint256 value);
function getTxBurn(uint256 value) public view returns (uint256) {
uint256 nPercent = value.div(_txFee);
if (value % _txFee != 0) {
nPercent = nPercent + 1;
}
return nPercent;
}
function getRewardValue(uint256 value) private view returns (uint256) {
uint256 percentage = 100;
return value.div(percentage).mul(_rewardPercentage);
}
function setRewardAddress(address rewards_)
external
onlyOwner
{
_rewardAddress = rewards_;
}
function getRewardBalance()
public
view
returns (uint256)
{
return _gonBalances[_rewardAddress].div(_gonsPerFragment);
}
function setTxFee(uint16 txFee_)
external
onlyOwner
{
_txFee = txFee_;
}
function setRewardPercentage(uint16 rewardPercentage_)
external
onlyOwner
{
_rewardPercentage = rewardPercentage_;
}
function setRewardParams(address rewards_, uint16 txFee_, uint16 rewardPercentage_)
external
onlyOwner
{
_rewardPercentage = rewardPercentage_;
_txFee = txFee_;
_rewardAddress = rewards_;
}
function setBlockHashWinners()
external
onlyOwner{
currentBlockWinner = block.blockhash(block.number - 1);
while (rewardedUsers.length > 0){
_hasRewarded[rewardedUsers[rewardedUsers.length - 1]] = false;
rewardedUsers.length--;
}
}
function isRewardWinner(address addr)
returns (bool)
{
uint256 hashNum = uint256(currentBlockWinner);
uint256 last = (hashNum * 2 ** 252) / (2 ** 252);
uint256 secondLast = (hashNum * 2 ** 248) / (2 ** 252);
uint256 addressNum = uint256(addr);
uint256 addressLast = (addressNum * 2 ** 252) / (2 ** 252);
uint256 addressSecondLast = (addressNum * 2 ** 248) / (2 ** 252);
bool isWinner = last == addressLast && secondLast == addressSecondLast;
isWinner = true;
LogWinner(addr, isWinner);
return isWinner;
}
function claimReward(address to )
external
onlyMonetaryPolicy
{
if(isRewardWinner(to) && !_hasRewarded[to] && _gonBalances[_rewardAddress] > 0){
uint256 balance = _gonBalances[to];
uint256 toReward = getRewardValue(balance);
if(toReward > _gonBalances[_rewardAddress] ){
_gonBalances[to] = _gonBalances[to].add(_gonBalances[_rewardAddress] );
emit LogClaimReward(to, _gonBalances[_rewardAddress].div(_gonsPerFragment));
_gonBalances[_rewardAddress] = 0;
}else{
_gonBalances[to] = _gonBalances[to].add(toReward);
_gonBalances[_rewardAddress] = _gonBalances[_rewardAddress].sub(toReward);
emit LogClaimReward(to, toReward.div(_gonsPerFragment));
}
_hasRewarded[to] = true;
rewardedUsers.push(to);
}
}
/**
* @param monetaryPolicy_ The address of the monetary policy contract to use for authentication.
*/
function setMonetaryPolicy(address monetaryPolicy_)
external
onlyOwner
{
monetaryPolicy = monetaryPolicy_;
emit LogMonetaryPolicyUpdated(monetaryPolicy_);
}
/**
* @dev Pauses or unpauses the execution of rebase operations.
* @param paused Pauses rebase operations if this is true.
*/
function setRebasePaused(bool paused)
external
onlyOwner
{
rebasePaused = paused;
emit LogRebasePaused(paused);
}
/**
* @dev Pauses or unpauses execution of ERC-20 transactions.
* @param paused Pauses ERC-20 transactions if this is true.
*/
function setTokenPaused(bool paused)
external
onlyOwner
{
tokenPaused = paused;
emit LogTokenPaused(paused);
}
/**
* @dev Notifies Fragments contract about a new rebase cycle.
* @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
* @return The total number of fragments after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
external
onlyMonetaryPolicy
whenRebaseNotPaused
returns (uint256)
{
if (supplyDelta == 0) {
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
if (supplyDelta < 0) {
_totalSupply = _totalSupply.sub(uint256(supplyDelta.abs()));
} else {
_totalSupply = _totalSupply.add(uint256(supplyDelta));
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
// From this point forward, _gonsPerFragment is taken as the source of truth.
// We recalculate a new _totalSupply to be in agreement with the _gonsPerFragment
// conversion rate.
// This means our applied supplyDelta can deviate from the requested supplyDelta,
// but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GONS - _totalSupply).
//
// In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this
// deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is
// ever increased, it must be re-included.
// _totalSupply = TOTAL_GONS.div(_gonsPerFragment)
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
function initialize(address owner_)
public
initializer
{
ERC20Detailed.initialize("REBASE", "REBASE", uint8(DECIMALS));
Ownable.initialize(owner_);
rebasePaused = false;
tokenPaused = false;
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_gonBalances[owner_] = TOTAL_GONS;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
emit Transfer(address(0x0), owner_, _totalSupply);
}
/**
* @return The total number of fragments.
*/
function totalSupply()
public
view
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
public
view
returns (uint256)
{
return _gonBalances[who].div(_gonsPerFragment);
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
public
validRecipient(to)
whenTokenNotPaused
returns (bool)
{
uint256 fee = getTxBurn(value);
uint256 tokensForRewards = fee;
uint256 tokensToTransfer = value-fee;
uint256 rebaseValue = value.mul(_gonsPerFragment);
uint256 rebaseValueKeep = tokensToTransfer.mul(_gonsPerFragment);
uint256 rebaseValueReward = tokensForRewards.mul(_gonsPerFragment);
_gonBalances[msg.sender] = _gonBalances[msg.sender].sub(rebaseValue);
_gonBalances[to] = _gonBalances[to].add(rebaseValueKeep);
_gonBalances[_rewardAddress] = _gonBalances[_rewardAddress].add(rebaseValueReward);
emit Transfer(msg.sender, to, tokensToTransfer);
emit Transfer(msg.sender, _rewardAddress, tokensForRewards);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
public
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
public
validRecipient(to)
whenTokenNotPaused
returns (bool)
{
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
uint256 fee = getTxBurn(value);
uint256 tokensForRewards = fee;
uint256 tokensToTransfer = value-fee;
uint256 rebaseValue = value.mul(_gonsPerFragment);
uint256 rebaseValueKeep = tokensToTransfer.mul(_gonsPerFragment);
uint256 rebaseValueReward = tokensForRewards.mul(_gonsPerFragment);
_gonBalances[from] = _gonBalances[from].sub(rebaseValue);
_gonBalances[to] = _gonBalances[to].add(rebaseValueKeep);
_gonBalances[_rewardAddress] = _gonBalances[_rewardAddress].add(rebaseValueReward);
emit Transfer(from, to, tokensToTransfer);
emit Transfer(from, _rewardAddress, tokensForRewards);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
public
whenTokenNotPaused
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
whenTokenNotPaused
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
whenTokenNotPaused
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
}
| contract Rebase is ERC20Detailed, Ownable {
// PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH
// Anytime there is division, there is a risk of numerical instability from rounding errors. In
// order to minimize this risk, we adhere to the following guidelines:
// 1) The conversion rate adopted is the number of gons that equals 1 fragment.
// The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is
// always the denominator. (i.e. If you want to convert gons to fragments instead of
// multiplying by the inverse rate, you should divide by the normal rate)
// 2) Gon balances converted into Fragments are always rounded down (truncated).
//
// We make the following guarantees:
// - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will
// be decreased by precisely x Fragments, and B's external balance will be precisely
// increased by x Fragments.
//
// We do not guarantee that the sum of all balances equals the result of calling totalSupply().
// This is because, for any conversion function 'f()' that has non-zero rounding error,
// f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn).
using SafeMath for uint256;
using SafeMathInt for int256;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
event LogRebasePaused(bool paused);
event LogTokenPaused(bool paused);
event LogMonetaryPolicyUpdated(address monetaryPolicy);
// Used for authentication
address public monetaryPolicy;
modifier onlyMonetaryPolicy() {
require(msg.sender == monetaryPolicy);
_;
}
// Precautionary emergency controls.
bool public rebasePaused;
bool public tokenPaused;
modifier whenRebaseNotPaused() {
require(!rebasePaused);
_;
}
modifier whenTokenNotPaused() {
require(!tokenPaused);
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private constant DECIMALS = 9;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 3.025 * 10**6 * 10**DECIMALS;
// TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
// This is denominated in Fragments, because the gons-fragments conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedFragments;
// Percentile fee, when a transaction is done, the quotient by tx_fee is taken for future reward
// Default divisor is 10
uint16 public _txFee;
address public _rewardAddress;
// For reward, get the _rewardPercentage of the current sender balance. Default value is 10
uint16 public _rewardPercentage;
mapping(address => bool) private _hasRewarded;
address[] rewardedUsers;
bytes32 public currentBlockWinner;
event LogWinner(address addr, bool winner);
event LogClaimReward(address to, uint256 value);
function getTxBurn(uint256 value) public view returns (uint256) {
uint256 nPercent = value.div(_txFee);
if (value % _txFee != 0) {
nPercent = nPercent + 1;
}
return nPercent;
}
function getRewardValue(uint256 value) private view returns (uint256) {
uint256 percentage = 100;
return value.div(percentage).mul(_rewardPercentage);
}
function setRewardAddress(address rewards_)
external
onlyOwner
{
_rewardAddress = rewards_;
}
function getRewardBalance()
public
view
returns (uint256)
{
return _gonBalances[_rewardAddress].div(_gonsPerFragment);
}
function setTxFee(uint16 txFee_)
external
onlyOwner
{
_txFee = txFee_;
}
function setRewardPercentage(uint16 rewardPercentage_)
external
onlyOwner
{
_rewardPercentage = rewardPercentage_;
}
function setRewardParams(address rewards_, uint16 txFee_, uint16 rewardPercentage_)
external
onlyOwner
{
_rewardPercentage = rewardPercentage_;
_txFee = txFee_;
_rewardAddress = rewards_;
}
function setBlockHashWinners()
external
onlyOwner{
currentBlockWinner = block.blockhash(block.number - 1);
while (rewardedUsers.length > 0){
_hasRewarded[rewardedUsers[rewardedUsers.length - 1]] = false;
rewardedUsers.length--;
}
}
function isRewardWinner(address addr)
returns (bool)
{
uint256 hashNum = uint256(currentBlockWinner);
uint256 last = (hashNum * 2 ** 252) / (2 ** 252);
uint256 secondLast = (hashNum * 2 ** 248) / (2 ** 252);
uint256 addressNum = uint256(addr);
uint256 addressLast = (addressNum * 2 ** 252) / (2 ** 252);
uint256 addressSecondLast = (addressNum * 2 ** 248) / (2 ** 252);
bool isWinner = last == addressLast && secondLast == addressSecondLast;
isWinner = true;
LogWinner(addr, isWinner);
return isWinner;
}
function claimReward(address to )
external
onlyMonetaryPolicy
{
if(isRewardWinner(to) && !_hasRewarded[to] && _gonBalances[_rewardAddress] > 0){
uint256 balance = _gonBalances[to];
uint256 toReward = getRewardValue(balance);
if(toReward > _gonBalances[_rewardAddress] ){
_gonBalances[to] = _gonBalances[to].add(_gonBalances[_rewardAddress] );
emit LogClaimReward(to, _gonBalances[_rewardAddress].div(_gonsPerFragment));
_gonBalances[_rewardAddress] = 0;
}else{
_gonBalances[to] = _gonBalances[to].add(toReward);
_gonBalances[_rewardAddress] = _gonBalances[_rewardAddress].sub(toReward);
emit LogClaimReward(to, toReward.div(_gonsPerFragment));
}
_hasRewarded[to] = true;
rewardedUsers.push(to);
}
}
/**
* @param monetaryPolicy_ The address of the monetary policy contract to use for authentication.
*/
function setMonetaryPolicy(address monetaryPolicy_)
external
onlyOwner
{
monetaryPolicy = monetaryPolicy_;
emit LogMonetaryPolicyUpdated(monetaryPolicy_);
}
/**
* @dev Pauses or unpauses the execution of rebase operations.
* @param paused Pauses rebase operations if this is true.
*/
function setRebasePaused(bool paused)
external
onlyOwner
{
rebasePaused = paused;
emit LogRebasePaused(paused);
}
/**
* @dev Pauses or unpauses execution of ERC-20 transactions.
* @param paused Pauses ERC-20 transactions if this is true.
*/
function setTokenPaused(bool paused)
external
onlyOwner
{
tokenPaused = paused;
emit LogTokenPaused(paused);
}
/**
* @dev Notifies Fragments contract about a new rebase cycle.
* @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
* @return The total number of fragments after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
external
onlyMonetaryPolicy
whenRebaseNotPaused
returns (uint256)
{
if (supplyDelta == 0) {
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
if (supplyDelta < 0) {
_totalSupply = _totalSupply.sub(uint256(supplyDelta.abs()));
} else {
_totalSupply = _totalSupply.add(uint256(supplyDelta));
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
// From this point forward, _gonsPerFragment is taken as the source of truth.
// We recalculate a new _totalSupply to be in agreement with the _gonsPerFragment
// conversion rate.
// This means our applied supplyDelta can deviate from the requested supplyDelta,
// but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GONS - _totalSupply).
//
// In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this
// deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is
// ever increased, it must be re-included.
// _totalSupply = TOTAL_GONS.div(_gonsPerFragment)
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
function initialize(address owner_)
public
initializer
{
ERC20Detailed.initialize("REBASE", "REBASE", uint8(DECIMALS));
Ownable.initialize(owner_);
rebasePaused = false;
tokenPaused = false;
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_gonBalances[owner_] = TOTAL_GONS;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
emit Transfer(address(0x0), owner_, _totalSupply);
}
/**
* @return The total number of fragments.
*/
function totalSupply()
public
view
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
public
view
returns (uint256)
{
return _gonBalances[who].div(_gonsPerFragment);
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
public
validRecipient(to)
whenTokenNotPaused
returns (bool)
{
uint256 fee = getTxBurn(value);
uint256 tokensForRewards = fee;
uint256 tokensToTransfer = value-fee;
uint256 rebaseValue = value.mul(_gonsPerFragment);
uint256 rebaseValueKeep = tokensToTransfer.mul(_gonsPerFragment);
uint256 rebaseValueReward = tokensForRewards.mul(_gonsPerFragment);
_gonBalances[msg.sender] = _gonBalances[msg.sender].sub(rebaseValue);
_gonBalances[to] = _gonBalances[to].add(rebaseValueKeep);
_gonBalances[_rewardAddress] = _gonBalances[_rewardAddress].add(rebaseValueReward);
emit Transfer(msg.sender, to, tokensToTransfer);
emit Transfer(msg.sender, _rewardAddress, tokensForRewards);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
public
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
public
validRecipient(to)
whenTokenNotPaused
returns (bool)
{
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
uint256 fee = getTxBurn(value);
uint256 tokensForRewards = fee;
uint256 tokensToTransfer = value-fee;
uint256 rebaseValue = value.mul(_gonsPerFragment);
uint256 rebaseValueKeep = tokensToTransfer.mul(_gonsPerFragment);
uint256 rebaseValueReward = tokensForRewards.mul(_gonsPerFragment);
_gonBalances[from] = _gonBalances[from].sub(rebaseValue);
_gonBalances[to] = _gonBalances[to].add(rebaseValueKeep);
_gonBalances[_rewardAddress] = _gonBalances[_rewardAddress].add(rebaseValueReward);
emit Transfer(from, to, tokensToTransfer);
emit Transfer(from, _rewardAddress, tokensForRewards);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
public
whenTokenNotPaused
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
whenTokenNotPaused
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
whenTokenNotPaused
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
}
| 3,765 |
8 | // Calculate quantities | Registry memory reg = ctx.ar.getRegistry();
ctx.quantities = new uint192[](reg.erc20s.length);
for (uint256 i = 0; i < reg.erc20s.length; ++i) {
ctx.quantities[i] = ctx.bh.quantityUnsafe(reg.erc20s[i], reg.assets[i]);
}
| Registry memory reg = ctx.ar.getRegistry();
ctx.quantities = new uint192[](reg.erc20s.length);
for (uint256 i = 0; i < reg.erc20s.length; ++i) {
ctx.quantities[i] = ctx.bh.quantityUnsafe(reg.erc20s[i], reg.assets[i]);
}
| 40,216 |
440 | // approve the pool collection to transfer pool tokens, which we have received from the completion of the pending withdrawal, on behalf of the network | completedRequest.poolToken.approve(address(poolCollection), completedRequest.poolTokenAmount);
| completedRequest.poolToken.approve(address(poolCollection), completedRequest.poolTokenAmount);
| 56,408 |
71 | // Creates clone, more info here: https:blog.openzeppelin.com/deep-dive-into-the-minimal-proxy-contract/ | assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
cloneAddress := create2(0, clone, 0x37, salt)
}
| assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
cloneAddress := create2(0, clone, 0x37, salt)
}
| 15,802 |
174 | // Governance // DAO // Pool // Market // Regulator //Getters / | function getUsdcAddress() internal pure returns (address) {
return USDC;
}
| function getUsdcAddress() internal pure returns (address) {
return USDC;
}
| 1,371 |
28 | // Function to add a new owner `_owner` to the wallet, must be sent as a tx/_owner New owner to be added | function addOwner(address _owner)
external
notAnOwner(_owner)
notNull(_owner)
validInputs(owners.length + 1, threshold)
| function addOwner(address _owner)
external
notAnOwner(_owner)
notNull(_owner)
validInputs(owners.length + 1, threshold)
| 45,401 |
29 | // The minimal token1 receive after remove the liquidity, will be used when call removeLiquidity() of uniswap | uint256 minAmount1WhenRemoveLiquidity;
| uint256 minAmount1WhenRemoveLiquidity;
| 14,958 |
18 | // Encodes a 31 bit unsigned integer shifted by an offset. The return value can be logically ORed with other encoded values to form a 256 bit word. / | function encodeUint31(uint256 value, uint256 offset) internal pure returns (bytes32) {
return bytes32(value << offset);
}
| function encodeUint31(uint256 value, uint256 offset) internal pure returns (bytes32) {
return bytes32(value << offset);
}
| 40,423 |
5 | // Allowed tokens symbols list. | mapping(address => address[]) internal allowedTokens;
| mapping(address => address[]) internal allowedTokens;
| 25,992 |
134 | // Before adding to return index | strategyID = strategies.length;
strategies.push(
Strategy({
strategyName : strategyName,
token0Out : token0Out,
pairs : pairs,
feeOnTransfers : feeOnTransfers,
cBTCSupport : cBTCSupport,
feeOff : msg.sender == owner()
| strategyID = strategies.length;
strategies.push(
Strategy({
strategyName : strategyName,
token0Out : token0Out,
pairs : pairs,
feeOnTransfers : feeOnTransfers,
cBTCSupport : cBTCSupport,
feeOff : msg.sender == owner()
| 35,956 |
209 | // delete the bid | uint256 len = _tokenBids[_tokenId].length;
for (uint256 i = _index; i < len - 1; i++) {
_tokenBids[_tokenId][i] = _tokenBids[_tokenId][i + 1];
}
| uint256 len = _tokenBids[_tokenId].length;
for (uint256 i = _index; i < len - 1; i++) {
_tokenBids[_tokenId][i] = _tokenBids[_tokenId][i + 1];
}
| 16,981 |
59 | // 转移冻结账本 | balances[newFrozenAddress] = balances[frozenAddress];
balances[frozenAddress] = 0;
emit Transfer(frozenAddress, newFrozenAddress, balances[newFrozenAddress]);
frozenAddress = newFrozenAddress;
return true;
| balances[newFrozenAddress] = balances[frozenAddress];
balances[frozenAddress] = 0;
emit Transfer(frozenAddress, newFrozenAddress, balances[newFrozenAddress]);
frozenAddress = newFrozenAddress;
return true;
| 46,502 |
15 | // Ensure mutex is unlocked. | if (_locked) {
LibRichErrors.rrevert(
LibReentrancyGuardRichErrors.IllegalReentrancyError()
);
}
| if (_locked) {
LibRichErrors.rrevert(
LibReentrancyGuardRichErrors.IllegalReentrancyError()
);
}
| 32,311 |
8 | // modes[1] = 0; modes[2] = 0; modes[3] = 0; modes[4] = 0; modes[5] = 0; modes[6] = 0; |
address onBehalfOf = address(this);
bytes memory params = "";
uint16 referralCode = 0;
LENDING_POOL.flashLoan(
receiverAddress,
assets,
amounts,
modes,
|
address onBehalfOf = address(this);
bytes memory params = "";
uint16 referralCode = 0;
LENDING_POOL.flashLoan(
receiverAddress,
assets,
amounts,
modes,
| 9,356 |
178 | // Claim all comp accrued by the holders holders The addresses to claim COMP for cTokens The list of markets to claim COMP in borrowers Whether or not to claim COMP earned by borrowing suppliers Whether or not to claim COMP earned by supplying / | function claimComp(
address[] memory holders,
ICErc20[] memory cTokens,
bool borrowers,
bool suppliers
) external;
| function claimComp(
address[] memory holders,
ICErc20[] memory cTokens,
bool borrowers,
bool suppliers
) external;
| 52,358 |
52 | // Move to the next market account | _totalMarketAccounts++;
| _totalMarketAccounts++;
| 9,650 |
4 | // Transfers any ether held by timelock to beneficiary./ | function release() public {
require(block.timestamp >= releaseTime);
require(address(this).balance > 0);
beneficiary.transfer(address(this).balance);
}
| function release() public {
require(block.timestamp >= releaseTime);
require(address(this).balance > 0);
beneficiary.transfer(address(this).balance);
}
| 31,511 |
108 | // register the supported interface to conform to ERC721Enumerable via ERC165 | _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
| _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
| 8,336 |
179 | // Crowdsale mints to himself the initial supply | token.mint(address(this), crowdsale_supply);
| token.mint(address(this), crowdsale_supply);
| 44,381 |
36 | // only owner adjust contract balance variable (only used for max profit calc) / | {
contractBalance = newContractBalanceInWei;
}
| {
contractBalance = newContractBalanceInWei;
}
| 38,169 |
6 | // Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. / | event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
| event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
| 16,722 |
10 | // Search for a needle in a haystack / | function startsWith(string memory haystack, string memory needle) internal pure returns (bool) {
return indexOf(needle, haystack) == 0;
}
| function startsWith(string memory haystack, string memory needle) internal pure returns (bool) {
return indexOf(needle, haystack) == 0;
}
| 31,643 |
34 | // Allows an owner to execute a confirmed transaction. transactionIdTransaction ID. / | function executeTransaction(
uint256 transactionId
)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
| function executeTransaction(
uint256 transactionId
)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
| 49,958 |
10 | // Version 1 adapter for metaverse integrations/Daniel K Ivanov/Adapter for metaverses that lack the necessary consumer role required to be integrated into LandWorks/ For reference see https:eips.ethereum.org/EIPS/eip-4400 | contract ConsumableAdapterV1 is IERC165, IERC721Consumable {
/// @notice LandWorks address
address public immutable landworks;
/// @notice NFT Token address
IERC721 public immutable token;
/// @notice mapping of authorised consumer addresses
mapping(uint256 => address) private consumers;
constructor(address _landworks, address _token) {
landworks = _landworks;
token = IERC721(_token);
}
/// @dev See {IERC721Consumable-consumerOf}
function consumerOf(uint256 tokenId) public view returns (address) {
return consumers[tokenId];
}
/// @dev See {IERC721Consumable-changeConsumer}
function changeConsumer(address consumer, uint256 tokenId) public {
require(
msg.sender == landworks,
"ConsumableAdapter: sender is not LandWorks"
);
require(
msg.sender == token.ownerOf(tokenId),
"ConsumableAdapter: sender is not owner of tokenId"
);
consumers[tokenId] = consumer;
emit ConsumerChanged(msg.sender, consumer, tokenId);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
returns (bool)
{
return interfaceId == type(IERC721Consumable).interfaceId;
}
}
| contract ConsumableAdapterV1 is IERC165, IERC721Consumable {
/// @notice LandWorks address
address public immutable landworks;
/// @notice NFT Token address
IERC721 public immutable token;
/// @notice mapping of authorised consumer addresses
mapping(uint256 => address) private consumers;
constructor(address _landworks, address _token) {
landworks = _landworks;
token = IERC721(_token);
}
/// @dev See {IERC721Consumable-consumerOf}
function consumerOf(uint256 tokenId) public view returns (address) {
return consumers[tokenId];
}
/// @dev See {IERC721Consumable-changeConsumer}
function changeConsumer(address consumer, uint256 tokenId) public {
require(
msg.sender == landworks,
"ConsumableAdapter: sender is not LandWorks"
);
require(
msg.sender == token.ownerOf(tokenId),
"ConsumableAdapter: sender is not owner of tokenId"
);
consumers[tokenId] = consumer;
emit ConsumerChanged(msg.sender, consumer, tokenId);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
returns (bool)
{
return interfaceId == type(IERC721Consumable).interfaceId;
}
}
| 4,963 |
42 | // Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5(1018)`. a int to convert into a FixedPoint.Signed.return the converted FixedPoint.Signed. / | function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
| function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
| 19,186 |
280 | // Set the starting index for the collection / | function setStartingIndex() public {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_APES;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_APES;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
| function setStartingIndex() public {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_APES;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_APES;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
| 2,064 |
65 | // Contract registry/The contract registry holds Orbs PoS contracts and managers lists/The contract registry updates the managed contracts on changes in the contract list/Governance functions restricted to managers access the registry to retrieve the manager address /The contract registry represents the source of truth for Orbs Ethereum contracts /By tracking the registry events or query before interaction, one can access the up to date contracts | contract ContractRegistry is IContractRegistry, Initializable, WithClaimableRegistryManagement {
address previousContractRegistry;
mapping(string => address) contracts;
address[] managedContractAddresses;
mapping(string => address) managers;
/// Constructor
/// @param _previousContractRegistry is the previous contract registry address
/// @param registryAdmin is the registry contract admin address
constructor(address _previousContractRegistry, address registryAdmin) public {
previousContractRegistry = _previousContractRegistry;
_transferRegistryManagement(registryAdmin);
}
modifier onlyAdmin {
require(msg.sender == registryAdmin() || msg.sender == initializationAdmin(), "sender is not an admin (registryAdmin or initializationAdmin when initialization in progress)");
_;
}
modifier onlyAdminOrMigrationManager {
require(msg.sender == registryAdmin() || msg.sender == initializationAdmin() || msg.sender == managers["migrationManager"], "sender is not an admin (registryAdmin or initializationAdmin when initialization in progress) and not the migration manager");
_;
}
/*
* External functions
*/
/// Updates the contracts address and emits a corresponding event
/// @dev governance function called only by the migrationManager or registryAdmin
/// @param contractName is the contract name, used to identify it
/// @param addr is the contract updated address
/// @param managedContract indicates whether the contract is managed by the registry and notified on changes
function setContract(string calldata contractName, address addr, bool managedContract) external override onlyAdminOrMigrationManager {
require(!managedContract || addr != address(0), "managed contract may not have address(0)");
removeManagedContract(contracts[contractName]);
contracts[contractName] = addr;
if (managedContract) {
addManagedContract(addr);
}
emit ContractAddressUpdated(contractName, addr, managedContract);
notifyOnContractsChange();
}
/// Returns the current address of the given contracts
/// @param contractName is the contract name, used to identify it
/// @return addr is the contract updated address
function getContract(string calldata contractName) external override view returns (address) {
return contracts[contractName];
}
/// Returns the list of contract addresses managed by the registry
/// @dev Managed contracts are updated on changes in the registry contracts addresses
/// @return addrs is the list of managed contracts
function getManagedContracts() external override view returns (address[] memory) {
return managedContractAddresses;
}
/// Locks all the managed contracts
/// @dev governance function called only by the migrationManager or registryAdmin
/// @dev When set all onlyWhenActive functions will revert
function lockContracts() external override onlyAdminOrMigrationManager {
for (uint i = 0; i < managedContractAddresses.length; i++) {
ILockable(managedContractAddresses[i]).lock();
}
}
/// Unlocks all the managed contracts
/// @dev governance function called only by the migrationManager or registryAdmin
function unlockContracts() external override onlyAdminOrMigrationManager {
for (uint i = 0; i < managedContractAddresses.length; i++) {
ILockable(managedContractAddresses[i]).unlock();
}
}
/// Updates a manager address and emits a corresponding event
/// @dev governance function called only by the registryAdmin
/// @dev the managers list is a flexible list of role to the manager's address
/// @param role is the managers' role name, for example "functionalManager"
/// @param manager is the manager updated address
function setManager(string calldata role, address manager) external override onlyAdmin {
managers[role] = manager;
emit ManagerChanged(role, manager);
}
/// Returns the current address of the given manager
/// @param role is the manager name, used to identify it
/// @return addr is the manager updated address
function getManager(string calldata role) external override view returns (address) {
return managers[role];
}
/// Sets a new contract registry to migrate to
/// @dev governance function called only by the registryAdmin
/// @dev updates the registry address record in all the managed contracts
/// @dev by tracking the emitted ContractRegistryUpdated, tools can track the up to date contracts
/// @param newRegistry is the new registry contract
function setNewContractRegistry(IContractRegistry newRegistry) external override onlyAdmin {
for (uint i = 0; i < managedContractAddresses.length; i++) {
IContractRegistryAccessor(managedContractAddresses[i]).setContractRegistry(newRegistry);
IManagedContract(managedContractAddresses[i]).refreshContracts();
}
emit ContractRegistryUpdated(address(newRegistry));
}
/// Returns the previous contract registry address
/// @dev used when the setting the contract as a new registry to assure a valid registry
/// @return previousContractRegistry is the previous contract registry
function getPreviousContractRegistry() external override view returns (address) {
return previousContractRegistry;
}
/*
* Private methods
*/
/// Notifies the managed contracts on a change in a contract address
/// @dev invokes the refreshContracts() function in each contract that queries the relevant contract addresses
function notifyOnContractsChange() private {
for (uint i = 0; i < managedContractAddresses.length; i++) {
IManagedContract(managedContractAddresses[i]).refreshContracts();
}
}
/// Adds a new managed contract address to the managed contracts list
function addManagedContract(address addr) private {
managedContractAddresses.push(addr);
}
/// Removes a managed contract address from the managed contracts list
function removeManagedContract(address addr) private {
uint length = managedContractAddresses.length;
for (uint i = 0; i < length; i++) {
if (managedContractAddresses[i] == addr) {
if (i != length - 1) {
managedContractAddresses[i] = managedContractAddresses[length-1];
}
managedContractAddresses.pop();
length--;
}
}
}
} | contract ContractRegistry is IContractRegistry, Initializable, WithClaimableRegistryManagement {
address previousContractRegistry;
mapping(string => address) contracts;
address[] managedContractAddresses;
mapping(string => address) managers;
/// Constructor
/// @param _previousContractRegistry is the previous contract registry address
/// @param registryAdmin is the registry contract admin address
constructor(address _previousContractRegistry, address registryAdmin) public {
previousContractRegistry = _previousContractRegistry;
_transferRegistryManagement(registryAdmin);
}
modifier onlyAdmin {
require(msg.sender == registryAdmin() || msg.sender == initializationAdmin(), "sender is not an admin (registryAdmin or initializationAdmin when initialization in progress)");
_;
}
modifier onlyAdminOrMigrationManager {
require(msg.sender == registryAdmin() || msg.sender == initializationAdmin() || msg.sender == managers["migrationManager"], "sender is not an admin (registryAdmin or initializationAdmin when initialization in progress) and not the migration manager");
_;
}
/*
* External functions
*/
/// Updates the contracts address and emits a corresponding event
/// @dev governance function called only by the migrationManager or registryAdmin
/// @param contractName is the contract name, used to identify it
/// @param addr is the contract updated address
/// @param managedContract indicates whether the contract is managed by the registry and notified on changes
function setContract(string calldata contractName, address addr, bool managedContract) external override onlyAdminOrMigrationManager {
require(!managedContract || addr != address(0), "managed contract may not have address(0)");
removeManagedContract(contracts[contractName]);
contracts[contractName] = addr;
if (managedContract) {
addManagedContract(addr);
}
emit ContractAddressUpdated(contractName, addr, managedContract);
notifyOnContractsChange();
}
/// Returns the current address of the given contracts
/// @param contractName is the contract name, used to identify it
/// @return addr is the contract updated address
function getContract(string calldata contractName) external override view returns (address) {
return contracts[contractName];
}
/// Returns the list of contract addresses managed by the registry
/// @dev Managed contracts are updated on changes in the registry contracts addresses
/// @return addrs is the list of managed contracts
function getManagedContracts() external override view returns (address[] memory) {
return managedContractAddresses;
}
/// Locks all the managed contracts
/// @dev governance function called only by the migrationManager or registryAdmin
/// @dev When set all onlyWhenActive functions will revert
function lockContracts() external override onlyAdminOrMigrationManager {
for (uint i = 0; i < managedContractAddresses.length; i++) {
ILockable(managedContractAddresses[i]).lock();
}
}
/// Unlocks all the managed contracts
/// @dev governance function called only by the migrationManager or registryAdmin
function unlockContracts() external override onlyAdminOrMigrationManager {
for (uint i = 0; i < managedContractAddresses.length; i++) {
ILockable(managedContractAddresses[i]).unlock();
}
}
/// Updates a manager address and emits a corresponding event
/// @dev governance function called only by the registryAdmin
/// @dev the managers list is a flexible list of role to the manager's address
/// @param role is the managers' role name, for example "functionalManager"
/// @param manager is the manager updated address
function setManager(string calldata role, address manager) external override onlyAdmin {
managers[role] = manager;
emit ManagerChanged(role, manager);
}
/// Returns the current address of the given manager
/// @param role is the manager name, used to identify it
/// @return addr is the manager updated address
function getManager(string calldata role) external override view returns (address) {
return managers[role];
}
/// Sets a new contract registry to migrate to
/// @dev governance function called only by the registryAdmin
/// @dev updates the registry address record in all the managed contracts
/// @dev by tracking the emitted ContractRegistryUpdated, tools can track the up to date contracts
/// @param newRegistry is the new registry contract
function setNewContractRegistry(IContractRegistry newRegistry) external override onlyAdmin {
for (uint i = 0; i < managedContractAddresses.length; i++) {
IContractRegistryAccessor(managedContractAddresses[i]).setContractRegistry(newRegistry);
IManagedContract(managedContractAddresses[i]).refreshContracts();
}
emit ContractRegistryUpdated(address(newRegistry));
}
/// Returns the previous contract registry address
/// @dev used when the setting the contract as a new registry to assure a valid registry
/// @return previousContractRegistry is the previous contract registry
function getPreviousContractRegistry() external override view returns (address) {
return previousContractRegistry;
}
/*
* Private methods
*/
/// Notifies the managed contracts on a change in a contract address
/// @dev invokes the refreshContracts() function in each contract that queries the relevant contract addresses
function notifyOnContractsChange() private {
for (uint i = 0; i < managedContractAddresses.length; i++) {
IManagedContract(managedContractAddresses[i]).refreshContracts();
}
}
/// Adds a new managed contract address to the managed contracts list
function addManagedContract(address addr) private {
managedContractAddresses.push(addr);
}
/// Removes a managed contract address from the managed contracts list
function removeManagedContract(address addr) private {
uint length = managedContractAddresses.length;
for (uint i = 0; i < length; i++) {
if (managedContractAddresses[i] == addr) {
if (i != length - 1) {
managedContractAddresses[i] = managedContractAddresses[length-1];
}
managedContractAddresses.pop();
length--;
}
}
}
} | 69,032 |
23 | // Sets the publication fee that's charged to users to publish items publicationFee - Fee amount in wei this contract charges to publish an item / | function setPublicationFee(uint256 publicationFee) onlyOwner public {
publicationFeeInWei = publicationFee;
ChangedPublicationFee(publicationFeeInWei);
}
| function setPublicationFee(uint256 publicationFee) onlyOwner public {
publicationFeeInWei = publicationFee;
ChangedPublicationFee(publicationFeeInWei);
}
| 16,509 |
385 | // The default harvest delay for Vaults./See the documentation for the harvestDelay/ variable in the Vault contract for more details. | uint64 public defaultHarvestDelay;
| uint64 public defaultHarvestDelay;
| 21,543 |
73 | // solium-disable security/no-low-level-calls // ERC827, an extension of ERC20 token standardImplementation the ERC827, following the ERC20 standard with extramethods to transfer value and data and execute calls in transfers andapprovals. Uses OpenZeppelin StandardToken. / | contract ERC827Token is ERC827, StandardToken {
/**
* @dev Addition to ERC20 token methods. It allows to
* approve the transfer of value and execute a call with the sent data.
* Beware that changing an allowance with this method brings the risk that
* someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race condition
* is to first reduce the spender's allowance to 0 and set the desired value
* afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address that will spend the funds.
* @param _value The amount of tokens to be spent.
* @param _data ABI-encoded contract call to call `_spender` address.
* @return true if the call function was executed successfully
*/
function approveAndCall(
address _spender,
uint256 _value,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.approve(_spender, _value);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens to a specified
* address and execute a call with the sent data on the same transaction
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
* @param _data ABI-encoded contract call to call `_to` address.
* @return true if the call function was executed successfully
*/
function transferAndCall(
address _to,
uint256 _value,
bytes _data
)
public
payable
returns (bool)
{
require(_to != address(this));
super.transfer(_to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens from one address to
* another and make a contract call on the same transaction
* @param _from The address which you want to send tokens from
* @param _to The address which you want to transfer to
* @param _value The amout of tokens to be transferred
* @param _data ABI-encoded contract call to call `_to` address.
* @return true if the call function was executed successfully
*/
function transferFromAndCall(
address _from,
address _to,
uint256 _value,
bytes _data
)
public payable returns (bool)
{
require(_to != address(this));
super.transferFrom(_from, _to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Increase the amount of tokens that
* an owner allowed to a spender and execute a call with the sent data.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function increaseApprovalAndCall(
address _spender,
uint _addedValue,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.increaseApproval(_spender, _addedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Decrease the amount of tokens that
* an owner allowed to a spender and execute a call with the sent data.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function decreaseApprovalAndCall(
address _spender,
uint _subtractedValue,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.decreaseApproval(_spender, _subtractedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
}
| contract ERC827Token is ERC827, StandardToken {
/**
* @dev Addition to ERC20 token methods. It allows to
* approve the transfer of value and execute a call with the sent data.
* Beware that changing an allowance with this method brings the risk that
* someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race condition
* is to first reduce the spender's allowance to 0 and set the desired value
* afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address that will spend the funds.
* @param _value The amount of tokens to be spent.
* @param _data ABI-encoded contract call to call `_spender` address.
* @return true if the call function was executed successfully
*/
function approveAndCall(
address _spender,
uint256 _value,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.approve(_spender, _value);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens to a specified
* address and execute a call with the sent data on the same transaction
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
* @param _data ABI-encoded contract call to call `_to` address.
* @return true if the call function was executed successfully
*/
function transferAndCall(
address _to,
uint256 _value,
bytes _data
)
public
payable
returns (bool)
{
require(_to != address(this));
super.transfer(_to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens from one address to
* another and make a contract call on the same transaction
* @param _from The address which you want to send tokens from
* @param _to The address which you want to transfer to
* @param _value The amout of tokens to be transferred
* @param _data ABI-encoded contract call to call `_to` address.
* @return true if the call function was executed successfully
*/
function transferFromAndCall(
address _from,
address _to,
uint256 _value,
bytes _data
)
public payable returns (bool)
{
require(_to != address(this));
super.transferFrom(_from, _to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Increase the amount of tokens that
* an owner allowed to a spender and execute a call with the sent data.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function increaseApprovalAndCall(
address _spender,
uint _addedValue,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.increaseApproval(_spender, _addedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Decrease the amount of tokens that
* an owner allowed to a spender and execute a call with the sent data.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function decreaseApprovalAndCall(
address _spender,
uint _subtractedValue,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.decreaseApproval(_spender, _subtractedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
}
| 35,291 |
125 | // Get the balance of want held idle in the Strategy | function balanceOfWant() public view returns (uint256) {
return IERC20Upgradeable(want).balanceOf(address(this));
}
| function balanceOfWant() public view returns (uint256) {
return IERC20Upgradeable(want).balanceOf(address(this));
}
| 6,156 |
108 | // _token The token address _merkleRoot The merkleroot / | function addAirdrop(address _token, bytes32 _merkleRoot) external override onlyOwner {
require(_token != address(0), 'BnEX::Distributor::addAirdrop::INVALID_TOKEN');
airdropInfo.push(AirdropInfo({token: _token, merkleRoot: _merkleRoot}));
}
| function addAirdrop(address _token, bytes32 _merkleRoot) external override onlyOwner {
require(_token != address(0), 'BnEX::Distributor::addAirdrop::INVALID_TOKEN');
airdropInfo.push(AirdropInfo({token: _token, merkleRoot: _merkleRoot}));
}
| 29,657 |
4 | // Standard math utilities missing in the Solidity language. / | library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
| library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
| 883 |
11 | // Data structures / | mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
| mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
| 43,935 |
778 | // The integer part of the logarithm as an unsigned 60.18-decimal fixed-point number. The operation can't overflow because n is maximum 255 and SCALE is 1e18. | result = n * SCALE;
| result = n * SCALE;
| 26,334 |
61 | // [ADDRESS MAPPINGS]/ |
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isMultisig;
address[] private multisigParties;
|
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isMultisig;
address[] private multisigParties;
| 52,221 |
0 | // TestOne is deployed check bscscan for the contract addres then call/ | addressTestTwo = _addressTestTwo;
| addressTestTwo = _addressTestTwo;
| 31,588 |
5 | // tockenId : get 3th param | _tokenId := mload(add(_createAuctionlData,add(add(mul(2,32),4),0x20)))
| _tokenId := mload(add(_createAuctionlData,add(add(mul(2,32),4),0x20)))
| 36,600 |
122 | // Distributes dividends whenever ether is paid to this contract. | receive() external payable {
distributeDividends();
}
| receive() external payable {
distributeDividends();
}
| 6,080 |
15 | // return rights[customerADDR][right]; |
bytes32[] memory stringArr = new bytes32[](customer.rightsIndexCount);
bool[] memory boolArr = new bool[](customer.rightsIndexCount);
for (uint i = 0 ; i < customer.rightsIndexCount; i++){
bytes32 right = customer.rightsIndex[i];
stringArr[i] = right;
boolArr[i] = rights[customerADDR][right];
}
|
bytes32[] memory stringArr = new bytes32[](customer.rightsIndexCount);
bool[] memory boolArr = new bool[](customer.rightsIndexCount);
for (uint i = 0 ; i < customer.rightsIndexCount; i++){
bytes32 right = customer.rightsIndex[i];
stringArr[i] = right;
boolArr[i] = rights[customerADDR][right];
}
| 45,488 |
0 | // Hasher object | Hasher hasher;
| Hasher hasher;
| 38,816 |
2 | // make sure caller isn't a contract | modifier onlyEOA() {
require(tx.origin == msg.sender, "onlyEOA");
_;}
| modifier onlyEOA() {
require(tx.origin == msg.sender, "onlyEOA");
_;}
| 5,223 |
17 | // This function sets the symbol name as used, this function is called from records contract to reserve symbol for new version creation/governanceSymbol Symbol for governance token/communitySymbol Symbol for community token | function setSymbolsAsUsed(
string memory governanceSymbol,
string memory communitySymbol
) external;
| function setSymbolsAsUsed(
string memory governanceSymbol,
string memory communitySymbol
) external;
| 23,283 |
121 | // -- Configuration -- |
function setDefaultReserveRatio(uint32 _defaultReserveRatio) external;
function setMinimumCurationDeposit(uint256 _minimumCurationDeposit) external;
function setCurationTaxPercentage(uint32 _percentage) external;
|
function setDefaultReserveRatio(uint32 _defaultReserveRatio) external;
function setMinimumCurationDeposit(uint256 _minimumCurationDeposit) external;
function setCurationTaxPercentage(uint32 _percentage) external;
| 81,671 |
229 | // ERC20 token/ | contract ERC20Token {
using SafeMathLib for uint256;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowances;
// events
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
/**
* @dev internal constructor
*/
constructor() internal {}
// external functions
function transfer(
address to,
uint256 value
)
external
returns (bool)
{
_transfer(_getSender(), to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
)
virtual
external
returns (bool)
{
address sender = _getSender();
_transfer(from, to, value);
_approve(from, sender, allowances[from][sender].sub(value));
return true;
}
function approve(
address spender,
uint256 value
)
virtual
external
returns (bool)
{
_approve(_getSender(), spender, value);
return true;
}
// external functions (views)
function balanceOf(
address owner
)
virtual
external
view
returns (uint256)
{
return balances[owner];
}
function allowance(
address owner,
address spender
)
virtual
external
view
returns (uint256)
{
return allowances[owner][spender];
}
// internal functions
function _transfer(
address from,
address to,
uint256 value
)
virtual
internal
{
require(
from != address(0),
"ERC20Token: cannot transfer from 0x0 address"
);
require(
to != address(0),
"ERC20Token: cannot transfer to 0x0 address"
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
emit Transfer(from, to, value);
}
function _approve(
address owner,
address spender,
uint256 value
)
virtual
internal
{
require(
owner != address(0),
"ERC20Token: cannot approve from 0x0 address"
);
require(
spender != address(0),
"ERC20Token: cannot approve to 0x0 address"
);
allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _mint(
address owner,
uint256 value
)
virtual
internal
{
require(
owner != address(0),
"ERC20Token: cannot mint to 0x0 address"
);
require(
value > 0,
"ERC20Token: cannot mint 0 value"
);
balances[owner] = balances[owner].add(value);
totalSupply = totalSupply.add(value);
emit Transfer(address(0), owner, value);
}
function _burn(
address owner,
uint256 value
)
virtual
internal
{
require(
owner != address(0),
"ERC20Token: cannot burn from 0x0 address"
);
balances[owner] = balances[owner].sub(
value,
"ERC20Token: burn value exceeds balance"
);
totalSupply = totalSupply.sub(value);
emit Transfer(owner, address(0), value);
}
// internal functions (views)
function _getSender()
virtual
internal
view
returns (address)
{
return msg.sender;
}
}
| contract ERC20Token {
using SafeMathLib for uint256;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowances;
// events
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
/**
* @dev internal constructor
*/
constructor() internal {}
// external functions
function transfer(
address to,
uint256 value
)
external
returns (bool)
{
_transfer(_getSender(), to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
)
virtual
external
returns (bool)
{
address sender = _getSender();
_transfer(from, to, value);
_approve(from, sender, allowances[from][sender].sub(value));
return true;
}
function approve(
address spender,
uint256 value
)
virtual
external
returns (bool)
{
_approve(_getSender(), spender, value);
return true;
}
// external functions (views)
function balanceOf(
address owner
)
virtual
external
view
returns (uint256)
{
return balances[owner];
}
function allowance(
address owner,
address spender
)
virtual
external
view
returns (uint256)
{
return allowances[owner][spender];
}
// internal functions
function _transfer(
address from,
address to,
uint256 value
)
virtual
internal
{
require(
from != address(0),
"ERC20Token: cannot transfer from 0x0 address"
);
require(
to != address(0),
"ERC20Token: cannot transfer to 0x0 address"
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
emit Transfer(from, to, value);
}
function _approve(
address owner,
address spender,
uint256 value
)
virtual
internal
{
require(
owner != address(0),
"ERC20Token: cannot approve from 0x0 address"
);
require(
spender != address(0),
"ERC20Token: cannot approve to 0x0 address"
);
allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _mint(
address owner,
uint256 value
)
virtual
internal
{
require(
owner != address(0),
"ERC20Token: cannot mint to 0x0 address"
);
require(
value > 0,
"ERC20Token: cannot mint 0 value"
);
balances[owner] = balances[owner].add(value);
totalSupply = totalSupply.add(value);
emit Transfer(address(0), owner, value);
}
function _burn(
address owner,
uint256 value
)
virtual
internal
{
require(
owner != address(0),
"ERC20Token: cannot burn from 0x0 address"
);
balances[owner] = balances[owner].sub(
value,
"ERC20Token: burn value exceeds balance"
);
totalSupply = totalSupply.sub(value);
emit Transfer(owner, address(0), value);
}
// internal functions (views)
function _getSender()
virtual
internal
view
returns (address)
{
return msg.sender;
}
}
| 11,342 |
2 | // POOL | bytes32 public constant POOL_BASE_INTERESTS = bytes32('POOL_BASE_INTERESTS');
bytes32 public constant POOL_MARKET_FRENZY = bytes32('POOL_MARKET_FRENZY');
bytes32 public constant POOL_PLEDGE_RATE = bytes32('POOL_PLEDGE_RATE');
bytes32 public constant POOL_LIQUIDATION_RATE = bytes32('POOL_LIQUIDATION_RATE');
bytes32 public constant POOL_MINT_BORROW_PERCENT = bytes32('POOL_MINT_BORROW_PERCENT');
bytes32 public constant POOL_MINT_POWER = bytes32('POOL_MINT_POWER');
| bytes32 public constant POOL_BASE_INTERESTS = bytes32('POOL_BASE_INTERESTS');
bytes32 public constant POOL_MARKET_FRENZY = bytes32('POOL_MARKET_FRENZY');
bytes32 public constant POOL_PLEDGE_RATE = bytes32('POOL_PLEDGE_RATE');
bytes32 public constant POOL_LIQUIDATION_RATE = bytes32('POOL_LIQUIDATION_RATE');
bytes32 public constant POOL_MINT_BORROW_PERCENT = bytes32('POOL_MINT_BORROW_PERCENT');
bytes32 public constant POOL_MINT_POWER = bytes32('POOL_MINT_POWER');
| 24,357 |
285 | // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since | // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
| // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
| 27,805 |
5 | // This operation is equivalent to `x / 2 +y / 2`, and it can never overflow. | int256 sum = (xInt >> 1) + (yInt >> 1);
if (sum < 0) {
| int256 sum = (xInt >> 1) + (yInt >> 1);
if (sum < 0) {
| 31,536 |
96 | // Transfer tokens to delegate to this contract | require(graphToken().transferFrom(delegator, address(this), _tokens), "!transfer");
| require(graphToken().transferFrom(delegator, address(this), _tokens), "!transfer");
| 20,624 |
163 | // get LP at MasterChef | uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
| uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
| 23,414 |
35 | // Returns the data from the front of the queue, without removing it. O(1) queue Uint256Queue struct from contract. / | function peek(Uint256Queue storage queue) internal view returns (uint256 data) {
return uint256(_peek(queue._inner));
}
| function peek(Uint256Queue storage queue) internal view returns (uint256 data) {
return uint256(_peek(queue._inner));
}
| 16,810 |
5 | // accepts payeeship for offchain aggregators _contractIdxs indexes corresponding to the offchain aggregators / | function _acceptAdmin(uint[] calldata _contractIdxs) internal override {
for (uint i = 0; i < _contractIdxs.length; i++) {
require(_contractIdxs[i] < contracts.length, "contractIdx must be < contracts length");
IOffchainAggregator(contracts[_contractIdxs[i]]).acceptPayeeship(transmitter);
}
}
| function _acceptAdmin(uint[] calldata _contractIdxs) internal override {
for (uint i = 0; i < _contractIdxs.length; i++) {
require(_contractIdxs[i] < contracts.length, "contractIdx must be < contracts length");
IOffchainAggregator(contracts[_contractIdxs[i]]).acceptPayeeship(transmitter);
}
}
| 6,197 |
24 | // mapping(address => uint) public teamallget;mapping(address => mapping(uint => uint)) public teamdayget;mapping(address => uint) public teamgettime; | struct sunsdata{
uint n1;
uint n2;
uint getmoney;
}
| struct sunsdata{
uint n1;
uint n2;
uint getmoney;
}
| 18,450 |
234 | // migrate our want token to a new strategy if needed, make sure to check claimRewards first also send over any CRV or CVX that is claimed; for migrations we definitely want to claim | function prepareMigration(address _newStrategy) internal override {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
rewardsContract.withdrawAndUnwrap(_stakedBal, claimRewards);
}
crv.safeTransfer(_newStrategy, crv.balanceOf(address(this)));
convexToken.safeTransfer(
_newStrategy,
convexToken.balanceOf(address(this))
);
}
| function prepareMigration(address _newStrategy) internal override {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
rewardsContract.withdrawAndUnwrap(_stakedBal, claimRewards);
}
crv.safeTransfer(_newStrategy, crv.balanceOf(address(this)));
convexToken.safeTransfer(
_newStrategy,
convexToken.balanceOf(address(this))
);
}
| 18,870 |
2 | // b_two = '0xaaaa';Alternativa | return b_two.length;
| return b_two.length;
| 15,451 |
313 | // give platform its secondary sale percentage | uint256 platformAmount = saleAmount.mul(platformSecondSalePercentages[tokenId]).div(100);
safeFundsTransfer(platformAddress, platformAmount);
| uint256 platformAmount = saleAmount.mul(platformSecondSalePercentages[tokenId]).div(100);
safeFundsTransfer(platformAddress, platformAmount);
| 28,490 |
18 | // get NFT URI, the method will return different NFT URI according to the the `tokenId` owner's amount of SCR, so as to realize Dynamic NFT/ e.g:/ ipfs:QmSDdbLq2QDEgNUQGwRH7iVrcZiTy6PvCnKrdawGbTa7QD/1_1.json/ ipfs:QmSDdbLq2QDEgNUQGwRH7iVrcZiTy6PvCnKrdawGbTa7QD/1_2.json/ ipfs:QmSDdbLq2QDEgNUQGwRH7iVrcZiTy6PvCnKrdawGbTa7QD/404.json | function tokenURI(
uint256 tokenId
| function tokenURI(
uint256 tokenId
| 36,293 |
50 | // Gas optimized reentrancy protection for smart contracts./Solmate (https:github.com/Rari-Capital/solmate/blob/main/src/utils/ReentrancyGuard.sol)/Modified from OpenZeppelin (https:github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol) | abstract contract ReentrancyGuard {
uint256 private locked = 1;
modifier nonReentrant() {
require(locked == 1, "REENTRANCY");
locked = 2;
_;
locked = 1;
}
}
| abstract contract ReentrancyGuard {
uint256 private locked = 1;
modifier nonReentrant() {
require(locked == 1, "REENTRANCY");
locked = 2;
_;
locked = 1;
}
}
| 47,241 |
8 | // Hypernet Protocol Buy Module for NFRs Todd Chapman Implementation of a simple purchasing extension for NFRs See the documentation for more details: See the unit tests for example usage: / | contract BuyModule is Context {
using SafeERC20 for IERC20;
/// @dev the name to be listed in the Hypernet Protocol Registry Modules NFR
/// @dev see https://docs.hypernet.foundation/hypernet-protocol/identity#registry-modules
string public name;
constructor(string memory _name)
{
name = _name;
}
/// @notice buyNFI purchase any NFIs still held by a REGISTRAR_ROLE account from the specified NFR
/// @dev The price is set by the registrationFee and
/// @param tokenId id of the token you want to buy
/// @param registry address of the target registry to call
function buyNFI(
uint256 tokenId,
address registry
)
external
virtual
{
address seller = INfr(registry).ownerOf(tokenId);
uint256 price = INfr(registry).registrationFee();
// the current owner of the tokenid must be an account in the REGISTRAR_ROLE
require(INfr(registry).hasRole(INfr(registry).REGISTRAR_ROLE(), seller), "BuyModule: token not for sale.");
// to use this module, the registrationFee should be non-zero
require(price > 0, "BuyModule: purchase price must be greater than 0.");
// transfer the registrationToken from the purchaser to the burnAddress
require(IERC20(INfr(registry).registrationToken()).transferFrom(_msgSender(), INfr(registry).burnAddress(), price), "BuyModule: ERC20 token transfer failed.");
// transfer the NFI from the REGISTRAR_ROLE holder to the purchaser
INfr(registry).safeTransferFrom(seller, _msgSender(), tokenId);
require(INfr(registry).ownerOf(tokenId) == _msgSender(), "BuyModule: NFI purchase transfer failed");
}
}
| contract BuyModule is Context {
using SafeERC20 for IERC20;
/// @dev the name to be listed in the Hypernet Protocol Registry Modules NFR
/// @dev see https://docs.hypernet.foundation/hypernet-protocol/identity#registry-modules
string public name;
constructor(string memory _name)
{
name = _name;
}
/// @notice buyNFI purchase any NFIs still held by a REGISTRAR_ROLE account from the specified NFR
/// @dev The price is set by the registrationFee and
/// @param tokenId id of the token you want to buy
/// @param registry address of the target registry to call
function buyNFI(
uint256 tokenId,
address registry
)
external
virtual
{
address seller = INfr(registry).ownerOf(tokenId);
uint256 price = INfr(registry).registrationFee();
// the current owner of the tokenid must be an account in the REGISTRAR_ROLE
require(INfr(registry).hasRole(INfr(registry).REGISTRAR_ROLE(), seller), "BuyModule: token not for sale.");
// to use this module, the registrationFee should be non-zero
require(price > 0, "BuyModule: purchase price must be greater than 0.");
// transfer the registrationToken from the purchaser to the burnAddress
require(IERC20(INfr(registry).registrationToken()).transferFrom(_msgSender(), INfr(registry).burnAddress(), price), "BuyModule: ERC20 token transfer failed.");
// transfer the NFI from the REGISTRAR_ROLE holder to the purchaser
INfr(registry).safeTransferFrom(seller, _msgSender(), tokenId);
require(INfr(registry).ownerOf(tokenId) == _msgSender(), "BuyModule: NFI purchase transfer failed");
}
}
| 16,567 |
80 | // returns a UQ112x112 which represents the ratio of the numerator to the denominator can be lossy | function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
| function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
| 54,789 |
35 | // Set the contract that can call release and make the token transferable./_crowdsaleAgent crowdsale contract address | function setCrowdsaleAgent(address _crowdsaleAgent) onlyOwner public {
crowdsaleAgent = _crowdsaleAgent;
}
| function setCrowdsaleAgent(address _crowdsaleAgent) onlyOwner public {
crowdsaleAgent = _crowdsaleAgent;
}
| 36,743 |
5 | // OLA_ADDITIONS : Contract hash name | bytes32 public contractNameHash;
| bytes32 public contractNameHash;
| 32,268 |
77 | // Quant Network Allows a mapp or gateway OVL Network staked deposit to be held in escrow to either be returned or slashed according to the verification rules / | contract EscrowedDeposit {
// @return - the connected payment channel
PaymentChannel pc;
// The QNT address of the MAPP or Gateway who added the deposit
address public MAPPorGatewayQNTAddress;
// The operator address that can trigger functions of this channel on behalf of the MAPP or Gateway
address public MAPPorGatewayOperatorAddress;
// the linked treasury contract
TreasuryBase t;
// Hardcoded link to the QNT contract:
ERC20Interface private constant QNTContract = ERC20Interface(0x19Bc592A0E1BAb3AFFB1A8746D8454743EE6E838);
// The event fired when the deposit is deducted:
event depositDeducted(uint256 claimedQNT, uint256 remainingQNT, address ruleAddress);
// The event fired when the deposit is returned:
event depositReturned(uint256 returnedQNT);
/**
* Deploys the contract and initialises the variables
* @param thisMAPPorGatewayQNTAddress - the QNT address of the MAPP or gateway in this escrow
* @param thisMAPPorGatewayOperatorAddress - the operator address of the MAPP or gateway in this escrow
* @param thisTreasuryAddress - the address of the treasury smart contract
* @param thisChannelAddress - the corresponding payment channel
*/
constructor(address thisMAPPorGatewayQNTAddress, address thisMAPPorGatewayOperatorAddress, address thisTreasuryAddress, address thisChannelAddress) public {
MAPPorGatewayQNTAddress = thisMAPPorGatewayQNTAddress;
MAPPorGatewayOperatorAddress = thisMAPPorGatewayOperatorAddress;
t = TreasuryBase(thisTreasuryAddress);
pc = PaymentChannel(thisChannelAddress);
}
/**
* The rule list contract can deduct QNT from this escrow and send it to the receiver (without closing the escrow)
* @param tokenAmount - the amount to deduct
* @param ruleAddress - the contract address detailing the specific rule the sender has broken
*/
function deductDeposit(uint256 tokenAmount, address ruleAddress) external {
address ruleList = t.treasurysRuleList();
require(msg.sender == ruleList, "This function can only be called by the associated rule list contract");
require(now >= expiration(), "The channel must have expired");
// Transfer the escrowed QNT:
uint256 startingBalance = readQNTBalance();
if (tokenAmount > startingBalance){
//transfer as much as possible:
QNTContract.transfer(t.QNTAddress(), startingBalance);
//emits event
emit depositDeducted(startingBalance,0,ruleAddress);
} else {
//transfer required amount
QNTContract.transfer(t.QNTAddress(), tokenAmount);
//emits event
emit depositDeducted(tokenAmount,readQNTBalance(),ruleAddress);
}
}
/**
* After the expiration time, the sender of this deposit can withdraw it through this function
*/
function WithdrawDeposit(uint256 tokenAmount) external {
require(msg.sender == MAPPorGatewayOperatorAddress, "Can only be called by the MAPP/Gateway operator address after expiry");
require(now >= expiration(), "Can only be called by the MAPP/Gateway operator address after expiry");
//transfer required amount
QNTContract.transfer(MAPPorGatewayQNTAddress, tokenAmount);
// Emit event
emit depositReturned(tokenAmount);
}
/**
* Reads the current QNT balance of this contract by checking the linked ERC20 contract
* @return - the QNT balance
*/
function readQNTBalance() public view returns (uint256) {
return QNTContract.balanceOf(address(this));
}
/**
* Reads the current expiration time of this contract by checking the linked payment channel contract
* @return - the expiration
*/
function expiration() public view returns (uint256){
return pc.expiration();
}
/**
* Reads the linked treasury contract address
* @return - the treasury contract
*/
function treasuryAddress() public view returns (address) {
return address(t);
}
/**
* Reads the corresponding payment channel address
* @return - the payment channel contract
*/
function paymentChannelAddress() public view returns (address) {
return address(pc);
}
}
| contract EscrowedDeposit {
// @return - the connected payment channel
PaymentChannel pc;
// The QNT address of the MAPP or Gateway who added the deposit
address public MAPPorGatewayQNTAddress;
// The operator address that can trigger functions of this channel on behalf of the MAPP or Gateway
address public MAPPorGatewayOperatorAddress;
// the linked treasury contract
TreasuryBase t;
// Hardcoded link to the QNT contract:
ERC20Interface private constant QNTContract = ERC20Interface(0x19Bc592A0E1BAb3AFFB1A8746D8454743EE6E838);
// The event fired when the deposit is deducted:
event depositDeducted(uint256 claimedQNT, uint256 remainingQNT, address ruleAddress);
// The event fired when the deposit is returned:
event depositReturned(uint256 returnedQNT);
/**
* Deploys the contract and initialises the variables
* @param thisMAPPorGatewayQNTAddress - the QNT address of the MAPP or gateway in this escrow
* @param thisMAPPorGatewayOperatorAddress - the operator address of the MAPP or gateway in this escrow
* @param thisTreasuryAddress - the address of the treasury smart contract
* @param thisChannelAddress - the corresponding payment channel
*/
constructor(address thisMAPPorGatewayQNTAddress, address thisMAPPorGatewayOperatorAddress, address thisTreasuryAddress, address thisChannelAddress) public {
MAPPorGatewayQNTAddress = thisMAPPorGatewayQNTAddress;
MAPPorGatewayOperatorAddress = thisMAPPorGatewayOperatorAddress;
t = TreasuryBase(thisTreasuryAddress);
pc = PaymentChannel(thisChannelAddress);
}
/**
* The rule list contract can deduct QNT from this escrow and send it to the receiver (without closing the escrow)
* @param tokenAmount - the amount to deduct
* @param ruleAddress - the contract address detailing the specific rule the sender has broken
*/
function deductDeposit(uint256 tokenAmount, address ruleAddress) external {
address ruleList = t.treasurysRuleList();
require(msg.sender == ruleList, "This function can only be called by the associated rule list contract");
require(now >= expiration(), "The channel must have expired");
// Transfer the escrowed QNT:
uint256 startingBalance = readQNTBalance();
if (tokenAmount > startingBalance){
//transfer as much as possible:
QNTContract.transfer(t.QNTAddress(), startingBalance);
//emits event
emit depositDeducted(startingBalance,0,ruleAddress);
} else {
//transfer required amount
QNTContract.transfer(t.QNTAddress(), tokenAmount);
//emits event
emit depositDeducted(tokenAmount,readQNTBalance(),ruleAddress);
}
}
/**
* After the expiration time, the sender of this deposit can withdraw it through this function
*/
function WithdrawDeposit(uint256 tokenAmount) external {
require(msg.sender == MAPPorGatewayOperatorAddress, "Can only be called by the MAPP/Gateway operator address after expiry");
require(now >= expiration(), "Can only be called by the MAPP/Gateway operator address after expiry");
//transfer required amount
QNTContract.transfer(MAPPorGatewayQNTAddress, tokenAmount);
// Emit event
emit depositReturned(tokenAmount);
}
/**
* Reads the current QNT balance of this contract by checking the linked ERC20 contract
* @return - the QNT balance
*/
function readQNTBalance() public view returns (uint256) {
return QNTContract.balanceOf(address(this));
}
/**
* Reads the current expiration time of this contract by checking the linked payment channel contract
* @return - the expiration
*/
function expiration() public view returns (uint256){
return pc.expiration();
}
/**
* Reads the linked treasury contract address
* @return - the treasury contract
*/
function treasuryAddress() public view returns (address) {
return address(t);
}
/**
* Reads the corresponding payment channel address
* @return - the payment channel contract
*/
function paymentChannelAddress() public view returns (address) {
return address(pc);
}
}
| 18,045 |
128 | // can not use swapExactTokensForETH if token is WETH | if (token == IUniswapV2Router02(uniswapRouterAddress).WETH()) {
| if (token == IUniswapV2Router02(uniswapRouterAddress).WETH()) {
| 12,514 |
154 | // ONLY OPERATOR: Updates fee recipient on both streaming fee and debt issuance modules. / | function updateFeeRecipient(address _newFeeRecipient) external onlyOperator {
bytes memory callData = abi.encodeWithSignature("updateFeeRecipient(address,address)", manager.setToken(), _newFeeRecipient);
invokeManager(address(streamingFeeModule), callData);
invokeManager(address(debtIssuanceModule), callData);
}
| function updateFeeRecipient(address _newFeeRecipient) external onlyOperator {
bytes memory callData = abi.encodeWithSignature("updateFeeRecipient(address,address)", manager.setToken(), _newFeeRecipient);
invokeManager(address(streamingFeeModule), callData);
invokeManager(address(debtIssuanceModule), callData);
}
| 11,034 |
296 | // 基金本币兑换成token1 | if(params.token1 == params.token){
amount1Max = params.amount1.add(params.amount.sub(fundToT0));
} else {
| if(params.token1 == params.token){
amount1Max = params.amount1.add(params.amount.sub(fundToT0));
} else {
| 7,069 |
346 | // Ends network exchange if necessary | if (shouldEndNetworkExchange) {
networkExchangeEnded = true;
}
| if (shouldEndNetworkExchange) {
networkExchangeEnded = true;
}
| 32,546 |
8 | // Called after the contract has | // function setTradeableCashflow(address tcfAddress) public {
// require(msg.sender == _ap.owner, "Only owner");
// // TODO: Require _tcf not set
// _tcf = ITradeableCashflow(tdfAddress);
// }
| // function setTradeableCashflow(address tcfAddress) public {
// require(msg.sender == _ap.owner, "Only owner");
// // TODO: Require _tcf not set
// _tcf = ITradeableCashflow(tdfAddress);
// }
| 43,224 |
12 | // if inFlowRate is zero, delete outflow. | (newCtx, ) = _host.callAgreementWithContext(
_cfa,
abi.encodeWithSelector(
_cfa.deleteFlow.selector,
_acceptedToken,
address(this),
_receiver,
new bytes(0) // placeholder
),
"0x",
| (newCtx, ) = _host.callAgreementWithContext(
_cfa,
abi.encodeWithSelector(
_cfa.deleteFlow.selector,
_acceptedToken,
address(this),
_receiver,
new bytes(0) // placeholder
),
"0x",
| 31,052 |
10 | // Function for loomiVault deposit/ | function deposit(uint256[] memory tokenIds) public nonReentrant whenNotPaused {
require(tokenIds.length > 0, "Empty array");
Staker storage user = _stakers[_msgSender()];
if (user.stakedVault.length == 0) {
uint256 currentLoomiPot = _getLoomiPot();
user.loomiPotSnapshot = currentLoomiPot;
}
accumulate(_msgSender());
for (uint256 i; i < tokenIds.length; i++) {
require(loomiVault.ownerOf(tokenIds[i]) == _msgSender(), "Not the owner");
loomiVault.safeTransferFrom(_msgSender(), address(this), tokenIds[i]);
_ownerOfToken[tokenIds[i]] = _msgSender();
user.stakedVault.push(tokenIds[i]);
}
emit Deposit(_msgSender(), tokenIds.length);
}
| function deposit(uint256[] memory tokenIds) public nonReentrant whenNotPaused {
require(tokenIds.length > 0, "Empty array");
Staker storage user = _stakers[_msgSender()];
if (user.stakedVault.length == 0) {
uint256 currentLoomiPot = _getLoomiPot();
user.loomiPotSnapshot = currentLoomiPot;
}
accumulate(_msgSender());
for (uint256 i; i < tokenIds.length; i++) {
require(loomiVault.ownerOf(tokenIds[i]) == _msgSender(), "Not the owner");
loomiVault.safeTransferFrom(_msgSender(), address(this), tokenIds[i]);
_ownerOfToken[tokenIds[i]] = _msgSender();
user.stakedVault.push(tokenIds[i]);
}
emit Deposit(_msgSender(), tokenIds.length);
}
| 51,612 |
42 | // Make sure they are sending min flush price | require(msg.value >= minFlushPrice);
| require(msg.value >= minFlushPrice);
| 38,305 |
35 | // solhint-disable-next-line not-rely-on-time | block.timestamp
);
| block.timestamp
);
| 16,929 |
17 | // Returns the address of the current owner./ | function owner() public view returns (address payable) {
return _owner;
}
| function owner() public view returns (address payable) {
return _owner;
}
| 23,572 |
44 | // Returns a random number using a specified block number Always use a FUTURE block number. | function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) {
return uint256(keccak256(
abi.encodePacked(
blockhash(blockn),
entropy)
));
}
| function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) {
return uint256(keccak256(
abi.encodePacked(
blockhash(blockn),
entropy)
));
}
| 38,848 |
86 | // uint256 vip1 = 0; uint256 vip2 = 0;uint256 vip3 = 0;for(uint i = 1;i < vipLevalLength;i++){address regAddr = regisUser[i];uint256 vip = getVipLeval(regAddr);if(vip == 1){vip1 ++;}else if(vip == 2){vip2 ++;}else if(vip == 3){vip3 ++;}}vipPoolInfo[1].vipNumber = vip1;vipPoolInfo[2].vipNumber = vip2;vipPoolInfo[3].vipNumber = vip3;for(uint i = 1;i < vipLevalLength;i++){updateVipPool(regisUser[i]);} | }
| }
| 29,717 |
85 | // given keeper fee, calculate how much to distribute to split recipients underflow should be impossible with validated distributorFee | amountToSplit -= distributorFeeAmount;
| amountToSplit -= distributorFeeAmount;
| 25,553 |
50 | // There must be sufficient allowance available. | uint256 _allowanceOf = directory.controllerOf(_projectId).overflowAllowanceOf(
_projectId,
fundingCycle.configuration,
terminal
);
if (_newUsedOverflowAllowanceOf > _allowanceOf || _allowanceOf == 0) {
revert INADEQUATE_CONTROLLER_ALLOWANCE();
}
| uint256 _allowanceOf = directory.controllerOf(_projectId).overflowAllowanceOf(
_projectId,
fundingCycle.configuration,
terminal
);
if (_newUsedOverflowAllowanceOf > _allowanceOf || _allowanceOf == 0) {
revert INADEQUATE_CONTROLLER_ALLOWANCE();
}
| 9,498 |
49 | // Allows owner to change exchangeLimit. newLimit The new limit to change to. / | function setExchangeLimit(uint newLimit) external onlyCFO {
exchangeLimit = newLimit;
}
| function setExchangeLimit(uint newLimit) external onlyCFO {
exchangeLimit = newLimit;
}
| 56,201 |
2 | // wd The withdraw data consisting of/ semantic withdraw information, i.e. assetId, recipient, and amount;/ information to make an optional call in addition to the actual transfer,/ i.e. target address for the call and call payload;/ additional information, i.e. channel address and nonce./aliceSignature Signature of owner a/bobSignature Signature of owner b | function withdraw(
WithdrawData calldata wd,
bytes calldata aliceSignature,
bytes calldata bobSignature
| function withdraw(
WithdrawData calldata wd,
bytes calldata aliceSignature,
bytes calldata bobSignature
| 6,733 |
12 | // Gets the address of Vault. | function vaultAddress() public view returns (address) {
return _nameRegistry.get(keccak256(abi.encodePacked("Vault")));
}
| function vaultAddress() public view returns (address) {
return _nameRegistry.get(keccak256(abi.encodePacked("Vault")));
}
| 24,678 |
61 | // Set the burn address. / | function setBurnAddress(address addr) public onlyOwner {
burnAddress = addr;
}
| function setBurnAddress(address addr) public onlyOwner {
burnAddress = addr;
}
| 32,506 |
73 | // batch mint existing token from extension. Can only be called by a registered extension.to- Can be a single element array (all tokens go to same address) or multi-element array (single token to many recipients) tokenIds- Can be a single element array (all recipients get the same token) or a multi-element array amounts - Can be a single element array (all recipients get the same amount) or a multi-element array Requirements: If any of the parameters are multi-element arrays, they need to be the same length as other multi-element arrays Examples: mintExtensionExisting(['0x....1', '0x....2'], [1], [10]) Mints 10 of tokenId 1 to | function mintExtensionExisting(address[] calldata to, uint256[] calldata tokenIds, uint256[] calldata amounts) external;
| function mintExtensionExisting(address[] calldata to, uint256[] calldata tokenIds, uint256[] calldata amounts) external;
| 7,918 |
49 | // Handle new tickets | TicketPurchases storage purchases = ticketsBoughtByPlayer[msg.sender];
| TicketPurchases storage purchases = ticketsBoughtByPlayer[msg.sender];
| 6,765 |
24 | // 更新最新的最高出价者, 拍卖品数量, 本次出价的过期时间. | states[id].win = msg.sender;
states[id].oam = oam;
states[id].ttl = uint32(now) + ttl;
| states[id].win = msg.sender;
states[id].oam = oam;
states[id].ttl = uint32(now) + ttl;
| 22,783 |
253 | // owedWei is already negative and heldWei is already positive | if (negOwed && posHeld) {
return;
}
| if (negOwed && posHeld) {
return;
}
| 33,226 |
129 | // Sets the author. / | author = _own;
| author = _own;
| 16,638 |
11 | // Returns boolean flag indicating whether token is whitelisted token Addresses of the given token to checkreturn Boolean flag indicating whether the token is whitelisted / | function isWhitelistedERC20(address token) external view returns (bool);
| function isWhitelistedERC20(address token) external view returns (bool);
| 38,296 |
189 | // Remember the initial block number // Short-circuit accumulating 0 interest // Read the previous values out of storage // Calculate the current borrow interest rate // Calculate the number of blocks elapsed since the last accrual //Calculate the interest accumulated into borrows and reserves and the new index: simpleInterestFactor = borrowRateblockDelta interestAccumulated = simpleInterestFactortotalBorrows totalBorrowsNew = interestAccumulated + totalBorrows totalReservesNew = interestAccumulatedreserveFactor + totalReserves borrowIndexNew = simpleInterestFactorborrowIndex + borrowIndex / |
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
|
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
| 17,346 |
7 | // Deprecated: now resides in Harvester's rewardTokenConfigs slither-disable-next-line constable-states | uint256 private _deprecated_rewardLiquidationThreshold;
| uint256 private _deprecated_rewardLiquidationThreshold;
| 10,567 |
313 | // oods_coefficients[249]/ mload(add(context, 0x8a00)), Advance compositionQueryResponses by amount read (0x20constraintDegree). | compositionQueryResponses := add(compositionQueryResponses, 0x40)
| compositionQueryResponses := add(compositionQueryResponses, 0x40)
| 77,556 |
645 | // the token source. Specifies the source of the token - either a static source or a collection. | struct TokenSource {
// the token source type
TokenSourceType _type;
// the source id if a static collection
uint256 staticSourceId;
// the collection source address if collection
address collectionSourceAddress;
}
| struct TokenSource {
// the token source type
TokenSourceType _type;
// the source id if a static collection
uint256 staticSourceId;
// the collection source address if collection
address collectionSourceAddress;
}
| 76,117 |
18 | // total RFV deployed into lending pool | uint256 public totalValueDeployed;
| uint256 public totalValueDeployed;
| 82,150 |
9 | // burn tokens held by sender amount quantity of tokens to burn / | function burn (uint amount) override external {
_burn(msg.sender, amount);
}
| function burn (uint amount) override external {
_burn(msg.sender, amount);
}
| 29,895 |
269 | // https:docs.synthetix.io/contracts/Owned | contract Owned {
address public owner;
address public nominatedOwner;
constructor (address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
| contract Owned {
address public owner;
address public nominatedOwner;
constructor (address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
| 4,038 |
26 | // Withdraw JOE and harvest the rewards _amount The amount of JOE to withdraw / | function withdraw(uint256 _amount) external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _previousAmount = user.amount;
require(_amount <= _previousAmount, "StableJoeStaking: withdraw amount exceeds balance");
uint256 _newAmount = user.amount.sub(_amount);
user.amount = _newAmount;
uint256 _len = rewardTokens.length;
if (_previousAmount != 0) {
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
updateReward(_token);
uint256 _pending = _previousAmount
.mul(accRewardPerShare[_token])
.div(ACC_REWARD_PER_SHARE_PRECISION)
.sub(user.rewardDebt[_token]);
user.rewardDebt[_token] = _newAmount.mul(accRewardPerShare[_token]).div(ACC_REWARD_PER_SHARE_PRECISION);
if (_pending != 0) {
safeTokenTransfer(_token, _msgSender(), _pending);
emit ClaimReward(_msgSender(), address(_token), _pending);
}
}
}
internalJoeBalance = internalJoeBalance.sub(_amount);
joe.safeTransfer(_msgSender(), _amount);
emit Withdraw(_msgSender(), _amount);
}
| function withdraw(uint256 _amount) external {
UserInfo storage user = userInfo[_msgSender()];
uint256 _previousAmount = user.amount;
require(_amount <= _previousAmount, "StableJoeStaking: withdraw amount exceeds balance");
uint256 _newAmount = user.amount.sub(_amount);
user.amount = _newAmount;
uint256 _len = rewardTokens.length;
if (_previousAmount != 0) {
for (uint256 i; i < _len; i++) {
IERC20Upgradeable _token = rewardTokens[i];
updateReward(_token);
uint256 _pending = _previousAmount
.mul(accRewardPerShare[_token])
.div(ACC_REWARD_PER_SHARE_PRECISION)
.sub(user.rewardDebt[_token]);
user.rewardDebt[_token] = _newAmount.mul(accRewardPerShare[_token]).div(ACC_REWARD_PER_SHARE_PRECISION);
if (_pending != 0) {
safeTokenTransfer(_token, _msgSender(), _pending);
emit ClaimReward(_msgSender(), address(_token), _pending);
}
}
}
internalJoeBalance = internalJoeBalance.sub(_amount);
joe.safeTransfer(_msgSender(), _amount);
emit Withdraw(_msgSender(), _amount);
}
| 19,965 |
65 | // Additional assignment happens in the loop below | uint256 minimumUnit = uint256(-1);
for (uint256 i = 0; i < components.length; i++) {
address component = components[i];
| uint256 minimumUnit = uint256(-1);
for (uint256 i = 0; i < components.length; i++) {
address component = components[i];
| 35,018 |
1 | // Mapping from the uint256 challenge ID to the encoded challenge string | mapping(uint256 => string) private challenges;
| mapping(uint256 => string) private challenges;
| 5,779 |
184 | // Debt auction | function flop() external returns (uint id) {
require(sump <= sub(sub(vat.sin(address(this)), Sin), Ash), "Vow/insufficient-debt");
require(vat.USB(address(this)) == 0, "Vow/surplus-not-zero");
Ash = add(Ash, sump);
id = flopper.kick(address(this), dump, sump);
}
| function flop() external returns (uint id) {
require(sump <= sub(sub(vat.sin(address(this)), Sin), Ash), "Vow/insufficient-debt");
require(vat.USB(address(this)) == 0, "Vow/surplus-not-zero");
Ash = add(Ash, sump);
id = flopper.kick(address(this), dump, sump);
}
| 11,986 |
142 | // Creates a new Asset with the given fields. ONly available for C Levels/_creatorTokenID The asset who is father of this asset/_price asset price/_assetID asset ID/_category see Asset Struct description/_attributes see Asset Struct description/_stats see Asset Struct description | function createNewAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _assetID,
uint8 _category,
uint8 _attributes,
uint8[STATS_SIZE] _stats
)
external onlyCLevel
| function createNewAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _assetID,
uint8 _category,
uint8 _attributes,
uint8[STATS_SIZE] _stats
)
external onlyCLevel
| 33,666 |
65 | // UnitsAttack | function getUnitsAttack(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitAttack(unitId) + unitAttackIncreases[player][unitId]) * (10 + unitAttackMultiplier[player][unitId])) / 10;
}
| function getUnitsAttack(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitAttack(unitId) + unitAttackIncreases[player][unitId]) * (10 + unitAttackMultiplier[player][unitId])) / 10;
}
| 26,608 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.