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
|
|---|---|---|---|---|
378
|
// Associate designer
|
designers[tokenId] = _designer;
return tokenId;
|
designers[tokenId] = _designer;
return tokenId;
| 2,853
|
67
|
// Address of operator
|
address public operator;
|
address public operator;
| 12,718
|
220
|
// WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible /
|
function _mint(address to, uint256 boosterId, string memory _typeOfBoost) internal {
require(to != address(0), "BOOSTERS: Cannot mint to zero address");
require(!_exists(boosterId), "BOOSTERS: Already minted");
BoostersEnumerableSet.ownedBooster memory newBooster = BoostersEnumerableSet.ownedBooster({ boostId: boosterId, _type: _typeOfBoost });
|
function _mint(address to, uint256 boosterId, string memory _typeOfBoost) internal {
require(to != address(0), "BOOSTERS: Cannot mint to zero address");
require(!_exists(boosterId), "BOOSTERS: Already minted");
BoostersEnumerableSet.ownedBooster memory newBooster = BoostersEnumerableSet.ownedBooster({ boostId: boosterId, _type: _typeOfBoost });
| 26,764
|
16
|
// External function for calculating how much SWM tokens are needed to be stakedin order to get 1 SRC20 tokensrc20 Address of src20 token contractreturn Amount of SWM tokens /
|
function getSrc20toSwmRatio(address src20) external returns (uint256) {
uint256 totalSupply = ISRC20(src20).totalSupply();
return totalSupply.mul(10 ** 18).div(_registry[src20].stake);
}
|
function getSrc20toSwmRatio(address src20) external returns (uint256) {
uint256 totalSupply = ISRC20(src20).totalSupply();
return totalSupply.mul(10 ** 18).div(_registry[src20].stake);
}
| 44,193
|
27
|
// Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with `errorMessage` as a fallback revert reason when `target` reverts. _Available since v3.1._/
|
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
|
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
| 31,482
|
145
|
// Hook that is called after any transfer of tokens. This includesminting and burning. Calling conditions: - when `from` and `to` are both non-zero.- `from` and `to` are never both zero. To learn more about hooks, head to xref:ROOT:extending-contracts.adocusing-hooks[Using Hooks]. /
|
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
|
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
| 3,479
|
242
|
// Used to store old model for use in the event that is emitted on success
|
InterestRateModel oldInterestRateModel;
|
InterestRateModel oldInterestRateModel;
| 259
|
111
|
// Gets the token name. return string representing the token name/
|
function name() external view returns (string memory) {
return _name;
}
|
function name() external view returns (string memory) {
return _name;
}
| 23,404
|
96
|
// Contract for locking mechanism.Locker can add and remove locked account.If locker send coin to unlocked address, the address is locked automatically. /
|
contract Lockable is Context {
using SafeMath for uint;
struct TimeLock {
uint amount;
uint expiresAt;
}
mapping(address => bool) private _lockers;
mapping(address => bool) private _locks;
mapping(address => TimeLock[]) private _timeLocks;
event LockerAdded(address indexed account);
event LockerRemoved(address indexed account);
event Locked(address indexed account);
event Unlocked(address indexed account);
event TimeLocked(address indexed account);
event TimeUnlocked(address indexed account);
/**
* @dev Throws if called by any account other than the locker.
*/
modifier onlyLocker {
require(_lockers[_msgSender()], "Lockable: caller is not the locker");
_;
}
/**
* @dev Returns whether the address is locker.
*/
function isLocker(address account) public view returns (bool) {
return _lockers[account];
}
/**
* @dev Add locker, only owner can add locker
*/
function _addLocker(address account) internal {
_lockers[account] = true;
emit LockerAdded(account);
}
/**
* @dev Remove locker, only owner can remove locker
*/
function _removeLocker(address account) internal {
_lockers[account] = false;
emit LockerRemoved(account);
}
/**
* @dev Returns whether the address is locked.
*/
function isLocked(address account) public view returns (bool) {
return _locks[account];
}
/**
* @dev Lock account, only locker can lock
*/
function _lock(address account) internal {
_locks[account] = true;
emit Locked(account);
}
/**
* @dev Unlock account, only locker can unlock
*/
function _unlock(address account) internal {
_locks[account] = false;
emit Unlocked(account);
}
/**
* @dev Add time lock, only locker can add
*/
function _addTimeLock(address account, uint amount, uint expiresAt) internal {
require(amount > 0, "Time Lock: lock amount must be greater than 0");
require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now");
_timeLocks[account].push(TimeLock(amount, expiresAt));
}
/**
* @dev Remove time lock, only locker can remove
* @param account The address want to know the time lock state.
* @param index Time lock index
*/
function _removeTimeLock(address account, uint8 index) internal {
require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid");
uint len = _timeLocks[account].length;
if (len - 1 != index) { // if it is not last item, swap it
_timeLocks[account][index] = _timeLocks[account][len - 1];
}
_timeLocks[account].pop();
}
/**
* @dev Get time lock array length
* @param account The address want to know the time lock length.
* @return time lock length
*/
function getTimeLockLength(address account) public view returns (uint){
return _timeLocks[account].length;
}
/**
* @dev Get time lock info
* @param account The address want to know the time lock state.
* @param index Time lock index
* @return time lock info
*/
function getTimeLock(address account, uint8 index) public view returns (uint, uint){
require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid");
return (_timeLocks[account][index].amount, _timeLocks[account][index].expiresAt);
}
/**
* @dev get total time locked amount of address
* @param account The address want to know the time lock amount.
* @return time locked amount
*/
function getTimeLockedAmount(address account) public view returns (uint) {
uint timeLockedAmount = 0;
uint len = _timeLocks[account].length;
for (uint i = 0; i < len; i++) {
if (block.timestamp < _timeLocks[account][i].expiresAt) {
timeLockedAmount = timeLockedAmount.add(_timeLocks[account][i].amount);
}
}
return timeLockedAmount;
}
}
|
contract Lockable is Context {
using SafeMath for uint;
struct TimeLock {
uint amount;
uint expiresAt;
}
mapping(address => bool) private _lockers;
mapping(address => bool) private _locks;
mapping(address => TimeLock[]) private _timeLocks;
event LockerAdded(address indexed account);
event LockerRemoved(address indexed account);
event Locked(address indexed account);
event Unlocked(address indexed account);
event TimeLocked(address indexed account);
event TimeUnlocked(address indexed account);
/**
* @dev Throws if called by any account other than the locker.
*/
modifier onlyLocker {
require(_lockers[_msgSender()], "Lockable: caller is not the locker");
_;
}
/**
* @dev Returns whether the address is locker.
*/
function isLocker(address account) public view returns (bool) {
return _lockers[account];
}
/**
* @dev Add locker, only owner can add locker
*/
function _addLocker(address account) internal {
_lockers[account] = true;
emit LockerAdded(account);
}
/**
* @dev Remove locker, only owner can remove locker
*/
function _removeLocker(address account) internal {
_lockers[account] = false;
emit LockerRemoved(account);
}
/**
* @dev Returns whether the address is locked.
*/
function isLocked(address account) public view returns (bool) {
return _locks[account];
}
/**
* @dev Lock account, only locker can lock
*/
function _lock(address account) internal {
_locks[account] = true;
emit Locked(account);
}
/**
* @dev Unlock account, only locker can unlock
*/
function _unlock(address account) internal {
_locks[account] = false;
emit Unlocked(account);
}
/**
* @dev Add time lock, only locker can add
*/
function _addTimeLock(address account, uint amount, uint expiresAt) internal {
require(amount > 0, "Time Lock: lock amount must be greater than 0");
require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now");
_timeLocks[account].push(TimeLock(amount, expiresAt));
}
/**
* @dev Remove time lock, only locker can remove
* @param account The address want to know the time lock state.
* @param index Time lock index
*/
function _removeTimeLock(address account, uint8 index) internal {
require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid");
uint len = _timeLocks[account].length;
if (len - 1 != index) { // if it is not last item, swap it
_timeLocks[account][index] = _timeLocks[account][len - 1];
}
_timeLocks[account].pop();
}
/**
* @dev Get time lock array length
* @param account The address want to know the time lock length.
* @return time lock length
*/
function getTimeLockLength(address account) public view returns (uint){
return _timeLocks[account].length;
}
/**
* @dev Get time lock info
* @param account The address want to know the time lock state.
* @param index Time lock index
* @return time lock info
*/
function getTimeLock(address account, uint8 index) public view returns (uint, uint){
require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid");
return (_timeLocks[account][index].amount, _timeLocks[account][index].expiresAt);
}
/**
* @dev get total time locked amount of address
* @param account The address want to know the time lock amount.
* @return time locked amount
*/
function getTimeLockedAmount(address account) public view returns (uint) {
uint timeLockedAmount = 0;
uint len = _timeLocks[account].length;
for (uint i = 0; i < len; i++) {
if (block.timestamp < _timeLocks[account][i].expiresAt) {
timeLockedAmount = timeLockedAmount.add(_timeLocks[account][i].amount);
}
}
return timeLockedAmount;
}
}
| 31,094
|
7
|
// Transfers `tokenId` token from `from` to `to`.
|
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
}
|
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
}
| 16,544
|
144
|
// Returns the token identifier for the `_index`th NFT. Sort order is not specified. _index A counter less than `totalSupply()`.return Token id. /
|
function tokenByIndex(
uint256 _index
)
external
view
|
function tokenByIndex(
uint256 _index
)
external
view
| 22,035
|
78
|
// TimeLocked/Applicature/helper mixed to other contracts to lock contract on a timestamp/Base class
|
contract TimeLocked {
uint256 public time;
mapping(address => bool) public excludedAddresses;
modifier isTimeLocked(address _holder, bool _timeLocked) {
bool locked = (block.timestamp < time);
require(excludedAddresses[_holder] == true || locked == _timeLocked);
_;
}
constructor(uint256 _time) public {
time = _time;
}
function updateExcludedAddress(address _address, bool _status) public;
}
|
contract TimeLocked {
uint256 public time;
mapping(address => bool) public excludedAddresses;
modifier isTimeLocked(address _holder, bool _timeLocked) {
bool locked = (block.timestamp < time);
require(excludedAddresses[_holder] == true || locked == _timeLocked);
_;
}
constructor(uint256 _time) public {
time = _time;
}
function updateExcludedAddress(address _address, bool _status) public;
}
| 36,594
|
8
|
// 1 - Uoptimal in WAD
|
_U_Optimal_inverted_WAD = WadRayMath.WAD.sub(U_optimal_WAD);
_R_base_RAY = WadRayMath.RAY.percentMul(R_base);
_R_slope1_RAY = WadRayMath.RAY.percentMul(R_slope1);
_R_slope2_RAY = WadRayMath.RAY.percentMul(R_slope2);
|
_U_Optimal_inverted_WAD = WadRayMath.WAD.sub(U_optimal_WAD);
_R_base_RAY = WadRayMath.RAY.percentMul(R_base);
_R_slope1_RAY = WadRayMath.RAY.percentMul(R_slope1);
_R_slope2_RAY = WadRayMath.RAY.percentMul(R_slope2);
| 34,150
|
20
|
// It's probably never going to happen, 4 billion cats is A LOT, but let's just be 100% sure we never let this happen.
|
require(newKittenId == uint256(uint32(newKittenId)), "4 Billion cats max");
emit Birth(owner, newKittenId, uint256(_kitty.mumId), uint256(_kitty.dadId), _kitty.genes);
|
require(newKittenId == uint256(uint32(newKittenId)), "4 Billion cats max");
emit Birth(owner, newKittenId, uint256(_kitty.mumId), uint256(_kitty.dadId), _kitty.genes);
| 17,255
|
294
|
// This is a function call as it minimized the bytecode size
|
requireSelfCall();
_;
|
requireSelfCall();
_;
| 26,780
|
18
|
// https:www.geeksforgeeks.org/bresenhams-circle-drawing-algorithm/
|
int256 x = 0;
int256 y = int256(r);
int256 d = 3 - 2 * r;
canvas = _drawCircle(canvas, char, xc, yc, uint256(x), uint256(y));
while (y >= x) {
x++;
if (d > 0) {
y--;
|
int256 x = 0;
int256 y = int256(r);
int256 d = 3 - 2 * r;
canvas = _drawCircle(canvas, char, xc, yc, uint256(x), uint256(y));
while (y >= x) {
x++;
if (d > 0) {
y--;
| 44,877
|
85
|
// Transfers ownership of the contract to a new account (`newOwner`).Internal function without access restriction. /
|
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
|
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
| 58,792
|
50
|
// Records number of AnyswapV3ERC20 token that account (second) will be allowed to spend on behalf of another account (first) through {transferFrom}.
|
mapping (address => mapping (address => uint256)) public override allowance;
event LogChangeVault(address indexed oldVault, address indexed newVault, uint indexed effectiveTime);
event LogChangeMPCOwner(address indexed oldOwner, address indexed newOwner, uint indexed effectiveHeight);
event LogSwapin(bytes32 indexed txhash, address indexed account, uint amount);
event LogSwapout(address indexed account, address indexed bindaddr, uint amount);
event LogAddAuth(address indexed auth, uint timestamp);
constructor(string memory _name, string memory _symbol, uint8 _decimals, address _underlying, address _vault) {
name = _name;
|
mapping (address => mapping (address => uint256)) public override allowance;
event LogChangeVault(address indexed oldVault, address indexed newVault, uint indexed effectiveTime);
event LogChangeMPCOwner(address indexed oldOwner, address indexed newOwner, uint indexed effectiveHeight);
event LogSwapin(bytes32 indexed txhash, address indexed account, uint amount);
event LogSwapout(address indexed account, address indexed bindaddr, uint amount);
event LogAddAuth(address indexed auth, uint timestamp);
constructor(string memory _name, string memory _symbol, uint8 _decimals, address _underlying, address _vault) {
name = _name;
| 1,402
|
2
|
// disable controller by setting ZeroAddress to the entry in controllers-mapping _controllerId The Id of controller-implementation in the controllers mapping /
|
function disableController(uint32 _controllerId) external;
|
function disableController(uint32 _controllerId) external;
| 3,491
|
0
|
// @custom:attribution https:github.com/GNSPS/solidity-bytes-utils/Slices a byte array with a given starting index and length. Returns a new byte array/ as opposed to a pointer to the original array. Will throw if trying to slice more/ bytes than exist in the array./_bytes Byte array to slice./_start Starting index of the slice./_length Length of the slice./ return Slice of the input byte array.
|
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
|
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
| 23,818
|
46
|
// emit event attack boss
|
emit eventAttackBoss(b.bossRoundNumber, msg.sender, _value, dame, now, isLastHit, crystalsBonus);
|
emit eventAttackBoss(b.bossRoundNumber, msg.sender, _value, dame, now, isLastHit, crystalsBonus);
| 19,371
|
27
|
// Synth loan storage struct
|
struct SynthLoanStruct {
// Acccount that created the loan
address payable account;
// Amount (in collateral token ) that they deposited
uint256 collateralAmount;
// Amount (in synths) that they issued to borrow
uint256 loanAmount;
// Minting Fee
uint256 mintingFee;
// When the loan was created
uint256 timeCreated;
// ID for the loan
uint256 loanID;
// When the loan was paidback (closed)
uint256 timeClosed;
// Applicable Interest rate
uint256 loanInterestRate;
// interest amounts accrued
uint256 accruedInterest;
// last timestamp interest amounts accrued
uint40 lastInterestAccrued;
}
|
struct SynthLoanStruct {
// Acccount that created the loan
address payable account;
// Amount (in collateral token ) that they deposited
uint256 collateralAmount;
// Amount (in synths) that they issued to borrow
uint256 loanAmount;
// Minting Fee
uint256 mintingFee;
// When the loan was created
uint256 timeCreated;
// ID for the loan
uint256 loanID;
// When the loan was paidback (closed)
uint256 timeClosed;
// Applicable Interest rate
uint256 loanInterestRate;
// interest amounts accrued
uint256 accruedInterest;
// last timestamp interest amounts accrued
uint40 lastInterestAccrued;
}
| 20,708
|
55
|
// Taxes for last round token winner
|
if (tokenWinner[_tokenId]!=address(0))
tokenWinner[_tokenId].transfer(feeThree);
|
if (tokenWinner[_tokenId]!=address(0))
tokenWinner[_tokenId].transfer(feeThree);
| 43,902
|
28
|
// receive() external payable { }
|
function setShare(address shareholder, uint256 amount) external override onlyToken {
if (shares[shareholder].amount > 0) {
distributeDividend(shareholder);
}
|
function setShare(address shareholder, uint256 amount) external override onlyToken {
if (shares[shareholder].amount > 0) {
distributeDividend(shareholder);
}
| 39,920
|
0
|
// As goal needs to be met for a successful crowdsalethe value needs to less or equal than a cap which is limit for accepted funds
|
require(_goal <= _cap);
|
require(_goal <= _cap);
| 47,999
|
21
|
// De-Whitelist new provider Module(s)/_modules Addresses of the modules which will be removed
|
function removeProviderModules(IGelatoProviderModule[] calldata _modules) external;
|
function removeProviderModules(IGelatoProviderModule[] calldata _modules) external;
| 31,825
|
129
|
// settle();
|
}
|
}
| 27,873
|
66
|
// Check permission of administrator. Implementation is within the AdminController contract.Data will be used for future extension. /
|
modifier onlyAdmin(bytes memory data) {
require(_adminController.isAdmin(msg.sender, data), "Caller is not the Admin");
_;
}
|
modifier onlyAdmin(bytes memory data) {
require(_adminController.isAdmin(msg.sender, data), "Caller is not the Admin");
_;
}
| 14,850
|
42
|
// get DEA and send to Vault
|
if(rewards > 0){
controller.buyForStrategy(
rewards,
vault.getRewardToken(),
address(vault)
);
}
|
if(rewards > 0){
controller.buyForStrategy(
rewards,
vault.getRewardToken(),
address(vault)
);
}
| 52,875
|
299
|
// avoid stack too deep
|
(, SignedDecimal.signedDecimal memory unrealizedPnl) =
getPositionNotionalAndUnrealizedPnl(_exchange, trader, PnlCalcOption.SPOT_PRICE);
positionResp.unrealizedPnlAfter = unrealizedPnl;
|
(, SignedDecimal.signedDecimal memory unrealizedPnl) =
getPositionNotionalAndUnrealizedPnl(_exchange, trader, PnlCalcOption.SPOT_PRICE);
positionResp.unrealizedPnlAfter = unrealizedPnl;
| 10,241
|
91
|
// increase asyncDefiInteractionHashes.length by 1
|
let oldState := and(not(shl(ASYNCDEFIINTERACTIONHASHES_BIT_OFFSET, ARRAY_LENGTH_MASK)), state)
let newState := or(oldState, shl(ASYNCDEFIINTERACTIONHASHES_BIT_OFFSET, add(asyncArrayLen, 0x01)))
sstore(rollupState.slot, newState)
|
let oldState := and(not(shl(ASYNCDEFIINTERACTIONHASHES_BIT_OFFSET, ARRAY_LENGTH_MASK)), state)
let newState := or(oldState, shl(ASYNCDEFIINTERACTIONHASHES_BIT_OFFSET, add(asyncArrayLen, 0x01)))
sstore(rollupState.slot, newState)
| 14,666
|
26
|
// swap fee for reward token
|
bool isSuccess = _swapTokensForGB(amount);
uint256 liqTokens = amount.div(4);
uint256 daoTokens = amount.sub(liqTokens);
if (isSuccess) {
IERC20(rewardToken).transfer(_DAOWalletAddress, daoTokens);
}
|
bool isSuccess = _swapTokensForGB(amount);
uint256 liqTokens = amount.div(4);
uint256 daoTokens = amount.sub(liqTokens);
if (isSuccess) {
IERC20(rewardToken).transfer(_DAOWalletAddress, daoTokens);
}
| 482
|
3
|
// Emitted when the beacon is changed. /
|
event BeaconUpgraded(address indexed beacon);
|
event BeaconUpgraded(address indexed beacon);
| 24,787
|
296
|
// Return the actual amount withdrawn if less than requested
|
uint256 _withdrawn = MathUpgradeable.min(_postWant, _amount);
emit WithdrawState(_amount, _preWant, _postWant, _withdrawn);
return _withdrawn;
|
uint256 _withdrawn = MathUpgradeable.min(_postWant, _amount);
emit WithdrawState(_amount, _preWant, _postWant, _withdrawn);
return _withdrawn;
| 32,151
|
34
|
// Pausable/Iulian Rotaru/Pausable logics, reading storage slot to retrieve pause state
|
contract Pausable {
//
// _ _
// ___ ___ _ __ ___| |_ __ _ _ __ | |_ ___
// / __/ _ \| '_ \/ __| __/ _` | '_ \| __/ __|
// | (_| (_) | | | \__ \ || (_| | | | | |_\__ \
// \___\___/|_| |_|___/\__\__,_|_| |_|\__|___/
//
// Storage slot for the Paused state
bytes32 internal constant _PAUSED_SLOT = 0x8dea8703c3cf94703383ce38a9c894669dccd4ca8e65ddb43267aa0248711450;
//
// _ _ __ _
// _ __ ___ ___ __| (_)/ _(_) ___ _ __ ___
// | '_ ` _ \ / _ \ / _` | | |_| |/ _ \ '__/ __|
// | | | | | | (_) | (_| | | _| | __/ | \__ \
// |_| |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/
//
// Allows methods to be called if paused
modifier whenPaused() {
require(StorageSlot.getBooleanSlot(_PAUSED_SLOT).value == true, 'P1');
_;
}
// Allows methods to be called if not paused
modifier whenNotPaused() {
require(StorageSlot.getBooleanSlot(_PAUSED_SLOT).value == false, 'P1');
_;
}
}
|
contract Pausable {
//
// _ _
// ___ ___ _ __ ___| |_ __ _ _ __ | |_ ___
// / __/ _ \| '_ \/ __| __/ _` | '_ \| __/ __|
// | (_| (_) | | | \__ \ || (_| | | | | |_\__ \
// \___\___/|_| |_|___/\__\__,_|_| |_|\__|___/
//
// Storage slot for the Paused state
bytes32 internal constant _PAUSED_SLOT = 0x8dea8703c3cf94703383ce38a9c894669dccd4ca8e65ddb43267aa0248711450;
//
// _ _ __ _
// _ __ ___ ___ __| (_)/ _(_) ___ _ __ ___
// | '_ ` _ \ / _ \ / _` | | |_| |/ _ \ '__/ __|
// | | | | | | (_) | (_| | | _| | __/ | \__ \
// |_| |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/
//
// Allows methods to be called if paused
modifier whenPaused() {
require(StorageSlot.getBooleanSlot(_PAUSED_SLOT).value == true, 'P1');
_;
}
// Allows methods to be called if not paused
modifier whenNotPaused() {
require(StorageSlot.getBooleanSlot(_PAUSED_SLOT).value == false, 'P1');
_;
}
}
| 50,748
|
10
|
// Events :
|
event TokensReleased(uint256 releasedAmount);
event TokenVestingRevoked(uint256 revokedAmount);
event LockAccepted();
event LockCanceled();
|
event TokensReleased(uint256 releasedAmount);
event TokenVestingRevoked(uint256 revokedAmount);
event LockAccepted();
event LockCanceled();
| 19,085
|
97
|
// IConstantFlowAgreementV1.getFlowOperatorDataByID implementation
|
function getFlowOperatorDataByID(
ISuperfluidToken token,
bytes32 flowOperatorId
)
external view override
returns(uint8 permissions, int96 flowRateAllowance)
|
function getFlowOperatorDataByID(
ISuperfluidToken token,
bytes32 flowOperatorId
)
external view override
returns(uint8 permissions, int96 flowRateAllowance)
| 11,406
|
11
|
// Returns the delay period before a new owner can be accepted. /
|
function delay() public view returns (uint256) {
return LibDiamond.acceptanceDelay();
}
|
function delay() public view returns (uint256) {
return LibDiamond.acceptanceDelay();
}
| 24,170
|
315
|
// If no owedToken needed for payout: give lender all owedToken, even if more than owed
|
if (transaction.payoutInHeldToken) {
assert(receivedOwedToken >= lenderOwedToken);
lenderOwedToken = receivedOwedToken;
}
|
if (transaction.payoutInHeldToken) {
assert(receivedOwedToken >= lenderOwedToken);
lenderOwedToken = receivedOwedToken;
}
| 46,005
|
139
|
// Submitted for verification at Etherscan.io on 2020-07-14// Submitted for verification at Etherscan.io on 2020-05-27/ File: zos-lib/contracts/Initializable.sol/ Maestro The Maestro is the main entry point for rebase operations. It coordinates the policyactions with external consumers. /
|
contract Maestro is Ownable {
struct Transaction {
bool enabled;
address destination;
bytes data;
}
event TransactionFailed(
address indexed destination,
uint256 index,
bytes data
);
// Stable ordering is not guaranteed.
Transaction[] public transactions;
RamifiPolicy public policy;
/**
* @param policy_ Address of the Ramifi policy.
*/
constructor(address policy_) public {
Ownable.initialize(msg.sender);
policy = RamifiPolicy(policy_);
}
/**
* @notice Main entry point to initiate a rebase operation.
* The Maestro calls rebase on the policy and notifies downstream applications.
* Contracts are guarded from calling, to avoid flash loan attacks on liquidity
* providers.
* If a transaction in the transaction list reverts, it is swallowed and the remaining
* transactions are executed.
*/
function rebase() external {
require(msg.sender == tx.origin); // solhint-disable-line avoid-tx-origin
policy.rebase();
for (uint256 i = 0; i < transactions.length; i++) {
Transaction storage t = transactions[i];
if (t.enabled) {
bool result = externalCall(t.destination, t.data);
if (!result) {
emit TransactionFailed(t.destination, i, t.data);
revert("Transaction Failed");
}
}
}
}
// Emergency Rebase
function emergencyRebase(uint256 _price)
external
onlyOwner
{
policy.emergencyRebase(_price);
}
/**
* @notice Adds a transaction that gets called for a downstream receiver of rebases
* @param destination Address of contract destination
* @param data Transaction data payload
*/
function addTransaction(address destination, bytes data)
external
onlyOwner
{
transactions.push(
Transaction({enabled: true, destination: destination, data: data})
);
}
/**
* @param index Index of transaction to remove.
* Transaction ordering may have changed since adding.
*/
function removeTransaction(uint256 index) external onlyOwner {
require(index < transactions.length, "index out of bounds");
if (index < transactions.length - 1) {
transactions[index] = transactions[transactions.length - 1];
}
transactions.length--;
}
/**
* @param index Index of transaction. Transaction ordering may have changed since adding.
* @param enabled True for enabled, false for disabled.
*/
function setTransactionEnabled(uint256 index, bool enabled)
external
onlyOwner
{
require(
index < transactions.length,
"index must be in range of stored tx list"
);
transactions[index].enabled = enabled;
}
/**
* @return Number of transactions, both enabled and disabled, in transactions list.
*/
function transactionsSize() external view returns (uint256) {
return transactions.length;
}
/**
* @dev wrapper to call the encoded transactions on downstream consumers.
* @param destination Address of destination contract.
* @param data The encoded data payload.
* @return True on success
*/
function externalCall(address destination, bytes data)
internal
returns (bool)
{
bool result;
assembly {
// solhint-disable-line no-inline-assembly
// "Allocate" memory for output
// (0x40 is where "free memory" pointer is stored by convention)
let outputAddress := mload(0x40)
// First 32 bytes are the padded length of data, so exclude that
let dataAddress := add(data, 32)
result := call(
// 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB)
// + callValueTransferGas (9000) + callNewAccountGas
// (25000, in case the destination address does not exist and needs creating)
sub(gas, 34710),
destination,
0, // transfer value in wei
dataAddress,
mload(data), // Size of the input, in bytes. Stored in position 0 of the array.
outputAddress,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
}
|
contract Maestro is Ownable {
struct Transaction {
bool enabled;
address destination;
bytes data;
}
event TransactionFailed(
address indexed destination,
uint256 index,
bytes data
);
// Stable ordering is not guaranteed.
Transaction[] public transactions;
RamifiPolicy public policy;
/**
* @param policy_ Address of the Ramifi policy.
*/
constructor(address policy_) public {
Ownable.initialize(msg.sender);
policy = RamifiPolicy(policy_);
}
/**
* @notice Main entry point to initiate a rebase operation.
* The Maestro calls rebase on the policy and notifies downstream applications.
* Contracts are guarded from calling, to avoid flash loan attacks on liquidity
* providers.
* If a transaction in the transaction list reverts, it is swallowed and the remaining
* transactions are executed.
*/
function rebase() external {
require(msg.sender == tx.origin); // solhint-disable-line avoid-tx-origin
policy.rebase();
for (uint256 i = 0; i < transactions.length; i++) {
Transaction storage t = transactions[i];
if (t.enabled) {
bool result = externalCall(t.destination, t.data);
if (!result) {
emit TransactionFailed(t.destination, i, t.data);
revert("Transaction Failed");
}
}
}
}
// Emergency Rebase
function emergencyRebase(uint256 _price)
external
onlyOwner
{
policy.emergencyRebase(_price);
}
/**
* @notice Adds a transaction that gets called for a downstream receiver of rebases
* @param destination Address of contract destination
* @param data Transaction data payload
*/
function addTransaction(address destination, bytes data)
external
onlyOwner
{
transactions.push(
Transaction({enabled: true, destination: destination, data: data})
);
}
/**
* @param index Index of transaction to remove.
* Transaction ordering may have changed since adding.
*/
function removeTransaction(uint256 index) external onlyOwner {
require(index < transactions.length, "index out of bounds");
if (index < transactions.length - 1) {
transactions[index] = transactions[transactions.length - 1];
}
transactions.length--;
}
/**
* @param index Index of transaction. Transaction ordering may have changed since adding.
* @param enabled True for enabled, false for disabled.
*/
function setTransactionEnabled(uint256 index, bool enabled)
external
onlyOwner
{
require(
index < transactions.length,
"index must be in range of stored tx list"
);
transactions[index].enabled = enabled;
}
/**
* @return Number of transactions, both enabled and disabled, in transactions list.
*/
function transactionsSize() external view returns (uint256) {
return transactions.length;
}
/**
* @dev wrapper to call the encoded transactions on downstream consumers.
* @param destination Address of destination contract.
* @param data The encoded data payload.
* @return True on success
*/
function externalCall(address destination, bytes data)
internal
returns (bool)
{
bool result;
assembly {
// solhint-disable-line no-inline-assembly
// "Allocate" memory for output
// (0x40 is where "free memory" pointer is stored by convention)
let outputAddress := mload(0x40)
// First 32 bytes are the padded length of data, so exclude that
let dataAddress := add(data, 32)
result := call(
// 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB)
// + callValueTransferGas (9000) + callNewAccountGas
// (25000, in case the destination address does not exist and needs creating)
sub(gas, 34710),
destination,
0, // transfer value in wei
dataAddress,
mload(data), // Size of the input, in bytes. Stored in position 0 of the array.
outputAddress,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
}
| 74,688
|
324
|
// locks an nft in the shelf requires an issued loan
|
function lock(uint loan) external owner(loan) {
if(address(subscriber) != address(0)) {
subscriber.lockEvent(loan);
}
NFTLike(shelf[loan].registry).transferFrom(msg.sender, address(this), shelf[loan].tokenId);
emit Lock(loan);
}
|
function lock(uint loan) external owner(loan) {
if(address(subscriber) != address(0)) {
subscriber.lockEvent(loan);
}
NFTLike(shelf[loan].registry).transferFrom(msg.sender, address(this), shelf[loan].tokenId);
emit Lock(loan);
}
| 19,868
|
3
|
// bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
|
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
|
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
| 62,566
|
0
|
// {ERC721} token, including:This contract uses {AccessControl} to lock permissioned functions using the/ Creates the borrowor note contract linked to a specific loan coreThe loan core reference is non-upgradeableSee (_setURI).Grants `PAUSER_ROLE`, `MINTER_ROLE`, and `BURNER_ROLE` to the sendercontract, provided it is an instance of LoanCore. Grants `DEFAULT_ADMIN_ROLE` to the account that deploys the contract. Admins /
|
constructor(string memory name, string memory symbol) ERC721(name, symbol) ERC721Permit(name) {
_setupRole(BURNER_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
|
constructor(string memory name, string memory symbol) ERC721(name, symbol) ERC721Permit(name) {
_setupRole(BURNER_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
| 23,335
|
17
|
// Burns a specific amount of tokens from the target address and decrements allowance. from The account whose tokens will be burned. value The amount of token to be burned. /
|
function burnFrom(address from, uint256 value) public {
persistBalanceDemurrage(from);
persistTotalSupplyDemurrage();
_burnFrom(from, value);
}
|
function burnFrom(address from, uint256 value) public {
persistBalanceDemurrage(from);
persistTotalSupplyDemurrage();
_burnFrom(from, value);
}
| 53,225
|
4
|
// pick ERC2771Context over Ownable
|
function _msgSender() internal view override(Context, ERC2771Context)
|
function _msgSender() internal view override(Context, ERC2771Context)
| 27,136
|
63
|
// AllocatedEditionsStorage MirrorXYZ /
|
contract AllocatedEditionsStorage {
// ============ Structs ============
/// @notice Contains general data about the NFT.
struct NFTMetadata {
string name;
string symbol;
bytes32 contentHash;
}
/// @notice Contains information pertaining to the edition spec.
struct EditionData {
// The number of tokens pre-allocated to the minter.
uint256 allocation;
// The maximum number of tokens that can be sold.
uint256 quantity;
// The price at which each token will be sold, in ETH.
uint256 price;
}
/// @notice Contains information about funds disbursement.
struct AdminData {
// Operator of this contract, receives premint.
address operator;
// Address that receive gov tokens via treasury.
address tributary;
// The account that will receive sales revenue.
address payable fundingRecipient;
// The fee taken when withdrawing funds
uint256 feePercentage;
}
// ============ Storage for Setup ============
/// @notice NFTMetadata`
string public baseURI;
bytes32 contentHash;
/// @notice EditionData
uint256 public allocation;
uint256 public quantity;
uint256 public price;
/// @notice EditionConfig
address public operator;
address public tributary;
address payable public fundingRecipient;
uint256 feePercentage;
/// @notice Treasury Config, provided at setup, for finding the treasury address.
address treasuryConfig;
// ============ Mutable Runtime Storage ============
/// @notice `nextTokenId` increments with each token purchased, globally across all editions.
uint256 internal nextTokenId;
/// @notice The number of tokens that have moved outside of the pre-mint allocation.
uint256 internal allocationsTransferred = 0;
/**
* @notice A special mapping of burned tokens, to take care of burning within
* the tokenId range of the allocation.
*/
mapping(uint256 => bool) internal _burned;
// ============ Mutable Internal NFT Storage ============
mapping(uint256 => address) internal _owners;
mapping(address => uint256) internal _balances;
mapping(uint256 => address) internal _tokenApprovals;
mapping(address => mapping(address => bool)) internal _operatorApprovals;
/// @notice Only allow one purchase per account.
mapping(address => bool) internal purchased;
// ============ Delegation logic ============
address public logic;
// OpenSea's Proxy Registry
address public proxyRegistry;
}
|
contract AllocatedEditionsStorage {
// ============ Structs ============
/// @notice Contains general data about the NFT.
struct NFTMetadata {
string name;
string symbol;
bytes32 contentHash;
}
/// @notice Contains information pertaining to the edition spec.
struct EditionData {
// The number of tokens pre-allocated to the minter.
uint256 allocation;
// The maximum number of tokens that can be sold.
uint256 quantity;
// The price at which each token will be sold, in ETH.
uint256 price;
}
/// @notice Contains information about funds disbursement.
struct AdminData {
// Operator of this contract, receives premint.
address operator;
// Address that receive gov tokens via treasury.
address tributary;
// The account that will receive sales revenue.
address payable fundingRecipient;
// The fee taken when withdrawing funds
uint256 feePercentage;
}
// ============ Storage for Setup ============
/// @notice NFTMetadata`
string public baseURI;
bytes32 contentHash;
/// @notice EditionData
uint256 public allocation;
uint256 public quantity;
uint256 public price;
/// @notice EditionConfig
address public operator;
address public tributary;
address payable public fundingRecipient;
uint256 feePercentage;
/// @notice Treasury Config, provided at setup, for finding the treasury address.
address treasuryConfig;
// ============ Mutable Runtime Storage ============
/// @notice `nextTokenId` increments with each token purchased, globally across all editions.
uint256 internal nextTokenId;
/// @notice The number of tokens that have moved outside of the pre-mint allocation.
uint256 internal allocationsTransferred = 0;
/**
* @notice A special mapping of burned tokens, to take care of burning within
* the tokenId range of the allocation.
*/
mapping(uint256 => bool) internal _burned;
// ============ Mutable Internal NFT Storage ============
mapping(uint256 => address) internal _owners;
mapping(address => uint256) internal _balances;
mapping(uint256 => address) internal _tokenApprovals;
mapping(address => mapping(address => bool)) internal _operatorApprovals;
/// @notice Only allow one purchase per account.
mapping(address => bool) internal purchased;
// ============ Delegation logic ============
address public logic;
// OpenSea's Proxy Registry
address public proxyRegistry;
}
| 47,299
|
16
|
// Owner can withdraw tokens/tokenAddress: The address of the token to withdraw./amt: The amount to withdraw/Contract should only hold `FUEL_TOKEN_ADDRESS` tokens, but we allow withdrawing any token for safety/WARNING : manually withdrawing tokens will leave the contract underfunded.
|
function withdrawTokens(address tokenAddress, uint256 amt) public onlyOwner {
ERC20(tokenAddress).transfer(msg.sender, amt);
}
|
function withdrawTokens(address tokenAddress, uint256 amt) public onlyOwner {
ERC20(tokenAddress).transfer(msg.sender, amt);
}
| 14,246
|
2
|
// set the send() LayerZero messaging library version to _version_version - new messaging library version
|
function setSendVersion(uint16 _version) external;
|
function setSendVersion(uint16 _version) external;
| 20,013
|
75
|
// CappedWhitelistedCrowdsale Crowdsale with a limit for total contributions and per-beneficiary caps. Combination of CappedCrowdsale and IndividuallyCappedCrowdsale /
|
contract TieredPriceCrowdsale is Crowdsale {
uint256 private _baseRate;
uint256 private _tier2Start;
uint256 private _tier3Start;
uint256 private _tier4Start;
constructor(
uint256 baseRate,
uint256 openingTimeTier2,
uint256 openingTimeTier3,
uint256 openingTimeTier4
)
public
{
require(baseRate > 0);
require(openingTimeTier2 > block.timestamp);
require(openingTimeTier3 >= openingTimeTier2);
require(openingTimeTier4 >= openingTimeTier3);
_baseRate = baseRate;
_tier4Start = openingTimeTier4;
_tier3Start = openingTimeTier3;
_tier2Start = openingTimeTier2;
}
function _getbonusRate()
internal view returns (uint256)
{
// Calculate current rate with bonus
if(_tier2Start > block.timestamp){
return(_baseRate * 6 / 5);
}
else if(_tier3Start > block.timestamp){
return(_baseRate * 11 / 10);
}
else if(_tier4Start > block.timestamp){
return(_baseRate * 21 / 20);
}
else {
return(_baseRate);
}
}
/**
* @return the current bonus level.
*/
function bonusRate() public view returns(uint256) {
return _getbonusRate();
}
/**
* @param tier Value that represents the tier
* @return Timestamp when the tier starts
*/
function tierStartTime(
uint256 tier
) external view returns(uint256)
{
if(tier == 2){
return _tier2Start;
}
else if(tier == 3){
return _tier3Start;
}
else if(tier == 4){
return _tier4Start;
}
return 0;
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(
uint256 weiAmount
)
internal view returns (uint256)
{
return weiAmount.mul(_getbonusRate());
}
}
|
contract TieredPriceCrowdsale is Crowdsale {
uint256 private _baseRate;
uint256 private _tier2Start;
uint256 private _tier3Start;
uint256 private _tier4Start;
constructor(
uint256 baseRate,
uint256 openingTimeTier2,
uint256 openingTimeTier3,
uint256 openingTimeTier4
)
public
{
require(baseRate > 0);
require(openingTimeTier2 > block.timestamp);
require(openingTimeTier3 >= openingTimeTier2);
require(openingTimeTier4 >= openingTimeTier3);
_baseRate = baseRate;
_tier4Start = openingTimeTier4;
_tier3Start = openingTimeTier3;
_tier2Start = openingTimeTier2;
}
function _getbonusRate()
internal view returns (uint256)
{
// Calculate current rate with bonus
if(_tier2Start > block.timestamp){
return(_baseRate * 6 / 5);
}
else if(_tier3Start > block.timestamp){
return(_baseRate * 11 / 10);
}
else if(_tier4Start > block.timestamp){
return(_baseRate * 21 / 20);
}
else {
return(_baseRate);
}
}
/**
* @return the current bonus level.
*/
function bonusRate() public view returns(uint256) {
return _getbonusRate();
}
/**
* @param tier Value that represents the tier
* @return Timestamp when the tier starts
*/
function tierStartTime(
uint256 tier
) external view returns(uint256)
{
if(tier == 2){
return _tier2Start;
}
else if(tier == 3){
return _tier3Start;
}
else if(tier == 4){
return _tier4Start;
}
return 0;
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(
uint256 weiAmount
)
internal view returns (uint256)
{
return weiAmount.mul(_getbonusRate());
}
}
| 50,378
|
32
|
// See `IERC20PoolBorrowerActions` and `IERC721PoolBorrowerActions` for descriptions === Write state === - `SettlerActions._settleAuction` (`_removeAuction`): decrement kicker locked accumulator, increment kicker claimable accumumlator decrement auctions count accumulator update auction queue state - `Loans.update` (`_upsert`): insert or update loan in loans array remove loan from loans array update borrower in `address => borrower` mapping === Reverts on === no debt to repay `NoDebt()` borrower debt less than pool min debt `AmountLTMinDebt()` borrower not sender `BorrowerNotSender()` not enough collateral to pull `InsufficientCollateral()` limit price reached `LimitIndexExceeded()` === Emit events === - `SettlerActions._settleAuction`: `AuctionNFTSettle` or `AuctionSettle` /
|
function repayDebt(
AuctionsState storage auctions_,
mapping(uint256 => Bucket) storage buckets_,
DepositsState storage deposits_,
LoansState storage loans_,
PoolState calldata poolState_,
address borrowerAddress_,
uint256 maxQuoteTokenAmountToRepay_,
uint256 collateralAmountToPull_,
uint256 limitIndex_
|
function repayDebt(
AuctionsState storage auctions_,
mapping(uint256 => Bucket) storage buckets_,
DepositsState storage deposits_,
LoansState storage loans_,
PoolState calldata poolState_,
address borrowerAddress_,
uint256 maxQuoteTokenAmountToRepay_,
uint256 collateralAmountToPull_,
uint256 limitIndex_
| 40,222
|
33
|
// Which KIM are you selling?
|
TokenAuction storage tokenOnAuction = tokenAuction[tokenIndex];
|
TokenAuction storage tokenOnAuction = tokenAuction[tokenIndex];
| 16,472
|
49
|
// Caches aggregated values from the User->Stake[] map to save computation. If lastAccountingTimestampSec is 0, there's no entry for that user.
|
struct UserTotals {
uint256 stakingShares;
uint256 stakingShareSeconds;
uint256 lastAccountingTimestampSec;
}
|
struct UserTotals {
uint256 stakingShares;
uint256 stakingShareSeconds;
uint256 lastAccountingTimestampSec;
}
| 27,979
|
19
|
// report new approval amount
|
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
|
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
| 53,676
|
20
|
// Reward ratio between LP staker and CLA staker
|
uint256 public lpRewardRatio;
uint256 private constant CLA_REWARD_RATIO_DIVISOR = 1e12;
uint256 private constant ACC_CLA_PRECISION = 1e12;
uint256 private constant YEAR = 12 * 30 * 24 * 60 * 60; // Blocks
|
uint256 public lpRewardRatio;
uint256 private constant CLA_REWARD_RATIO_DIVISOR = 1e12;
uint256 private constant ACC_CLA_PRECISION = 1e12;
uint256 private constant YEAR = 12 * 30 * 24 * 60 * 60; // Blocks
| 3,806
|
142
|
// Add a new lp to the pool. Can only be called by the owner. DO NOT add the same LP token more than once. Rewards will be messed up if you do.
|
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate
|
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate
| 60,304
|
8
|
// ----------------------------------------------------------------------------Modifiers ----------------------------------------------------------------------------
|
modifier onlyCEO() {
require(msg.sender == CEOAddress);
_;
}
|
modifier onlyCEO() {
require(msg.sender == CEOAddress);
_;
}
| 8,353
|
4
|
// Add asset proxy and log registration.
|
assetProxies[assetProxyId] = assetProxy;
emit AssetProxySet(assetProxyId, newAssetProxy, oldAssetProxy);
|
assetProxies[assetProxyId] = assetProxy;
emit AssetProxySet(assetProxyId, newAssetProxy, oldAssetProxy);
| 48,179
|
3
|
// contextB
|
uint64 currBufferIndex;
uint40 prevResetIndex;
uint40 currResetIndex;
|
uint64 currBufferIndex;
uint40 prevResetIndex;
uint40 currResetIndex;
| 10,929
|
22
|
// We highly recommend revalidating the upkeep in the performUpkeep function
|
if ((block.timestamp - lastTimeStamp) > interval ) {
lastTimeStamp = block.timestamp;
counter = counter + 1;
pairOpponents();
}
|
if ((block.timestamp - lastTimeStamp) > interval ) {
lastTimeStamp = block.timestamp;
counter = counter + 1;
pairOpponents();
}
| 20,918
|
76
|
// Checks whether the period in which the crowdsale is open has already elapsed.return Whether crowdsale period has elapsed /
|
function hasClosed() public view returns (bool) {
return block.timestamp > _closingTime;
}
|
function hasClosed() public view returns (bool) {
return block.timestamp > _closingTime;
}
| 11,353
|
208
|
// buildDeck();
|
string memory cardone = getCardOne(tokenId);
|
string memory cardone = getCardOne(tokenId);
| 8,337
|
241
|
// Restrict approvals to OPERATOR_ROLE members
|
bool private _tradingRestricted = false;
|
bool private _tradingRestricted = false;
| 72,699
|
3
|
// extension node
|
require(_nibblesToTraverse(Rlp.toData(currentNodeList[0]), nibblePath, pathPtr) != 0, "invalid extension node");
nodeKey = Rlp.toBytes32(currentNodeList[1]);
|
require(_nibblesToTraverse(Rlp.toData(currentNodeList[0]), nibblePath, pathPtr) != 0, "invalid extension node");
nodeKey = Rlp.toBytes32(currentNodeList[1]);
| 19,625
|
10
|
// reward factory only allow this to be called once even if ownerremoves ability to inject malicious staking contractstoken factory can also be immutable
|
if (rewardFactory == address(0)) {
rewardFactory = _rfactory;
tokenFactory = _tfactory;
}
|
if (rewardFactory == address(0)) {
rewardFactory = _rfactory;
tokenFactory = _tfactory;
}
| 9,808
|
16
|
// Public airdrop of tokens to _other_ addresses/to list of addresses to airdrop to
|
function airdrop(address[] memory to) public {
require(mintIsOpen(), "Mint not open");
for (uint256 i = 0; i < to.length; i++) {
_mint(to[i], currentTokenId.current());
currentTokenId.increment();
}
}
|
function airdrop(address[] memory to) public {
require(mintIsOpen(), "Mint not open");
for (uint256 i = 0; i < to.length; i++) {
_mint(to[i], currentTokenId.current());
currentTokenId.increment();
}
}
| 36,754
|
114
|
// transfers ether from smartcontract to zebiwallet
|
function withdraw(uint256 _value) public onlyOwner {
wallet.transfer(_value);
Withdraw(_value);
}
|
function withdraw(uint256 _value) public onlyOwner {
wallet.transfer(_value);
Withdraw(_value);
}
| 25,556
|
50
|
// F1 - F10: OK C1 - C24: OK
|
function bridgeFor(address token) public view returns (address bridge) {
bridge = _bridges[token];
if (bridge == address(0)) {
bridge = wavax;
}
}
|
function bridgeFor(address token) public view returns (address bridge) {
bridge = _bridges[token];
if (bridge == address(0)) {
bridge = wavax;
}
}
| 7,178
|
2
|
// initial balance to dev wallet to be split between vendor contract and staking rewards contract
|
uint _dev_Marketing_Tokens = 10000000;//10000000 to dev to be left with 100000
uint _thiscontract_Tokens = 5000000;//10000000 to dev to be left with 100000
_approve(address(this), address(dev_marketing_wallet), _dev_Marketing_Tokens);
|
uint _dev_Marketing_Tokens = 10000000;//10000000 to dev to be left with 100000
uint _thiscontract_Tokens = 5000000;//10000000 to dev to be left with 100000
_approve(address(this), address(dev_marketing_wallet), _dev_Marketing_Tokens);
| 25,933
|
20
|
// emit NewLog(id, _signature, _hashOfMessage);
|
emit NewLog(id, _signature, _encryptedMessage);
return true;
|
emit NewLog(id, _signature, _encryptedMessage);
return true;
| 29,808
|
168
|
// withdraw everything from the strategy to accurately check the share value
|
if (numberOfShares == totalSupply) {
(bool status,) = bridgeStrategy.delegatecall(abi.encodeWithSelector(IBridgeStrategy(bridgeStrategy).withdrawAllToVault.selector, strategy));
require(status, "V:17");
} else {
|
if (numberOfShares == totalSupply) {
(bool status,) = bridgeStrategy.delegatecall(abi.encodeWithSelector(IBridgeStrategy(bridgeStrategy).withdrawAllToVault.selector, strategy));
require(status, "V:17");
} else {
| 1,154
|
66
|
// Contract symbol
|
string public symbol = "TIGERLIST";
|
string public symbol = "TIGERLIST";
| 44,327
|
20
|
// Execute swaps
|
for (uint256 i = 0; i < tokens.length; i++) {
if (tokens[i] != token) {
uint256 balance = IERC20(tokens[i]).balanceOf(address(this));
if (balance > 0) {
uint256[] memory amountsOut = _router.getAmountsOut(balance, paths[i]);
_handlePath(
paths[i],
balance,
|
for (uint256 i = 0; i < tokens.length; i++) {
if (tokens[i] != token) {
uint256 balance = IERC20(tokens[i]).balanceOf(address(this));
if (balance > 0) {
uint256[] memory amountsOut = _router.getAmountsOut(balance, paths[i]);
_handlePath(
paths[i],
balance,
| 26,495
|
165
|
// Returns a newly allocated string containing the concatenation of `self` and `other`. self The first slice to concatenate. other The second slice to concatenate.return The concatenation of the two strings. /
|
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
|
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
| 38,227
|
51
|
// Swap - A StableSwap implementation in solidity. This contract is responsible for custody of closely pegged assets (eg. group of stablecoins)and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokensin desired ratios for an exchange of the pool token that represents their share of the pool.Users can burn pool tokens and withdraw their share of token(s). Each time a swap between the pooled tokens happens, a set fee incurs which effectively getsdistributed to the LPs. In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - whichstops the ratio of the tokens
|
contract Mobius_atUST_Swap is OwnerPausable, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using MathUtils for uint256;
using SwapUtils for SwapUtils.Swap;
// Struct storing data responsible for automatic market maker functionalities. In order to
// access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol
SwapUtils.Swap public swapStorage;
// Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool.
// getTokenIndex function also relies on this mapping to retrieve token index.
mapping(address => uint8) private tokenIndexes;
/*** 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,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event RemoveLiquidity(
address indexed provider,
uint256[] tokenAmounts,
uint256 lpTokenSupply
);
event RemoveLiquidityOne(
address indexed provider,
uint256 lpTokenAmount,
uint256 lpTokenSupply,
uint256 boughtId,
uint256 tokensBought
);
event RemoveLiquidityImbalance(
address indexed provider,
uint256[] tokenAmounts,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event NewAdminFee(uint256 newAdminFee);
event NewSwapFee(uint256 newSwapFee);
event NewDepositFee(uint256 newDepositFee);
event NewWithdrawFee(uint256 newWithdrawFee);
event RampA(
uint256 oldA,
uint256 newA,
uint256 initialTime,
uint256 futureTime
);
event StopRampA(uint256 currentA, uint256 time);
/**
* @notice Deploys this Swap contract with given parameters as default
* values. This will also deploy a LPToken that represents users
* LP position. The owner of LPToken will be this contract - which means
* only this contract is allowed to mint new tokens.
*
* @param _pooledTokens an array of ERC20s this pool will accept
* @param decimals the decimals to use for each pooled token,
* eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS
* @param lpTokenName the long-form name of the token to be deployed
* @param lpTokenSymbol the short symbol for the token to be deployed
* @param _a the amplification coefficient * n * (n - 1). See the
* StableSwap paper for details
* @param _fee default swap fee to be initialized with
* @param _adminFee default adminFee to be initialized with
* @param _depositFee default depositFee to be initialized with
* @param _withdrawFee default withdrawFee to be initialized with
* @param _devaddr default _devaddr to be initialized with
*/
constructor(
IERC20[] memory _pooledTokens,
uint8[] memory decimals,
string memory lpTokenName,
string memory lpTokenSymbol,
uint256 _a,
uint256 _fee,
uint256 _adminFee,
uint256 _depositFee,
uint256 _withdrawFee,
address _devaddr
) public OwnerPausable() ReentrancyGuard() {
// Check _pooledTokens and precisions parameter
require(_pooledTokens.length > 1, "_pooledTokens.length <= 1");
require(_pooledTokens.length <= 32, "_pooledTokens.length > 32");
require(
_pooledTokens.length == decimals.length,
"_pooledTokens decimals mismatch"
);
uint256[] memory precisionMultipliers = new uint256[](decimals.length);
for (uint8 i = 0; i < _pooledTokens.length; i++) {
if (i > 0) {
// Check if index is already used. Check if 0th element is a duplicate.
require(
tokenIndexes[address(_pooledTokens[i])] == 0 &&
_pooledTokens[0] != _pooledTokens[i],
"Duplicate tokens"
);
}
require(
address(_pooledTokens[i]) != address(0),
"The 0 address isn't an ERC-20"
);
require(
decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS,
"Token decimals exceeds max"
);
precisionMultipliers[i] =
10 **
uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub(
uint256(decimals[i])
);
tokenIndexes[address(_pooledTokens[i])] = i;
}
// Check _a, _fee, _adminFee, _depositFee, _withdrawFee
require(_a < SwapUtils.MAX_A, "_a exceeds maximum");
require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum");
require(
_adminFee < SwapUtils.MAX_ADMIN_FEE,
"_adminFee exceeds maximum"
);
require(
_withdrawFee < SwapUtils.MAX_WITHDRAW_FEE,
"_withdrawFee exceeds maximum"
);
require(
_depositFee < SwapUtils.MAX_DEPOSIT_FEE,
"_depositFee exceeds maximum"
);
// Initialize swapStorage struct
swapStorage.lpToken = new LPToken(
lpTokenName,
lpTokenSymbol,
SwapUtils.POOL_PRECISION_DECIMALS
);
swapStorage.pooledTokens = _pooledTokens;
swapStorage.tokenPrecisionMultipliers = precisionMultipliers;
swapStorage.balances = new uint256[](_pooledTokens.length);
swapStorage.initialA = _a.mul(SwapUtils.A_PRECISION);
swapStorage.futureA = _a.mul(SwapUtils.A_PRECISION);
swapStorage.initialATime = 0;
swapStorage.futureATime = 0;
swapStorage.swapFee = _fee;
swapStorage.adminFee = _adminFee;
swapStorage.defaultDepositFee = _depositFee;
swapStorage.defaultWithdrawFee = _withdrawFee;
swapStorage.devaddr = _devaddr;
}
/*** MODIFIERS ***/
/**
* @notice Modifier to check deadline against current timestamp
* @param deadline latest timestamp to accept this transaction
*/
modifier deadlineCheck(uint256 deadline) {
require(block.timestamp <= deadline, "Deadline not met");
_;
}
/*** VIEW FUNCTIONS ***/
/**
* @notice Return A, the amplification coefficient * n * (n - 1)
* @dev See the StableSwap paper for details
* @return A parameter
*/
function getA() external view returns (uint256) {
return swapStorage.getA();
}
/**
* @notice Return A in its raw precision form
* @dev See the StableSwap paper for details
* @return A parameter in its raw precision form
*/
function getAPrecise() external view returns (uint256) {
return swapStorage.getAPrecise();
}
/**
* @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range.
* @param index the index of the token
* @return address of the token at given index
*/
function getToken(uint8 index) public view returns (IERC20) {
require(index < swapStorage.pooledTokens.length, "Out of range");
return swapStorage.pooledTokens[index];
}
/**
* @notice Return the index of the given token address. Reverts if no matching
* token is found.
* @param tokenAddress address of the token
* @return the index of the given token address
*/
function getTokenIndex(address tokenAddress) external view returns (uint8) {
uint8 index = tokenIndexes[tokenAddress];
require(
address(getToken(index)) == tokenAddress,
"Token does not exist"
);
return index;
}
/**
* @notice Return timestamp of last deposit of given address
* @return timestamp of the last deposit made by the given address
*/
function getDepositTimestamp(address user) external view returns (uint256) {
return swapStorage.getDepositTimestamp(user);
}
/**
* @notice Return current balance of the pooled token at given index
* @param index the index of the token
* @return current balance of the pooled token at given index with token's native precision
*/
function getTokenBalance(uint8 index) external view returns (uint256) {
require(index < swapStorage.pooledTokens.length, "Index out of range");
return swapStorage.balances[index];
}
/**
* @notice Return balances of pooled tokens
* @return current balances of all tokens in pool
*/
function getBalances() external view returns (uint256[] memory) {
return swapStorage.balances;
}
/**
@notice Returns the swap fee
@return current swap fee
*/
function getSwapFee() external view returns (uint256) {
return swapStorage.swapFee;
}
/**
@notice Returns address of lp token
@return address of lp token
*/
function getLpToken() external view returns (address) {
return address(swapStorage.lpToken);
}
/**
* @notice Get the virtual price, to help calculate profit
* @return the virtual price, scaled to the POOL_PRECISION_DECIMALS
*/
function getVirtualPrice() external view returns (uint256) {
return swapStorage.getVirtualPrice();
}
/**
* @notice Calculate amount of tokens you receive on swap
* @param tokenIndexFrom the token the user wants to sell
* @param tokenIndexTo the token the user wants to buy
* @param dx the amount of tokens the user wants to sell. If the token charges
* a fee on transfers, use the amount that gets transferred after the fee.
* @return amount of tokens the user will receive
*/
function calculateSwap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256) {
return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx);
}
/**
* @notice A simple method to calculate prices from deposits or
* withdrawals, excluding fees but including slippage. This is
* helpful as an input into the various "min" parameters on calls
* to fight front-running
*
* @dev This shouldn't be used outside frontends for user estimates.
*
* @param account address that is depositing or withdrawing tokens
* @param amounts an array of token amounts to deposit or withdrawal,
* corresponding to pooledTokens. The amount should be in each
* pooled token's native precision. If a token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @param deposit whether this is a deposit or a withdrawal
* @return token amount the user will receive
*/
function calculateTokenAmount(
address account,
uint256[] calldata amounts,
bool deposit
) external view returns (uint256) {
return swapStorage.calculateTokenAmount(account, amounts, deposit);
}
/**
* @notice A simple method to calculate amount of each underlying
* tokens that is returned upon burning given amount of LP tokens
* @param account the address that is withdrawing tokens
* @param amount the amount of LP tokens that would be burned on withdrawal
* @return array of token balances that the user will receive
*/
function calculateRemoveLiquidity(address account, uint256 amount)
external
view
returns (uint256[] memory)
{
return swapStorage.calculateRemoveLiquidity(account, amount);
}
/**
* @notice Calculate the amount of underlying token available to withdraw
* when withdrawing via only single token
* @param account the address that is withdrawing tokens
* @param tokenAmount the amount of LP token to burn
* @param tokenIndex index of which token will be withdrawn
* @return availableTokenAmount calculated amount of underlying token
* available to withdraw
*/
function calculateRemoveLiquidityOneToken(
address account,
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256 availableTokenAmount) {
(availableTokenAmount, ) = swapStorage.calculateWithdrawOneToken(
account,
tokenAmount,
tokenIndex
);
}
/**
* @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee
* decays linearly over period of 4 weeks. For example, depositing and withdrawing right away
* will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you
* no additional fees.
* @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals
* @param user address you want to calculate withdraw fee of
* @return current withdraw fee of the user
*/
function calculateCurrentWithdrawFee(address user)
external
view
returns (uint256)
{
return swapStorage.calculateCurrentWithdrawFee(user);
}
/**
* @notice This function reads the accumulated amount of admin fees of the token with given index
* @param index Index of the pooled token
* @return admin's token balance in the token's precision
*/
function getAdminBalance(uint256 index) external view returns (uint256) {
return swapStorage.getAdminBalance(index);
}
/*** STATE MODIFYING FUNCTIONS ***/
/**
* @notice Swap two tokens using this pool
* @param tokenIndexFrom the token the user wants to swap from
* @param tokenIndexTo the token the user wants to swap to
* @param dx the amount of tokens the user wants to swap from
* @param minDy the min amount the user would like to receive, or revert.
* @param deadline latest timestamp to accept this transaction
*/
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
)
external
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy);
}
/**
* @notice Add liquidity to the pool with given amounts
* @param amounts the amounts of each token to add, in their native precision
* @param minToMint the minimum LP tokens adding this amount of liquidity
* should mint, otherwise revert. Handy for front-running mitigation
* @param deadline latest timestamp to accept this transaction
* @return amount of LP token user minted and received
*/
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
)
external
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return swapStorage.addLiquidity(amounts, minToMint);
}
/**
* @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @dev Liquidity can always be removed, even when the pool is paused.
* @param amount the amount of LP tokens to burn
* @param minAmounts the minimum amounts of each token in the pool
* acceptable for this burn. Useful as a front-running mitigation
* @param deadline latest timestamp to accept this transaction
* @return amounts of tokens user received
*/
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external nonReentrant deadlineCheck(deadline) returns (uint256[] memory) {
return swapStorage.removeLiquidity(amount, minAmounts);
}
/**
* @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @param tokenAmount the amount of the token you want to receive
* @param tokenIndex the index of the token you want to receive
* @param minAmount the minimum amount to withdraw, otherwise revert
* @param deadline latest timestamp to accept this transaction
* @return amount of chosen token user received
*/
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
)
external
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return
swapStorage.removeLiquidityOneToken(
tokenAmount,
tokenIndex,
minAmount
);
}
/**
* @notice Remove liquidity from the pool, weighted differently than the
* pool's current balances. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @param amounts how much of each token to withdraw
* @param maxBurnAmount the max LP token provider is willing to pay to
* remove liquidity. Useful as a front-running mitigation.
* @param deadline latest timestamp to accept this transaction
* @return amount of LP tokens burned
*/
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
)
external
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount);
}
/*** ADMIN FUNCTIONS ***/
/**
* @notice Updates the user withdraw fee. This function can only be called by
* the pool token. Should be used to update the withdraw fee on transfer of pool tokens.
* Transferring your pool token will reset the 4 weeks period. If the recipient is already
* holding some pool tokens, the withdraw fee will be discounted in respective amounts.
* @param recipient address of the recipient of pool token
* @param transferAmount amount of pool token to transfer
*/
function updateUserWithdrawFee(address recipient, uint256 transferAmount)
external
{
require(
msg.sender == address(swapStorage.lpToken),
"Only callable by pool token"
);
swapStorage.updateUserWithdrawFee(recipient, transferAmount);
}
/**
* @notice Withdraw all admin fees to the contract owner
*/
function withdrawAdminFees() external onlyOwner {
swapStorage.withdrawAdminFees(owner());
}
/**
* @notice Update the admin fee. Admin fee takes portion of the swap fee.
* @param newAdminFee new admin fee to be applied on future transactions
*/
function setAdminFee(uint256 newAdminFee) external onlyOwner {
swapStorage.setAdminFee(newAdminFee);
}
/**
* @notice Update the swap fee to be applied on swaps
* @param newSwapFee new swap fee to be applied on future transactions
*/
function setSwapFee(uint256 newSwapFee) external onlyOwner {
swapStorage.setSwapFee(newSwapFee);
}
/**
* @notice Update the deposit fee.
* @param newDepositFee new deposit fee to be applied on future deposits
*/
function setDefaultDepositFee(uint256 newDepositFee) external onlyOwner {
swapStorage.setDefaultDepositFee(newDepositFee);
}
/**
* @notice Update the withdraw fee. This fee decays linearly over 4 weeks since
* user's last deposit.
* @param newWithdrawFee new withdraw fee to be applied on future deposits
*/
function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner {
swapStorage.setDefaultWithdrawFee(newWithdrawFee);
}
/**
* @notice Start ramping up or down A parameter towards given futureA and futureTime
* Checks if the change is too rapid, and commits the new A value only when it falls under
* the limit range.
* @param futureA the new A to ramp towards
* @param futureTime timestamp when the new A should be reached
*/
function rampA(uint256 futureA, uint256 futureTime) external onlyOwner {
swapStorage.rampA(futureA, futureTime);
}
/**
* @notice Stop ramping A immediately. Reverts if ramp A is already stopped.
*/
function stopRampA() external onlyOwner {
swapStorage.stopRampA();
}
// Update dev address by the previous dev.
function setDevAddress(address _devaddr) external onlyOwner {
swapStorage.setDevAddress(_devaddr);
}
}
|
contract Mobius_atUST_Swap is OwnerPausable, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using MathUtils for uint256;
using SwapUtils for SwapUtils.Swap;
// Struct storing data responsible for automatic market maker functionalities. In order to
// access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol
SwapUtils.Swap public swapStorage;
// Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool.
// getTokenIndex function also relies on this mapping to retrieve token index.
mapping(address => uint8) private tokenIndexes;
/*** 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,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event RemoveLiquidity(
address indexed provider,
uint256[] tokenAmounts,
uint256 lpTokenSupply
);
event RemoveLiquidityOne(
address indexed provider,
uint256 lpTokenAmount,
uint256 lpTokenSupply,
uint256 boughtId,
uint256 tokensBought
);
event RemoveLiquidityImbalance(
address indexed provider,
uint256[] tokenAmounts,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event NewAdminFee(uint256 newAdminFee);
event NewSwapFee(uint256 newSwapFee);
event NewDepositFee(uint256 newDepositFee);
event NewWithdrawFee(uint256 newWithdrawFee);
event RampA(
uint256 oldA,
uint256 newA,
uint256 initialTime,
uint256 futureTime
);
event StopRampA(uint256 currentA, uint256 time);
/**
* @notice Deploys this Swap contract with given parameters as default
* values. This will also deploy a LPToken that represents users
* LP position. The owner of LPToken will be this contract - which means
* only this contract is allowed to mint new tokens.
*
* @param _pooledTokens an array of ERC20s this pool will accept
* @param decimals the decimals to use for each pooled token,
* eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS
* @param lpTokenName the long-form name of the token to be deployed
* @param lpTokenSymbol the short symbol for the token to be deployed
* @param _a the amplification coefficient * n * (n - 1). See the
* StableSwap paper for details
* @param _fee default swap fee to be initialized with
* @param _adminFee default adminFee to be initialized with
* @param _depositFee default depositFee to be initialized with
* @param _withdrawFee default withdrawFee to be initialized with
* @param _devaddr default _devaddr to be initialized with
*/
constructor(
IERC20[] memory _pooledTokens,
uint8[] memory decimals,
string memory lpTokenName,
string memory lpTokenSymbol,
uint256 _a,
uint256 _fee,
uint256 _adminFee,
uint256 _depositFee,
uint256 _withdrawFee,
address _devaddr
) public OwnerPausable() ReentrancyGuard() {
// Check _pooledTokens and precisions parameter
require(_pooledTokens.length > 1, "_pooledTokens.length <= 1");
require(_pooledTokens.length <= 32, "_pooledTokens.length > 32");
require(
_pooledTokens.length == decimals.length,
"_pooledTokens decimals mismatch"
);
uint256[] memory precisionMultipliers = new uint256[](decimals.length);
for (uint8 i = 0; i < _pooledTokens.length; i++) {
if (i > 0) {
// Check if index is already used. Check if 0th element is a duplicate.
require(
tokenIndexes[address(_pooledTokens[i])] == 0 &&
_pooledTokens[0] != _pooledTokens[i],
"Duplicate tokens"
);
}
require(
address(_pooledTokens[i]) != address(0),
"The 0 address isn't an ERC-20"
);
require(
decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS,
"Token decimals exceeds max"
);
precisionMultipliers[i] =
10 **
uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub(
uint256(decimals[i])
);
tokenIndexes[address(_pooledTokens[i])] = i;
}
// Check _a, _fee, _adminFee, _depositFee, _withdrawFee
require(_a < SwapUtils.MAX_A, "_a exceeds maximum");
require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum");
require(
_adminFee < SwapUtils.MAX_ADMIN_FEE,
"_adminFee exceeds maximum"
);
require(
_withdrawFee < SwapUtils.MAX_WITHDRAW_FEE,
"_withdrawFee exceeds maximum"
);
require(
_depositFee < SwapUtils.MAX_DEPOSIT_FEE,
"_depositFee exceeds maximum"
);
// Initialize swapStorage struct
swapStorage.lpToken = new LPToken(
lpTokenName,
lpTokenSymbol,
SwapUtils.POOL_PRECISION_DECIMALS
);
swapStorage.pooledTokens = _pooledTokens;
swapStorage.tokenPrecisionMultipliers = precisionMultipliers;
swapStorage.balances = new uint256[](_pooledTokens.length);
swapStorage.initialA = _a.mul(SwapUtils.A_PRECISION);
swapStorage.futureA = _a.mul(SwapUtils.A_PRECISION);
swapStorage.initialATime = 0;
swapStorage.futureATime = 0;
swapStorage.swapFee = _fee;
swapStorage.adminFee = _adminFee;
swapStorage.defaultDepositFee = _depositFee;
swapStorage.defaultWithdrawFee = _withdrawFee;
swapStorage.devaddr = _devaddr;
}
/*** MODIFIERS ***/
/**
* @notice Modifier to check deadline against current timestamp
* @param deadline latest timestamp to accept this transaction
*/
modifier deadlineCheck(uint256 deadline) {
require(block.timestamp <= deadline, "Deadline not met");
_;
}
/*** VIEW FUNCTIONS ***/
/**
* @notice Return A, the amplification coefficient * n * (n - 1)
* @dev See the StableSwap paper for details
* @return A parameter
*/
function getA() external view returns (uint256) {
return swapStorage.getA();
}
/**
* @notice Return A in its raw precision form
* @dev See the StableSwap paper for details
* @return A parameter in its raw precision form
*/
function getAPrecise() external view returns (uint256) {
return swapStorage.getAPrecise();
}
/**
* @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range.
* @param index the index of the token
* @return address of the token at given index
*/
function getToken(uint8 index) public view returns (IERC20) {
require(index < swapStorage.pooledTokens.length, "Out of range");
return swapStorage.pooledTokens[index];
}
/**
* @notice Return the index of the given token address. Reverts if no matching
* token is found.
* @param tokenAddress address of the token
* @return the index of the given token address
*/
function getTokenIndex(address tokenAddress) external view returns (uint8) {
uint8 index = tokenIndexes[tokenAddress];
require(
address(getToken(index)) == tokenAddress,
"Token does not exist"
);
return index;
}
/**
* @notice Return timestamp of last deposit of given address
* @return timestamp of the last deposit made by the given address
*/
function getDepositTimestamp(address user) external view returns (uint256) {
return swapStorage.getDepositTimestamp(user);
}
/**
* @notice Return current balance of the pooled token at given index
* @param index the index of the token
* @return current balance of the pooled token at given index with token's native precision
*/
function getTokenBalance(uint8 index) external view returns (uint256) {
require(index < swapStorage.pooledTokens.length, "Index out of range");
return swapStorage.balances[index];
}
/**
* @notice Return balances of pooled tokens
* @return current balances of all tokens in pool
*/
function getBalances() external view returns (uint256[] memory) {
return swapStorage.balances;
}
/**
@notice Returns the swap fee
@return current swap fee
*/
function getSwapFee() external view returns (uint256) {
return swapStorage.swapFee;
}
/**
@notice Returns address of lp token
@return address of lp token
*/
function getLpToken() external view returns (address) {
return address(swapStorage.lpToken);
}
/**
* @notice Get the virtual price, to help calculate profit
* @return the virtual price, scaled to the POOL_PRECISION_DECIMALS
*/
function getVirtualPrice() external view returns (uint256) {
return swapStorage.getVirtualPrice();
}
/**
* @notice Calculate amount of tokens you receive on swap
* @param tokenIndexFrom the token the user wants to sell
* @param tokenIndexTo the token the user wants to buy
* @param dx the amount of tokens the user wants to sell. If the token charges
* a fee on transfers, use the amount that gets transferred after the fee.
* @return amount of tokens the user will receive
*/
function calculateSwap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256) {
return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx);
}
/**
* @notice A simple method to calculate prices from deposits or
* withdrawals, excluding fees but including slippage. This is
* helpful as an input into the various "min" parameters on calls
* to fight front-running
*
* @dev This shouldn't be used outside frontends for user estimates.
*
* @param account address that is depositing or withdrawing tokens
* @param amounts an array of token amounts to deposit or withdrawal,
* corresponding to pooledTokens. The amount should be in each
* pooled token's native precision. If a token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @param deposit whether this is a deposit or a withdrawal
* @return token amount the user will receive
*/
function calculateTokenAmount(
address account,
uint256[] calldata amounts,
bool deposit
) external view returns (uint256) {
return swapStorage.calculateTokenAmount(account, amounts, deposit);
}
/**
* @notice A simple method to calculate amount of each underlying
* tokens that is returned upon burning given amount of LP tokens
* @param account the address that is withdrawing tokens
* @param amount the amount of LP tokens that would be burned on withdrawal
* @return array of token balances that the user will receive
*/
function calculateRemoveLiquidity(address account, uint256 amount)
external
view
returns (uint256[] memory)
{
return swapStorage.calculateRemoveLiquidity(account, amount);
}
/**
* @notice Calculate the amount of underlying token available to withdraw
* when withdrawing via only single token
* @param account the address that is withdrawing tokens
* @param tokenAmount the amount of LP token to burn
* @param tokenIndex index of which token will be withdrawn
* @return availableTokenAmount calculated amount of underlying token
* available to withdraw
*/
function calculateRemoveLiquidityOneToken(
address account,
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256 availableTokenAmount) {
(availableTokenAmount, ) = swapStorage.calculateWithdrawOneToken(
account,
tokenAmount,
tokenIndex
);
}
/**
* @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee
* decays linearly over period of 4 weeks. For example, depositing and withdrawing right away
* will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you
* no additional fees.
* @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals
* @param user address you want to calculate withdraw fee of
* @return current withdraw fee of the user
*/
function calculateCurrentWithdrawFee(address user)
external
view
returns (uint256)
{
return swapStorage.calculateCurrentWithdrawFee(user);
}
/**
* @notice This function reads the accumulated amount of admin fees of the token with given index
* @param index Index of the pooled token
* @return admin's token balance in the token's precision
*/
function getAdminBalance(uint256 index) external view returns (uint256) {
return swapStorage.getAdminBalance(index);
}
/*** STATE MODIFYING FUNCTIONS ***/
/**
* @notice Swap two tokens using this pool
* @param tokenIndexFrom the token the user wants to swap from
* @param tokenIndexTo the token the user wants to swap to
* @param dx the amount of tokens the user wants to swap from
* @param minDy the min amount the user would like to receive, or revert.
* @param deadline latest timestamp to accept this transaction
*/
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
)
external
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy);
}
/**
* @notice Add liquidity to the pool with given amounts
* @param amounts the amounts of each token to add, in their native precision
* @param minToMint the minimum LP tokens adding this amount of liquidity
* should mint, otherwise revert. Handy for front-running mitigation
* @param deadline latest timestamp to accept this transaction
* @return amount of LP token user minted and received
*/
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
)
external
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return swapStorage.addLiquidity(amounts, minToMint);
}
/**
* @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @dev Liquidity can always be removed, even when the pool is paused.
* @param amount the amount of LP tokens to burn
* @param minAmounts the minimum amounts of each token in the pool
* acceptable for this burn. Useful as a front-running mitigation
* @param deadline latest timestamp to accept this transaction
* @return amounts of tokens user received
*/
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external nonReentrant deadlineCheck(deadline) returns (uint256[] memory) {
return swapStorage.removeLiquidity(amount, minAmounts);
}
/**
* @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @param tokenAmount the amount of the token you want to receive
* @param tokenIndex the index of the token you want to receive
* @param minAmount the minimum amount to withdraw, otherwise revert
* @param deadline latest timestamp to accept this transaction
* @return amount of chosen token user received
*/
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
)
external
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return
swapStorage.removeLiquidityOneToken(
tokenAmount,
tokenIndex,
minAmount
);
}
/**
* @notice Remove liquidity from the pool, weighted differently than the
* pool's current balances. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @param amounts how much of each token to withdraw
* @param maxBurnAmount the max LP token provider is willing to pay to
* remove liquidity. Useful as a front-running mitigation.
* @param deadline latest timestamp to accept this transaction
* @return amount of LP tokens burned
*/
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
)
external
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount);
}
/*** ADMIN FUNCTIONS ***/
/**
* @notice Updates the user withdraw fee. This function can only be called by
* the pool token. Should be used to update the withdraw fee on transfer of pool tokens.
* Transferring your pool token will reset the 4 weeks period. If the recipient is already
* holding some pool tokens, the withdraw fee will be discounted in respective amounts.
* @param recipient address of the recipient of pool token
* @param transferAmount amount of pool token to transfer
*/
function updateUserWithdrawFee(address recipient, uint256 transferAmount)
external
{
require(
msg.sender == address(swapStorage.lpToken),
"Only callable by pool token"
);
swapStorage.updateUserWithdrawFee(recipient, transferAmount);
}
/**
* @notice Withdraw all admin fees to the contract owner
*/
function withdrawAdminFees() external onlyOwner {
swapStorage.withdrawAdminFees(owner());
}
/**
* @notice Update the admin fee. Admin fee takes portion of the swap fee.
* @param newAdminFee new admin fee to be applied on future transactions
*/
function setAdminFee(uint256 newAdminFee) external onlyOwner {
swapStorage.setAdminFee(newAdminFee);
}
/**
* @notice Update the swap fee to be applied on swaps
* @param newSwapFee new swap fee to be applied on future transactions
*/
function setSwapFee(uint256 newSwapFee) external onlyOwner {
swapStorage.setSwapFee(newSwapFee);
}
/**
* @notice Update the deposit fee.
* @param newDepositFee new deposit fee to be applied on future deposits
*/
function setDefaultDepositFee(uint256 newDepositFee) external onlyOwner {
swapStorage.setDefaultDepositFee(newDepositFee);
}
/**
* @notice Update the withdraw fee. This fee decays linearly over 4 weeks since
* user's last deposit.
* @param newWithdrawFee new withdraw fee to be applied on future deposits
*/
function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner {
swapStorage.setDefaultWithdrawFee(newWithdrawFee);
}
/**
* @notice Start ramping up or down A parameter towards given futureA and futureTime
* Checks if the change is too rapid, and commits the new A value only when it falls under
* the limit range.
* @param futureA the new A to ramp towards
* @param futureTime timestamp when the new A should be reached
*/
function rampA(uint256 futureA, uint256 futureTime) external onlyOwner {
swapStorage.rampA(futureA, futureTime);
}
/**
* @notice Stop ramping A immediately. Reverts if ramp A is already stopped.
*/
function stopRampA() external onlyOwner {
swapStorage.stopRampA();
}
// Update dev address by the previous dev.
function setDevAddress(address _devaddr) external onlyOwner {
swapStorage.setDevAddress(_devaddr);
}
}
| 24,646
|
37
|
// addListing(): add a point to the registry, including its corresponding price and owner address. optional reserved buyer address can be included.
|
function addListing(uint32 _point, uint96 _price, address _reservedBuyer) external
|
function addListing(uint32 _point, uint96 _price, address _reservedBuyer) external
| 36,110
|
2
|
// ERC-20 Transfer event
|
event Transfer(address indexed from, address indexed to, uint256 tokens);
|
event Transfer(address indexed from, address indexed to, uint256 tokens);
| 36,609
|
128
|
// Override to prevent immediate delivery of tokens.
|
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
|
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
| 8,002
|
44
|
// makes an attempt to set an account to the list of known ones, for mining Limbo 0 address will not be added
|
function TryAddToAccountList(address account) internal {
if (account == address(0) || _existInSet[account]) return;
_existInSet[account] = true;
_SetOfAccounts.push(account);
}
|
function TryAddToAccountList(address account) internal {
if (account == address(0) || _existInSet[account]) return;
_existInSet[account] = true;
_SetOfAccounts.push(account);
}
| 23,340
|
197
|
// Function setOpenSaleActive to activate/desactivate the opensale/
|
function setOpenSaleActive(
bool _isActive
)
external
onlyOwner
|
function setOpenSaleActive(
bool _isActive
)
external
onlyOwner
| 10,979
|
50
|
// TokenVault TokenVault is a token holder contract that will allow abeneficiary to spend the tokens from some function of a specified ERC20 token /
|
contract TokenVault {
using SafeERC20 for ERC20;
// ERC20 token contract being held
ERC20 public token;
constructor(ERC20 _token) {
require(address(_token) != address(0), "Token is zero address");
token = _token;
}
/**
* @notice Allow the token itself to send tokens
* using transferFrom().
*/
function fillUpAllowance() external returns(bool){
uint256 amount = token.balanceOf(address(this));
require(amount > 0, "Amount is zero");
token.approve(address(token), amount);
return true;
}
}
|
contract TokenVault {
using SafeERC20 for ERC20;
// ERC20 token contract being held
ERC20 public token;
constructor(ERC20 _token) {
require(address(_token) != address(0), "Token is zero address");
token = _token;
}
/**
* @notice Allow the token itself to send tokens
* using transferFrom().
*/
function fillUpAllowance() external returns(bool){
uint256 amount = token.balanceOf(address(this));
require(amount > 0, "Amount is zero");
token.approve(address(token), amount);
return true;
}
}
| 17,466
|
24
|
// The initial COMP index for a market
|
uint224 public constant compInitialIndex = 1e36;
|
uint224 public constant compInitialIndex = 1e36;
| 14,022
|
23
|
// reduce the sender balance by the amount he sends
|
senderBalance -= _value;
balances[msg.sender] = senderBalance;
|
senderBalance -= _value;
balances[msg.sender] = senderBalance;
| 41,552
|
1
|
// deposit eth on behalf of proxy
|
DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount));
|
DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount));
| 14,932
|
28
|
// Total token supply.
|
function totalSupply() public pure returns (uint256) {
return 1;
}
|
function totalSupply() public pure returns (uint256) {
return 1;
}
| 75,459
|
400
|
// EIP-712 typehash for token approval via EIP-2612 permit.
|
bytes32 public constant PERMIT_TYPEHASH = keccak256(
'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'
);
|
bytes32 public constant PERMIT_TYPEHASH = keccak256(
'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'
);
| 43,948
|
130
|
// redeem bond for user_recipient address_stake bool return uint /
|
function redeem( address _recipient, bool _stake ) external returns ( uint ) {
Bond memory info = bondInfo[ _recipient ];
uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining)
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _recipient ]; // delete user info
emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data
return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due
} else { // if unfinished
// calculate payout vested
uint payout = info.payout.mul( percentVested ).div( 10000 );
// store updated deposit info
bondInfo[ _recipient ] = Bond({
payout: info.payout.sub( payout ),
vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ),
lastBlock: block.number,
pricePaid: info.pricePaid
});
emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout );
return stakeOrSend( _recipient, _stake, payout );
}
}
|
function redeem( address _recipient, bool _stake ) external returns ( uint ) {
Bond memory info = bondInfo[ _recipient ];
uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining)
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _recipient ]; // delete user info
emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data
return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due
} else { // if unfinished
// calculate payout vested
uint payout = info.payout.mul( percentVested ).div( 10000 );
// store updated deposit info
bondInfo[ _recipient ] = Bond({
payout: info.payout.sub( payout ),
vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ),
lastBlock: block.number,
pricePaid: info.pricePaid
});
emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout );
return stakeOrSend( _recipient, _stake, payout );
}
}
| 69,240
|
49
|
// Initializes a Chainlink request Sets the ID, callback address, and callback function signature on the request self The uninitialized request _id The Job Specification ID _callbackAddress The callback address _callbackFunction The callback function signaturereturn The initialized request /
|
function initialize(
Request memory self,
bytes32 _id,
address _callbackAddress,
bytes4 _callbackFunction
|
function initialize(
Request memory self,
bytes32 _id,
address _callbackAddress,
bytes4 _callbackFunction
| 64,403
|
112
|
// If the vault has an existing strategy, withdraw all funds from it.
|
if (strategy != address(0x0)) {
IStrategy(strategy).withdrawAll();
}
|
if (strategy != address(0x0)) {
IStrategy(strategy).withdrawAll();
}
| 26,250
|
38
|
// TWAP min delta (10-min)
|
uint256 minDeltaTwap;
event TwapUpdated(uint256 priceCumulativeLast, uint256 blockTimestampLast, uint256 priceAverageLast);
constructor(address router, address factory) Ownable() ERC20() {
uniswapV2Router = router;
uniswapV2Factory = factory;
}
|
uint256 minDeltaTwap;
event TwapUpdated(uint256 priceCumulativeLast, uint256 blockTimestampLast, uint256 priceAverageLast);
constructor(address router, address factory) Ownable() ERC20() {
uniswapV2Router = router;
uniswapV2Factory = factory;
}
| 26,577
|
11
|
// Update the address that the contract will make OperatorFilter checks against. When set to the zeroaddress, checks will be bypassed. OnlyOwner.@custom:event OperatorFilterRegistryAddressUpdated newRegistry The address of the registry that will be used for this contract /
|
function updateOperatorFilterRegistryAddress(address newRegistry) public virtual {
if (msg.sender != owner()) {
revert OnlyOwner();
}
UpdatableOperatorFiltererUpgradeableStorage.layout()._operatorFilterRegistry = newRegistry;
emit OperatorFilterRegistryAddressUpdated(newRegistry);
}
|
function updateOperatorFilterRegistryAddress(address newRegistry) public virtual {
if (msg.sender != owner()) {
revert OnlyOwner();
}
UpdatableOperatorFiltererUpgradeableStorage.layout()._operatorFilterRegistry = newRegistry;
emit OperatorFilterRegistryAddressUpdated(newRegistry);
}
| 10,026
|
10
|
// adds a bridge operator to the registry/bridgeOperator address
|
function add(address bridgeOperator) public onlyOwner {
require(bridgeOperator != address(0));
bridgeOperators[bridgeOperator] = true;
AddedBridgeOperator(bridgeOperator);
}
|
function add(address bridgeOperator) public onlyOwner {
require(bridgeOperator != address(0));
bridgeOperators[bridgeOperator] = true;
AddedBridgeOperator(bridgeOperator);
}
| 28,474
|
4
|
// Order is actually filled
|
result = safeAdd (
result, safeMul (nodeOrder.price, remainingAmount));
toSell = safeSub (toSell, remainingAmount);
|
result = safeAdd (
result, safeMul (nodeOrder.price, remainingAmount));
toSell = safeSub (toSell, remainingAmount);
| 29,512
|
1,025
|
// After the Boost/Repay check if the ratio doesn't trigger another call
|
function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
CdpHolder memory holder;
(, holder) = subscriptionsContract.getCdpHolder(_cdpId);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
|
function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
CdpHolder memory holder;
(, holder) = subscriptionsContract.getCdpHolder(_cdpId);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
| 26,119
|
187
|
// linaToken.mint(msg.sender, totalStaking.add(totalReward) );
|
linaToken.transfer(msg.sender, totalStaking.add(totalReward) );
emit Claim(msg.sender, totalReward, totalStaking);
return true;
|
linaToken.transfer(msg.sender, totalStaking.add(totalReward) );
emit Claim(msg.sender, totalReward, totalStaking);
return true;
| 13,974
|
50
|
// Total amount of staking rewards available
|
uint256 public override rewardsAmount;
|
uint256 public override rewardsAmount;
| 10,316
|
114
|
// Copies 32 bytes of `src` starting at `srcIndex` into `dst` starting at `dstIndex`. /
|
function memcpy32(string memory src, uint srcIndex, bytes memory dst, uint dstIndex) internal pure {
assembly {
mstore(add(add(dst, 32), dstIndex), mload(add(add(src, 32), srcIndex)))
}
}
|
function memcpy32(string memory src, uint srcIndex, bytes memory dst, uint dstIndex) internal pure {
assembly {
mstore(add(add(dst, 32), dstIndex), mload(add(add(src, 32), srcIndex)))
}
}
| 18,985
|
26
|
// Check if it is an airline
|
function isAirline
(
address airlineAddress
)
external
view
returns(bool)
|
function isAirline
(
address airlineAddress
)
external
view
returns(bool)
| 2,894
|
27
|
// Remember the initial block number // Short-circuit accumulating 0 interest // Read the previous values out of storage // Calculate the current borrow interest rate / Error.TOKEN_ERROR.failOpaque(FailureInfo.BORROW_RATE_ABSURDLY_HIGH, borrowRateMantissa);
|
borrowRateMantissa = BORROW_RATE_MAX_MANTISSA;
|
borrowRateMantissa = BORROW_RATE_MAX_MANTISSA;
| 28,302
|
27
|
// depositing X RING for 12 months, interest is about (1_unitInterestX / 107) KTON default: 1000
|
bytes32 public constant UINT_BANK_UNIT_INTEREST = "UINT_BANK_UNIT_INTEREST";
|
bytes32 public constant UINT_BANK_UNIT_INTEREST = "UINT_BANK_UNIT_INTEREST";
| 81,952
|
137
|
// Total dsec
|
uint256 epoch_dsec = total_dsec[epoch];
epoch_wound_down[epoch] = true;
emit WindDownEpochState(previous_epoch, SFI_earned[epoch], epoch_dsec);
|
uint256 epoch_dsec = total_dsec[epoch];
epoch_wound_down[epoch] = true;
emit WindDownEpochState(previous_epoch, SFI_earned[epoch], epoch_dsec);
| 33,279
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.