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 |
|---|---|---|---|---|
9 | // Allows the proxy owner to upgrade and call the new implementationto initialize whatever is needed through a low level call. _implementation the address of the new implementation to be set. _data the msg.data to bet sent in the low level call. This parameter may include the functionsignature of the implementation to be called with the needed payload. / | function upgradeToAndCall(address _implementation, bytes _data) external payable ifAdmin {
upgradeImplementation(_implementation);
//solium-disable-next-line security/no-call-value
require(address(this).call.value(msg.value)(_data), "Upgrade error: initialization method call failed");
}
| function upgradeToAndCall(address _implementation, bytes _data) external payable ifAdmin {
upgradeImplementation(_implementation);
//solium-disable-next-line security/no-call-value
require(address(this).call.value(msg.value)(_data), "Upgrade error: initialization method call failed");
}
| 19,135 |
155 | // metadata URI | string private _baseTokenURI;
string private _hiddenMetadataUri ='ipfs://no/hidden.json';
| string private _baseTokenURI;
string private _hiddenMetadataUri ='ipfs://no/hidden.json';
| 776 |
13 | // this won't work for ERC721 re-entrancy | instance.safeTransferFrom(address(this), parentAddress, _tokenId, data);
| instance.safeTransferFrom(address(this), parentAddress, _tokenId, data);
| 9,258 |
635 | // Reduce it | amountSDVD = amountSDVD.sub(excessToken);
| amountSDVD = amountSDVD.sub(excessToken);
| 19,448 |
2 | // Access is restricted to the current owner / | modifier only_owner() {
require(msg.sender == owner);
_;
}
| modifier only_owner() {
require(msg.sender == owner);
_;
}
| 20,729 |
31 | // creates new LockedAccount instance/policy governs execution permissions to admin functions/assetToken token contract representing funds locked/neumark Neumark token contract/penaltyDisbursalAddress address of disbursal contract for penalty fees/lockPeriod period for which funds are locked, in seconds/penaltyFraction decimal fraction of unlocked amount paid as penalty,/ if unlocked before lockPeriod is over/this implementation does not allow spending funds on ICOs but provides/ a migration mechanism to final LockedAccount with such functionality | constructor(
IAccessPolicy policy,
IERC677Token assetToken,
Neumark neumark,
address penaltyDisbursalAddress,
uint256 lockPeriod,
uint256 penaltyFraction
)
MigrationSource(policy, ROLE_LOCKED_ACCOUNT_ADMIN)
Reclaimable()
| constructor(
IAccessPolicy policy,
IERC677Token assetToken,
Neumark neumark,
address penaltyDisbursalAddress,
uint256 lockPeriod,
uint256 penaltyFraction
)
MigrationSource(policy, ROLE_LOCKED_ACCOUNT_ADMIN)
Reclaimable()
| 20,602 |
35 | // Count expected tokens price | uint tokens = _value / price();
| uint tokens = _value / price();
| 10,247 |
60 | // The creator of the contract is the initial CFO. | cfoAddress = msg.sender;
| cfoAddress = msg.sender;
| 29,398 |
28 | // solhint-enable no-empty-blocks // Returns encoded string uri _name Name of the Contract _symbol Symbol for the Contract / | function _createContractMetadata(string memory _name, string memory _symbol) internal pure returns (string memory) {
| function _createContractMetadata(string memory _name, string memory _symbol) internal pure returns (string memory) {
| 12,942 |
3 | // 累计所有冻结仓位的债务总量 SUM(swap.supply) | function frozensupplies(address token, address[] memory frozens)
public
view
returns (uint256)
| function frozensupplies(address token, address[] memory frozens)
public
view
returns (uint256)
| 4,725 |
193 | // MNTToken with Governance. | contract MNTToken is ERC20("mnt", "MNT"), Ownable {
uint256 private _cap = 100000000e18;
uint256 private _initial_supply = 500000e18;
uint256 private _totalLock;
uint256 public lockFromBlock;
uint256 public lockToBlock;
uint256 public transferBurnRate;
bool public farmingEnabled;
mapping(address => uint256) private _locks;
mapping(address => bool) private _transferBurnExceptAddresses;
mapping(address => uint256) private _lastUnlockBlock;
event Lock(address indexed to, uint256 value);
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
function circulatingSupply() public view returns (uint256) {
return totalSupply().sub(_totalLock);
}
function totalLock() public view returns (uint256) {
return _totalLock;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - minted tokens must not cause the total supply to go over the cap.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) { // When minting tokens
require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded");
}
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual override {
if (transferBurnRate > 0 && _transferBurnExceptAddresses[sender] != true && _transferBurnExceptAddresses[recipient] != true && recipient != address(0)) {
uint256 _burntAmount = amount * transferBurnRate / 100;
// Burn transferBurnRate% from amount
super._burn(sender, _burntAmount);
// Recalibrate the transfer amount
amount = amount - _burntAmount;
}
super._transfer(sender, recipient, amount);
_moveDelegates(_delegates[sender], _delegates[recipient], amount);
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function totalBalanceOf(address _holder) public view returns (uint256) {
return _locks[_holder].add(balanceOf(_holder));
}
function lockOf(address _holder) public view returns (uint256) {
return _locks[_holder];
}
function lastUnlockBlock(address _holder) public view returns (uint256) {
return _lastUnlockBlock[_holder];
}
function lock(address _holder, uint256 _amount) public onlyOwner {
require(_holder != address(0), "ERC20: lock to the zero address");
require(_amount <= balanceOf(_holder), "ERC20: lock amount over blance");
_transfer(_holder, address(this), _amount);
_locks[_holder] = _locks[_holder].add(_amount);
_totalLock = _totalLock.add(_amount);
if (_lastUnlockBlock[_holder] < lockFromBlock) {
_lastUnlockBlock[_holder] = lockFromBlock;
}
emit Lock(_holder, _amount);
}
function canUnlockAmount(address _holder) public view returns (uint256) {
if (block.number < lockFromBlock) {
return 0;
}
else if (block.number >= lockToBlock) {
return _locks[_holder];
}
else {
uint256 releaseBlock = block.number.sub(_lastUnlockBlock[_holder]);
uint256 numberLockBlock = lockToBlock.sub(_lastUnlockBlock[_holder]);
return _locks[_holder].mul(releaseBlock).div(numberLockBlock);
}
}
function unlock() public {
require(_locks[msg.sender] > 0, "ERC20: cannot unlock");
uint256 amount = canUnlockAmount(msg.sender);
// just for sure
if (amount > balanceOf(address(this))) {
amount = balanceOf(address(this));
}
_transfer(address(this), msg.sender, amount);
_locks[msg.sender] = _locks[msg.sender].sub(amount);
_lastUnlockBlock[msg.sender] = block.number;
_totalLock = _totalLock.sub(amount);
}
// This function is for dev address migrate all balance to a multi sig address
function transferAll(address _to) public {
_locks[_to] = _locks[_to].add(_locks[msg.sender]);
if (_lastUnlockBlock[_to] < lockFromBlock) {
_lastUnlockBlock[_to] = lockFromBlock;
}
if (_lastUnlockBlock[_to] < _lastUnlockBlock[msg.sender]) {
_lastUnlockBlock[_to] = _lastUnlockBlock[msg.sender];
}
_locks[msg.sender] = 0;
_lastUnlockBlock[msg.sender] = 0;
_transfer(msg.sender, _to, balanceOf(msg.sender));
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "MNT::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "MNT::delegateBySig: invalid nonce");
require(now <= expiry, "MNT::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "MNT::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "MNT::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual returns (bool) {
_burn(_msgSender(), amount);
return true;
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual returns (bool) {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
return true;
}
function setTransferBurnRate(uint256 _tranferBurnRate) public onlyOwner {
require(_tranferBurnRate <= 100, "Burning Rate on Transfer cannot be more than 100%");
transferBurnRate = _tranferBurnRate;
}
// In some circumstance, we should not burn MNT on transfer, eg: Transfer from owner to distribute bounty, from depositing to swap for liquidity
function addTransferBurnExceptAddress(address _transferBurnExceptAddress) public onlyOwner {
_transferBurnExceptAddresses[_transferBurnExceptAddress] = true;
}
function removeTransferBurnExceptAddress(address _transferBurnExceptAddress) public onlyOwner {
delete _transferBurnExceptAddresses[_transferBurnExceptAddress];
}
function startFarming() public onlyOwner {
require(farmingEnabled == false, "Farming has been started already!");
lockFromBlock = block.number;
lockToBlock = lockFromBlock + 2000;
farmingEnabled = true;
}
constructor() public {
lockFromBlock = 999999999;
lockToBlock = 999999999;
farmingEnabled = false;
_mint(msg.sender, _initial_supply); // Mint 5000 MNT for bounty program
_moveDelegates(address(0), msg.sender, _initial_supply);
}
}
| contract MNTToken is ERC20("mnt", "MNT"), Ownable {
uint256 private _cap = 100000000e18;
uint256 private _initial_supply = 500000e18;
uint256 private _totalLock;
uint256 public lockFromBlock;
uint256 public lockToBlock;
uint256 public transferBurnRate;
bool public farmingEnabled;
mapping(address => uint256) private _locks;
mapping(address => bool) private _transferBurnExceptAddresses;
mapping(address => uint256) private _lastUnlockBlock;
event Lock(address indexed to, uint256 value);
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
function circulatingSupply() public view returns (uint256) {
return totalSupply().sub(_totalLock);
}
function totalLock() public view returns (uint256) {
return _totalLock;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - minted tokens must not cause the total supply to go over the cap.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) { // When minting tokens
require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded");
}
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual override {
if (transferBurnRate > 0 && _transferBurnExceptAddresses[sender] != true && _transferBurnExceptAddresses[recipient] != true && recipient != address(0)) {
uint256 _burntAmount = amount * transferBurnRate / 100;
// Burn transferBurnRate% from amount
super._burn(sender, _burntAmount);
// Recalibrate the transfer amount
amount = amount - _burntAmount;
}
super._transfer(sender, recipient, amount);
_moveDelegates(_delegates[sender], _delegates[recipient], amount);
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function totalBalanceOf(address _holder) public view returns (uint256) {
return _locks[_holder].add(balanceOf(_holder));
}
function lockOf(address _holder) public view returns (uint256) {
return _locks[_holder];
}
function lastUnlockBlock(address _holder) public view returns (uint256) {
return _lastUnlockBlock[_holder];
}
function lock(address _holder, uint256 _amount) public onlyOwner {
require(_holder != address(0), "ERC20: lock to the zero address");
require(_amount <= balanceOf(_holder), "ERC20: lock amount over blance");
_transfer(_holder, address(this), _amount);
_locks[_holder] = _locks[_holder].add(_amount);
_totalLock = _totalLock.add(_amount);
if (_lastUnlockBlock[_holder] < lockFromBlock) {
_lastUnlockBlock[_holder] = lockFromBlock;
}
emit Lock(_holder, _amount);
}
function canUnlockAmount(address _holder) public view returns (uint256) {
if (block.number < lockFromBlock) {
return 0;
}
else if (block.number >= lockToBlock) {
return _locks[_holder];
}
else {
uint256 releaseBlock = block.number.sub(_lastUnlockBlock[_holder]);
uint256 numberLockBlock = lockToBlock.sub(_lastUnlockBlock[_holder]);
return _locks[_holder].mul(releaseBlock).div(numberLockBlock);
}
}
function unlock() public {
require(_locks[msg.sender] > 0, "ERC20: cannot unlock");
uint256 amount = canUnlockAmount(msg.sender);
// just for sure
if (amount > balanceOf(address(this))) {
amount = balanceOf(address(this));
}
_transfer(address(this), msg.sender, amount);
_locks[msg.sender] = _locks[msg.sender].sub(amount);
_lastUnlockBlock[msg.sender] = block.number;
_totalLock = _totalLock.sub(amount);
}
// This function is for dev address migrate all balance to a multi sig address
function transferAll(address _to) public {
_locks[_to] = _locks[_to].add(_locks[msg.sender]);
if (_lastUnlockBlock[_to] < lockFromBlock) {
_lastUnlockBlock[_to] = lockFromBlock;
}
if (_lastUnlockBlock[_to] < _lastUnlockBlock[msg.sender]) {
_lastUnlockBlock[_to] = _lastUnlockBlock[msg.sender];
}
_locks[msg.sender] = 0;
_lastUnlockBlock[msg.sender] = 0;
_transfer(msg.sender, _to, balanceOf(msg.sender));
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "MNT::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "MNT::delegateBySig: invalid nonce");
require(now <= expiry, "MNT::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "MNT::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "MNT::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual returns (bool) {
_burn(_msgSender(), amount);
return true;
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual returns (bool) {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
return true;
}
function setTransferBurnRate(uint256 _tranferBurnRate) public onlyOwner {
require(_tranferBurnRate <= 100, "Burning Rate on Transfer cannot be more than 100%");
transferBurnRate = _tranferBurnRate;
}
// In some circumstance, we should not burn MNT on transfer, eg: Transfer from owner to distribute bounty, from depositing to swap for liquidity
function addTransferBurnExceptAddress(address _transferBurnExceptAddress) public onlyOwner {
_transferBurnExceptAddresses[_transferBurnExceptAddress] = true;
}
function removeTransferBurnExceptAddress(address _transferBurnExceptAddress) public onlyOwner {
delete _transferBurnExceptAddresses[_transferBurnExceptAddress];
}
function startFarming() public onlyOwner {
require(farmingEnabled == false, "Farming has been started already!");
lockFromBlock = block.number;
lockToBlock = lockFromBlock + 2000;
farmingEnabled = true;
}
constructor() public {
lockFromBlock = 999999999;
lockToBlock = 999999999;
farmingEnabled = false;
_mint(msg.sender, _initial_supply); // Mint 5000 MNT for bounty program
_moveDelegates(address(0), msg.sender, _initial_supply);
}
}
| 11,981 |
43 | // Emitted when a member is disabled either by the owner or the by the member itself | event DisableMember(address indexed member, uint256 tokensRemainder);
| event DisableMember(address indexed member, uint256 tokensRemainder);
| 24,562 |
1,338 | // EVENTS // MODIFIERS/ Update config settings if possible. | modifier updateConfig() {
_updateConfig();
_;
}
| modifier updateConfig() {
_updateConfig();
_;
}
| 21,841 |
109 | // If the upgrade hasn't been registered, register with the current time. | if (registrationTime == 0) {
timeLockedUpgrades[upgradeHash] = block.timestamp;
emit UpgradeRegistered(
upgradeHash,
block.timestamp
);
return;
}
| if (registrationTime == 0) {
timeLockedUpgrades[upgradeHash] = block.timestamp;
emit UpgradeRegistered(
upgradeHash,
block.timestamp
);
return;
}
| 80,926 |
47 | // Price Updates /// | function updateCollateralPrice(address _spot, bytes32 _ilk) public {
Pricing(_spot).poke(_ilk);
}
| function updateCollateralPrice(address _spot, bytes32 _ilk) public {
Pricing(_spot).poke(_ilk);
}
| 31,033 |
77 | // Return balance of a certain address. _owner The address whose balance we want to check./ | {
return balances[_owner];
}
| {
return balances[_owner];
}
| 42,967 |
255 | // check if a specific balance decrease is allowed (i.e. doesn't bring the user borrow position health factor under 1e18)_reserve the address of the reserve_user the address of the user_amount the amount to decrease return true if the decrease of the balance is allowed/ | {
// Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables
balanceDecreaseAllowedLocalVars memory vars;
(
vars.decimals,
,
vars.reserveLiquidationThreshold,
vars.reserveUsageAsCollateralEnabled
) = core.getReserveConfiguration(_reserve);
if (
!vars.reserveUsageAsCollateralEnabled ||
!core.isUserUseReserveAsCollateralEnabled(_reserve, _user)
) {
return true; //if reserve is not used as collateral, no reasons to block the transfer
}
(
,
vars.collateralBalanceETH,
vars.borrowBalanceETH,
vars.totalFeesETH,
,
vars.currentLiquidationThreshold,
,
) = calculateUserGlobalData(_user);
if (vars.borrowBalanceETH == 0) {
return true; //no borrows - no reasons to block the transfer
}
IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());
vars.amountToDecreaseETH = oracle.getAssetPrice(_reserve).mul(_amount).div(
10 ** vars.decimals
);
vars.collateralBalancefterDecrease = vars.collateralBalanceETH.sub(
vars.amountToDecreaseETH
);
//if there is a borrow, there can't be 0 collateral
if (vars.collateralBalancefterDecrease == 0) {
return false;
}
vars.liquidationThresholdAfterDecrease = vars
.collateralBalanceETH
.mul(vars.currentLiquidationThreshold)
.sub(vars.amountToDecreaseETH.mul(vars.reserveLiquidationThreshold))
.div(vars.collateralBalancefterDecrease);
uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalancesInternal(
vars.collateralBalancefterDecrease,
vars.borrowBalanceETH,
vars.totalFeesETH,
vars.liquidationThresholdAfterDecrease
);
return healthFactorAfterDecrease > HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
}
| {
// Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables
balanceDecreaseAllowedLocalVars memory vars;
(
vars.decimals,
,
vars.reserveLiquidationThreshold,
vars.reserveUsageAsCollateralEnabled
) = core.getReserveConfiguration(_reserve);
if (
!vars.reserveUsageAsCollateralEnabled ||
!core.isUserUseReserveAsCollateralEnabled(_reserve, _user)
) {
return true; //if reserve is not used as collateral, no reasons to block the transfer
}
(
,
vars.collateralBalanceETH,
vars.borrowBalanceETH,
vars.totalFeesETH,
,
vars.currentLiquidationThreshold,
,
) = calculateUserGlobalData(_user);
if (vars.borrowBalanceETH == 0) {
return true; //no borrows - no reasons to block the transfer
}
IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());
vars.amountToDecreaseETH = oracle.getAssetPrice(_reserve).mul(_amount).div(
10 ** vars.decimals
);
vars.collateralBalancefterDecrease = vars.collateralBalanceETH.sub(
vars.amountToDecreaseETH
);
//if there is a borrow, there can't be 0 collateral
if (vars.collateralBalancefterDecrease == 0) {
return false;
}
vars.liquidationThresholdAfterDecrease = vars
.collateralBalanceETH
.mul(vars.currentLiquidationThreshold)
.sub(vars.amountToDecreaseETH.mul(vars.reserveLiquidationThreshold))
.div(vars.collateralBalancefterDecrease);
uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalancesInternal(
vars.collateralBalancefterDecrease,
vars.borrowBalanceETH,
vars.totalFeesETH,
vars.liquidationThresholdAfterDecrease
);
return healthFactorAfterDecrease > HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
}
| 39,623 |
121 | // Fallback function to purchase a single ticket. | function () public payable {
}
| function () public payable {
}
| 5,436 |
334 | // xref:ROOT:erc1155.adocbatch-operations[Batched] version of {_mint}. Requirements: - `ids` and `amounts` must have the same length.- If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return theacceptance magic value. / | function _mintBatch(
| function _mintBatch(
| 20,828 |
172 | // govBrinc tokens created per block. | uint256 public govBrincPerBlock;
| uint256 public govBrincPerBlock;
| 58,006 |
3 | // checks if _msgSender is the controller of the vault | modifier onlyVaultController() {
require(_msgSender() == address(_controller), "sender not VaultController");
_;
}
| modifier onlyVaultController() {
require(_msgSender() == address(_controller), "sender not VaultController");
_;
}
| 37,623 |
73 | // get Permission structure_methodsignature request to retrieve the Permission struct for this methodsignature return Permission/ | bool active) {
return (permissions[_methodsignature].name,
permissions[_methodsignature].description,
permissions[_methodsignature].contract_name,
permissions[_methodsignature].active);
}
| bool active) {
return (permissions[_methodsignature].name,
permissions[_methodsignature].description,
permissions[_methodsignature].contract_name,
permissions[_methodsignature].active);
}
| 19,262 |
76 | // Accumulated ERC20s per share, times 1e36. | uint256 _accERC20PerShare = 0;
| uint256 _accERC20PerShare = 0;
| 23,446 |
39 | // Constructor that gives msg.sender all of existing tokens. | constructor(address _frozenAddress) public {
require(_frozenAddress != address(0) && _frozenAddress != msg.sender);
frozenAddress = _frozenAddress;
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
| constructor(address _frozenAddress) public {
require(_frozenAddress != address(0) && _frozenAddress != msg.sender);
frozenAddress = _frozenAddress;
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
| 12,720 |
1 | // Indicates that the contract is in the process of being initialized. / | bool private _initializing;
| bool private _initializing;
| 1,394 |
103 | // Get position unit from total notional amount_setTokenSupply Supply of SetToken in precise units (10^18) _totalNotionalTotal notional amount of component prior toreturnDefault position unit / | function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_setTokenSupply);
}
| function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_setTokenSupply);
}
| 7,899 |
0 | // This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}./ Initializes the proxy with `beacon`. If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. Thiswill typically be an encoded function call, and allows initializating the storage of the proxy like a Solidityconstructor. Requirements: - `beacon` must be a contract with the interface {IBeacon}. / | constructor(address beacon, bytes memory data) payable {
assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1));
_upgradeBeaconToAndCall(beacon, data, false);
}
| constructor(address beacon, bytes memory data) payable {
assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1));
_upgradeBeaconToAndCall(beacon, data, false);
}
| 33,087 |
98 | // Balance is below collateral! | if (_balance <= _collat) return 0;
| if (_balance <= _collat) return 0;
| 20,750 |
69 | // Set rewards (This includes old pending rewards and does not include new pending rewards) | staker.monaRevenueRewardsEarned = staker.monaRevenueRewardsEarned.add(rewards);
| staker.monaRevenueRewardsEarned = staker.monaRevenueRewardsEarned.add(rewards);
| 37,991 |
5 | // Zeroize the slot after the string. | mstore(str, 0)
| mstore(str, 0)
| 17,990 |
0 | // Returns the address starting at byte 0/length and overflow checks must be carried out before calling/_bytes The input bytes string to slice/ return _address The address starting at byte 0 | function toAddress(bytes calldata _bytes) internal pure returns (address _address) {
if (_bytes.length < Constants.ADDR_SIZE) revert SliceOutOfBounds();
assembly {
_address := shr(96, calldataload(_bytes.offset))
}
| function toAddress(bytes calldata _bytes) internal pure returns (address _address) {
if (_bytes.length < Constants.ADDR_SIZE) revert SliceOutOfBounds();
assembly {
_address := shr(96, calldataload(_bytes.offset))
}
| 7,204 |
16 | // Receives a dispute request for an arbitrable item from the Foreign Chain. Should only be called by the xDAI/ETH bridge. _arbitrable The address of the arbitrable contract. _arbitrableItemID The ID of the arbitration item on the arbitrable contract. _plaintiff The address of the dispute creator. / | function receiveDisputeRequest(
| function receiveDisputeRequest(
| 5,082 |
28 | // checkNonDecreasing returns true if array values are monotonically nondecreasing | function checkNonDecreasing(uint256[] memory arr) internal pure returns (bool) {
for (uint256 i = 1; i < arr.length; i++) {
if (arr[i - 1] > arr[i]) {
return false;
}
}
return true;
}
| function checkNonDecreasing(uint256[] memory arr) internal pure returns (bool) {
for (uint256 i = 1; i < arr.length; i++) {
if (arr[i - 1] > arr[i]) {
return false;
}
}
return true;
}
| 6,629 |
177 | // firstUpline has a place | treeChildren[firstUpline][treeType][cNodeID][i]
= treeNode(treeRoot,treeType,treeNodeID);
| treeChildren[firstUpline][treeType][cNodeID][i]
= treeNode(treeRoot,treeType,treeNodeID);
| 39,845 |
85 | // DirectorOfGroup - 6 | setFeeDistributionAndStatusThreshold(6, [400, 240, 160, 80, 45], thresholds[6]);
| setFeeDistributionAndStatusThreshold(6, [400, 240, 160, 80, 45], thresholds[6]);
| 72,139 |
62 | // Private. -----------------------/ Function that request random words to Chainlink oracle. Requirements: | * - {onlyOwner} modifier.
* - {onlyIfLotteryNotEnded} modifier.
* - This contract must be connected to the VRFv2Consumer contract via `connectToVRFv2ConsumerContract()`.
*
*/
function _getRandom()
private
onlyOwner
onlyIfLotteryNotEnded
onlyIfIsPaused
{
VRFv2Consumer vrf = _vrf;
require(
address(vrf) != address(0),
"[Lottery]: La direccion del VRFv2 no es valida."
);
// FIXME - ERROR References:
// - https://github.com/smartcontractkit/chainlink/blob/e1e78865d4f3e609e7977777d7fb0604913b63ed/contracts/src/v0.8/VRFCoordinatorV2.sol#L376
// - https://ethereum.stackexchange.com/questions/134835/chainlink-vrf-how-to-call-requestrandomwords-in-fulfillrandomwords
// - https://hackernoon.com/hack-solidity-reentrancy-attack
uint256 requestId = vrf.getLastRequestId(); // FIXME: Esta funcionando porque esta cogiendo los resultados anteriores a esta ejecucion.
//uint256 requestId = vrf.requestRandomWords();
require(
requestId != 0,
"[Lottery]: Todavia no se ha realizado la request a Chainlink."
);
(_isFulfilled, _randomWords) = vrf.getRequestStatus(requestId);
}
| * - {onlyOwner} modifier.
* - {onlyIfLotteryNotEnded} modifier.
* - This contract must be connected to the VRFv2Consumer contract via `connectToVRFv2ConsumerContract()`.
*
*/
function _getRandom()
private
onlyOwner
onlyIfLotteryNotEnded
onlyIfIsPaused
{
VRFv2Consumer vrf = _vrf;
require(
address(vrf) != address(0),
"[Lottery]: La direccion del VRFv2 no es valida."
);
// FIXME - ERROR References:
// - https://github.com/smartcontractkit/chainlink/blob/e1e78865d4f3e609e7977777d7fb0604913b63ed/contracts/src/v0.8/VRFCoordinatorV2.sol#L376
// - https://ethereum.stackexchange.com/questions/134835/chainlink-vrf-how-to-call-requestrandomwords-in-fulfillrandomwords
// - https://hackernoon.com/hack-solidity-reentrancy-attack
uint256 requestId = vrf.getLastRequestId(); // FIXME: Esta funcionando porque esta cogiendo los resultados anteriores a esta ejecucion.
//uint256 requestId = vrf.requestRandomWords();
require(
requestId != 0,
"[Lottery]: Todavia no se ha realizado la request a Chainlink."
);
(_isFulfilled, _randomWords) = vrf.getRequestStatus(requestId);
}
| 30,919 |
95 | // Can't send reclaimed funds to the zero address. | if (_beneficiary == address(0)) revert REDEEM_TO_ZERO_ADDRESS();
| if (_beneficiary == address(0)) revert REDEEM_TO_ZERO_ADDRESS();
| 14,317 |
5 | // Not technically true since we didn't register yet, but this is consistent with the error messages of other specialization settings. | _require(tokenX != tokenY, Errors.TOKEN_ALREADY_REGISTERED);
_require(tokenX < tokenY, Errors.UNSORTED_TOKENS);
| _require(tokenX != tokenY, Errors.TOKEN_ALREADY_REGISTERED);
_require(tokenX < tokenY, Errors.UNSORTED_TOKENS);
| 26,646 |
34 | // 40 is the final reward era, almost all tokens mintedonce the final era is reached, more tokens will not be given out because the assert function | if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 39)
{
rewardEra = rewardEra + 1;
}
| if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 39)
{
rewardEra = rewardEra + 1;
}
| 34,339 |
27 | // turning `amount` of wETH into ETH | try weth.withdraw(amount) {
| try weth.withdraw(amount) {
| 14,324 |
53 | // 更新staking池 | updatePool(0);
| updatePool(0);
| 23,636 |
10 | // Multi Send - Allows to batch multiple transactions into one./Nick Dodson - <nick.dodson@consensys.net>/Gonçalo Sá - <goncalo.sa@consensys.net>/Stefan George - <stefan@gnosis.io>/Richard Meissner - <richard@gnosis.io> | contract MultiSend {
bytes32 constant private GUARD_VALUE = keccak256("multisend.guard.bytes32");
bytes32 guard;
constructor() public {
guard = GUARD_VALUE;
}
/// @dev Sends multiple transactions and reverts all if one fails.
/// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of
/// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte),
/// to as a address (=> 20 bytes),
/// value as a uint256 (=> 32 bytes),
/// data length as a uint256 (=> 32 bytes),
/// data as bytes.
/// see abi.encodePacked for more information on packed encoding
function multiSend(bytes memory transactions)
public
payable
{
require(guard != GUARD_VALUE, "MultiSend should only be called via delegatecall");
// solium-disable-next-line security/no-inline-assembly
assembly {
let length := mload(transactions)
let i := 0x20
for { } lt(i, length) { } {
// First byte of the data is the operation.
// We shift by 248 bits (256 - 8 [operation byte]) it right since mload will always load 32 bytes (a word).
// This will also zero out unused data.
let operation := shr(0xf8, mload(add(transactions, i)))
// We offset the load address by 1 byte (operation byte)
// We shift it right by 96 bits (256 - 160 [20 address bytes]) to right-align the data and zero out unused data.
let to := shr(0x60, mload(add(transactions, add(i, 0x01))))
// We offset the load address by 21 byte (operation byte + 20 address bytes)
let value := mload(add(transactions, add(i, 0x15)))
// We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes)
let dataLength := mload(add(transactions, add(i, 0x35)))
// We offset the load address by 85 byte (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes)
let data := add(transactions, add(i, 0x55))
let success := 0
switch operation
case 0 { success := call(gas, to, value, data, dataLength, 0, 0) }
case 1 { success := delegatecall(gas, to, data, dataLength, 0, 0) }
if eq(success, 0) { revert(0, 0) }
// Next entry starts at 85 byte + data length
i := add(i, add(0x55, dataLength))
}
}
}
| contract MultiSend {
bytes32 constant private GUARD_VALUE = keccak256("multisend.guard.bytes32");
bytes32 guard;
constructor() public {
guard = GUARD_VALUE;
}
/// @dev Sends multiple transactions and reverts all if one fails.
/// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of
/// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte),
/// to as a address (=> 20 bytes),
/// value as a uint256 (=> 32 bytes),
/// data length as a uint256 (=> 32 bytes),
/// data as bytes.
/// see abi.encodePacked for more information on packed encoding
function multiSend(bytes memory transactions)
public
payable
{
require(guard != GUARD_VALUE, "MultiSend should only be called via delegatecall");
// solium-disable-next-line security/no-inline-assembly
assembly {
let length := mload(transactions)
let i := 0x20
for { } lt(i, length) { } {
// First byte of the data is the operation.
// We shift by 248 bits (256 - 8 [operation byte]) it right since mload will always load 32 bytes (a word).
// This will also zero out unused data.
let operation := shr(0xf8, mload(add(transactions, i)))
// We offset the load address by 1 byte (operation byte)
// We shift it right by 96 bits (256 - 160 [20 address bytes]) to right-align the data and zero out unused data.
let to := shr(0x60, mload(add(transactions, add(i, 0x01))))
// We offset the load address by 21 byte (operation byte + 20 address bytes)
let value := mload(add(transactions, add(i, 0x15)))
// We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes)
let dataLength := mload(add(transactions, add(i, 0x35)))
// We offset the load address by 85 byte (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes)
let data := add(transactions, add(i, 0x55))
let success := 0
switch operation
case 0 { success := call(gas, to, value, data, dataLength, 0, 0) }
case 1 { success := delegatecall(gas, to, data, dataLength, 0, 0) }
if eq(success, 0) { revert(0, 0) }
// Next entry starts at 85 byte + data length
i := add(i, add(0x55, dataLength))
}
}
}
| 40,068 |
112 | // ZKSwap storage contract/Matter Labs/ZKSwap L2 Labs | contract Storage {
/// @notice Flag indicates that upgrade preparation status is active
/// @dev Will store false in case of not active upgrade mode
bool public upgradePreparationActive;
/// @notice Upgrade preparation activation timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint public upgradePreparationActivationTime;
/// @notice Verifier contract. Used to verify block proof and exit proof
Verifier internal verifier;
VerifierExit internal verifierExit;
/// @notice Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list
Governance internal governance;
/// @notice ZKSeaNFT contract. Contains the nft info in layer1 and layer2
IZKSeaNFT internal zkSeaNFT;
UniswapV2Factory internal pairmanager;
struct BalanceToWithdraw {
uint128 balanceToWithdraw;
uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value
}
/// @notice Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw
mapping(bytes22 => BalanceToWithdraw) public balancesToWithdraw;
/// @notice verified withdrawal pending to be executed.
struct PendingWithdrawal {
address to;
uint16 tokenId;
}
/// @notice Verified but not executed withdrawals for addresses stored in here (key is pendingWithdrawal's index in pending withdrawals queue)
mapping(uint32 => PendingWithdrawal) public pendingWithdrawals;
uint32 public firstPendingWithdrawalIndex;
uint32 public numberOfPendingWithdrawals;
/// @notice Total number of verified blocks i.e. blocks[totalBlocksVerified] points at the latest verified block (block 0 is genesis)
uint32 public totalBlocksVerified;
/// @notice Total number of checked blocks
uint32 public totalBlocksChecked;
/// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block
uint32 public totalBlocksCommitted;
/// @notice Rollup block data (once per block)
/// @member validator Block producer
/// @member committedAtBlock ETH block number at which this block was committed
/// @member cumulativeOnchainOperations Total number of operations in this and all previous blocks
/// @member priorityOperations Total number of priority operations for this block
/// @member commitment Hash of the block circuit commitment
/// @member stateRoot New tree root hash
///
/// Consider memory alignment when changing field order: https://solidity.readthedocs.io/en/v0.4.21/miscellaneous.html
struct Block {
uint32 committedAtBlock;
uint64 priorityOperations;
uint32 chunks;
bytes32 withdrawalsDataHash; /// can be restricted to 16 bytes to reduce number of required storage slots
bytes32 commitment;
bytes32 stateRoot;
}
/// @notice Blocks by Franklin block id
mapping(uint32 => Block) public blocks;
/// @notice Onchain operations - operations processed inside rollup blocks
/// @member opType Onchain operation type
/// @member amount Amount used in the operation
/// @member pubData Operation pubdata
struct OnchainOperation {
Operations.OpType opType;
bytes pubData;
}
/// @notice Flag indicates that a user has exited certain token balance (per account id and tokenId)
mapping(uint32 => mapping(uint16 => bool)) public exited;
mapping(uint32 => mapping(uint32 => bool)) public swap_exited;
mapping(uint64 => bool) public nft_exited;
/// @notice Flag indicates that exodus (mass exit) mode is triggered
/// @notice Once it was raised, it can not be cleared again, and all users must exit
bool public exodusMode;
/// @notice User authenticated fact hashes for some nonce.
mapping(address => mapping(uint32 => bytes32)) public authFacts;
/// @notice Priority Operation container
/// @member opType Priority operation type
/// @member pubData Priority operation public data
/// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before)
struct PriorityOperation {
Operations.OpType opType;
bytes pubData;
uint256 expirationBlock;
}
/// @notice Priority Requests mapping (request id - operation)
/// @dev Contains op type, pubdata and expiration block of unsatisfied requests.
/// @dev Numbers are in order of requests receiving
mapping(uint64 => PriorityOperation) public priorityRequests;
/// @notice First open priority request id
uint64 public firstPriorityRequestId;
/// @notice Total number of requests
uint64 public totalOpenPriorityRequests;
/// @notice Total number of committed requests.
/// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big
uint64 public totalCommittedPriorityRequests;
/// @notice Packs address and token id into single word to use as a key in balances mapping
function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) {
return bytes22((uint176(_address) | (uint176(_tokenId) << 160)));
}
/// @notice Gets value from balancesToWithdraw
function getBalanceToWithdraw(address _address, uint16 _tokenId) external view returns (uint128) {
return balancesToWithdraw[packAddressAndTokenId(_address, _tokenId)].balanceToWithdraw;
}
address public zkSyncCommitBlockAddress;
address public zkSyncExitAddress;
address public zkSeaAddress;
/// @notice Limit the max amount for each ERC20 deposit
uint128 public maxDepositAmount;
/// @notice withdraw erc20 token gas limit
uint256 public withdrawGasLimit;
/// @notice withdraw nft gas limit
uint256 public withdrawNFTGasLimit;
}
| contract Storage {
/// @notice Flag indicates that upgrade preparation status is active
/// @dev Will store false in case of not active upgrade mode
bool public upgradePreparationActive;
/// @notice Upgrade preparation activation timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint public upgradePreparationActivationTime;
/// @notice Verifier contract. Used to verify block proof and exit proof
Verifier internal verifier;
VerifierExit internal verifierExit;
/// @notice Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list
Governance internal governance;
/// @notice ZKSeaNFT contract. Contains the nft info in layer1 and layer2
IZKSeaNFT internal zkSeaNFT;
UniswapV2Factory internal pairmanager;
struct BalanceToWithdraw {
uint128 balanceToWithdraw;
uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value
}
/// @notice Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw
mapping(bytes22 => BalanceToWithdraw) public balancesToWithdraw;
/// @notice verified withdrawal pending to be executed.
struct PendingWithdrawal {
address to;
uint16 tokenId;
}
/// @notice Verified but not executed withdrawals for addresses stored in here (key is pendingWithdrawal's index in pending withdrawals queue)
mapping(uint32 => PendingWithdrawal) public pendingWithdrawals;
uint32 public firstPendingWithdrawalIndex;
uint32 public numberOfPendingWithdrawals;
/// @notice Total number of verified blocks i.e. blocks[totalBlocksVerified] points at the latest verified block (block 0 is genesis)
uint32 public totalBlocksVerified;
/// @notice Total number of checked blocks
uint32 public totalBlocksChecked;
/// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block
uint32 public totalBlocksCommitted;
/// @notice Rollup block data (once per block)
/// @member validator Block producer
/// @member committedAtBlock ETH block number at which this block was committed
/// @member cumulativeOnchainOperations Total number of operations in this and all previous blocks
/// @member priorityOperations Total number of priority operations for this block
/// @member commitment Hash of the block circuit commitment
/// @member stateRoot New tree root hash
///
/// Consider memory alignment when changing field order: https://solidity.readthedocs.io/en/v0.4.21/miscellaneous.html
struct Block {
uint32 committedAtBlock;
uint64 priorityOperations;
uint32 chunks;
bytes32 withdrawalsDataHash; /// can be restricted to 16 bytes to reduce number of required storage slots
bytes32 commitment;
bytes32 stateRoot;
}
/// @notice Blocks by Franklin block id
mapping(uint32 => Block) public blocks;
/// @notice Onchain operations - operations processed inside rollup blocks
/// @member opType Onchain operation type
/// @member amount Amount used in the operation
/// @member pubData Operation pubdata
struct OnchainOperation {
Operations.OpType opType;
bytes pubData;
}
/// @notice Flag indicates that a user has exited certain token balance (per account id and tokenId)
mapping(uint32 => mapping(uint16 => bool)) public exited;
mapping(uint32 => mapping(uint32 => bool)) public swap_exited;
mapping(uint64 => bool) public nft_exited;
/// @notice Flag indicates that exodus (mass exit) mode is triggered
/// @notice Once it was raised, it can not be cleared again, and all users must exit
bool public exodusMode;
/// @notice User authenticated fact hashes for some nonce.
mapping(address => mapping(uint32 => bytes32)) public authFacts;
/// @notice Priority Operation container
/// @member opType Priority operation type
/// @member pubData Priority operation public data
/// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before)
struct PriorityOperation {
Operations.OpType opType;
bytes pubData;
uint256 expirationBlock;
}
/// @notice Priority Requests mapping (request id - operation)
/// @dev Contains op type, pubdata and expiration block of unsatisfied requests.
/// @dev Numbers are in order of requests receiving
mapping(uint64 => PriorityOperation) public priorityRequests;
/// @notice First open priority request id
uint64 public firstPriorityRequestId;
/// @notice Total number of requests
uint64 public totalOpenPriorityRequests;
/// @notice Total number of committed requests.
/// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big
uint64 public totalCommittedPriorityRequests;
/// @notice Packs address and token id into single word to use as a key in balances mapping
function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) {
return bytes22((uint176(_address) | (uint176(_tokenId) << 160)));
}
/// @notice Gets value from balancesToWithdraw
function getBalanceToWithdraw(address _address, uint16 _tokenId) external view returns (uint128) {
return balancesToWithdraw[packAddressAndTokenId(_address, _tokenId)].balanceToWithdraw;
}
address public zkSyncCommitBlockAddress;
address public zkSyncExitAddress;
address public zkSeaAddress;
/// @notice Limit the max amount for each ERC20 deposit
uint128 public maxDepositAmount;
/// @notice withdraw erc20 token gas limit
uint256 public withdrawGasLimit;
/// @notice withdraw nft gas limit
uint256 public withdrawNFTGasLimit;
}
| 22,431 |
54 | // TUSD -> USDC | uint256 _totalAmount = IERC20(underlyingTokens[1]).balanceOf(address(this));
Curve(yPool).exchange_underlying(int128(3), int128(1), _totalAmount,uint256(0));
| uint256 _totalAmount = IERC20(underlyingTokens[1]).balanceOf(address(this));
Curve(yPool).exchange_underlying(int128(3), int128(1), _totalAmount,uint256(0));
| 51,552 |
93 | // update global fee tracker | if (state.liquidity > 0)
state.feeGrowthGlobalX128 += FullMath.mulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity);
| if (state.liquidity > 0)
state.feeGrowthGlobalX128 += FullMath.mulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity);
| 27,610 |
61 | // Calculate the net withdrawal amount by subtracting `senderInterest` and `sablierInterest`.Because the decimal points are lost when we truncate Exponentials, the recipient will implicitly earn`recipientInterest` plus a tiny-weeny amount of interest, max 2e-8 in cToken denomination. / | (vars.mathErr, vars.recipientBalanceWithoutSenderInterest) = subUInt(recipientBalance, senderInterest);
require(vars.mathErr == MathError.NO_ERROR, "recipient balance without sender interest calculation error");
(vars.mathErr, vars.netRecipientBalance) = subUInt(vars.recipientBalanceWithoutSenderInterest, sablierInterest);
require(vars.mathErr == MathError.NO_ERROR, "net recipient balance calculation error");
| (vars.mathErr, vars.recipientBalanceWithoutSenderInterest) = subUInt(recipientBalance, senderInterest);
require(vars.mathErr == MathError.NO_ERROR, "recipient balance without sender interest calculation error");
(vars.mathErr, vars.netRecipientBalance) = subUInt(vars.recipientBalanceWithoutSenderInterest, sablierInterest);
require(vars.mathErr == MathError.NO_ERROR, "net recipient balance calculation error");
| 51,771 |
3 | // Convert signed 64.64 fixed point number into signed 64-bit integer numberrounding down.x signed 64.64-bit fixed point numberreturn signed 64-bit integer number / | function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
| function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
| 19,277 |
40 | // place the arb you would like to perform below |
OrFeedInterface orfeed= OrFeedInterface(0x8316B082621CFedAB95bf4a44a1d4B64a6ffc336);
|
OrFeedInterface orfeed= OrFeedInterface(0x8316B082621CFedAB95bf4a44a1d4B64a6ffc336);
| 38,049 |
207 | // The signed data contains the operator, the token IDs, amounts, and a nonce. Note that we use the selector of the external function here! | bytes32 data = keccak256(abi.encodePacked(address(this), this.signedBatchTransferWithOperator.selector, msg.sender, _from, _ids, _amounts, signedTransferNonce[_from]));
_signedBatchTransferInternal(_from, _to, _ids, _amounts, data, _signature);
| bytes32 data = keccak256(abi.encodePacked(address(this), this.signedBatchTransferWithOperator.selector, msg.sender, _from, _ids, _amounts, signedTransferNonce[_from]));
_signedBatchTransferInternal(_from, _to, _ids, _amounts, data, _signature);
| 46,654 |
394 | // Transfers some tokens on behalf of address `_from' (token owner) to some other address `_to`In contrast to `safeTransferFrom` doesn't check recipient smart contract to support ERC20 tokens (ERC20Receiver) Designed to be used by developers when the receiver is known to support ERC20 tokens but doesn't implement ERC20Receiver interface Called by token owner on his own or approved address, an address approved earlier by token owner to transfer some amount of tokens on its behalf Throws on any error likeinsufficient token balance orincorrect `_to` address:zero address orsame as `_from` address (self transfer) Returns silently on success, throws otherwise_from token owner which | function unsafeTransferFrom(address _from, address _to, uint256 _value) public {
// if `_from` is equal to sender, require transfers feature to be enabled
// otherwise require transfers on behalf feature to be enabled
require(_from == msg.sender && isFeatureEnabled(FEATURE_TRANSFERS)
|| _from != msg.sender && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF),
_from == msg.sender? "transfers are disabled": "transfers on behalf are disabled");
// non-zero source address check - Zeppelin
// obviously, zero source address is a client mistake
// it's not part of ERC20 standard but it's reasonable to fail fast
// since for zero value transfer transaction succeeds otherwise
require(_from != address(0), "ERC20: transfer from the zero address"); // Zeppelin msg
// non-zero recipient address check
require(_to != address(0), "ERC20: transfer to the zero address"); // Zeppelin msg
// sender and recipient cannot be the same
require(_from != _to, "sender and recipient are the same (_from = _to)");
// sending tokens to the token smart contract itself is a client mistake
require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)");
// according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20
// "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event."
if(_value == 0) {
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
// don't forget to return - we're done
return;
}
// no need to make arithmetic overflow check on the _value - by design of mint()
// in case of transfer on behalf
if(_from != msg.sender) {
// read allowance value - the amount of tokens allowed to transfer - into the stack
uint256 _allowance = transferAllowances[_from][msg.sender];
// verify sender has an allowance to transfer amount of tokens requested
require(_allowance >= _value, "ERC20: transfer amount exceeds allowance"); // Zeppelin msg
// update allowance value on the stack
_allowance -= _value;
// update the allowance value in storage
transferAllowances[_from][msg.sender] = _allowance;
// emit an improved atomic approve event
emit Approved(_from, msg.sender, _allowance + _value, _allowance);
// emit an ERC20 approval event to reflect the decrease
emit Approval(_from, msg.sender, _allowance);
}
// verify sender has enough tokens to transfer on behalf
require(tokenBalances[_from] >= _value, "ERC20: transfer amount exceeds balance"); // Zeppelin msg
// perform the transfer:
// decrease token owner (sender) balance
tokenBalances[_from] -= _value;
// increase `_to` address (receiver) balance
tokenBalances[_to] += _value;
// move voting power associated with the tokens transferred
__moveVotingPower(votingDelegates[_from], votingDelegates[_to], _value);
// emit an improved transfer event
emit Transferred(msg.sender, _from, _to, _value);
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
}
| function unsafeTransferFrom(address _from, address _to, uint256 _value) public {
// if `_from` is equal to sender, require transfers feature to be enabled
// otherwise require transfers on behalf feature to be enabled
require(_from == msg.sender && isFeatureEnabled(FEATURE_TRANSFERS)
|| _from != msg.sender && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF),
_from == msg.sender? "transfers are disabled": "transfers on behalf are disabled");
// non-zero source address check - Zeppelin
// obviously, zero source address is a client mistake
// it's not part of ERC20 standard but it's reasonable to fail fast
// since for zero value transfer transaction succeeds otherwise
require(_from != address(0), "ERC20: transfer from the zero address"); // Zeppelin msg
// non-zero recipient address check
require(_to != address(0), "ERC20: transfer to the zero address"); // Zeppelin msg
// sender and recipient cannot be the same
require(_from != _to, "sender and recipient are the same (_from = _to)");
// sending tokens to the token smart contract itself is a client mistake
require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)");
// according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20
// "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event."
if(_value == 0) {
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
// don't forget to return - we're done
return;
}
// no need to make arithmetic overflow check on the _value - by design of mint()
// in case of transfer on behalf
if(_from != msg.sender) {
// read allowance value - the amount of tokens allowed to transfer - into the stack
uint256 _allowance = transferAllowances[_from][msg.sender];
// verify sender has an allowance to transfer amount of tokens requested
require(_allowance >= _value, "ERC20: transfer amount exceeds allowance"); // Zeppelin msg
// update allowance value on the stack
_allowance -= _value;
// update the allowance value in storage
transferAllowances[_from][msg.sender] = _allowance;
// emit an improved atomic approve event
emit Approved(_from, msg.sender, _allowance + _value, _allowance);
// emit an ERC20 approval event to reflect the decrease
emit Approval(_from, msg.sender, _allowance);
}
// verify sender has enough tokens to transfer on behalf
require(tokenBalances[_from] >= _value, "ERC20: transfer amount exceeds balance"); // Zeppelin msg
// perform the transfer:
// decrease token owner (sender) balance
tokenBalances[_from] -= _value;
// increase `_to` address (receiver) balance
tokenBalances[_to] += _value;
// move voting power associated with the tokens transferred
__moveVotingPower(votingDelegates[_from], votingDelegates[_to], _value);
// emit an improved transfer event
emit Transferred(msg.sender, _from, _to, _value);
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
}
| 7,104 |
1 | // If the function actually runs out of gas, not just hitting the safety gas limit, we revert the whole transaction. This solves an issue where the gas estimaton didn't provide enough gas by default for the function to succeed. See https:medium.com/@wighawag/ethereum-the-concept-of-gas-and-its-dangers-28d0eb809bb2 | if (_isOutOfGas(gasLeftBefore)) {
revert OUT_OF_GAS();
}
| if (_isOutOfGas(gasLeftBefore)) {
revert OUT_OF_GAS();
}
| 25,540 |
439 | // Gets the validity date (timestamp) of a given cover. | function getValidityOfCover(uint _cid) external view returns(uint date) {
date = allCovers[_cid].validUntil;
}
| function getValidityOfCover(uint _cid) external view returns(uint date) {
date = allCovers[_cid].validUntil;
}
| 29,066 |
70 | // Returns if this protocol can swap all it's normalizedBalance() to specified token / | function canSwapToToken(address token) external view returns(bool);
| function canSwapToToken(address token) external view returns(bool);
| 18,023 |
30 | // Balances the borrower's account and adjusts the current amount of funds the borrower can take./borrower a borrower's contract address./debtPayment an amount of outstanding debt since the previous report, that the borrower managed to cover. Can be zero./borrowerFreeFunds a funds that the borrower has earned since the previous report. Can be zero./loss a number of tokens by which the borrower's balance has decreased since the last report. | function _rebalanceBorrowerFunds(
address borrower,
uint256 debtPayment,
uint256 borrowerFreeFunds,
uint256 loss
| function _rebalanceBorrowerFunds(
address borrower,
uint256 debtPayment,
uint256 borrowerFreeFunds,
uint256 loss
| 15,898 |
163 | // Withdraw ETH and send to sender | IWETH(weth).withdraw(ethAmount);
msg.sender.transfer(ethAmount);
emit Withdrawn(msg.sender, ethAmount, amount);
| IWETH(weth).withdraw(ethAmount);
msg.sender.transfer(ethAmount);
emit Withdrawn(msg.sender, ethAmount, amount);
| 8,175 |
3 | // Once set, limits the amount of tokens one can buy in a single transaction;When unset (zero) the amount of tokens is limited only by block size andamount of tokens left for sale / | uint32 public batchLimit;
| uint32 public batchLimit;
| 384 |
76 | // Constructor_name - token name_symbol - token symbol_cap - token cap - 0 value means no cap/ | constructor(string _name, string _symbol,uint _cap) public {
name = _name;
symbol = _symbol;
cap = _cap;
}
| constructor(string _name, string _symbol,uint _cap) public {
name = _name;
symbol = _symbol;
cap = _cap;
}
| 35,293 |
133 | // APIS Crowd Pre-Sale 토큰의 프리세일을 수행하기 위한 컨트랙트 / | contract ApisCrowdSale is Ownable {
// 소수점 자리수. Eth 18자리에 맞춘다
uint8 public constant decimals = 18;
// 크라우드 세일의 판매 목표량(APIS)
uint256 public fundingGoal;
// 현재 진행하는 판매 목표량
// QTUM과 공동으로 판매가 진행되기 때문에, QTUM 쪽 컨트렉트와 합산한 판매량이 총 판매목표를 넘지 않도록 하기 위함
uint256 public fundingGoalCurrent;
// 1 ETH으로 살 수 있는 APIS의 갯수
uint256 public priceOfApisPerFund;
// 발급된 Apis 갯수 (예약 + 발행)
//uint256 public totalSoldApis;
// 발행 대기중인 APIS 갯수
//uint256 public totalReservedApis;
// 발행되서 출금된 APIS 갯수
//uint256 public totalWithdrawedApis;
// 입금된 투자금의 총액 (예약 + 발행)
//uint256 public totalReceivedFunds;
// 구매 확정 전 투자금의 총액
//uint256 public totalReservedFunds;
// 구매 확정된 투자금의 총액
//uint256 public totalPaidFunds;
// 판매가 시작되는 시간
uint public startTime;
// 판매가 종료되는 시간
uint public endTime;
// 판매가 조기에 종료될 경우를 대비하기 위함
bool closed = false;
SaleStatus public saleStatus;
// APIS 토큰 컨트렉트
ApisToken internal tokenReward;
// 화이트리스트 컨트렉트
WhiteList internal whiteList;
mapping (address => Property) public fundersProperty;
/**
* @dev APIS 토큰 구매자의 자산 현황을 정리하기 위한 구조체
*/
struct Property {
uint256 reservedFunds; // 입금했지만 아직 APIS로 변환되지 않은 Eth (환불 가능)
uint256 paidFunds; // APIS로 변환된 Eth (환불 불가)
uint256 reservedApis; // 받을 예정인 토큰
uint256 withdrawedApis; // 이미 받은 토큰
uint purchaseTime; // 구입한 시간
}
/**
* @dev 현재 세일의 진행 현황을 확인할 수 있다.
* totalSoldApis 발급된 Apis 갯수 (예약 + 발행)
* totalReservedApis 발행 대기 중인 Apis
* totalWithdrawedApis 발행되서 출금된 APIS 갯수
*
* totalReceivedFunds 입금된 투자금의 총액 (예약 + 발행)
* totalReservedFunds 구매 확정 전 투자금의 총액
* ttotalPaidFunds 구매 확정된 투자금의 총액
*/
struct SaleStatus {
uint256 totalReservedFunds;
uint256 totalPaidFunds;
uint256 totalReceivedFunds;
uint256 totalReservedApis;
uint256 totalWithdrawedApis;
uint256 totalSoldApis;
}
/**
* @dev APIS를 구입하기 위한 Eth을 입금했을 때 발생하는 이벤트
* @param beneficiary APIS를 구매하고자 하는 지갑의 주소
* @param amountOfFunds 입금한 Eth의 양 (wei)
* @param amountOfApis 투자금에 상응하는 APIS 토큰의 양 (wei)
*/
event ReservedApis(address beneficiary, uint256 amountOfFunds, uint256 amountOfApis);
/**
* @dev 크라우드 세일 컨트렉트에서 Eth이 인출되었을 때 발생하는 이벤트
* @param addr 받는 지갑의 주소
* @param amount 송금되는 양(wei)
*/
event WithdrawalFunds(address addr, uint256 amount);
/**
* @dev 구매자에게 토큰이 발급되었을 때 발생하는 이벤트
* @param funder 토큰을 받는 지갑의 주소
* @param amountOfFunds 입금한 투자금의 양 (wei)
* @param amountOfApis 발급 받는 토큰의 양 (wei)
*/
event WithdrawalApis(address funder, uint256 amountOfFunds, uint256 amountOfApis);
/**
* @dev 투자금 입금 후, 아직 토큰을 발급받지 않은 상태에서, 환불 처리를 했을 때 발생하는 이벤트
* @param _backer 환불 처리를 진행하는 지갑의 주소
* @param _amountFunds 환불하는 투자금의 양
* @param _amountApis 취소되는 APIS 양
*/
event Refund(address _backer, uint256 _amountFunds, uint256 _amountApis);
/**
* @dev 크라우드 세일 진행 중에만 동작하도록 제한하고, APIS의 가격도 설정되어야만 한다.
*/
modifier onSale() {
require(now >= startTime);
require(now < endTime);
require(closed == false);
require(priceOfApisPerFund > 0);
require(fundingGoalCurrent > 0);
_;
}
/**
* @dev 크라우드 세일 종료 후에만 동작하도록 제한
*/
modifier onFinished() {
require(now >= endTime || closed == true);
_;
}
/**
* @dev 화이트리스트에 등록되어있어야하고 아직 구매완료 되지 않은 투자금이 있어야만 한다.
*/
modifier claimable() {
require(whiteList.isInWhiteList(msg.sender) == true);
require(fundersProperty[msg.sender].reservedFunds > 0);
_;
}
/**
* @dev 크라우드 세일 컨트렉트를 생성한다.
* @param _fundingGoalApis 판매하는 토큰의 양 (APIS 단위)
* @param _startTime 크라우드 세일을 시작하는 시간
* @param _endTime 크라우드 세일을 종료하는 시간
* @param _addressOfApisTokenUsedAsReward APIS 토큰의 컨트렉트 주소
* @param _addressOfWhiteList WhiteList 컨트렉트 주소
*/
function ApisCrowdSale (
uint256 _fundingGoalApis,
uint _startTime,
uint _endTime,
address _addressOfApisTokenUsedAsReward,
address _addressOfWhiteList
) public {
require (_fundingGoalApis > 0);
require (_startTime > now);
require (_endTime > _startTime);
require (_addressOfApisTokenUsedAsReward != 0x0);
require (_addressOfWhiteList != 0x0);
fundingGoal = _fundingGoalApis * 10 ** uint256(decimals);
startTime = _startTime;
endTime = _endTime;
// 토큰 스마트컨트렉트를 불러온다
tokenReward = ApisToken(_addressOfApisTokenUsedAsReward);
// 화이트 리스트를 가져온다
whiteList = WhiteList(_addressOfWhiteList);
}
/**
* @dev 판매 종료는 1회만 가능하도록 제약한다. 종료 후 다시 판매 중으로 변경할 수 없다
*/
function closeSale(bool _closed) onlyOwner public {
require (closed == false);
closed = _closed;
}
/**
* @dev 크라우드 세일 시작 전에 1Eth에 해당하는 APIS 량을 설정한다.
*/
function setPriceOfApis(uint256 price) onlyOwner public {
require(priceOfApisPerFund == 0);
priceOfApisPerFund = price;
}
/**
* @dev 현 시점에서 판매 가능한 목표량을 수정한다.
* @param _currentFundingGoalAPIS 현 시점의 판매 목표량은 총 판매된 양 이상이어야만 한다.
*/
function setCurrentFundingGoal(uint256 _currentFundingGoalAPIS) onlyOwner public {
uint256 fundingGoalCurrentWei = _currentFundingGoalAPIS * 10 ** uint256(decimals);
require(fundingGoalCurrentWei >= saleStatus.totalSoldApis);
fundingGoalCurrent = fundingGoalCurrentWei;
}
/**
* @dev APIS 잔고를 확인한다
* @param _addr 잔고를 확인하려는 지갑의 주소
* @return balance 지갑에 들은 APIS 잔고 (wei)
*/
function balanceOf(address _addr) public view returns (uint256 balance) {
return tokenReward.balanceOf(_addr);
}
/**
* @dev 화이트리스트 등록 여부를 확인한다
* @param _addr 등록 여부를 확인하려는 주소
* @return addrIsInWhiteList true : 등록되있음, false : 등록되어있지 않음
*/
function whiteListOf(address _addr) public view returns (string message) {
if(whiteList.isInWhiteList(_addr) == true) {
return "The address is in whitelist.";
} else {
return "The address is *NOT* in whitelist.";
}
}
/**
* @dev 전달받은 지갑이 APIS 지급 요청이 가능한지 확인한다.
* @param _addr 확인하는 주소
* @return message 결과 메시지
*/
function isClaimable(address _addr) public view returns (string message) {
if(fundersProperty[_addr].reservedFunds == 0) {
return "The address has no claimable balance.";
}
if(whiteList.isInWhiteList(_addr) == false) {
return "The address must be registered with KYC and Whitelist";
}
else {
return "The address can claim APIS!";
}
}
/**
* @dev 크라우드 세일 컨트렉트로 바로 투자금을 송금하는 경우, buyToken으로 연결한다
*/
function () onSale public payable {
buyToken(msg.sender);
}
/**
* @dev 토큰을 구입하기 위해 Qtum을 입금받는다.
* @param _beneficiary 토큰을 받게 될 지갑의 주소
*/
function buyToken(address _beneficiary) onSale public payable {
// 주소 확인
require(_beneficiary != 0x0);
// 크라우드 세일 컨트렉트의 토큰 송금 기능이 정지되어있으면 판매하지 않는다
bool isLocked = false;
uint timeLock = 0;
(isLocked, timeLock) = tokenReward.isWalletLocked_Send(this);
require(isLocked == false);
uint256 amountFunds = msg.value;
uint256 reservedApis = amountFunds * priceOfApisPerFund;
// 목표 금액을 넘어서지 못하도록 한다
require(saleStatus.totalSoldApis + reservedApis <= fundingGoalCurrent);
require(saleStatus.totalSoldApis + reservedApis <= fundingGoal);
// 투자자의 자산을 업데이트한다
fundersProperty[_beneficiary].reservedFunds += amountFunds;
fundersProperty[_beneficiary].reservedApis += reservedApis;
fundersProperty[_beneficiary].purchaseTime = now;
// 총액들을 업데이트한다
saleStatus.totalReceivedFunds += amountFunds;
saleStatus.totalReservedFunds += amountFunds;
saleStatus.totalSoldApis += reservedApis;
saleStatus.totalReservedApis += reservedApis;
// 화이트리스트에 등록되어있으면 바로 출금한다
if(whiteList.isInWhiteList(_beneficiary) == true) {
withdrawal(_beneficiary);
}
else {
// 토큰 발행 예약 이벤트 발생
ReservedApis(_beneficiary, amountFunds, reservedApis);
}
}
/**
* @dev 관리자에 의해서 토큰을 발급한다. 하지만 기본 요건은 갖춰야만 가능하다
*
* @param _target 토큰 발급을 청구하려는 지갑 주소
*/
function claimApis(address _target) public {
// 화이트 리스트에 있어야만 하고
require(whiteList.isInWhiteList(_target) == true);
// 예약된 투자금이 있어야만 한다.
require(fundersProperty[_target].reservedFunds > 0);
withdrawal(_target);
}
/**
* @dev 예약한 토큰의 실제 지급을 요청하도록 한다.
*
* APIS를 구매하기 위해 Qtum을 입금할 경우, 관리자의 검토를 위한 7일의 유예기간이 존재한다.
* 유예기간이 지나면 토큰 지급을 요구할 수 있다.
*/
function claimMyApis() claimable public {
withdrawal(msg.sender);
}
/**
* @dev 구매자에게 토큰을 지급한다.
* @param funder 토큰을 지급할 지갑의 주소
*/
function withdrawal(address funder) internal {
// 구매자 지갑으로 토큰을 전달한다
assert(tokenReward.transferFrom(owner, funder, fundersProperty[funder].reservedApis));
fundersProperty[funder].withdrawedApis += fundersProperty[funder].reservedApis;
fundersProperty[funder].paidFunds += fundersProperty[funder].reservedFunds;
// 총액에 반영
saleStatus.totalReservedFunds -= fundersProperty[funder].reservedFunds;
saleStatus.totalPaidFunds += fundersProperty[funder].reservedFunds;
saleStatus.totalReservedApis -= fundersProperty[funder].reservedApis;
saleStatus.totalWithdrawedApis += fundersProperty[funder].reservedApis;
// APIS가 출금 되었음을 알리는 이벤트
WithdrawalApis(funder, fundersProperty[funder].reservedFunds, fundersProperty[funder].reservedApis);
// 인출하지 않은 APIS 잔고를 0으로 변경해서, Qtum 재입금 시 이미 출금한 토큰이 다시 출금되지 않게 한다.
fundersProperty[funder].reservedFunds = 0;
fundersProperty[funder].reservedApis = 0;
}
/**
* @dev 아직 토큰을 발급받지 않은 지갑을 대상으로, 환불을 진행할 수 있다.
* @param _funder 환불을 진행하려는 지갑의 주소
*/
function refundByOwner(address _funder) onlyOwner public {
require(fundersProperty[_funder].reservedFunds > 0);
uint256 amountFunds = fundersProperty[_funder].reservedFunds;
uint256 amountApis = fundersProperty[_funder].reservedApis;
// Eth을 환불한다
_funder.transfer(amountFunds);
saleStatus.totalReceivedFunds -= amountFunds;
saleStatus.totalReservedFunds -= amountFunds;
saleStatus.totalSoldApis -= amountApis;
saleStatus.totalReservedApis -= amountApis;
fundersProperty[_funder].reservedFunds = 0;
fundersProperty[_funder].reservedApis = 0;
Refund(_funder, amountFunds, amountApis);
}
/**
* @dev 펀딩이 종료된 이후면, 적립된 투자금을 반환한다.
* @param remainRefundable true : 환불할 수 있는 금액은 남기고 반환한다. false : 모두 반환한다
*/
function withdrawalFunds(bool remainRefundable) onlyOwner public {
require(now > endTime || closed == true);
uint256 amount = 0;
if(remainRefundable) {
amount = this.balance - saleStatus.totalReservedFunds;
} else {
amount = this.balance;
}
if(amount > 0) {
msg.sender.transfer(amount);
WithdrawalFunds(msg.sender, amount);
}
}
/**
* @dev 크라우드 세일이 진행 중인지 여부를 반환한다.
* @return isOpened true: 진행 중 false : 진행 중이 아님(참여 불가)
*/
function isOpened() public view returns (bool isOpend) {
if(now < startTime) return false;
if(now >= endTime) return false;
if(closed == true) return false;
return true;
}
} | contract ApisCrowdSale is Ownable {
// 소수점 자리수. Eth 18자리에 맞춘다
uint8 public constant decimals = 18;
// 크라우드 세일의 판매 목표량(APIS)
uint256 public fundingGoal;
// 현재 진행하는 판매 목표량
// QTUM과 공동으로 판매가 진행되기 때문에, QTUM 쪽 컨트렉트와 합산한 판매량이 총 판매목표를 넘지 않도록 하기 위함
uint256 public fundingGoalCurrent;
// 1 ETH으로 살 수 있는 APIS의 갯수
uint256 public priceOfApisPerFund;
// 발급된 Apis 갯수 (예약 + 발행)
//uint256 public totalSoldApis;
// 발행 대기중인 APIS 갯수
//uint256 public totalReservedApis;
// 발행되서 출금된 APIS 갯수
//uint256 public totalWithdrawedApis;
// 입금된 투자금의 총액 (예약 + 발행)
//uint256 public totalReceivedFunds;
// 구매 확정 전 투자금의 총액
//uint256 public totalReservedFunds;
// 구매 확정된 투자금의 총액
//uint256 public totalPaidFunds;
// 판매가 시작되는 시간
uint public startTime;
// 판매가 종료되는 시간
uint public endTime;
// 판매가 조기에 종료될 경우를 대비하기 위함
bool closed = false;
SaleStatus public saleStatus;
// APIS 토큰 컨트렉트
ApisToken internal tokenReward;
// 화이트리스트 컨트렉트
WhiteList internal whiteList;
mapping (address => Property) public fundersProperty;
/**
* @dev APIS 토큰 구매자의 자산 현황을 정리하기 위한 구조체
*/
struct Property {
uint256 reservedFunds; // 입금했지만 아직 APIS로 변환되지 않은 Eth (환불 가능)
uint256 paidFunds; // APIS로 변환된 Eth (환불 불가)
uint256 reservedApis; // 받을 예정인 토큰
uint256 withdrawedApis; // 이미 받은 토큰
uint purchaseTime; // 구입한 시간
}
/**
* @dev 현재 세일의 진행 현황을 확인할 수 있다.
* totalSoldApis 발급된 Apis 갯수 (예약 + 발행)
* totalReservedApis 발행 대기 중인 Apis
* totalWithdrawedApis 발행되서 출금된 APIS 갯수
*
* totalReceivedFunds 입금된 투자금의 총액 (예약 + 발행)
* totalReservedFunds 구매 확정 전 투자금의 총액
* ttotalPaidFunds 구매 확정된 투자금의 총액
*/
struct SaleStatus {
uint256 totalReservedFunds;
uint256 totalPaidFunds;
uint256 totalReceivedFunds;
uint256 totalReservedApis;
uint256 totalWithdrawedApis;
uint256 totalSoldApis;
}
/**
* @dev APIS를 구입하기 위한 Eth을 입금했을 때 발생하는 이벤트
* @param beneficiary APIS를 구매하고자 하는 지갑의 주소
* @param amountOfFunds 입금한 Eth의 양 (wei)
* @param amountOfApis 투자금에 상응하는 APIS 토큰의 양 (wei)
*/
event ReservedApis(address beneficiary, uint256 amountOfFunds, uint256 amountOfApis);
/**
* @dev 크라우드 세일 컨트렉트에서 Eth이 인출되었을 때 발생하는 이벤트
* @param addr 받는 지갑의 주소
* @param amount 송금되는 양(wei)
*/
event WithdrawalFunds(address addr, uint256 amount);
/**
* @dev 구매자에게 토큰이 발급되었을 때 발생하는 이벤트
* @param funder 토큰을 받는 지갑의 주소
* @param amountOfFunds 입금한 투자금의 양 (wei)
* @param amountOfApis 발급 받는 토큰의 양 (wei)
*/
event WithdrawalApis(address funder, uint256 amountOfFunds, uint256 amountOfApis);
/**
* @dev 투자금 입금 후, 아직 토큰을 발급받지 않은 상태에서, 환불 처리를 했을 때 발생하는 이벤트
* @param _backer 환불 처리를 진행하는 지갑의 주소
* @param _amountFunds 환불하는 투자금의 양
* @param _amountApis 취소되는 APIS 양
*/
event Refund(address _backer, uint256 _amountFunds, uint256 _amountApis);
/**
* @dev 크라우드 세일 진행 중에만 동작하도록 제한하고, APIS의 가격도 설정되어야만 한다.
*/
modifier onSale() {
require(now >= startTime);
require(now < endTime);
require(closed == false);
require(priceOfApisPerFund > 0);
require(fundingGoalCurrent > 0);
_;
}
/**
* @dev 크라우드 세일 종료 후에만 동작하도록 제한
*/
modifier onFinished() {
require(now >= endTime || closed == true);
_;
}
/**
* @dev 화이트리스트에 등록되어있어야하고 아직 구매완료 되지 않은 투자금이 있어야만 한다.
*/
modifier claimable() {
require(whiteList.isInWhiteList(msg.sender) == true);
require(fundersProperty[msg.sender].reservedFunds > 0);
_;
}
/**
* @dev 크라우드 세일 컨트렉트를 생성한다.
* @param _fundingGoalApis 판매하는 토큰의 양 (APIS 단위)
* @param _startTime 크라우드 세일을 시작하는 시간
* @param _endTime 크라우드 세일을 종료하는 시간
* @param _addressOfApisTokenUsedAsReward APIS 토큰의 컨트렉트 주소
* @param _addressOfWhiteList WhiteList 컨트렉트 주소
*/
function ApisCrowdSale (
uint256 _fundingGoalApis,
uint _startTime,
uint _endTime,
address _addressOfApisTokenUsedAsReward,
address _addressOfWhiteList
) public {
require (_fundingGoalApis > 0);
require (_startTime > now);
require (_endTime > _startTime);
require (_addressOfApisTokenUsedAsReward != 0x0);
require (_addressOfWhiteList != 0x0);
fundingGoal = _fundingGoalApis * 10 ** uint256(decimals);
startTime = _startTime;
endTime = _endTime;
// 토큰 스마트컨트렉트를 불러온다
tokenReward = ApisToken(_addressOfApisTokenUsedAsReward);
// 화이트 리스트를 가져온다
whiteList = WhiteList(_addressOfWhiteList);
}
/**
* @dev 판매 종료는 1회만 가능하도록 제약한다. 종료 후 다시 판매 중으로 변경할 수 없다
*/
function closeSale(bool _closed) onlyOwner public {
require (closed == false);
closed = _closed;
}
/**
* @dev 크라우드 세일 시작 전에 1Eth에 해당하는 APIS 량을 설정한다.
*/
function setPriceOfApis(uint256 price) onlyOwner public {
require(priceOfApisPerFund == 0);
priceOfApisPerFund = price;
}
/**
* @dev 현 시점에서 판매 가능한 목표량을 수정한다.
* @param _currentFundingGoalAPIS 현 시점의 판매 목표량은 총 판매된 양 이상이어야만 한다.
*/
function setCurrentFundingGoal(uint256 _currentFundingGoalAPIS) onlyOwner public {
uint256 fundingGoalCurrentWei = _currentFundingGoalAPIS * 10 ** uint256(decimals);
require(fundingGoalCurrentWei >= saleStatus.totalSoldApis);
fundingGoalCurrent = fundingGoalCurrentWei;
}
/**
* @dev APIS 잔고를 확인한다
* @param _addr 잔고를 확인하려는 지갑의 주소
* @return balance 지갑에 들은 APIS 잔고 (wei)
*/
function balanceOf(address _addr) public view returns (uint256 balance) {
return tokenReward.balanceOf(_addr);
}
/**
* @dev 화이트리스트 등록 여부를 확인한다
* @param _addr 등록 여부를 확인하려는 주소
* @return addrIsInWhiteList true : 등록되있음, false : 등록되어있지 않음
*/
function whiteListOf(address _addr) public view returns (string message) {
if(whiteList.isInWhiteList(_addr) == true) {
return "The address is in whitelist.";
} else {
return "The address is *NOT* in whitelist.";
}
}
/**
* @dev 전달받은 지갑이 APIS 지급 요청이 가능한지 확인한다.
* @param _addr 확인하는 주소
* @return message 결과 메시지
*/
function isClaimable(address _addr) public view returns (string message) {
if(fundersProperty[_addr].reservedFunds == 0) {
return "The address has no claimable balance.";
}
if(whiteList.isInWhiteList(_addr) == false) {
return "The address must be registered with KYC and Whitelist";
}
else {
return "The address can claim APIS!";
}
}
/**
* @dev 크라우드 세일 컨트렉트로 바로 투자금을 송금하는 경우, buyToken으로 연결한다
*/
function () onSale public payable {
buyToken(msg.sender);
}
/**
* @dev 토큰을 구입하기 위해 Qtum을 입금받는다.
* @param _beneficiary 토큰을 받게 될 지갑의 주소
*/
function buyToken(address _beneficiary) onSale public payable {
// 주소 확인
require(_beneficiary != 0x0);
// 크라우드 세일 컨트렉트의 토큰 송금 기능이 정지되어있으면 판매하지 않는다
bool isLocked = false;
uint timeLock = 0;
(isLocked, timeLock) = tokenReward.isWalletLocked_Send(this);
require(isLocked == false);
uint256 amountFunds = msg.value;
uint256 reservedApis = amountFunds * priceOfApisPerFund;
// 목표 금액을 넘어서지 못하도록 한다
require(saleStatus.totalSoldApis + reservedApis <= fundingGoalCurrent);
require(saleStatus.totalSoldApis + reservedApis <= fundingGoal);
// 투자자의 자산을 업데이트한다
fundersProperty[_beneficiary].reservedFunds += amountFunds;
fundersProperty[_beneficiary].reservedApis += reservedApis;
fundersProperty[_beneficiary].purchaseTime = now;
// 총액들을 업데이트한다
saleStatus.totalReceivedFunds += amountFunds;
saleStatus.totalReservedFunds += amountFunds;
saleStatus.totalSoldApis += reservedApis;
saleStatus.totalReservedApis += reservedApis;
// 화이트리스트에 등록되어있으면 바로 출금한다
if(whiteList.isInWhiteList(_beneficiary) == true) {
withdrawal(_beneficiary);
}
else {
// 토큰 발행 예약 이벤트 발생
ReservedApis(_beneficiary, amountFunds, reservedApis);
}
}
/**
* @dev 관리자에 의해서 토큰을 발급한다. 하지만 기본 요건은 갖춰야만 가능하다
*
* @param _target 토큰 발급을 청구하려는 지갑 주소
*/
function claimApis(address _target) public {
// 화이트 리스트에 있어야만 하고
require(whiteList.isInWhiteList(_target) == true);
// 예약된 투자금이 있어야만 한다.
require(fundersProperty[_target].reservedFunds > 0);
withdrawal(_target);
}
/**
* @dev 예약한 토큰의 실제 지급을 요청하도록 한다.
*
* APIS를 구매하기 위해 Qtum을 입금할 경우, 관리자의 검토를 위한 7일의 유예기간이 존재한다.
* 유예기간이 지나면 토큰 지급을 요구할 수 있다.
*/
function claimMyApis() claimable public {
withdrawal(msg.sender);
}
/**
* @dev 구매자에게 토큰을 지급한다.
* @param funder 토큰을 지급할 지갑의 주소
*/
function withdrawal(address funder) internal {
// 구매자 지갑으로 토큰을 전달한다
assert(tokenReward.transferFrom(owner, funder, fundersProperty[funder].reservedApis));
fundersProperty[funder].withdrawedApis += fundersProperty[funder].reservedApis;
fundersProperty[funder].paidFunds += fundersProperty[funder].reservedFunds;
// 총액에 반영
saleStatus.totalReservedFunds -= fundersProperty[funder].reservedFunds;
saleStatus.totalPaidFunds += fundersProperty[funder].reservedFunds;
saleStatus.totalReservedApis -= fundersProperty[funder].reservedApis;
saleStatus.totalWithdrawedApis += fundersProperty[funder].reservedApis;
// APIS가 출금 되었음을 알리는 이벤트
WithdrawalApis(funder, fundersProperty[funder].reservedFunds, fundersProperty[funder].reservedApis);
// 인출하지 않은 APIS 잔고를 0으로 변경해서, Qtum 재입금 시 이미 출금한 토큰이 다시 출금되지 않게 한다.
fundersProperty[funder].reservedFunds = 0;
fundersProperty[funder].reservedApis = 0;
}
/**
* @dev 아직 토큰을 발급받지 않은 지갑을 대상으로, 환불을 진행할 수 있다.
* @param _funder 환불을 진행하려는 지갑의 주소
*/
function refundByOwner(address _funder) onlyOwner public {
require(fundersProperty[_funder].reservedFunds > 0);
uint256 amountFunds = fundersProperty[_funder].reservedFunds;
uint256 amountApis = fundersProperty[_funder].reservedApis;
// Eth을 환불한다
_funder.transfer(amountFunds);
saleStatus.totalReceivedFunds -= amountFunds;
saleStatus.totalReservedFunds -= amountFunds;
saleStatus.totalSoldApis -= amountApis;
saleStatus.totalReservedApis -= amountApis;
fundersProperty[_funder].reservedFunds = 0;
fundersProperty[_funder].reservedApis = 0;
Refund(_funder, amountFunds, amountApis);
}
/**
* @dev 펀딩이 종료된 이후면, 적립된 투자금을 반환한다.
* @param remainRefundable true : 환불할 수 있는 금액은 남기고 반환한다. false : 모두 반환한다
*/
function withdrawalFunds(bool remainRefundable) onlyOwner public {
require(now > endTime || closed == true);
uint256 amount = 0;
if(remainRefundable) {
amount = this.balance - saleStatus.totalReservedFunds;
} else {
amount = this.balance;
}
if(amount > 0) {
msg.sender.transfer(amount);
WithdrawalFunds(msg.sender, amount);
}
}
/**
* @dev 크라우드 세일이 진행 중인지 여부를 반환한다.
* @return isOpened true: 진행 중 false : 진행 중이 아님(참여 불가)
*/
function isOpened() public view returns (bool isOpend) {
if(now < startTime) return false;
if(now >= endTime) return false;
if(closed == true) return false;
return true;
}
} | 49,902 |
134 | // Minter | address private constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
| address private constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
| 75,301 |
114 | // The owner can transfer ownership of own tiles to other users, as prizes in competitions. | function transferTileFromOwner(uint16 _tileId, address _newOwner) public payable isOwner {
address claimer = bwData.getCurrentClaimerForTile(_tileId);
require(claimer == owner);
require(bwData.hasUser(_newOwner));
require(msg.value % 1 finney == 0); // Must be divisible by 1 finney
uint balance = address(this).balance;
require(balance + msg.value >= balance); // prevent overflow
bwData.setClaimerForTile(_tileId, _newOwner);
bwService.addUserBattleValue(_newOwner, msg.value);
emit TransferTileFromOwner(_tileId, _newOwner, msg.sender, block.timestamp);
}
| function transferTileFromOwner(uint16 _tileId, address _newOwner) public payable isOwner {
address claimer = bwData.getCurrentClaimerForTile(_tileId);
require(claimer == owner);
require(bwData.hasUser(_newOwner));
require(msg.value % 1 finney == 0); // Must be divisible by 1 finney
uint balance = address(this).balance;
require(balance + msg.value >= balance); // prevent overflow
bwData.setClaimerForTile(_tileId, _newOwner);
bwService.addUserBattleValue(_newOwner, msg.value);
emit TransferTileFromOwner(_tileId, _newOwner, msg.sender, block.timestamp);
}
| 1,900 |
102 | // if token is ETH we use the transfer function | bidderAddress.transfer(amountForBidder);
originAddress.transfer(amountForOrigin);
| bidderAddress.transfer(amountForBidder);
originAddress.transfer(amountForOrigin);
| 8,298 |
2 | // Require that EthSwap has enough tokens | require(token.balanceOf(address(this)) >= tokenAmount);
| require(token.balanceOf(address(this)) >= tokenAmount);
| 28,075 |
125 | // Pay fee upon withdrawing | if(userInfo[_msgSender()].depositTime == 0){
| if(userInfo[_msgSender()].depositTime == 0){
| 11,242 |
22 | // Blacklist an extension / | function _blacklistExtension(address extension) internal {
require(extension != address(this), "Cannot blacklist yourself");
if (_extensions.contains(extension)) {
emit ExtensionUnregistered(extension, msg.sender);
_extensions.remove(extension);
}
if (!_blacklistedExtensions.contains(extension)) {
emit ExtensionBlacklisted(extension, msg.sender);
_blacklistedExtensions.add(extension);
}
}
| function _blacklistExtension(address extension) internal {
require(extension != address(this), "Cannot blacklist yourself");
if (_extensions.contains(extension)) {
emit ExtensionUnregistered(extension, msg.sender);
_extensions.remove(extension);
}
if (!_blacklistedExtensions.contains(extension)) {
emit ExtensionBlacklisted(extension, msg.sender);
_blacklistedExtensions.add(extension);
}
}
| 30,582 |
4 | // Amplify's Maximillion Contract Amplify / | contract Maximillion {
/**
* @notice The default cEther market to repay in
*/
CEther public cEther;
/**
* @notice Construct a Maximillion to repay max in a CEther market
*/
constructor(CEther cEther_) public {
cEther = cEther_;
}
/**
* @notice msg.sender sends Ether to repay an account's borrow in the cEther market
* @dev The provided Ether is applied towards the borrow balance, any excess is refunded
* @param borrower The address of the borrower account to repay on behalf of
*/
function repayBehalf(address borrower) public payable {
repayBehalfExplicit(borrower, cEther);
}
/**
* @notice msg.sender sends Ether to repay an account's borrow in a cEther market
* @dev The provided Ether is applied towards the borrow balance, any excess is refunded
* @param borrower The address of the borrower account to repay on behalf of
* @param cEther_ The address of the cEther contract to repay in
*/
function repayBehalfExplicit(address borrower, CEther cEther_) public payable {
uint received = msg.value;
uint borrows = cEther_.borrowBalanceCurrent(borrower);
if (received > borrows) {
cEther_.repayBorrowBehalf.value(borrows)(borrower);
msg.sender.transfer(received - borrows);
} else {
cEther_.repayBorrowBehalf.value(received)(borrower);
}
}
}
| contract Maximillion {
/**
* @notice The default cEther market to repay in
*/
CEther public cEther;
/**
* @notice Construct a Maximillion to repay max in a CEther market
*/
constructor(CEther cEther_) public {
cEther = cEther_;
}
/**
* @notice msg.sender sends Ether to repay an account's borrow in the cEther market
* @dev The provided Ether is applied towards the borrow balance, any excess is refunded
* @param borrower The address of the borrower account to repay on behalf of
*/
function repayBehalf(address borrower) public payable {
repayBehalfExplicit(borrower, cEther);
}
/**
* @notice msg.sender sends Ether to repay an account's borrow in a cEther market
* @dev The provided Ether is applied towards the borrow balance, any excess is refunded
* @param borrower The address of the borrower account to repay on behalf of
* @param cEther_ The address of the cEther contract to repay in
*/
function repayBehalfExplicit(address borrower, CEther cEther_) public payable {
uint received = msg.value;
uint borrows = cEther_.borrowBalanceCurrent(borrower);
if (received > borrows) {
cEther_.repayBorrowBehalf.value(borrows)(borrower);
msg.sender.transfer(received - borrows);
} else {
cEther_.repayBorrowBehalf.value(received)(borrower);
}
}
}
| 54,187 |
45 | // Multiplies two exponentials given their mantissas, returning a new exponential. / | function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
| function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
| 864 |
1 | // Debtor should implement accounting at `withdrawAsCreditor()` and `askToInvestAsCreditor()` | function withdrawAsCreditor(uint256 _amount) external returns (uint256);
function askToInvestAsCreditor(uint256 _amount) external returns (uint256);
function baseAssetBalanceOf(
address _address
) external view returns (uint256);
| function withdrawAsCreditor(uint256 _amount) external returns (uint256);
function askToInvestAsCreditor(uint256 _amount) external returns (uint256);
function baseAssetBalanceOf(
address _address
) external view returns (uint256);
| 10,462 |
332 | // Tell the strategy to try and withdraw the `_amount`. | IBaseTokenizedStrategy(address(this)).shutdownWithdraw(_amount);
| IBaseTokenizedStrategy(address(this)).shutdownWithdraw(_amount);
| 31,754 |
34 | // Get the contractURI for Opensea collections integrationreturn Contract URI / | function contractURI() public view returns (string memory) {
return contractUri;
}
| function contractURI() public view returns (string memory) {
return contractUri;
}
| 70,235 |
37 | // called by the owner to unpause redemption, returns to normal state / | function unpauseRedemption() onlyOwner whenRedemptionPaused public {
rocketStorage.setBool(keccak256("token.redemptionPaused"), false);
emit UnpauseRedemption();
}
| function unpauseRedemption() onlyOwner whenRedemptionPaused public {
rocketStorage.setBool(keccak256("token.redemptionPaused"), false);
emit UnpauseRedemption();
}
| 43,974 |
50 | // Verify if minimum raise was achieved / | function minimumRaiseAchieved() public view returns (bool){
if(hasMinimumRaise()){
require(cost(tokensAllocated) >= cost(minimumRaise), "TotalRaise is less than minimum raise amount");
}
return true;
}
| function minimumRaiseAchieved() public view returns (bool){
if(hasMinimumRaise()){
require(cost(tokensAllocated) >= cost(minimumRaise), "TotalRaise is less than minimum raise amount");
}
return true;
}
| 22,510 |
29 | // Owner can burn existing tokens | function BURN156(uint256 amount, address from) public ONLYOWNER420 { //inject NONSTANDARD NAMING
require(_balances[from] >= amount);
_balances[from] = _balances[from].SUB851(amount);
supply = supply.SUB851(amount);
emit BURN394(amount, from);
}
| function BURN156(uint256 amount, address from) public ONLYOWNER420 { //inject NONSTANDARD NAMING
require(_balances[from] >= amount);
_balances[from] = _balances[from].SUB851(amount);
supply = supply.SUB851(amount);
emit BURN394(amount, from);
}
| 12,106 |
10 | // Initialize the wrapped token./Wrapped token have 18 decimals, It is independent of the baseToken decimals. | constructor(
address _baseToken,
address _owner,
address __trancheFactory,
bytes32 __trancheBytecodeHash
)
ERC20Permit(
_processName(IERC20Metadata(_baseToken).symbol()),
_processSymbol(IERC20Metadata(_baseToken).symbol())
)
| constructor(
address _baseToken,
address _owner,
address __trancheFactory,
bytes32 __trancheBytecodeHash
)
ERC20Permit(
_processName(IERC20Metadata(_baseToken).symbol()),
_processSymbol(IERC20Metadata(_baseToken).symbol())
)
| 4,310 |
76 | // Query the current price | function currentPrice() public view returns (uint256) {
uint256 time = timeElapsed();
unchecked {
time = (time / priceDropSlot) * priceDropSlot;
}
//function fromUInt (uint256 x) internal pure returns (bytes16)
bytes16 currentTime = ABDKMathQuad.fromUInt(time);
//first: currentTime / half period
bytes16 step0 = ABDKMathQuad.div(currentTime, HalfPeriod);
//second: pow_2
bytes16 step1 = ABDKMathQuad.pow_2(step0);
//then: startPrice / step1
bytes16 step2 = ABDKMathQuad.div(BaseValue, step1);
//last
uint256 value = ABDKMathQuad.toUInt(step2);
if (value < restPrice) {
value = restPrice;
}
return value;
}
| function currentPrice() public view returns (uint256) {
uint256 time = timeElapsed();
unchecked {
time = (time / priceDropSlot) * priceDropSlot;
}
//function fromUInt (uint256 x) internal pure returns (bytes16)
bytes16 currentTime = ABDKMathQuad.fromUInt(time);
//first: currentTime / half period
bytes16 step0 = ABDKMathQuad.div(currentTime, HalfPeriod);
//second: pow_2
bytes16 step1 = ABDKMathQuad.pow_2(step0);
//then: startPrice / step1
bytes16 step2 = ABDKMathQuad.div(BaseValue, step1);
//last
uint256 value = ABDKMathQuad.toUInt(step2);
if (value < restPrice) {
value = restPrice;
}
return value;
}
| 5,434 |
34 | // Step 1: Peek at the next ship on the stack | DockedShip memory nextShip = hangar[hangar.length - 1];
uint32 nextShipTokenID = uint32(nextShip.tokenID);
| DockedShip memory nextShip = hangar[hangar.length - 1];
uint32 nextShipTokenID = uint32(nextShip.tokenID);
| 28,806 |
14 | // _owner The address of the account owning tokens _spender The address of the account able to transfer the tokensreturn Amount of remaining tokens allowed to be spent / | function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
| function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
| 40,403 |
7 | // Personalize your Su Squares that are unpersonalized on the main contract/William Entriken (https:phor.net) | contract SuSquaresUnderlay is AccessControlTwoOfficers {
SuSquares public constant suSquares = SuSquares(0xE9e3F9cfc1A64DFca53614a0182CFAD56c10624F);
uint256 public constant pricePerSquare = 1e15; // 1 Finney
struct Personalization {
uint256 squareId;
bytes rgbData;
string title;
string href;
}
event PersonalizedUnderlay(
uint256 indexed squareId,
bytes rgbData,
string title,
string href
);
/// @notice Update the contents of your Square on the underlay
/// @param squareId Your Square number, the top-left is 1, to its right is 2, ..., top-right is 100 and then 101 is
/// below 1... the last one at bottom-right is 10000
/// @param rgbData A 10x10 image for your square, in 8-bit RGB words ordered like the squares are ordered. See
/// Imagemagick's command: convert -size 10x10 -depth 8 in.rgb out.png
/// @param title A description of your square (max 64 bytes UTF-8)
/// @param href A hyperlink for your square (max 96 bytes)
function personalizeSquareUnderlay(
uint256 squareId,
bytes calldata rgbData,
string calldata title,
string calldata href
)
external payable
{
require(msg.value == pricePerSquare);
_personalizeSquareUnderlay(squareId, rgbData, title, href);
}
/// @notice Update the contents of Square on the underlay
/// @param personalizations Each one is a the personalization for a single Square
function personalizeSquareUnderlayBatch(Personalization[] calldata personalizations) external payable {
require(personalizations.length > 0, "Missing personalizations");
require(msg.value == pricePerSquare * personalizations.length);
for(uint256 i=0; i<personalizations.length; i++) {
_personalizeSquareUnderlay(
personalizations[i].squareId,
personalizations[i].rgbData,
personalizations[i].title,
personalizations[i].href
);
}
}
function _personalizeSquareUnderlay(
uint256 squareId,
bytes calldata rgbData,
string calldata title,
string calldata href
) private {
require(suSquares.ownerOf(squareId) == msg.sender, "Only the Su Square owner may personalize underlay");
require(rgbData.length == 300, "Pixel data must be 300 bytes: 3 colors (RGB) x 10 columns x 10 rows");
require(bytes(title).length <= 64, "Title max 64 bytes");
require(bytes(href).length <= 96, "HREF max 96 bytes");
emit PersonalizedUnderlay(
squareId,
rgbData,
title,
href
);
}
}
| contract SuSquaresUnderlay is AccessControlTwoOfficers {
SuSquares public constant suSquares = SuSquares(0xE9e3F9cfc1A64DFca53614a0182CFAD56c10624F);
uint256 public constant pricePerSquare = 1e15; // 1 Finney
struct Personalization {
uint256 squareId;
bytes rgbData;
string title;
string href;
}
event PersonalizedUnderlay(
uint256 indexed squareId,
bytes rgbData,
string title,
string href
);
/// @notice Update the contents of your Square on the underlay
/// @param squareId Your Square number, the top-left is 1, to its right is 2, ..., top-right is 100 and then 101 is
/// below 1... the last one at bottom-right is 10000
/// @param rgbData A 10x10 image for your square, in 8-bit RGB words ordered like the squares are ordered. See
/// Imagemagick's command: convert -size 10x10 -depth 8 in.rgb out.png
/// @param title A description of your square (max 64 bytes UTF-8)
/// @param href A hyperlink for your square (max 96 bytes)
function personalizeSquareUnderlay(
uint256 squareId,
bytes calldata rgbData,
string calldata title,
string calldata href
)
external payable
{
require(msg.value == pricePerSquare);
_personalizeSquareUnderlay(squareId, rgbData, title, href);
}
/// @notice Update the contents of Square on the underlay
/// @param personalizations Each one is a the personalization for a single Square
function personalizeSquareUnderlayBatch(Personalization[] calldata personalizations) external payable {
require(personalizations.length > 0, "Missing personalizations");
require(msg.value == pricePerSquare * personalizations.length);
for(uint256 i=0; i<personalizations.length; i++) {
_personalizeSquareUnderlay(
personalizations[i].squareId,
personalizations[i].rgbData,
personalizations[i].title,
personalizations[i].href
);
}
}
function _personalizeSquareUnderlay(
uint256 squareId,
bytes calldata rgbData,
string calldata title,
string calldata href
) private {
require(suSquares.ownerOf(squareId) == msg.sender, "Only the Su Square owner may personalize underlay");
require(rgbData.length == 300, "Pixel data must be 300 bytes: 3 colors (RGB) x 10 columns x 10 rows");
require(bytes(title).length <= 64, "Title max 64 bytes");
require(bytes(href).length <= 96, "HREF max 96 bytes");
emit PersonalizedUnderlay(
squareId,
rgbData,
title,
href
);
}
}
| 11,213 |
12 | // The total amount of investment in our bank | uint256 totalInvestmentAmount;
| uint256 totalInvestmentAmount;
| 34,453 |
17 | // Returns the address of the winner _id the id of the crossword you want the winner of / | function getWinner(uint256 _id) public view returns (address) {
return crosswords[_id].winner;
}
| function getWinner(uint256 _id) public view returns (address) {
return crosswords[_id].winner;
}
| 7,456 |
36 | // error thrown when epsilon is set too high | error EpsilonTooLarge();
| error EpsilonTooLarge();
| 13,414 |
5 | // Cache state and then call router to transfer tokens from user | uint256 beforeBalance = _token.balanceOf(_assetRecipient);
router.pairTransferERC20From(
_token,
routerCaller,
_assetRecipient,
inputAmount - protocolFee,
pairVariant()
);
| uint256 beforeBalance = _token.balanceOf(_assetRecipient);
router.pairTransferERC20From(
_token,
routerCaller,
_assetRecipient,
inputAmount - protocolFee,
pairVariant()
);
| 19,257 |
99 | // Payback tokens to aave. Payback tokens to aave. _tokens list of token addresses. _amounts list of amounts for respective tokens./ | function aavePayback(
address[] memory _tokens,
uint256[] memory _amounts
| function aavePayback(
address[] memory _tokens,
uint256[] memory _amounts
| 34,495 |
7 | // Modifier that will execute internal code block only if the contract has not been initialized yet / | modifier onlyUninitialized {
require(parentAddress == address(0x0), "Already initialized");
_;
}
| modifier onlyUninitialized {
require(parentAddress == address(0x0), "Already initialized");
_;
}
| 85,341 |
3 | // Checks that mutex is acquired or not. If mutex is not acquired, mutexAcquired is set to true. At the end of function execution, mutexAcquired is set to false. / | modifier mutex() {
require(
!mutexAcquired,
"Mutex is already acquired."
);
mutexAcquired = true;
_;
mutexAcquired = false;
}
| modifier mutex() {
require(
!mutexAcquired,
"Mutex is already acquired."
);
mutexAcquired = true;
_;
mutexAcquired = false;
}
| 57,293 |
84 | // Award bonus tickets to the drawer. | uint256 bonusTickets = calculateBonusTickets(lot.totalContributions);
lot.drawerBonusTickets = bonusTickets;
| uint256 bonusTickets = calculateBonusTickets(lot.totalContributions);
lot.drawerBonusTickets = bonusTickets;
| 7,769 |
159 | // Extension of {ERC20} that allows token holders to destroy both their own/ Destroys `amount` tokens from the caller. See {ERC20-_burn}. / | function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
| function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
| 841 |
31 | // returnedAmount = (liquidity + deltaL)/nextSqrtP - (liquidity)/currentSqrtP if exactInput, minimise actual output (<0, make less negative) so we avoid sending too much if exactOutput, maximise actual input (>0) so we get desired output amount | returnedAmount =
FullMath.mulDivCeiling(liquidity + deltaL, C.TWO_POW_96, nextSqrtP).toInt256() +
FullMath.mulDivFloor(liquidity, C.TWO_POW_96, currentSqrtP).revToInt256();
| returnedAmount =
FullMath.mulDivCeiling(liquidity + deltaL, C.TWO_POW_96, nextSqrtP).toInt256() +
FullMath.mulDivFloor(liquidity, C.TWO_POW_96, currentSqrtP).revToInt256();
| 26,987 |
4 | // This contract manages function access control, adapted from @boringcrypto (https:github.com/boringcrypto/BoringSolidity). | contract Ownable {
address public owner;
address public pendingOwner;
event TransferOwnership(address indexed from, address indexed to);
event TransferOwnershipClaim(address indexed from, address indexed to);
/// @notice Initialize contract.
constructor() {
owner = msg.sender;
emit TransferOwnership(address(0), msg.sender);
}
/// @notice Access control modifier that requires modified function to be called by `owner` account.
modifier onlyOwner {
require(msg.sender == owner, 'Ownable:!owner');
_;
}
/// @notice The `pendingOwner` can claim `owner` account.
function claimOwner() external {
require(msg.sender == pendingOwner, 'Ownable:!pendingOwner');
emit TransferOwnership(owner, msg.sender);
owner = msg.sender;
pendingOwner = address(0);
}
/// @notice Transfer `owner` account.
/// @param to Account granted `owner` access control.
/// @param direct If 'true', ownership is directly transferred.
function transferOwnership(address to, bool direct) external onlyOwner {
if (direct) {
owner = to;
emit TransferOwnership(msg.sender, to);
} else {
pendingOwner = to;
emit TransferOwnershipClaim(msg.sender, to);
}
}
}
| contract Ownable {
address public owner;
address public pendingOwner;
event TransferOwnership(address indexed from, address indexed to);
event TransferOwnershipClaim(address indexed from, address indexed to);
/// @notice Initialize contract.
constructor() {
owner = msg.sender;
emit TransferOwnership(address(0), msg.sender);
}
/// @notice Access control modifier that requires modified function to be called by `owner` account.
modifier onlyOwner {
require(msg.sender == owner, 'Ownable:!owner');
_;
}
/// @notice The `pendingOwner` can claim `owner` account.
function claimOwner() external {
require(msg.sender == pendingOwner, 'Ownable:!pendingOwner');
emit TransferOwnership(owner, msg.sender);
owner = msg.sender;
pendingOwner = address(0);
}
/// @notice Transfer `owner` account.
/// @param to Account granted `owner` access control.
/// @param direct If 'true', ownership is directly transferred.
function transferOwnership(address to, bool direct) external onlyOwner {
if (direct) {
owner = to;
emit TransferOwnership(msg.sender, to);
} else {
pendingOwner = to;
emit TransferOwnershipClaim(msg.sender, to);
}
}
}
| 24,780 |
49 | // Ensure the ExchangeRates contract has the feed for sJPY; | exchangerates_i.addAggregator("sJPY", 0xBcE206caE7f0ec07b545EddE332A47C2F75bbeb3);
| exchangerates_i.addAggregator("sJPY", 0xBcE206caE7f0ec07b545EddE332A47C2F75bbeb3);
| 26,571 |
8 | // _markedForManualClaim[id] = address(0); | bool result = _unsafeTransfer(receiverAddress, amount, false);
require(
result,
"LiquidTokenStakingPool: failed to send rewards to receiverAddress"
);
emit RewardsClaimed(receiverAddress, msg.sender, amount);
| bool result = _unsafeTransfer(receiverAddress, amount, false);
require(
result,
"LiquidTokenStakingPool: failed to send rewards to receiverAddress"
);
emit RewardsClaimed(receiverAddress, msg.sender, amount);
| 33,171 |
474 | // Liquidatable Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. The liquidation has a liveness period before expiring successfully, during which someone can "dispute" theliquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based ona DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute falseliquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, aprospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. / | contract Liquidatable is PricelessPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PricelessPositionManager only.
uint256 expirationTimestamp;
uint256 withdrawalLiveness;
address collateralAddress;
address finderAddress;
address tokenFactoryAddress;
address timerAddress;
address excessTokenBeneficiary;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPct;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPct;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPct;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 withdrawalAmount,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PricelessPositionManager(
params.expirationTimestamp,
params.withdrawalLiveness,
params.collateralAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.syntheticName,
params.syntheticSymbol,
params.tokenFactoryAddress,
params.minSponsorTokens,
params.timerAddress,
params.excessTokenBeneficiary
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1), "CR is more than 100%");
require(
params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1),
"Rewards are more than 100%"
);
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPct = params.disputeBondPct;
sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
disputerDisputeRewardPct = params.disputerDisputeRewardPct;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
// maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(
ratio
);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.PreDispute,
liquidationTime: getCurrentTime(),
tokensOutstanding: tokensLiquidated,
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp <= getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(liquidationLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
tokensLiquidated.rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPct` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.PendingDispute;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* the sponsor, liquidator, and/or disputer can call this method to receive payments.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* Once all collateral is withdrawn, delete the liquidation data.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return amountWithdrawn the total amount of underlying returned from the liquidation.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(msg.sender == liquidation.disputer) ||
(msg.sender == liquidation.liquidator) ||
(msg.sender == liquidation.sponsor),
"Caller cannot withdraw rewards"
);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(
feeAttenuation
);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation can withdraw different amounts.
// Once a caller has been paid their address deleted from the struct.
// This prevents them from being paid multiple from times the same liquidation.
FixedPoint.Unsigned memory withdrawalAmount = FixedPoint.fromUnscaledUint(0);
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users can withdraw from the contract.
if (msg.sender == liquidation.disputer) {
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
FixedPoint.Unsigned memory payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
withdrawalAmount = withdrawalAmount.add(payToDisputer);
delete liquidation.disputer;
}
if (msg.sender == liquidation.sponsor) {
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
FixedPoint.Unsigned memory remainingCollateral = collateral.sub(tokenRedemptionValue);
FixedPoint.Unsigned memory payToSponsor = sponsorDisputeReward.add(remainingCollateral);
withdrawalAmount = withdrawalAmount.add(payToSponsor);
delete liquidation.sponsor;
}
if (msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in
// the constructor when these params are set.
FixedPoint.Unsigned memory payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(
disputerDisputeReward
);
withdrawalAmount = withdrawalAmount.add(payToLiquidator);
delete liquidation.liquidator;
}
// Free up space once all collateral is withdrawn by removing the liquidation object from the array.
if (
liquidation.disputer == address(0) &&
liquidation.sponsor == address(0) &&
liquidation.liquidator == address(0)
) {
delete liquidations[sponsor][liquidationId];
}
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed && msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
withdrawalAmount = collateral.add(disputeBondAmount).add(finalFee);
delete liquidations[sponsor][liquidationId];
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.PreDispute && msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: collateral + returned final fee
withdrawalAmount = collateral.add(finalFee);
delete liquidations[sponsor][liquidationId];
}
require(withdrawalAmount.isGreaterThan(0), "Invalid withdrawal amount");
// Decrease the total collateral held in liquidatable by the amount withdrawn.
amountWithdrawn = _removeCollateral(rawLiquidationCollateral, withdrawalAmount);
emit LiquidationWithdrawn(msg.sender, amountWithdrawn.rawValue, liquidation.state, settlementPrice.rawValue);
// Transfer amount withdrawn from this contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
return amountWithdrawn;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return.
// If the liquidation is in the PendingDispute state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == PendingDispute and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.PendingDispute) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(
liquidation.settlementPrice
);
// The required collateral is the value of the tokens in underlying * required collateral ratio.
FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement);
// If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal override view returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized,
"Invalid liquidation ID"
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.PreDispute) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)),
"Liquidation not withdrawable"
);
}
}
| contract Liquidatable is PricelessPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PricelessPositionManager only.
uint256 expirationTimestamp;
uint256 withdrawalLiveness;
address collateralAddress;
address finderAddress;
address tokenFactoryAddress;
address timerAddress;
address excessTokenBeneficiary;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPct;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPct;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPct;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 withdrawalAmount,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PricelessPositionManager(
params.expirationTimestamp,
params.withdrawalLiveness,
params.collateralAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.syntheticName,
params.syntheticSymbol,
params.tokenFactoryAddress,
params.minSponsorTokens,
params.timerAddress,
params.excessTokenBeneficiary
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1), "CR is more than 100%");
require(
params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1),
"Rewards are more than 100%"
);
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPct = params.disputeBondPct;
sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
disputerDisputeRewardPct = params.disputerDisputeRewardPct;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
// maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(
ratio
);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.PreDispute,
liquidationTime: getCurrentTime(),
tokensOutstanding: tokensLiquidated,
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp <= getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(liquidationLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
tokensLiquidated.rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPct` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.PendingDispute;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* the sponsor, liquidator, and/or disputer can call this method to receive payments.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* Once all collateral is withdrawn, delete the liquidation data.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return amountWithdrawn the total amount of underlying returned from the liquidation.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(msg.sender == liquidation.disputer) ||
(msg.sender == liquidation.liquidator) ||
(msg.sender == liquidation.sponsor),
"Caller cannot withdraw rewards"
);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(
feeAttenuation
);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation can withdraw different amounts.
// Once a caller has been paid their address deleted from the struct.
// This prevents them from being paid multiple from times the same liquidation.
FixedPoint.Unsigned memory withdrawalAmount = FixedPoint.fromUnscaledUint(0);
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users can withdraw from the contract.
if (msg.sender == liquidation.disputer) {
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
FixedPoint.Unsigned memory payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
withdrawalAmount = withdrawalAmount.add(payToDisputer);
delete liquidation.disputer;
}
if (msg.sender == liquidation.sponsor) {
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
FixedPoint.Unsigned memory remainingCollateral = collateral.sub(tokenRedemptionValue);
FixedPoint.Unsigned memory payToSponsor = sponsorDisputeReward.add(remainingCollateral);
withdrawalAmount = withdrawalAmount.add(payToSponsor);
delete liquidation.sponsor;
}
if (msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in
// the constructor when these params are set.
FixedPoint.Unsigned memory payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(
disputerDisputeReward
);
withdrawalAmount = withdrawalAmount.add(payToLiquidator);
delete liquidation.liquidator;
}
// Free up space once all collateral is withdrawn by removing the liquidation object from the array.
if (
liquidation.disputer == address(0) &&
liquidation.sponsor == address(0) &&
liquidation.liquidator == address(0)
) {
delete liquidations[sponsor][liquidationId];
}
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed && msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
withdrawalAmount = collateral.add(disputeBondAmount).add(finalFee);
delete liquidations[sponsor][liquidationId];
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.PreDispute && msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: collateral + returned final fee
withdrawalAmount = collateral.add(finalFee);
delete liquidations[sponsor][liquidationId];
}
require(withdrawalAmount.isGreaterThan(0), "Invalid withdrawal amount");
// Decrease the total collateral held in liquidatable by the amount withdrawn.
amountWithdrawn = _removeCollateral(rawLiquidationCollateral, withdrawalAmount);
emit LiquidationWithdrawn(msg.sender, amountWithdrawn.rawValue, liquidation.state, settlementPrice.rawValue);
// Transfer amount withdrawn from this contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
return amountWithdrawn;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return.
// If the liquidation is in the PendingDispute state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == PendingDispute and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.PendingDispute) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(
liquidation.settlementPrice
);
// The required collateral is the value of the tokens in underlying * required collateral ratio.
FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement);
// If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal override view returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized,
"Invalid liquidation ID"
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.PreDispute) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)),
"Liquidation not withdrawable"
);
}
}
| 37,066 |
76 | // records[_id].reference = _reference; | stringStorage[keccak256(abi.encodePacked("records.", _id, ".reference"))] = _reference;
| stringStorage[keccak256(abi.encodePacked("records.", _id, ".reference"))] = _reference;
| 43,753 |
89 | // return Number of transactions, both enabled and disabled, in transactions list. / |
function transactionsSize()
external
view
returns (uint256)
|
function transactionsSize()
external
view
returns (uint256)
| 36,046 |
68 | // Performs a swap with a single Pool. If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokenstaken from the Pool, which must be greater than or equal to `limit`. If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokenssent to the Pool, which must be less than or equal to `limit`. Internal Balance usage and the recipient are determined by the `funds` struct. Emits a `Swap` event. / | function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external returns (uint256 amountCalculated);
| function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external returns (uint256 amountCalculated);
| 58,639 |
90 | // ------------------------------------------------------------------------ Owner can set address of token contract ------------------------------------------------------------------------ | function setTokenContractAddress(address _tokenContractAddress) public onlyOwner {
require(_tokenContractAddress != address(0));
tokenContractAddress = _tokenContractAddress;
}
| function setTokenContractAddress(address _tokenContractAddress) public onlyOwner {
require(_tokenContractAddress != address(0));
tokenContractAddress = _tokenContractAddress;
}
| 65,901 |
26 | // 是否有权限操作 | modifier isApprovedMint {
require(_msgSender() == owner || isPartnerMint[_msgSender()]);
_;
}
| modifier isApprovedMint {
require(_msgSender() == owner || isPartnerMint[_msgSender()]);
_;
}
| 16,516 |
37 | // Provides information about the current execution context, including thesender of the transaction and its data. While these are generally availablevia msg.sender and msg.data, they should not be accessed in such a directmanner, since when dealing with GSN meta-transactions the account sending andpaying for execution may not be the actual sender (as far as an applicationis concerned). This contract is only required for intermediate, library-like contracts. / | abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
| abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
| 107 |
10 | // proxy address of itself, can be used for cross-delegate calls but also safety checking. | address proxy;
| address proxy;
| 8 |
4 | // membershipId -> boolean. | mapping(string => bool) public _membershipSet;
| mapping(string => bool) public _membershipSet;
| 26,308 |
9 | // ============ constructor ============ / | constructor(address _zeroExAddress, address _wethAddress) public {
zeroExAddress = _zeroExAddress;
wethAddress = _wethAddress;
getSpender = _zeroExAddress;
}
| constructor(address _zeroExAddress, address _wethAddress) public {
zeroExAddress = _zeroExAddress;
wethAddress = _wethAddress;
getSpender = _zeroExAddress;
}
| 31,214 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.