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
|
---|---|---|---|---|
4 | // remove addresses from the whitelist _addrs addressesreturn true if at least one address was removed from the whitelist,false if all addresses weren't in the whitelist in the first place / | function removeAddressesFromWhitelist(address[] _addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < _addrs.length; i++) {
if (removeAddressFromWhitelist(_addrs[i])) {
success = true;
}
}
}
| function removeAddressesFromWhitelist(address[] _addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < _addrs.length; i++) {
if (removeAddressFromWhitelist(_addrs[i])) {
success = true;
}
}
}
| 43,234 |
21 | // tokenOutputAmount/baseInputAmount = tokenPriceFromOracle/basePriceFromOraclebaseInputAmount = tokenOutputAmountbasePriceFromOracle/tokenPriceFromOracle | function getBaseInputAmountFromTokenOutput(uint256 tokenOutputAmount, uint256 baseReserve, uint256 tokenReserve) public view returns (uint256) {
require(baseReserve > 0 && tokenReserve > 0, "INVALID_VALUE");
uint256 tokenPriceFromOracle = garbiOracle.getLatestPrice(address(token));
uint256 basePriceFromOracle = garbiOracle.getLatestPrice(address(base));
uint256 baseInputAmount = tokenOutputAmount.mul(basePriceFromOracle).div(tokenPriceFromOracle);
return baseInputAmount;
}
| function getBaseInputAmountFromTokenOutput(uint256 tokenOutputAmount, uint256 baseReserve, uint256 tokenReserve) public view returns (uint256) {
require(baseReserve > 0 && tokenReserve > 0, "INVALID_VALUE");
uint256 tokenPriceFromOracle = garbiOracle.getLatestPrice(address(token));
uint256 basePriceFromOracle = garbiOracle.getLatestPrice(address(base));
uint256 baseInputAmount = tokenOutputAmount.mul(basePriceFromOracle).div(tokenPriceFromOracle);
return baseInputAmount;
}
| 19,746 |
6 | // return if minting is finished or not. / | function mintingFinished() public view returns (bool) {
return _mintingFinished;
}
| function mintingFinished() public view returns (bool) {
return _mintingFinished;
}
| 30,509 |
86 | // Override to extend the way in which ether is converted to bonus tokens. _tokenAmount Value in wei to be converted into tokensreturn Number of bonus tokens that can be distributed with the specified bonus percent / | function _getBonusAmount(uint256 _tokenAmount, uint256 _bonusIndex) internal view returns (uint256) {
uint256 bonusValue = _tokenAmount.mul(bonusLevels[_bonusIndex]);
return bonusValue.div(100);
}
| function _getBonusAmount(uint256 _tokenAmount, uint256 _bonusIndex) internal view returns (uint256) {
uint256 bonusValue = _tokenAmount.mul(bonusLevels[_bonusIndex]);
return bonusValue.div(100);
}
| 6,563 |
56 | // Remove the tokens from the balance of the buyer. | holdings[msg.sender] -= amount;
int256 payoutDiff = (int256) (earningsPerBond * amount);//we don't add in numETH because it is immedietly paid out.
| holdings[msg.sender] -= amount;
int256 payoutDiff = (int256) (earningsPerBond * amount);//we don't add in numETH because it is immedietly paid out.
| 59,109 |
30 | // function to set reward percent | function setRewardPercent(uint256 silver, uint256 gold, uint256 platinum) external onlyOwner returns(bool){
require(silver != 0 && gold != 0 && platinum !=0,"Invalid Reward Value or Zero value, Please Try Again!!!");
TOKEN_REWARD_PERCENT_SILVER = silver;
TOKEN_REWARD_PERCENT_GOLD = gold;
TOKEN_REWARD_PERCENT_PLATINUM = platinum;
return true;
}
| function setRewardPercent(uint256 silver, uint256 gold, uint256 platinum) external onlyOwner returns(bool){
require(silver != 0 && gold != 0 && platinum !=0,"Invalid Reward Value or Zero value, Please Try Again!!!");
TOKEN_REWARD_PERCENT_SILVER = silver;
TOKEN_REWARD_PERCENT_GOLD = gold;
TOKEN_REWARD_PERCENT_PLATINUM = platinum;
return true;
}
| 75,213 |
6 | // Check if Mining gold is Enabled | require(a.enableMine, "NA");
| require(a.enableMine, "NA");
| 27,450 |
239 | // approved specific tokens | mapping(address => EnumerableSet.UintSet) private _approvedTokens;
mapping(address => range[]) private _approvedTokenRange;
| mapping(address => EnumerableSet.UintSet) private _approvedTokens;
mapping(address => range[]) private _approvedTokenRange;
| 9,876 |
73 | // Throws unless `msg.sender` is the current owner, an authorized operator, or theapproved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` isthe zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, thisfunction checks if `_to` is a smart contract (code size > 0). If so, it calls`onERC721Received` on `_to` and throws if the return value is not`bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. Transfers the ownership of an NFT from one address to another address. This function canbe changed to payable. _from The current owner of the NFT. _to The new owner. _tokenId The NFT | function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external
override
| function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external
override
| 2,959 |
0 | // Required. Unique identifier of the book, auto assigned by the system. | uint bookId;
| uint bookId;
| 36,711 |
17 | // EIP 2612 | function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
| function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
| 20,737 |
4 | // 避免转帐的地址是0x0 | require(_to != 0x0);
| require(_to != 0x0);
| 35,646 |
10 | // Update the user's deposit amount | userDeposits[msg.sender] += msg.value;
| userDeposits[msg.sender] += msg.value;
| 10,604 |
66 | // Called when `_owner` sends ether to the MiniMe Token contract/_owner The address that sent the ether to create tokens/ return True if the ether is accepted, false if it throws | function proxyPayment(address _owner) payable public returns (bool);
| function proxyPayment(address _owner) payable public returns (bool);
| 22,018 |
287 | // Get total notional amount of Default position_setTokenSupply Supply of SetToken in precise units (10^18) _positionUnit Quantity of Position units returnTotal notional amount of units / | function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit)
internal
pure
returns (uint256)
| function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit)
internal
pure
returns (uint256)
| 58,504 |
42 | // Decrement num to delete | numToDelete--;
| numToDelete--;
| 19,552 |
33 | // Calculates the sell amount reduced by the spread. sellAmount The original sell amount.return The reduced sell amount, computed as (1 - spread)sellAmount / | function getReducedSellAmount(uint256 sellAmount)
private
view
returns (FixidityLib.Fraction memory)
| function getReducedSellAmount(uint256 sellAmount)
private
view
returns (FixidityLib.Fraction memory)
| 36,462 |
105 | // Constructor function/ | constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
| constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
| 5,654 |
14 | // The active `token1` liquidity amount following the last swap.This value is used to determine active liquidity balances after potential rebases until the next future swap. / | uint112 internal pool1Last;
| uint112 internal pool1Last;
| 35,515 |
129 | // DAI/Rari | pool = ISaffronPool(pools[9]);
base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[9]) > 0) pool.hourly_strategy(adapters[1]);
| pool = ISaffronPool(pools[9]);
base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[9]) > 0) pool.hourly_strategy(adapters[1]);
| 6,076 |
88 | // BalanceManager calls to update expire time of a plan when a deposit/withdrawal happens. _user Address whose balance was updated. _expiry New time plans expire./ | {
if (plans[_user].length == 0) return;
Plan storage plan = plans[_user][plans[_user].length-1];
if (_expiry <= block.timestamp) _removeLatestTotals(_user);
plan.endTime = uint64(_expiry);
}
| {
if (plans[_user].length == 0) return;
Plan storage plan = plans[_user][plans[_user].length-1];
if (_expiry <= block.timestamp) _removeLatestTotals(_user);
plan.endTime = uint64(_expiry);
}
| 27,370 |
83 | // UNBASE ERC20 token UNBASE is a normal ERC20 token, but its supply can be adjusted by splitting and combining tokens proportionally across all wallets.UNBASE balances are internally represented with a hidden denomination, 'shares'. We support splitting the currency in expansion and combining the currency on contraction by changing the exchange rate between the hidden 'shares' and the public 'UNBASE'. / | contract UnbaseToken is ERC20, 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 shares that equals 1 UNBASE.
// The inverse rate must not be used--totalShares is always the numerator and _totalSupply is
// always the denominator. (i.e. If you want to convert shares to UNBASE instead of
// multiplying by the inverse rate, you should divide by the normal rate)
// 2) Share balances converted into UnbaseToken are always rounded down (truncated).
//
// We make the following guarantees:
// - If address 'A' transfers x UnbaseToken to address 'B'. A's resulting external balance will
// be decreased by precisely x UnbaseToken, and B's external balance will be precisely
// increased by x UnbaseToken.
//
// 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;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
event LogUserBanStatusUpdated(address user, bool banned);
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private constant DECIMALS = 18;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_SUPPLY = 1000000 * 10**DECIMALS;
uint256 private constant INITIAL_SHARES = (MAX_UINT256) - (MAX_UINT256 % INITIAL_SUPPLY);
uint256 public _totalShares;
uint256 public _totalSupply;
uint256 public _sharesPerUNBASE;
address public _unbaseUniswapLPContract;
uint256 public _epoch = 0;
uint256 public _unbasePercent = 20000; // 1e5 = 100%. At each rebase event, _totalSupply is reduced by unbasePercent
mapping(address => uint256) private _shareBalances;
mapping(address => bool) public bannedUsers;
// This is denominated in UnbaseToken, because the shares-UNBASE conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedUNBASE;
bool public transfersPaused;
bool public rebasesPaused;
mapping(address => bool) public transferPauseExemptList;
constructor() public ERC20("Unbase Protocol", "UNB") {
_totalShares = INITIAL_SHARES;
_totalSupply = INITIAL_SUPPLY;
_shareBalances[owner()] = _totalShares;
_sharesPerUNBASE = _totalShares.div(_totalSupply);
// Ban the Kucoin hacker
bannedUsers[0xeB31973E0FeBF3e3D7058234a5eBbAe1aB4B8c23] = true;
emit Transfer(address(0x0), owner(), _totalSupply);
}
function setTransfersPaused(bool _transfersPaused)
public
onlyOwner
{
transfersPaused = _transfersPaused;
}
function setTransferPauseExempt(address user, bool exempt)
public
onlyOwner
{
if (exempt) {
transferPauseExemptList[user] = true;
} else {
delete transferPauseExemptList[user];
}
}
function setRebasesPaused(bool _rebasesPaused)
public
onlyOwner
{
rebasesPaused = _rebasesPaused;
}
function setUnbasePercent(uint256 _newUnbasePercent)
public
onlyOwner
{
_unbasePercent = _newUnbasePercent;
}
function setUnbaseUniswapLPContract(address _newUnbaseUniswapLPContract)
public
onlyOwner
{
_unbaseUniswapLPContract = _newUnbaseUniswapLPContract;
}
/**
* @dev Notifies UnbaseToken contract about a new rebase cycle.
* @return The total number of UNBASE after the supply adjustment.
*/
function rebase()
public
onlyOwner
returns (uint256)
{
require(!rebasesPaused, "rebases paused");
_totalSupply = _totalSupply.sub(_totalSupply.mul(_unbasePercent).div(1e5));
_sharesPerUNBASE = _totalShares.div(_totalSupply);
_epoch = _epoch.add(1);
// From this point forward, _sharesPerUNBASE is taken as the source of truth.
// We recalculate a new _totalSupply to be in agreement with the _sharesPerUNBASE
// conversion rate.
// This means our applied supplyDelta can deviate from the requested supplyDelta,
// but this deviation is guaranteed to be < (_totalSupply^2)/(totalShares - _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.
emit LogRebase(_epoch, _totalSupply);
IUniswapSync(_unbaseUniswapLPContract).sync();
return _totalSupply;
}
function totalShares()
public
view
returns (uint256)
{
return _totalShares;
}
function sharesOf(address user)
public
view
returns (uint256)
{
return _shareBalances[user];
}
function setUserBanStatus(address user, bool banned)
public
onlyOwner
{
if (banned) {
bannedUsers[user] = true;
} else {
delete bannedUsers[user];
}
emit LogUserBanStatusUpdated(user, banned);
}
/**
* @return The total number of UNBASE.
*/
function totalSupply()
public
override
view
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
public
override
view
returns (uint256)
{
return _shareBalances[who].div(_sharesPerUNBASE);
}
/**
* @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
override(ERC20)
validRecipient(to)
returns (bool)
{
require(bannedUsers[msg.sender] == false, "you are banned");
require(!transfersPaused || transferPauseExemptList[msg.sender], "paused");
uint256 shareValue = value.mul(_sharesPerUNBASE);
_shareBalances[msg.sender] = _shareBalances[msg.sender].sub(shareValue);
_shareBalances[to] = _shareBalances[to].add(shareValue);
emit Transfer(msg.sender, to, value);
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
override
view
returns (uint256)
{
return _allowedUNBASE[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
override
validRecipient(to)
returns (bool)
{
require(bannedUsers[msg.sender] == false, "you are banned");
require(!transfersPaused || transferPauseExemptList[msg.sender], "paused");
_allowedUNBASE[from][msg.sender] = _allowedUNBASE[from][msg.sender].sub(value);
uint256 shareValue = value.mul(_sharesPerUNBASE);
_shareBalances[from] = _shareBalances[from].sub(shareValue);
_shareBalances[to] = _shareBalances[to].add(shareValue);
emit Transfer(from, to, value);
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
override
returns (bool)
{
require(!transfersPaused || transferPauseExemptList[msg.sender], "paused");
_allowedUNBASE[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
override
returns (bool)
{
require(!transfersPaused || transferPauseExemptList[msg.sender], "paused");
_allowedUNBASE[msg.sender][spender] = _allowedUNBASE[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedUNBASE[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
override
returns (bool)
{
require(!transfersPaused || transferPauseExemptList[msg.sender], "paused");
uint256 oldValue = _allowedUNBASE[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedUNBASE[msg.sender][spender] = 0;
} else {
_allowedUNBASE[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedUNBASE[msg.sender][spender]);
return true;
}
} | contract UnbaseToken is ERC20, 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 shares that equals 1 UNBASE.
// The inverse rate must not be used--totalShares is always the numerator and _totalSupply is
// always the denominator. (i.e. If you want to convert shares to UNBASE instead of
// multiplying by the inverse rate, you should divide by the normal rate)
// 2) Share balances converted into UnbaseToken are always rounded down (truncated).
//
// We make the following guarantees:
// - If address 'A' transfers x UnbaseToken to address 'B'. A's resulting external balance will
// be decreased by precisely x UnbaseToken, and B's external balance will be precisely
// increased by x UnbaseToken.
//
// 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;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
event LogUserBanStatusUpdated(address user, bool banned);
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private constant DECIMALS = 18;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_SUPPLY = 1000000 * 10**DECIMALS;
uint256 private constant INITIAL_SHARES = (MAX_UINT256) - (MAX_UINT256 % INITIAL_SUPPLY);
uint256 public _totalShares;
uint256 public _totalSupply;
uint256 public _sharesPerUNBASE;
address public _unbaseUniswapLPContract;
uint256 public _epoch = 0;
uint256 public _unbasePercent = 20000; // 1e5 = 100%. At each rebase event, _totalSupply is reduced by unbasePercent
mapping(address => uint256) private _shareBalances;
mapping(address => bool) public bannedUsers;
// This is denominated in UnbaseToken, because the shares-UNBASE conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedUNBASE;
bool public transfersPaused;
bool public rebasesPaused;
mapping(address => bool) public transferPauseExemptList;
constructor() public ERC20("Unbase Protocol", "UNB") {
_totalShares = INITIAL_SHARES;
_totalSupply = INITIAL_SUPPLY;
_shareBalances[owner()] = _totalShares;
_sharesPerUNBASE = _totalShares.div(_totalSupply);
// Ban the Kucoin hacker
bannedUsers[0xeB31973E0FeBF3e3D7058234a5eBbAe1aB4B8c23] = true;
emit Transfer(address(0x0), owner(), _totalSupply);
}
function setTransfersPaused(bool _transfersPaused)
public
onlyOwner
{
transfersPaused = _transfersPaused;
}
function setTransferPauseExempt(address user, bool exempt)
public
onlyOwner
{
if (exempt) {
transferPauseExemptList[user] = true;
} else {
delete transferPauseExemptList[user];
}
}
function setRebasesPaused(bool _rebasesPaused)
public
onlyOwner
{
rebasesPaused = _rebasesPaused;
}
function setUnbasePercent(uint256 _newUnbasePercent)
public
onlyOwner
{
_unbasePercent = _newUnbasePercent;
}
function setUnbaseUniswapLPContract(address _newUnbaseUniswapLPContract)
public
onlyOwner
{
_unbaseUniswapLPContract = _newUnbaseUniswapLPContract;
}
/**
* @dev Notifies UnbaseToken contract about a new rebase cycle.
* @return The total number of UNBASE after the supply adjustment.
*/
function rebase()
public
onlyOwner
returns (uint256)
{
require(!rebasesPaused, "rebases paused");
_totalSupply = _totalSupply.sub(_totalSupply.mul(_unbasePercent).div(1e5));
_sharesPerUNBASE = _totalShares.div(_totalSupply);
_epoch = _epoch.add(1);
// From this point forward, _sharesPerUNBASE is taken as the source of truth.
// We recalculate a new _totalSupply to be in agreement with the _sharesPerUNBASE
// conversion rate.
// This means our applied supplyDelta can deviate from the requested supplyDelta,
// but this deviation is guaranteed to be < (_totalSupply^2)/(totalShares - _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.
emit LogRebase(_epoch, _totalSupply);
IUniswapSync(_unbaseUniswapLPContract).sync();
return _totalSupply;
}
function totalShares()
public
view
returns (uint256)
{
return _totalShares;
}
function sharesOf(address user)
public
view
returns (uint256)
{
return _shareBalances[user];
}
function setUserBanStatus(address user, bool banned)
public
onlyOwner
{
if (banned) {
bannedUsers[user] = true;
} else {
delete bannedUsers[user];
}
emit LogUserBanStatusUpdated(user, banned);
}
/**
* @return The total number of UNBASE.
*/
function totalSupply()
public
override
view
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
public
override
view
returns (uint256)
{
return _shareBalances[who].div(_sharesPerUNBASE);
}
/**
* @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
override(ERC20)
validRecipient(to)
returns (bool)
{
require(bannedUsers[msg.sender] == false, "you are banned");
require(!transfersPaused || transferPauseExemptList[msg.sender], "paused");
uint256 shareValue = value.mul(_sharesPerUNBASE);
_shareBalances[msg.sender] = _shareBalances[msg.sender].sub(shareValue);
_shareBalances[to] = _shareBalances[to].add(shareValue);
emit Transfer(msg.sender, to, value);
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
override
view
returns (uint256)
{
return _allowedUNBASE[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
override
validRecipient(to)
returns (bool)
{
require(bannedUsers[msg.sender] == false, "you are banned");
require(!transfersPaused || transferPauseExemptList[msg.sender], "paused");
_allowedUNBASE[from][msg.sender] = _allowedUNBASE[from][msg.sender].sub(value);
uint256 shareValue = value.mul(_sharesPerUNBASE);
_shareBalances[from] = _shareBalances[from].sub(shareValue);
_shareBalances[to] = _shareBalances[to].add(shareValue);
emit Transfer(from, to, value);
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
override
returns (bool)
{
require(!transfersPaused || transferPauseExemptList[msg.sender], "paused");
_allowedUNBASE[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
override
returns (bool)
{
require(!transfersPaused || transferPauseExemptList[msg.sender], "paused");
_allowedUNBASE[msg.sender][spender] = _allowedUNBASE[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedUNBASE[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
override
returns (bool)
{
require(!transfersPaused || transferPauseExemptList[msg.sender], "paused");
uint256 oldValue = _allowedUNBASE[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedUNBASE[msg.sender][spender] = 0;
} else {
_allowedUNBASE[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedUNBASE[msg.sender][spender]);
return true;
}
} | 21,244 |
14 | // Third variant of contract deployment. | function deployWithMsgBody(
TvmCell stateInit,
int8 wid,
uint128 initialBalance,
TvmCell payload
)
public
checkOwnerAndAccept
| function deployWithMsgBody(
TvmCell stateInit,
int8 wid,
uint128 initialBalance,
TvmCell payload
)
public
checkOwnerAndAccept
| 49,198 |
187 | // Claim all expired wTokens | claimAllExpiredTokens();
| claimAllExpiredTokens();
| 7,061 |
194 | // Get orders of owner by page _owner The owner address _from The begin id of the node to get _limit The total nodes of one page _direction Direction to step inreturn The order ids and the next id / | function getOrdersOfOwner(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
| function getOrdersOfOwner(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
| 14,510 |
121 | // Returns the Rule associated to the specified ruleId / | function rule(uint256 _ruleId) public view returns (IRule) {
return rules[_ruleId];
}
| function rule(uint256 _ruleId) public view returns (IRule) {
return rules[_ruleId];
}
| 3,370 |
24 | // assert(b > 0);Solidity automatically throws when dividing by 0 | uint c = a / b;
| uint c = a / b;
| 30,329 |
25 | // Create sell offer for cat with a certain minimum sale price in wei (by cat owner only) / | function offerCatForSale(uint catIndex, uint minSalePriceInWei) {
require (catIndexToAddress[catIndex] == msg.sender); // Require that sender is cat owner
require (catIndex < _totalSupply); // Require that cat index is valid
catsForSale[catIndex] = Offer(true, catIndex, msg.sender, minSalePriceInWei, 0x0); // Set cat for sale flag to true and update with price details
CatOffered(catIndex, minSalePriceInWei, 0x0); // Create EVM event to log details of cat sale
}
| function offerCatForSale(uint catIndex, uint minSalePriceInWei) {
require (catIndexToAddress[catIndex] == msg.sender); // Require that sender is cat owner
require (catIndex < _totalSupply); // Require that cat index is valid
catsForSale[catIndex] = Offer(true, catIndex, msg.sender, minSalePriceInWei, 0x0); // Set cat for sale flag to true and update with price details
CatOffered(catIndex, minSalePriceInWei, 0x0); // Create EVM event to log details of cat sale
}
| 59,888 |
18 | // Org: Get User Details | function getUserBasicDetails(address _userAddress) external view registeredOrg(msg.sender) returns (string memory, State, string memory, string memory, string memory, string memory, string memory) {
require(kycRequests[_userAddress][msg.sender].state == State.Approved, "BGV Request is not approved by customer yet.");
User memory user = users[_userAddress];
if(!kycRequests[_userAddress][msg.sender].canViewAddress)
{
user.permanentAddress = "";
user.currentAddress = "";
}
if(!kycRequests[_userAddress][msg.sender].canViewContactDetails)
{
user.email = "";
user.phone = "";
}
if(!kycRequests[_userAddress][msg.sender].canViewReferences)
{
user.refEmail = "";
}
return (user.uname, user.state, user.permanentAddress, user.currentAddress, user.email, user.phone, user.refEmail);
}
| function getUserBasicDetails(address _userAddress) external view registeredOrg(msg.sender) returns (string memory, State, string memory, string memory, string memory, string memory, string memory) {
require(kycRequests[_userAddress][msg.sender].state == State.Approved, "BGV Request is not approved by customer yet.");
User memory user = users[_userAddress];
if(!kycRequests[_userAddress][msg.sender].canViewAddress)
{
user.permanentAddress = "";
user.currentAddress = "";
}
if(!kycRequests[_userAddress][msg.sender].canViewContactDetails)
{
user.email = "";
user.phone = "";
}
if(!kycRequests[_userAddress][msg.sender].canViewReferences)
{
user.refEmail = "";
}
return (user.uname, user.state, user.permanentAddress, user.currentAddress, user.email, user.phone, user.refEmail);
}
| 18,228 |
42 | // RootAuthorizer: delegateCallAuthorizer not set | string constant DELEGATE_CALL_AUTH_NOT_SET = "E42";
| string constant DELEGATE_CALL_AUTH_NOT_SET = "E42";
| 38,015 |
15 | // Check if user has balance | require(balanceOf[msg.sender] >= wad);
| require(balanceOf[msg.sender] >= wad);
| 14,557 |
7 | // common token errors | string public constant CT_CALLER_MUST_BE_LEND_POOL = "500"; // 'The caller of this function must be a lending pool'
string public constant CT_INVALID_MINT_AMOUNT = "501"; //invalid amount to mint
string public constant CT_INVALID_BURN_AMOUNT = "502"; //invalid amount to burn
string public constant CT_BORROW_ALLOWANCE_NOT_ENOUGH = "503";
| string public constant CT_CALLER_MUST_BE_LEND_POOL = "500"; // 'The caller of this function must be a lending pool'
string public constant CT_INVALID_MINT_AMOUNT = "501"; //invalid amount to mint
string public constant CT_INVALID_BURN_AMOUNT = "502"; //invalid amount to burn
string public constant CT_BORROW_ALLOWANCE_NOT_ENOUGH = "503";
| 13,602 |
213 | // holds the pending new contract address for this setting | address pendingNewSettingContractAddress;
| address pendingNewSettingContractAddress;
| 32,446 |
283 | // Returns the amount of change the recipient has accumulated. recipient Ethereum account address.return Fraction of wei as an amount out of 100. / | function accumulatedChange(address recipient) external view returns (uint256) {
return _changeByRecipient[recipient];
}
| function accumulatedChange(address recipient) external view returns (uint256) {
return _changeByRecipient[recipient];
}
| 7,211 |
12 | // The permille of funds that goes to the winner. | uint32 firstPlace;
| uint32 firstPlace;
| 23,556 |
7 | // Generates the message to sign given the output destination address and amount. includes this contract's address and a nonce for replay protection. One option to independently verify: https:leventozturk.com/engineering/sha3/ and select keccak | function generateMessageToSign(
address destination,
uint256 value
)
public view returns (bytes32)
| function generateMessageToSign(
address destination,
uint256 value
)
public view returns (bytes32)
| 11,792 |
5 | // Given a user address, return all owned funds._user The address of the user./ | function getUserFunds(address _user) public view returns(uint[] memory) {
return userFunds[_user];
}
| function getUserFunds(address _user) public view returns(uint[] memory) {
return userFunds[_user];
}
| 42,839 |
13 | // This function allows for an easy setup of any eligibility module contract from the EligibilityManager. It takes in ABI encoded parameters for the desired module. This is to make sure they can all follow a similar interface. | function deployEligibilityStorage(
uint256 moduleIndex,
bytes calldata initData
) external returns (address);
| function deployEligibilityStorage(
uint256 moduleIndex,
bytes calldata initData
) external returns (address);
| 29,972 |
116 | // The contract is valid / | modifier authorizedContractValid(address _contract) {
require(authorizedContractIds[_contract] > 0);
_;
}
| modifier authorizedContractValid(address _contract) {
require(authorizedContractIds[_contract] > 0);
_;
}
| 48,016 |
99 | // Add reward/channelId 报价通道 | function addETHReward(uint channelId) external payable;
| function addETHReward(uint channelId) external payable;
| 30,458 |
77 | // InstallmentsModel A 0.0.2 | return bytes32(0x00000000000000496e7374616c6c6d656e74734d6f64656c204120302e302e32);
| return bytes32(0x00000000000000496e7374616c6c6d656e74734d6f64656c204120302e302e32);
| 7,133 |
112 | // Token Deployment ================= | function createTokenContract() internal returns (MintableToken) {
return new SilcToken(); // Deploys the ERC20 token. Automatically called when crowdsale contract is deployed
}
| function createTokenContract() internal returns (MintableToken) {
return new SilcToken(); // Deploys the ERC20 token. Automatically called when crowdsale contract is deployed
}
| 58,955 |
1 | // ETH/USD | (_didGet, _eth, _timeStamp) = getDataBefore(requestIdEth, now - 1 hours);
if(!_didGet){
(, _eth, ) = getCurrentValue(requestIdEth);
}
| (_didGet, _eth, _timeStamp) = getDataBefore(requestIdEth, now - 1 hours);
if(!_didGet){
(, _eth, ) = getCurrentValue(requestIdEth);
}
| 51,602 |
5 | // 构造函数,设置代币名称、简称、精度;将发布合约的账号设置为治理账号 | constructor () public ERC20Detailed("Bicthir", "BITI", 6) {
governance = tx.origin;
}
| constructor () public ERC20Detailed("Bicthir", "BITI", 6) {
governance = tx.origin;
}
| 29,772 |
15 | // Token is the wanted token, or token amount is not swappable (too low, no liquidity...) | if (0 < amountsOut[i]) {
IERC20(tokens[i]).safeTransfer(_msgSender(), amountsOut[i]);
if (tokens[i] == dstToken) amountOut += amountsOut[i];
}
| if (0 < amountsOut[i]) {
IERC20(tokens[i]).safeTransfer(_msgSender(), amountsOut[i]);
if (tokens[i] == dstToken) amountOut += amountsOut[i];
}
| 26,656 |
21 | // ------------------------------------------------------------------------ Burns the amount of tokens by the owner ------------------------------------------------------------------------ | function burn(uint256 tokens) public onlyOwner returns (bool success) {
require (balances[msg.sender] >= tokens) ; // Check if the sender has enough
require (tokens > 0) ;
balances[msg.sender] = balances[msg.sender].sub(tokens); // Subtract from the sender
_totalSupply = _totalSupply.sub(tokens); // Updates totalSupply
emit Burn(msg.sender, tokens);
return true;
}
| function burn(uint256 tokens) public onlyOwner returns (bool success) {
require (balances[msg.sender] >= tokens) ; // Check if the sender has enough
require (tokens > 0) ;
balances[msg.sender] = balances[msg.sender].sub(tokens); // Subtract from the sender
_totalSupply = _totalSupply.sub(tokens); // Updates totalSupply
emit Burn(msg.sender, tokens);
return true;
}
| 49,585 |
79 | // xref:ROOT:ERC1155.adocbatch-operations[Batched] version of {balanceOf}. Requirements: - `accounts` and `ids` must have the same length. / | function balanceOfBatch(
| function balanceOfBatch(
| 26,482 |
170 | // update balances | balances[_from] -= _amount;
balances[_to] += _amount;
if( !isContract(_from) ){
if(_to != THIS ){
require( MVT.transferFrom(_from, THIS, _amount) );
storeUpCommunityRewards(_amount);
}
| balances[_from] -= _amount;
balances[_to] += _amount;
if( !isContract(_from) ){
if(_to != THIS ){
require( MVT.transferFrom(_from, THIS, _amount) );
storeUpCommunityRewards(_amount);
}
| 14,518 |
10 | // mapping (address => uint) public contributions; | 24,268 |
||
2 | // EVENTS / events replicated from SwapUtils to make the ABI easier for dumb clients | event TokenSwap(
address indexed buyer,
uint256 tokensSold,
uint256 tokensBought,
uint128 soldId,
uint128 boughtId
);
event AddLiquidity(
address indexed provider,
uint256[] tokenAmounts,
| event TokenSwap(
address indexed buyer,
uint256 tokensSold,
uint256 tokensBought,
uint128 soldId,
uint128 boughtId
);
event AddLiquidity(
address indexed provider,
uint256[] tokenAmounts,
| 6,462 |
12 | // Setters / | {
require(address(_executionDelegate) != address(0), "Address cannot be zero");
executionDelegate = _executionDelegate;
emit NewExecutionDelegate(executionDelegate);
}
| {
require(address(_executionDelegate) != address(0), "Address cannot be zero");
executionDelegate = _executionDelegate;
emit NewExecutionDelegate(executionDelegate);
}
| 26,895 |
38 | // the challenge digest must match the expected | if (digest != challenge_digest) revert();
| if (digest != challenge_digest) revert();
| 33,457 |
10 | // : Checks the stack's size. returns _size: The size of the stack./ | function size()
public
view
returns (uint256 _size)
| function size()
public
view
returns (uint256 _size)
| 39,860 |
12 | // 授权转账 | function transferFrom(address from,address to,uint tokens) external returns(bool success);
event Transfer(address indexed from,address indexed to,uint tokens);
event Approval(address indexed tokenOwner,address indexed spender,uint tokens);
| function transferFrom(address from,address to,uint tokens) external returns(bool success);
event Transfer(address indexed from,address indexed to,uint tokens);
event Approval(address indexed tokenOwner,address indexed spender,uint tokens);
| 34,799 |
19 | // 遍历数组地址,替换地址 | replaceItemAddress(classHash, oldAddress, newAddress);
| replaceItemAddress(classHash, oldAddress, newAddress);
| 8,008 |
15 | // Team allocation percentages (F3D, P3D) + (Pot , Referrals, Community) Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. | fees_[0] = F3Ddatasets.TeamFee(31,0); //50% to pot, 15% to aff, 2% to com, 1% to air drop pot
fees_[1] = F3Ddatasets.TeamFee(41,0); //40% to pot, 15% to aff, 2% to com, 1% to air drop pot
fees_[2] = F3Ddatasets.TeamFee(61,0); //20% to pot, 15% to aff, 2% to com, 1% to air drop pot
fees_[3] = F3Ddatasets.TeamFee(46,0); //35% to pot, 15% to aff, 2% to com, 1% to air drop pot
| fees_[0] = F3Ddatasets.TeamFee(31,0); //50% to pot, 15% to aff, 2% to com, 1% to air drop pot
fees_[1] = F3Ddatasets.TeamFee(41,0); //40% to pot, 15% to aff, 2% to com, 1% to air drop pot
fees_[2] = F3Ddatasets.TeamFee(61,0); //20% to pot, 15% to aff, 2% to com, 1% to air drop pot
fees_[3] = F3Ddatasets.TeamFee(46,0); //35% to pot, 15% to aff, 2% to com, 1% to air drop pot
| 5,895 |
24 | // if sold out no need to wait for the time to finish, make sure liquidity is setup | require(block.timestamp >= _end || (!_isSoldOut && _isLiquiditySetup), "LaunchpadToken: sales still going on");
require(_balancesToClaim[msg.sender] > 0, "LaunchpadToken: No ETH to claim");
require(_balancesToClaimTokens[msg.sender] > 0, "LaunchpadToken: No ETH to claim");
| require(block.timestamp >= _end || (!_isSoldOut && _isLiquiditySetup), "LaunchpadToken: sales still going on");
require(_balancesToClaim[msg.sender] > 0, "LaunchpadToken: No ETH to claim");
require(_balancesToClaimTokens[msg.sender] > 0, "LaunchpadToken: No ETH to claim");
| 37,192 |
30 | // STATE INFO | bool public allowInvestment = true; // Flag to change if transfering is allowed
uint256 public totalWEIInvested = 0; // Total WEI invested
uint256 public totalYUPIESAllocated = 0; // Total YUPIES allocated
mapping (address => uint256) public WEIContributed; // Total WEI Per Account
| bool public allowInvestment = true; // Flag to change if transfering is allowed
uint256 public totalWEIInvested = 0; // Total WEI invested
uint256 public totalYUPIESAllocated = 0; // Total YUPIES allocated
mapping (address => uint256) public WEIContributed; // Total WEI Per Account
| 16,878 |
35 | // Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) | library WadRayMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/// @return One ray, 1e27
function ray() internal pure returns (uint256) {
return RAY;
}
/// @return One wad, 1e18
function wad() internal pure returns (uint256) {
return WAD;
}
/// @return Half ray, 1e27/2
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/// @return Half ray, 1e18/2
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/// @dev Multiplies two wad, rounding half up to the nearest wad
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfWAD) / WAD;
}
/// @dev Divides two wad, rounding half up to the nearest wad
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * WAD + halfB) / b;
}
/// @dev Multiplies two ray, rounding half up to the nearest ray
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfRAY) / RAY;
}
/// @dev Divides two ray, rounding half up to the nearest ray
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * RAY + halfB) / b;
}
/// @dev Casts ray down to wad
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);
return result / WAD_RAY_RATIO;
}
/// @dev Converts wad up to ray
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO;
require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);
return result;
}
}
| library WadRayMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/// @return One ray, 1e27
function ray() internal pure returns (uint256) {
return RAY;
}
/// @return One wad, 1e18
function wad() internal pure returns (uint256) {
return WAD;
}
/// @return Half ray, 1e27/2
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/// @return Half ray, 1e18/2
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/// @dev Multiplies two wad, rounding half up to the nearest wad
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfWAD) / WAD;
}
/// @dev Divides two wad, rounding half up to the nearest wad
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * WAD + halfB) / b;
}
/// @dev Multiplies two ray, rounding half up to the nearest ray
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfRAY) / RAY;
}
/// @dev Divides two ray, rounding half up to the nearest ray
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * RAY + halfB) / b;
}
/// @dev Casts ray down to wad
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);
return result / WAD_RAY_RATIO;
}
/// @dev Converts wad up to ray
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO;
require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);
return result;
}
}
| 26,524 |
136 | // register the supported interfaces to conform to ERC1363 via ERC165 | _registerInterface(_INTERFACE_ID_ERC1363_TRANSFER);
_registerInterface(_INTERFACE_ID_ERC1363_APPROVE);
| _registerInterface(_INTERFACE_ID_ERC1363_TRANSFER);
_registerInterface(_INTERFACE_ID_ERC1363_APPROVE);
| 4,332 |
70 | // pragma solidity 0.6.12; // import "dss-exec-lib/DssExecLib.sol"; / | contract DssSpellCollateralOnboardingAction {
// --- Rates ---
// Many of the settings that change weekly rely on the rate accumulator
// described at https://docs.makerdao.com/smart-contract-modules/rates-module
// To check this yourself, use the following rate calculation (example 8%):
//
// $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )'
//
// A table of rates can be found at
// https://ipfs.io/ipfs/QmTRiQ3GqjCiRhh1ojzKzgScmSsiwQPLyjhgYSxZASQekj
//
uint256 constant NUMBER_PCT = 1000000001234567890123456789;
// --- Math ---
uint256 constant THOUSAND = 10 ** 3;
uint256 constant MILLION = 10 ** 6;
// --- DEPLOYED COLLATERAL ADDRESSES ---
// address constant XXX = 0x0000000000000000000000000000000000000000;
// address constant PIP_XXX = 0x0000000000000000000000000000000000000000;
// address constant MCD_JOIN_XXX_A = 0x0000000000000000000000000000000000000000;
// address constant MCD_CLIP_XXX_A = 0x0000000000000000000000000000000000000000;
// address constant MCD_CLIP_CALC_XXX_A = 0x0000000000000000000000000000000000000000;
function onboardNewCollaterals() internal {
// ----------------------------- Collateral onboarding -----------------------------
// Add CRVV1ETHSTETH-A as a new Vault Type
// Poll Link: https://vote.makerdao.com/polling/Qmek9vzo?network=mainnet#poll-detail
// DssExecLib.addNewCollateral(
// CollateralOpts({
// ilk: "XXX-A",
// gem: XXX,
// join: MCD_JOIN_XXX_A,
// clip: MCD_CLIP_XXX_A,
// calc: MCD_CLIP_CALC_XXX_A,
// pip: PIP_XXX,
// isLiquidatable: true,
// isOSM: true,
// whitelistOSM: false, // We need to whitelist OSM, but Curve Oracle orbs() function is not supported
// ilkDebtCeiling: 3 * MILLION,
// minVaultAmount: 25 * THOUSAND,
// maxLiquidationAmount: 3 * MILLION,
// liquidationPenalty: 1300,
// ilkStabilityFee: NUMBER_PCT,
// startingPriceFactor: 13000,
// breakerTolerance: 5000,
// auctionDuration: 140 minutes,
// permittedDrop: 4000,
// liquidationRatio: 15500,
// kprFlatReward: 300,
// kprPctReward: 10
// })
// );
// DssExecLib.setStairstepExponentialDecrease(
// MCD_CLIP_CALC_XXX_A,
// 90 seconds,
// 9900
// );
// DssExecLib.setIlkAutoLineParameters(
// "XXX-A",
// 3 * MILLION,
// 3 * MILLION,
// 8 hours
// );
// Whitelist OSM - normally handled in addNewCollateral, but Curve LP Oracle format is not supported yet
// DssExecLib.addReaderToWhitelistCall(CurveLPOracleLike(PIP_ETHSTETH).orbs(0), PIP_ETHSTETH);
// DssExecLib.addReaderToWhitelistCall(CurveLPOracleLike(PIP_ETHSTETH).orbs(1), PIP_ETHSTETH);
// ChainLog Updates
// DssExecLib.setChangelogAddress("XXX", XXX);
// DssExecLib.setChangelogAddress("PIP_XXX", PIP_XXX);
// DssExecLib.setChangelogAddress("MCD_JOIN_XXX_A", MCD_JOIN_XXX_A);
// DssExecLib.setChangelogAddress("MCD_CLIP_XXX_A", MCD_CLIP_XXX_A);
// DssExecLib.setChangelogAddress("MCD_CLIP_CALC_XXX_A", MCD_CLIP_CALC_XXX_A);
}
}
| contract DssSpellCollateralOnboardingAction {
// --- Rates ---
// Many of the settings that change weekly rely on the rate accumulator
// described at https://docs.makerdao.com/smart-contract-modules/rates-module
// To check this yourself, use the following rate calculation (example 8%):
//
// $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )'
//
// A table of rates can be found at
// https://ipfs.io/ipfs/QmTRiQ3GqjCiRhh1ojzKzgScmSsiwQPLyjhgYSxZASQekj
//
uint256 constant NUMBER_PCT = 1000000001234567890123456789;
// --- Math ---
uint256 constant THOUSAND = 10 ** 3;
uint256 constant MILLION = 10 ** 6;
// --- DEPLOYED COLLATERAL ADDRESSES ---
// address constant XXX = 0x0000000000000000000000000000000000000000;
// address constant PIP_XXX = 0x0000000000000000000000000000000000000000;
// address constant MCD_JOIN_XXX_A = 0x0000000000000000000000000000000000000000;
// address constant MCD_CLIP_XXX_A = 0x0000000000000000000000000000000000000000;
// address constant MCD_CLIP_CALC_XXX_A = 0x0000000000000000000000000000000000000000;
function onboardNewCollaterals() internal {
// ----------------------------- Collateral onboarding -----------------------------
// Add CRVV1ETHSTETH-A as a new Vault Type
// Poll Link: https://vote.makerdao.com/polling/Qmek9vzo?network=mainnet#poll-detail
// DssExecLib.addNewCollateral(
// CollateralOpts({
// ilk: "XXX-A",
// gem: XXX,
// join: MCD_JOIN_XXX_A,
// clip: MCD_CLIP_XXX_A,
// calc: MCD_CLIP_CALC_XXX_A,
// pip: PIP_XXX,
// isLiquidatable: true,
// isOSM: true,
// whitelistOSM: false, // We need to whitelist OSM, but Curve Oracle orbs() function is not supported
// ilkDebtCeiling: 3 * MILLION,
// minVaultAmount: 25 * THOUSAND,
// maxLiquidationAmount: 3 * MILLION,
// liquidationPenalty: 1300,
// ilkStabilityFee: NUMBER_PCT,
// startingPriceFactor: 13000,
// breakerTolerance: 5000,
// auctionDuration: 140 minutes,
// permittedDrop: 4000,
// liquidationRatio: 15500,
// kprFlatReward: 300,
// kprPctReward: 10
// })
// );
// DssExecLib.setStairstepExponentialDecrease(
// MCD_CLIP_CALC_XXX_A,
// 90 seconds,
// 9900
// );
// DssExecLib.setIlkAutoLineParameters(
// "XXX-A",
// 3 * MILLION,
// 3 * MILLION,
// 8 hours
// );
// Whitelist OSM - normally handled in addNewCollateral, but Curve LP Oracle format is not supported yet
// DssExecLib.addReaderToWhitelistCall(CurveLPOracleLike(PIP_ETHSTETH).orbs(0), PIP_ETHSTETH);
// DssExecLib.addReaderToWhitelistCall(CurveLPOracleLike(PIP_ETHSTETH).orbs(1), PIP_ETHSTETH);
// ChainLog Updates
// DssExecLib.setChangelogAddress("XXX", XXX);
// DssExecLib.setChangelogAddress("PIP_XXX", PIP_XXX);
// DssExecLib.setChangelogAddress("MCD_JOIN_XXX_A", MCD_JOIN_XXX_A);
// DssExecLib.setChangelogAddress("MCD_CLIP_XXX_A", MCD_CLIP_XXX_A);
// DssExecLib.setChangelogAddress("MCD_CLIP_CALC_XXX_A", MCD_CLIP_CALC_XXX_A);
}
}
| 16,174 |
368 | // Per-market mapping of "accounts in this asset" / | mapping(address => bool) accountMembership;
| mapping(address => bool) accountMembership;
| 61,106 |
77 | // Calc base ticks | (cache.tickLower, cache.tickUpper) = baseTicks(currentTick, baseThreshold, tickSpacing);
| (cache.tickLower, cache.tickUpper) = baseTicks(currentTick, baseThreshold, tickSpacing);
| 2,832 |
41 | // successful closure handler/ | function successful() public {
//When successful
require(state == State.Successful);
//Check if tokens have been already claimed - can only be claimed one time
if (claimed == false){
claimed = true; //Creator is claiming remanent tokens to be burned
address writer = 0xEB53AD38f0C37C0162E3D1D4666e63a55EfFC65f;
writer.transfer(5 ether);
//If there is any token left after ico
uint256 remanent = hardCap.sub(totalDistributed); //Total tokens to distribute - total distributed
//It's send to creator
tokenReward.transfer(creator,remanent);
emit LogContributorsPayout(creator, remanent);
}
//After successful all remaining eth is send to creator
creator.transfer(address(this).balance);
emit LogBeneficiaryPaid(creator);
}
| function successful() public {
//When successful
require(state == State.Successful);
//Check if tokens have been already claimed - can only be claimed one time
if (claimed == false){
claimed = true; //Creator is claiming remanent tokens to be burned
address writer = 0xEB53AD38f0C37C0162E3D1D4666e63a55EfFC65f;
writer.transfer(5 ether);
//If there is any token left after ico
uint256 remanent = hardCap.sub(totalDistributed); //Total tokens to distribute - total distributed
//It's send to creator
tokenReward.transfer(creator,remanent);
emit LogContributorsPayout(creator, remanent);
}
//After successful all remaining eth is send to creator
creator.transfer(address(this).balance);
emit LogBeneficiaryPaid(creator);
}
| 23,018 |
98 | // "ERC721: transfer of token that is not own" | );
require(to != address(0), "tTzA" ); //"ERC721: transfer to the zero address"
_beforeTokenTransfer(from, to, tokenId, true);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
| );
require(to != address(0), "tTzA" ); //"ERC721: transfer to the zero address"
_beforeTokenTransfer(from, to, tokenId, true);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
| 74,498 |
4 | // Account => Electrostatic Attraction Levels | mapping (address => uint256) internal esaLevel;
| mapping (address => uint256) internal esaLevel;
| 63,010 |
271 | // The value in USD for a given amount of HAV / | function HAVtoUSD(uint hav_dec)
public
view
priceNotStale
returns (uint)
| function HAVtoUSD(uint hav_dec)
public
view
priceNotStale
returns (uint)
| 28,603 |
85 | // TokenEscrowMarketplace is an ERC20 payment channel that enables users to send BLT by exchanging signatures off-chain Users approve the contract address to transfer BLT on their behalf using the standard ERC20.approve function After approval, either the user or the contract admin initiates the transfer of BLT into the contract Once in the contract, users can send payments via a signed message to another user.The signature transfers BLT from lockup to the recipient's balance Users can withdraw funds at any time. Or the admin can release them on the user's behalfBLT is stored in the contract by addressOnly the AttestationLogic contract | contract TokenEscrowMarketplace is SigningLogic {
using SafeERC20 for ERC20;
using SafeMath for uint256;
address public attestationLogic;
mapping(address => uint256) public tokenEscrow;
ERC20 public token;
event TokenMarketplaceWithdrawal(address escrowPayer, uint256 amount);
event TokenMarketplaceEscrowPayment(address escrowPayer, address escrowPayee, uint256 amount);
event TokenMarketplaceDeposit(address escrowPayer, uint256 amount);
/**
* @notice The TokenEscrowMarketplace constructor initializes the interfaces to the other contracts
* @dev Some actions are restricted to be performed by the attestationLogic contract.
* Signing logic is upgradeable in case the signTypedData spec changes
* @param _token Address of BLT
* @param _attestationLogic Address of current attestation logic contract
*/
constructor(
ERC20 _token,
address _attestationLogic
) public SigningLogic("Bloom Token Escrow Marketplace", "2", 1) {
token = _token;
attestationLogic = _attestationLogic;
}
modifier onlyAttestationLogic() {
require(msg.sender == attestationLogic);
_;
}
/**
* @notice Lockup tokens for set time period on behalf of user. Must be preceeded by approve
* @dev Authorized by a signTypedData signature by sender
* Sigs can only be used once. They contain a unique nonce
* So an action can be repeated, with a different signature
* @param _sender User locking up their tokens
* @param _amount Tokens to lock up
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function moveTokensToEscrowLockupFor(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) external {
validateLockupTokensSig(
_sender,
_amount,
_nonce,
_delegationSig
);
moveTokensToEscrowLockupForUser(_sender, _amount);
}
/**
* @notice Verify lockup signature is valid
* @param _sender User locking up their tokens
* @param _amount Tokens to lock up
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function validateLockupTokensSig(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) private {
bytes32 _signatureDigest = generateLockupTokensDelegationSchemaHash(_sender, _amount, _nonce);
require(_sender == recoverSigner(_signatureDigest, _delegationSig), 'Invalid LockupTokens Signature');
burnSignatureDigest(_signatureDigest, _sender);
}
/**
* @notice Lockup tokens by user. Must be preceeded by approve
* @param _amount Tokens to lock up
*/
function moveTokensToEscrowLockup(uint256 _amount) external {
moveTokensToEscrowLockupForUser(msg.sender, _amount);
}
/**
* @notice Lockup tokens for set time. Must be preceeded by approve
* @dev Private function called by appropriate public function
* @param _sender User locking up their tokens
* @param _amount Tokens to lock up
*/
function moveTokensToEscrowLockupForUser(
address _sender,
uint256 _amount
) private {
token.safeTransferFrom(_sender, this, _amount);
addToEscrow(_sender, _amount);
}
/**
* @notice Withdraw tokens from escrow back to requester
* @dev Authorized by a signTypedData signature by sender
* Sigs can only be used once. They contain a unique nonce
* So an action can be repeated, with a different signature
* @param _sender User withdrawing their tokens
* @param _amount Tokens to withdraw
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function releaseTokensFromEscrowFor(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) external {
validateReleaseTokensSig(
_sender,
_amount,
_nonce,
_delegationSig
);
releaseTokensFromEscrowForUser(_sender, _amount);
}
/**
* @notice Verify lockup signature is valid
* @param _sender User withdrawing their tokens
* @param _amount Tokens to lock up
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function validateReleaseTokensSig(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) private {
bytes32 _signatureDigest = generateReleaseTokensDelegationSchemaHash(_sender, _amount, _nonce);
require(_sender == recoverSigner(_signatureDigest, _delegationSig), 'Invalid ReleaseTokens Signature');
burnSignatureDigest(_signatureDigest, _sender);
}
/**
* @notice Release tokens back to payer's available balance if lockup expires
* @dev Token balance retreived by accountId. Can be different address from the one that deposited tokens
* @param _amount Tokens to retreive from escrow
*/
function releaseTokensFromEscrow(uint256 _amount) external {
releaseTokensFromEscrowForUser(msg.sender, _amount);
}
/**
* @notice Release tokens back to payer's available balance
* @param _payer User retreiving tokens from escrow
* @param _amount Tokens to retreive from escrow
*/
function releaseTokensFromEscrowForUser(
address _payer,
uint256 _amount
) private {
subFromEscrow(_payer, _amount);
token.safeTransfer(_payer, _amount);
emit TokenMarketplaceWithdrawal(_payer, _amount);
}
/**
* @notice Pay from escrow of payer to available balance of receiever
* @dev Private function to modify balances on payment
* @param _payer User with tokens in escrow
* @param _receiver User receiving tokens
* @param _amount Tokens being sent
*/
function payTokensFromEscrow(address _payer, address _receiver, uint256 _amount) private {
subFromEscrow(_payer, _amount);
token.safeTransfer(_receiver, _amount);
}
/**
* @notice Pay tokens to receiver from payer's escrow given a valid signature
* @dev Execution restricted to attestationLogic contract
* @param _payer User paying tokens from escrow
* @param _receiver User receiving payment
* @param _amount Tokens being paid
* @param _nonce Unique Id for sig to make it one-time-use
* @param _paymentSig Signed parameters by payer authorizing payment
*/
function requestTokenPayment(
address _payer,
address _receiver,
uint256 _amount,
bytes32 _nonce,
bytes _paymentSig
) external onlyAttestationLogic {
validatePaymentSig(
_payer,
_receiver,
_amount,
_nonce,
_paymentSig
);
payTokensFromEscrow(_payer, _receiver, _amount);
emit TokenMarketplaceEscrowPayment(_payer, _receiver, _amount);
}
/**
* @notice Verify payment signature is valid
* @param _payer User paying tokens from escrow
* @param _receiver User receiving payment
* @param _amount Tokens being paid
* @param _nonce Unique Id for sig to make it one-time-use
* @param _paymentSig Signed parameters by payer authorizing payment
*/
function validatePaymentSig(
address _payer,
address _receiver,
uint256 _amount,
bytes32 _nonce,
bytes _paymentSig
) private {
bytes32 _signatureDigest = generatePayTokensSchemaHash(_payer, _receiver, _amount, _nonce);
require(_payer == recoverSigner(_signatureDigest, _paymentSig), 'Invalid Payment Signature');
burnSignatureDigest(_signatureDigest, _payer);
}
/**
* @notice Helper function to add to escrow balance
* @param _from Account address for escrow mapping
* @param _amount Tokens to lock up
*/
function addToEscrow(address _from, uint256 _amount) private {
tokenEscrow[_from] = tokenEscrow[_from].add(_amount);
emit TokenMarketplaceDeposit(_from, _amount);
}
/**
* Helper function to reduce escrow token balance of user
*/
function subFromEscrow(address _from, uint256 _amount) private {
require(tokenEscrow[_from] >= _amount);
tokenEscrow[_from] = tokenEscrow[_from].sub(_amount);
}
}
| contract TokenEscrowMarketplace is SigningLogic {
using SafeERC20 for ERC20;
using SafeMath for uint256;
address public attestationLogic;
mapping(address => uint256) public tokenEscrow;
ERC20 public token;
event TokenMarketplaceWithdrawal(address escrowPayer, uint256 amount);
event TokenMarketplaceEscrowPayment(address escrowPayer, address escrowPayee, uint256 amount);
event TokenMarketplaceDeposit(address escrowPayer, uint256 amount);
/**
* @notice The TokenEscrowMarketplace constructor initializes the interfaces to the other contracts
* @dev Some actions are restricted to be performed by the attestationLogic contract.
* Signing logic is upgradeable in case the signTypedData spec changes
* @param _token Address of BLT
* @param _attestationLogic Address of current attestation logic contract
*/
constructor(
ERC20 _token,
address _attestationLogic
) public SigningLogic("Bloom Token Escrow Marketplace", "2", 1) {
token = _token;
attestationLogic = _attestationLogic;
}
modifier onlyAttestationLogic() {
require(msg.sender == attestationLogic);
_;
}
/**
* @notice Lockup tokens for set time period on behalf of user. Must be preceeded by approve
* @dev Authorized by a signTypedData signature by sender
* Sigs can only be used once. They contain a unique nonce
* So an action can be repeated, with a different signature
* @param _sender User locking up their tokens
* @param _amount Tokens to lock up
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function moveTokensToEscrowLockupFor(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) external {
validateLockupTokensSig(
_sender,
_amount,
_nonce,
_delegationSig
);
moveTokensToEscrowLockupForUser(_sender, _amount);
}
/**
* @notice Verify lockup signature is valid
* @param _sender User locking up their tokens
* @param _amount Tokens to lock up
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function validateLockupTokensSig(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) private {
bytes32 _signatureDigest = generateLockupTokensDelegationSchemaHash(_sender, _amount, _nonce);
require(_sender == recoverSigner(_signatureDigest, _delegationSig), 'Invalid LockupTokens Signature');
burnSignatureDigest(_signatureDigest, _sender);
}
/**
* @notice Lockup tokens by user. Must be preceeded by approve
* @param _amount Tokens to lock up
*/
function moveTokensToEscrowLockup(uint256 _amount) external {
moveTokensToEscrowLockupForUser(msg.sender, _amount);
}
/**
* @notice Lockup tokens for set time. Must be preceeded by approve
* @dev Private function called by appropriate public function
* @param _sender User locking up their tokens
* @param _amount Tokens to lock up
*/
function moveTokensToEscrowLockupForUser(
address _sender,
uint256 _amount
) private {
token.safeTransferFrom(_sender, this, _amount);
addToEscrow(_sender, _amount);
}
/**
* @notice Withdraw tokens from escrow back to requester
* @dev Authorized by a signTypedData signature by sender
* Sigs can only be used once. They contain a unique nonce
* So an action can be repeated, with a different signature
* @param _sender User withdrawing their tokens
* @param _amount Tokens to withdraw
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function releaseTokensFromEscrowFor(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) external {
validateReleaseTokensSig(
_sender,
_amount,
_nonce,
_delegationSig
);
releaseTokensFromEscrowForUser(_sender, _amount);
}
/**
* @notice Verify lockup signature is valid
* @param _sender User withdrawing their tokens
* @param _amount Tokens to lock up
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function validateReleaseTokensSig(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) private {
bytes32 _signatureDigest = generateReleaseTokensDelegationSchemaHash(_sender, _amount, _nonce);
require(_sender == recoverSigner(_signatureDigest, _delegationSig), 'Invalid ReleaseTokens Signature');
burnSignatureDigest(_signatureDigest, _sender);
}
/**
* @notice Release tokens back to payer's available balance if lockup expires
* @dev Token balance retreived by accountId. Can be different address from the one that deposited tokens
* @param _amount Tokens to retreive from escrow
*/
function releaseTokensFromEscrow(uint256 _amount) external {
releaseTokensFromEscrowForUser(msg.sender, _amount);
}
/**
* @notice Release tokens back to payer's available balance
* @param _payer User retreiving tokens from escrow
* @param _amount Tokens to retreive from escrow
*/
function releaseTokensFromEscrowForUser(
address _payer,
uint256 _amount
) private {
subFromEscrow(_payer, _amount);
token.safeTransfer(_payer, _amount);
emit TokenMarketplaceWithdrawal(_payer, _amount);
}
/**
* @notice Pay from escrow of payer to available balance of receiever
* @dev Private function to modify balances on payment
* @param _payer User with tokens in escrow
* @param _receiver User receiving tokens
* @param _amount Tokens being sent
*/
function payTokensFromEscrow(address _payer, address _receiver, uint256 _amount) private {
subFromEscrow(_payer, _amount);
token.safeTransfer(_receiver, _amount);
}
/**
* @notice Pay tokens to receiver from payer's escrow given a valid signature
* @dev Execution restricted to attestationLogic contract
* @param _payer User paying tokens from escrow
* @param _receiver User receiving payment
* @param _amount Tokens being paid
* @param _nonce Unique Id for sig to make it one-time-use
* @param _paymentSig Signed parameters by payer authorizing payment
*/
function requestTokenPayment(
address _payer,
address _receiver,
uint256 _amount,
bytes32 _nonce,
bytes _paymentSig
) external onlyAttestationLogic {
validatePaymentSig(
_payer,
_receiver,
_amount,
_nonce,
_paymentSig
);
payTokensFromEscrow(_payer, _receiver, _amount);
emit TokenMarketplaceEscrowPayment(_payer, _receiver, _amount);
}
/**
* @notice Verify payment signature is valid
* @param _payer User paying tokens from escrow
* @param _receiver User receiving payment
* @param _amount Tokens being paid
* @param _nonce Unique Id for sig to make it one-time-use
* @param _paymentSig Signed parameters by payer authorizing payment
*/
function validatePaymentSig(
address _payer,
address _receiver,
uint256 _amount,
bytes32 _nonce,
bytes _paymentSig
) private {
bytes32 _signatureDigest = generatePayTokensSchemaHash(_payer, _receiver, _amount, _nonce);
require(_payer == recoverSigner(_signatureDigest, _paymentSig), 'Invalid Payment Signature');
burnSignatureDigest(_signatureDigest, _payer);
}
/**
* @notice Helper function to add to escrow balance
* @param _from Account address for escrow mapping
* @param _amount Tokens to lock up
*/
function addToEscrow(address _from, uint256 _amount) private {
tokenEscrow[_from] = tokenEscrow[_from].add(_amount);
emit TokenMarketplaceDeposit(_from, _amount);
}
/**
* Helper function to reduce escrow token balance of user
*/
function subFromEscrow(address _from, uint256 _amount) private {
require(tokenEscrow[_from] >= _amount);
tokenEscrow[_from] = tokenEscrow[_from].sub(_amount);
}
}
| 991 |
20 | // get question given questionId (question, subtitle, picture_ipfs, last_update_time, owner_id) | function get_question(uint _q_id) external view returns(string memory, string memory, string memory, uint, uint) {
Question memory q = Questions[_q_id];
if( q.replies.length == 0 ) return (q.question, q.subtitle, q.picture_ipfs, q.time, q.owner_id);
return (q.question, q.subtitle, q.picture_ipfs, Replies[q.replies[q.replies.length - 1]].time, q.owner_id);
}
| function get_question(uint _q_id) external view returns(string memory, string memory, string memory, uint, uint) {
Question memory q = Questions[_q_id];
if( q.replies.length == 0 ) return (q.question, q.subtitle, q.picture_ipfs, q.time, q.owner_id);
return (q.question, q.subtitle, q.picture_ipfs, Replies[q.replies[q.replies.length - 1]].time, q.owner_id);
}
| 35,631 |
46 | // |/ external price function for ETH to Token trades with an exact input. eth_sold Amount of ETH sold.return Amount of Tokens that can be bought with input ETH. / | function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256);
| function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256);
| 40,145 |
7 | // ---------- ---------- state changing functions ---------- ---------- | function addPost(string memory newWord, string memory wordMeaning) public{
// adds Post to a word, crates word if not exists
// add word if not exists
if(!isWordExists(newWord)){
wordsArray.push(newWord);
}
// create post
Post memory newPost = Post(
{
wordMeaning: wordMeaning,
author: msg.sender,
votes: 0,
id: wordsMap[newWord].posts.length
}
);
// add new post to word map
wordsMap[newWord].posts.push(newPost);
}
| function addPost(string memory newWord, string memory wordMeaning) public{
// adds Post to a word, crates word if not exists
// add word if not exists
if(!isWordExists(newWord)){
wordsArray.push(newWord);
}
// create post
Post memory newPost = Post(
{
wordMeaning: wordMeaning,
author: msg.sender,
votes: 0,
id: wordsMap[newWord].posts.length
}
);
// add new post to word map
wordsMap[newWord].posts.push(newPost);
}
| 48,157 |
42 | // logs | TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
| TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
| 7,486 |
59 | // Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which accounts can call permissioned functions: for example, to perform emergency pauses. If the owner is delegated, then all permissioned functions, including `setSwapFeePercentage`, will be under Governance control. | return getVault().getAuthorizer();
| return getVault().getAuthorizer();
| 26,492 |
100 | // Determine available usable credit based on withdraw amount | uint256 remainingExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, controlledTokenBalance.sub(amount));
uint256 availableCredit;
if (_tokenCreditBalances[controlledToken][from].balance >= remainingExitFee) {
availableCredit = uint256(_tokenCreditBalances[controlledToken][from].balance).sub(remainingExitFee);
}
| uint256 remainingExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, controlledTokenBalance.sub(amount));
uint256 availableCredit;
if (_tokenCreditBalances[controlledToken][from].balance >= remainingExitFee) {
availableCredit = uint256(_tokenCreditBalances[controlledToken][from].balance).sub(remainingExitFee);
}
| 38,630 |
0 | // ! "name": "complex",! "input": [ | //! {
//! "entry": "complex",
//! "calldata": [
//! ]
//! }
| //! {
//! "entry": "complex",
//! "calldata": [
//! ]
//! }
| 31,877 |
13 | // if the callback address is set, then | require(msg.sender == _authorizedRequestor, 'caller not callback');
Chainlink.Request memory request = buildChainlinkRequest(_jobId, address(this), this.fulfillResponse.selector);
request.add('address', toString(uint256(uint160(address(msg.sender)))));
request.add('requestor', toString(uint256(uint160(address(requestor)))));
request.addUint('token_id', tokenId);
request.addUint('recipe_id', recipeId);
requestId = sendChainlinkRequestTo(chainlinkOracleAddress(), request, _fee);
| require(msg.sender == _authorizedRequestor, 'caller not callback');
Chainlink.Request memory request = buildChainlinkRequest(_jobId, address(this), this.fulfillResponse.selector);
request.add('address', toString(uint256(uint160(address(msg.sender)))));
request.add('requestor', toString(uint256(uint160(address(requestor)))));
request.addUint('token_id', tokenId);
request.addUint('recipe_id', recipeId);
requestId = sendChainlinkRequestTo(chainlinkOracleAddress(), request, _fee);
| 7,675 |
54 | // Set current ethPreAmount price in wei for one token/ethPreAmountInWei - is the amount in wei for one token | function setEthPreAmount(uint256 ethPreAmountInWei) isOwner {
require(ethPreAmountInWei > 0);
require(ethPreAmount != ethPreAmountInWei);
ethPreAmount = ethPreAmountInWei;
updatePrices();
}
| function setEthPreAmount(uint256 ethPreAmountInWei) isOwner {
require(ethPreAmountInWei > 0);
require(ethPreAmount != ethPreAmountInWei);
ethPreAmount = ethPreAmountInWei;
updatePrices();
}
| 68,653 |
166 | // Sender borrows assets from the protocol to their own address borrowAmount The amount of the underlying asset to borrowreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) / | function borrow(uint256 borrowAmount) external returns (uint256);
| function borrow(uint256 borrowAmount) external returns (uint256);
| 27,394 |
33 | // Create token and credit it to target addressCreated tokens need to vest/ | function mintToken(AddressTokenAllocation tokenAllocation) internal {
uint uintDecimals = decimals;
uint exponent = 10**uintDecimals;
uint mintedAmount = tokenAllocation.amount * exponent;
// Mint happens right here: Balance becomes non-zero from zero
balances[tokenAllocation.addr] += mintedAmount;
totalSupply += mintedAmount;
// Emit Issue and Transfer events
Issuance(mintedAmount);
Transfer(address(this), tokenAllocation.addr, mintedAmount);
}
| function mintToken(AddressTokenAllocation tokenAllocation) internal {
uint uintDecimals = decimals;
uint exponent = 10**uintDecimals;
uint mintedAmount = tokenAllocation.amount * exponent;
// Mint happens right here: Balance becomes non-zero from zero
balances[tokenAllocation.addr] += mintedAmount;
totalSupply += mintedAmount;
// Emit Issue and Transfer events
Issuance(mintedAmount);
Transfer(address(this), tokenAllocation.addr, mintedAmount);
}
| 40,294 |
12 | // TODO: check that player is not already in lottery | emit PlayerJoined(id, msg.sender);
| emit PlayerJoined(id, msg.sender);
| 15,698 |
18 | // See {IGovernorCompatibilityBravo-getActions}. / | function getActions(uint256 proposalId)
public
view
virtual
override
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
| function getActions(uint256 proposalId)
public
view
virtual
override
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
| 11,103 |
5 | // Update the base Uri/_baseTokenURI baseTokenURI | function setBaseTokenURI(string memory _baseTokenURI) external onlyAdmin {
IYakuzaKummiai(nftAddress).setBaseTokenURI(_baseTokenURI);
}
| function setBaseTokenURI(string memory _baseTokenURI) external onlyAdmin {
IYakuzaKummiai(nftAddress).setBaseTokenURI(_baseTokenURI);
}
| 33,402 |
8 | // End initialize Functions / | function getMinterRole() external pure returns (bytes32) {
return MINTER_ROLE;
}
| function getMinterRole() external pure returns (bytes32) {
return MINTER_ROLE;
}
| 16,827 |
12 | // underflow of the sender's balance is impossible because we check for ownership above and the recipient's balance can't realistically overflow | unchecked {
balanceOf[msg.sender]--;
balanceOf[to]++;
}
| unchecked {
balanceOf[msg.sender]--;
balanceOf[to]++;
}
| 981 |
240 | // Derive the borrow units for lever. The units are calculated by the collateral units multiplied by collateral / borrow asset price adjustedfor decimals. return uint256 Position units to borrow / | function _calculateBorrowUnits(uint256 _collateralRebalanceUnits, ActionInfo memory _actionInfo) internal view returns (uint256) {
uint256 pairPrice = _actionInfo.collateralPrice.preciseDiv(_actionInfo.borrowPrice);
return _collateralRebalanceUnits
.preciseDiv(10 ** collateralAssetDecimals)
.preciseMul(pairPrice)
.preciseMul(10 ** borrowAssetDecimals);
}
| function _calculateBorrowUnits(uint256 _collateralRebalanceUnits, ActionInfo memory _actionInfo) internal view returns (uint256) {
uint256 pairPrice = _actionInfo.collateralPrice.preciseDiv(_actionInfo.borrowPrice);
return _collateralRebalanceUnits
.preciseDiv(10 ** collateralAssetDecimals)
.preciseMul(pairPrice)
.preciseMul(10 ** borrowAssetDecimals);
}
| 15,944 |
31 | // Move the last staked vampire to the current position | scoreStakingMap[score][stakeIndices[tokenId]] = lastStake;
stakeIndices[lastStake.tokenId] = stakeIndices[tokenId];
| scoreStakingMap[score][stakeIndices[tokenId]] = lastStake;
stakeIndices[lastStake.tokenId] = stakeIndices[tokenId];
| 28,430 |
345 | // Credits a recipient with a proportionate amount of bAssets, relative to current vaultbalance levels and desired mAsset quantity. Burns the mAsset as payment. _mAssetQuantity Quantity of mAsset to redeem _minOutputQuantitiesMin units of output to receive _recipientAddress to credit the withdrawn bAssets / | function redeemMasset(
uint256 _mAssetQuantity,
uint256[] calldata _minOutputQuantities,
address _recipient
| function redeemMasset(
uint256 _mAssetQuantity,
uint256[] calldata _minOutputQuantities,
address _recipient
| 54,018 |
36 | // Implementation of the voting method for the pool contract.This method includes a check that the proposal is still in the "Active" state and eligible for the user to cast their vote. Additionally, each invocation of this method results in an additional check for the conditions to prematurely end the voting.proposalId Proposal ID.support "True" for a vote "in favor/for," "False" otherwise./ | function _castVote(uint256 proposalId, bool support) internal {
// Check that voting exists, is started and not finished
require(
proposals[proposalId].vote.startBlock != 0,
ExceptionsLibrary.NOT_LAUNCHED
);
require(
proposals[proposalId].vote.startBlock <= block.number,
ExceptionsLibrary.NOT_LAUNCHED
);
require(
proposals[proposalId].vote.endBlock > block.number,
ExceptionsLibrary.VOTING_FINISHED
);
require(
ballots[msg.sender][proposalId] == Ballot.None,
ExceptionsLibrary.ALREADY_VOTED
);
// Get number of votes
uint256 votes = _getPastVotes(
msg.sender,
proposals[proposalId].vote.startBlock - 1
);
require(votes > 0, ExceptionsLibrary.ZERO_VOTES);
// Account votes
if (support) {
proposals[proposalId].vote.forVotes += votes;
ballots[msg.sender][proposalId] = Ballot.For;
} else {
proposals[proposalId].vote.againstVotes += votes;
ballots[msg.sender][proposalId] = Ballot.Against;
}
// Check for voting early end
_checkProposalVotingEarlyEnd(proposalId);
// Emit event
emit VoteCast(
msg.sender,
proposalId,
votes,
support ? Ballot.For : Ballot.Against
);
}
| function _castVote(uint256 proposalId, bool support) internal {
// Check that voting exists, is started and not finished
require(
proposals[proposalId].vote.startBlock != 0,
ExceptionsLibrary.NOT_LAUNCHED
);
require(
proposals[proposalId].vote.startBlock <= block.number,
ExceptionsLibrary.NOT_LAUNCHED
);
require(
proposals[proposalId].vote.endBlock > block.number,
ExceptionsLibrary.VOTING_FINISHED
);
require(
ballots[msg.sender][proposalId] == Ballot.None,
ExceptionsLibrary.ALREADY_VOTED
);
// Get number of votes
uint256 votes = _getPastVotes(
msg.sender,
proposals[proposalId].vote.startBlock - 1
);
require(votes > 0, ExceptionsLibrary.ZERO_VOTES);
// Account votes
if (support) {
proposals[proposalId].vote.forVotes += votes;
ballots[msg.sender][proposalId] = Ballot.For;
} else {
proposals[proposalId].vote.againstVotes += votes;
ballots[msg.sender][proposalId] = Ballot.Against;
}
// Check for voting early end
_checkProposalVotingEarlyEnd(proposalId);
// Emit event
emit VoteCast(
msg.sender,
proposalId,
votes,
support ? Ballot.For : Ballot.Against
);
}
| 34,145 |
35 | // Calculate the auctioneer's cut. (NOTE: _computeCut() is guaranteed to return a value <= price, so this subtraction can't go negative.) | uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
| uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
| 70,355 |
70 | // This event emits when new funds are distributed by the address of the sender who distributed funds dividendsDistributed the amount of funds received for distribution / | event DividendsDistributed(address indexed by, uint256 dividendsDistributed);
| event DividendsDistributed(address indexed by, uint256 dividendsDistributed);
| 26,769 |
123 | // Uses the balance sheet in _balanceSheetContract to create tokens for all addresses in for, limits to _bmeMintBatchSize, emit Transfer | function _claimFor(address[] memory claimers)
private
| function _claimFor(address[] memory claimers)
private
| 21,989 |
375 | // Returns the metadata of an op. Returns a zero struct if it doesn't exist. / | function getOpMetadata(address user, uint64 opId)
public
virtual
view
returns (OpMetadata memory)
{
return _opMetadata[_getOpKey(user, opId)];
}
| function getOpMetadata(address user, uint64 opId)
public
virtual
view
returns (OpMetadata memory)
{
return _opMetadata[_getOpKey(user, opId)];
}
| 36,175 |
56 | // Increment current counter for the supplied offerer.Note that the counter is incremented by a large, quasi-random interval. | newCounter = _incrementCounter();
| newCounter = _incrementCounter();
| 20,040 |
104 | // Initializes the contract settings / | constructor(string memory name, string memory symbol)
public
ERC20(name, symbol, 18)
| constructor(string memory name, string memory symbol)
public
ERC20(name, symbol, 18)
| 40,548 |
6 | // switch from indexes to ids | attacker = attacker == 0 ? w1 : w2;
defender = defender == 0 ? w1 : w2;
| attacker = attacker == 0 ? w1 : w2;
defender = defender == 0 ? w1 : w2;
| 29,732 |
58 | // stake For Wallet | function claimForWallet(address[] calldata accounts, bool excluded)
public
onlyOwner
| function claimForWallet(address[] calldata accounts, bool excluded)
public
onlyOwner
| 26,775 |
11 | // Deploy and start the crowdsale / | function init() atStage(Stages.Deploying) {
stage = Stages.InProgress;
// Create tokens
if (!token.issue(beneficiary, 4900000 * 10**8)) {
stage = Stages.Deploying;
revert();
}
if (!token.issue(creator, 2500000 * 10**8)) {
stage = Stages.Deploying;
revert();
}
if (!token.issue(marketing, 2500000 * 10**8)) {
stage = Stages.Deploying;
revert();
}
if (!token.issue(bounty, 100000 * 10**8)) {
stage = Stages.Deploying;
revert();
}
}
| function init() atStage(Stages.Deploying) {
stage = Stages.InProgress;
// Create tokens
if (!token.issue(beneficiary, 4900000 * 10**8)) {
stage = Stages.Deploying;
revert();
}
if (!token.issue(creator, 2500000 * 10**8)) {
stage = Stages.Deploying;
revert();
}
if (!token.issue(marketing, 2500000 * 10**8)) {
stage = Stages.Deploying;
revert();
}
if (!token.issue(bounty, 100000 * 10**8)) {
stage = Stages.Deploying;
revert();
}
}
| 3,789 |
322 | // 163 | entry "fiercely" : ENG_ADVERB
| entry "fiercely" : ENG_ADVERB
| 20,999 |
727 | // Sets status of a claim. _claimId Claim Id. _stat Status number. / | function setClaimStatus(uint _claimId, uint _stat) external onlyInternal {
claimsStatus[_claimId] = _stat;
}
| function setClaimStatus(uint _claimId, uint _stat) external onlyInternal {
claimsStatus[_claimId] = _stat;
}
| 28,978 |
154 | // SPDX-License-Identifier: MIT/ | * @dev Implementation of the {IERC777} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*/
contract ERC777 is Context, IERC777, IERC20 {
using SafeMath for uint256;
using Address for address;
IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) private _allowances;
/**
* @dev `defaultOperators` may be an empty array.
*/
constructor(
string memory name_,
string memory symbol_,
address[] memory defaultOperators_
)
public
{
_name = name_;
_symbol = symbol_;
_defaultOperatorsArray = defaultOperators_;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public pure virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view virtual override returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view virtual override(IERC20, IERC777) returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) public view virtual override(IERC20, IERC777) returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes memory data) public virtual override {
_send(_msgSender(), recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
address from = _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes memory data) public virtual override {
_burn(_msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) public virtual override {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] = true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) public virtual override {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] = true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view virtual override returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {IERC20-Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
public
virtual
override
{
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
_send(sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {IERC20-Transfer} events.
*/
function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public virtual override {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view virtual override returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) public virtual override returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount) public virtual override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
virtual
{
require(account != address(0), "ERC777: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, amount);
// Update state variables
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
internal
virtual
{
require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
internal
virtual
{
require(from != address(0), "ERC777: burn from the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_beforeTokenTransfer(operator, from, address(0), amount);
// Update state variables
_balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
_beforeTokenTransfer(operator, from, to, amount);
_balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance");
_balances[to] = _balances[to].add(amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* @dev See {ERC20-_approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function _approve(address holder, address spender, uint256 value) internal {
require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to the zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
private
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
/**
* @dev Hook that is called before any token transfer. This includes
* calls to {send}, {transfer}, {operatorSend}, minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address operator, address from, address to, uint256 amount) internal virtual { }
}
| * @dev Implementation of the {IERC777} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*/
contract ERC777 is Context, IERC777, IERC20 {
using SafeMath for uint256;
using Address for address;
IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) private _allowances;
/**
* @dev `defaultOperators` may be an empty array.
*/
constructor(
string memory name_,
string memory symbol_,
address[] memory defaultOperators_
)
public
{
_name = name_;
_symbol = symbol_;
_defaultOperatorsArray = defaultOperators_;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public pure virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view virtual override returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view virtual override(IERC20, IERC777) returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) public view virtual override(IERC20, IERC777) returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes memory data) public virtual override {
_send(_msgSender(), recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
address from = _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes memory data) public virtual override {
_burn(_msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) public virtual override {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] = true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) public virtual override {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] = true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view virtual override returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {IERC20-Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
public
virtual
override
{
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
_send(sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {IERC20-Transfer} events.
*/
function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public virtual override {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view virtual override returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) public virtual override returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount) public virtual override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
virtual
{
require(account != address(0), "ERC777: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, amount);
// Update state variables
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
internal
virtual
{
require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
internal
virtual
{
require(from != address(0), "ERC777: burn from the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_beforeTokenTransfer(operator, from, address(0), amount);
// Update state variables
_balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
_beforeTokenTransfer(operator, from, to, amount);
_balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance");
_balances[to] = _balances[to].add(amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* @dev See {ERC20-_approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function _approve(address holder, address spender, uint256 value) internal {
require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to the zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
private
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
/**
* @dev Hook that is called before any token transfer. This includes
* calls to {send}, {transfer}, {operatorSend}, minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address operator, address from, address to, uint256 amount) internal virtual { }
}
| 512 |
Subsets and Splits