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
165
// Returns the bond of a given darknode.
function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].bond; }
function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].bond; }
11,740
72
// We will set a minimum amount of tokens to be swaped => 5M
uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled);
uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled);
2,525
45
// Uniswap
address constant UNIV2_ROUTER2 = 0x1B7D628EEE764EB08d88ea2470B6351adf4681C0;
address constant UNIV2_ROUTER2 = 0x1B7D628EEE764EB08d88ea2470B6351adf4681C0;
2,200
7
// / Constructor for the BalanceTracker contract that sets an immutable variable. _profitWallet The address to send remaining ETH profits to. /
constructor( address payable _profitWallet ) { require(_profitWallet != address(0), "BalanceTracker: PROFIT_WALLET cannot be address(0)"); PROFIT_WALLET = _profitWallet; _disableInitializers(); }
constructor( address payable _profitWallet ) { require(_profitWallet != address(0), "BalanceTracker: PROFIT_WALLET cannot be address(0)"); PROFIT_WALLET = _profitWallet; _disableInitializers(); }
19,900
24
// Вывод средств с ICO (пользователь сам вызывает функцию)
function refund() public returns (bool success) { require(allowRefunds(), 'Refunds is not allowed, ICO is in progress'); uint amount = contributions[msg.sender]; if (amount > 0) { // It is important to set this to zero because the recipient // can call this function again as part of the receiving call // before `send` returns. contributions[msg.sender] = 0; if (!msg.sender.send(amount)) { // No need to call throw here, just reset the amount owing contributions[msg.sender] = amount; return false; } } return true; }
function refund() public returns (bool success) { require(allowRefunds(), 'Refunds is not allowed, ICO is in progress'); uint amount = contributions[msg.sender]; if (amount > 0) { // It is important to set this to zero because the recipient // can call this function again as part of the receiving call // before `send` returns. contributions[msg.sender] = 0; if (!msg.sender.send(amount)) { // No need to call throw here, just reset the amount owing contributions[msg.sender] = amount; return false; } } return true; }
47,812
1
// A flag that only has effect if a projectId is also specified, and that project has issued its tokens. If so, this flag indicates if the tokens that result from making a payment to the project should be delivered staked or unstaked to the beneficiary.
bool preferClaimed;
bool preferClaimed;
27,013
98
// -如果失败的调用有返回回滚提示,则拼接到回滚消息.
if (resulti.returnData.length > 4){ revertMsg = string(abi.encodePacked(revertMsg," Reason:",abi.decode(resulti.returnData.slice(4,resulti.returnData.length - 4),(string)))); }
if (resulti.returnData.length > 4){ revertMsg = string(abi.encodePacked(revertMsg," Reason:",abi.decode(resulti.returnData.slice(4,resulti.returnData.length - 4),(string)))); }
19,533
199
// Cache the end of the memory to calculate the length later.
let end := str
let end := str
3,701
151
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
9,741
6
// ICO per-address limit tracking
mapping(address => uint) internal ICOBuyIn; uint public tokensMintedDuringICO; uint public ethInvestedDuringICO; uint public currentEthInvested; uint internal tokenSupply = 0; uint internal divTokenSupply = 0;
mapping(address => uint) internal ICOBuyIn; uint public tokensMintedDuringICO; uint public ethInvestedDuringICO; uint public currentEthInvested; uint internal tokenSupply = 0; uint internal divTokenSupply = 0;
53,464
170
// HomeAMBErc677ToErc677Home side implementation for erc677-to-erc677 mediator intended to work on top of AMB bridge. It is designed to be used as an implementation contract of EternalStorageProxy contract./
contract HomeAMBErc677ToErc677 is BasicAMBErc677ToErc677 { /** * @dev Executes action on the request to deposit tokens relayed from the other network * @param _recipient address of tokens receiver * @param _value amount of bridged tokens */ function executeActionOnBridgedTokens(address _recipient, uint256 _value) internal { uint256 value = _shiftValue(_value); bytes32 _messageId = messageId(); IBurnableMintableERC677Token(erc677token()).mint(_recipient, value); emit TokensBridged(_recipient, value, _messageId); } /** * @dev Executes action on withdrawal of bridged tokens * @param _token address of token contract * @param _from address of tokens sender * @param _value requsted amount of bridged tokens * @param _data alternative receiver, if specified */ function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, uint256 _value, bytes _data) internal { if (!lock()) { IBurnableMintableERC677Token(_token).burn(_value); passMessage(_from, chooseReceiver(_from, _data), _value); } } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // For home side of the bridge, tokens are not locked at the contract, they are minted and burned instead. // So, its is safe to allow claiming of any tokens. Native coins are allowed as well. claimValues(_token, _to); } function executeActionOnFixedTokens(address _recipient, uint256 _value) internal { IBurnableMintableERC677Token(erc677token()).mint(_recipient, _value); } }
contract HomeAMBErc677ToErc677 is BasicAMBErc677ToErc677 { /** * @dev Executes action on the request to deposit tokens relayed from the other network * @param _recipient address of tokens receiver * @param _value amount of bridged tokens */ function executeActionOnBridgedTokens(address _recipient, uint256 _value) internal { uint256 value = _shiftValue(_value); bytes32 _messageId = messageId(); IBurnableMintableERC677Token(erc677token()).mint(_recipient, value); emit TokensBridged(_recipient, value, _messageId); } /** * @dev Executes action on withdrawal of bridged tokens * @param _token address of token contract * @param _from address of tokens sender * @param _value requsted amount of bridged tokens * @param _data alternative receiver, if specified */ function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, uint256 _value, bytes _data) internal { if (!lock()) { IBurnableMintableERC677Token(_token).burn(_value); passMessage(_from, chooseReceiver(_from, _data), _value); } } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // For home side of the bridge, tokens are not locked at the contract, they are minted and burned instead. // So, its is safe to allow claiming of any tokens. Native coins are allowed as well. claimValues(_token, _to); } function executeActionOnFixedTokens(address _recipient, uint256 _value) internal { IBurnableMintableERC677Token(erc677token()).mint(_recipient, _value); } }
38,333
117
// ================= End Contract Variables ======================
IUniswapV2Router public constant uniswapRouterV2 = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uint public constant ONE_HUNDRED_X_100 = 10000; uint public immutable contractStartTime; address public immutable TRUSTED_DEPOSIT_TOKEN_ADDRESS;
IUniswapV2Router public constant uniswapRouterV2 = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uint public constant ONE_HUNDRED_X_100 = 10000; uint public immutable contractStartTime; address public immutable TRUSTED_DEPOSIT_TOKEN_ADDRESS;
3,256
5
// Allowance amounts on behalf of others
mapping (address => mapping (address => uint256)) internal allowances;
mapping (address => mapping (address => uint256)) internal allowances;
47,444
0
// Interface of the ERC777TokensRecipient standard as defined in the EIP. Accounts can be notified of `IERC777` tokens being sent to them by having acontract implement this interface (contract holders can be their ownimplementer) and registering it on the See `IERC1820Registry` and `ERC1820Implementer`. /
interface IERC777Recipient { /** * @dev Called by an `IERC777` token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * `IERC777.balanceOf`, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint amount, bytes calldata userData, bytes calldata operatorData ) external; }
interface IERC777Recipient { /** * @dev Called by an `IERC777` token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * `IERC777.balanceOf`, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint amount, bytes calldata userData, bytes calldata operatorData ) external; }
16,563
29
// Takes up to the total amount required to fund an answer. Reimburses the rest. Creates an appeal if at least two answers are funded. _arbitrationID The ID of the arbitration. _answer One of the possible rulings the arbitrator can give that the funder considers to be the correct answer to the question.return Whether the answer was fully funded or not. /
function fundAppeal(uint256 _arbitrationID, uint256 _answer) external payable override returns (bool) { Arbitration storage arbitration = arbitrations[_arbitrationID]; require(arbitration.status == Status.Created, "No dispute to appeal."); (uint256 appealPeriodStart, uint256 appealPeriodEnd) = arbitrator.appealPeriod(arbitration.disputeID); require(block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Appeal period is over."); // Answer is equal to ruling - 1. uint256 winner = arbitrator.currentRuling(arbitration.disputeID); uint256 multiplier; if (winner == _answer + 1) { multiplier = winnerMultiplier; } else { require( block.timestamp - appealPeriodStart < (appealPeriodEnd - appealPeriodStart) / 2, "Appeal period is over for loser." ); multiplier = loserMultiplier; } Round storage round = arbitration.rounds[arbitration.rounds.length - 1]; require(!round.hasPaid[_answer], "Appeal fee is already paid."); uint256 appealCost = arbitrator.appealCost(arbitration.disputeID, arbitratorExtraData); uint256 totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); // Take up to the amount necessary to fund the current round at the current costs. uint256 contribution = totalCost.subCap(round.paidFees[_answer]) > msg.value ? msg.value : totalCost.subCap(round.paidFees[_answer]); emit Contribution(_arbitrationID, arbitration.rounds.length - 1, _answer + 1, msg.sender, contribution); round.contributions[msg.sender][_answer] += contribution; round.paidFees[_answer] += contribution; if (round.paidFees[_answer] >= totalCost) { round.feeRewards += round.paidFees[_answer]; round.fundedAnswers.push(_answer); round.hasPaid[_answer] = true; emit RulingFunded(_arbitrationID, arbitration.rounds.length - 1, _answer + 1); } if (round.fundedAnswers.length > 1) { // At least two sides are fully funded. arbitration.rounds.push(); round.feeRewards = round.feeRewards.subCap(appealCost); arbitrator.appeal{value: appealCost}(arbitration.disputeID, arbitratorExtraData); } msg.sender.transfer(msg.value.subCap(contribution)); // Sending extra value back to contributor. return round.hasPaid[_answer]; }
function fundAppeal(uint256 _arbitrationID, uint256 _answer) external payable override returns (bool) { Arbitration storage arbitration = arbitrations[_arbitrationID]; require(arbitration.status == Status.Created, "No dispute to appeal."); (uint256 appealPeriodStart, uint256 appealPeriodEnd) = arbitrator.appealPeriod(arbitration.disputeID); require(block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Appeal period is over."); // Answer is equal to ruling - 1. uint256 winner = arbitrator.currentRuling(arbitration.disputeID); uint256 multiplier; if (winner == _answer + 1) { multiplier = winnerMultiplier; } else { require( block.timestamp - appealPeriodStart < (appealPeriodEnd - appealPeriodStart) / 2, "Appeal period is over for loser." ); multiplier = loserMultiplier; } Round storage round = arbitration.rounds[arbitration.rounds.length - 1]; require(!round.hasPaid[_answer], "Appeal fee is already paid."); uint256 appealCost = arbitrator.appealCost(arbitration.disputeID, arbitratorExtraData); uint256 totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); // Take up to the amount necessary to fund the current round at the current costs. uint256 contribution = totalCost.subCap(round.paidFees[_answer]) > msg.value ? msg.value : totalCost.subCap(round.paidFees[_answer]); emit Contribution(_arbitrationID, arbitration.rounds.length - 1, _answer + 1, msg.sender, contribution); round.contributions[msg.sender][_answer] += contribution; round.paidFees[_answer] += contribution; if (round.paidFees[_answer] >= totalCost) { round.feeRewards += round.paidFees[_answer]; round.fundedAnswers.push(_answer); round.hasPaid[_answer] = true; emit RulingFunded(_arbitrationID, arbitration.rounds.length - 1, _answer + 1); } if (round.fundedAnswers.length > 1) { // At least two sides are fully funded. arbitration.rounds.push(); round.feeRewards = round.feeRewards.subCap(appealCost); arbitrator.appeal{value: appealCost}(arbitration.disputeID, arbitratorExtraData); } msg.sender.transfer(msg.value.subCap(contribution)); // Sending extra value back to contributor. return round.hasPaid[_answer]; }
53,287
492
// method to recover any stuck erc20 tokens (ie compound COMP) _token the ERC20 token to recover /
function recover(ERC20 _token) public onlyAvatar { require( _token.transfer(address(avatar), _token.balanceOf(address(this))), "recover transfer failed" ); }
function recover(ERC20 _token) public onlyAvatar { require( _token.transfer(address(avatar), _token.balanceOf(address(this))), "recover transfer failed" ); }
49,645
23
// Clean user storage
if (userLock.amount == 0) { uint256[] storage userLocks = users[msg.sender].locksForToken[_lpToken]; userLocks[_index] = userLocks[userLocks.length-1]; userLocks.pop(); if (userLocks.length == 0) { users[msg.sender].lockedTokens.remove(_lpToken); }
if (userLock.amount == 0) { uint256[] storage userLocks = users[msg.sender].locksForToken[_lpToken]; userLocks[_index] = userLocks[userLocks.length-1]; userLocks.pop(); if (userLocks.length == 0) { users[msg.sender].lockedTokens.remove(_lpToken); }
23,137
50
// Registers controller/id Bytes32 id of controller/controller Address of controller
function registerController(bytes32 id, address controller) external;
function registerController(bytes32 id, address controller) external;
69,744
11
// set the actual output length
mstore(result, encodedLen)
mstore(result, encodedLen)
46,739
15
// Function used to check the number of tokens `account` has minted./account Account to check balance for.
function balance(address account) external view returns (uint256) { return _numberMinted(account); }
function balance(address account) external view returns (uint256) { return _numberMinted(account); }
40,998
38
// For owner /
function withdraw(uint256 amount) public onlyOwner { if (amount == 0) { owner.transfer(address(this).balance); } else { owner.transfer(amount); } }
function withdraw(uint256 amount) public onlyOwner { if (amount == 0) { owner.transfer(address(this).balance); } else { owner.transfer(amount); } }
5,773
25
// determine what index the present sender is:
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
79,381
56
// Updates the listing Fee of the contract /
function updateListingFee(uint _listingFee) public payable { require(treasury == msg.sender, "Only marketplace owner can update listing Fee."); listingFee = _listingFee; }
function updateListingFee(uint _listingFee) public payable { require(treasury == msg.sender, "Only marketplace owner can update listing Fee."); listingFee = _listingFee; }
83,460
10
// Bank node lending rewards contract
BankNodeLendingRewards public override bankNodeLendingRewards;
BankNodeLendingRewards public override bankNodeLendingRewards;
7,873
225
// Nothing in vault to allocate
if (vaultValue == 0) return; uint256 strategiesValue = _totalValueInStrategies();
if (vaultValue == 0) return; uint256 strategiesValue = _totalValueInStrategies();
23,707
4
// Show info about redeemed ETH Gift Card // Show info about new ETH Gift Card Created /
modifier enoughForRedeem(uint _cardId) { require ( giftCards[_cardId] <= poolTotalAmount, "Not enough on account for withdrawal" ); _; }
modifier enoughForRedeem(uint _cardId) { require ( giftCards[_cardId] <= poolTotalAmount, "Not enough on account for withdrawal" ); _; }
20,072
4
// ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplifiedproxy whose upgrades are fully controlled by the current implementation. /
interface IERC1822ProxiableUpgradeable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); }
interface IERC1822ProxiableUpgradeable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); }
33,433
183
// {ERC721Enumerable}. /
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256;
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256;
15,612
81
// We exit in a single token, so we initialize amountsOut with zeros
uint256[] memory amountsOut = new uint256[](2);
uint256[] memory amountsOut = new uint256[](2);
14,870
21
// Return true if and only if the contract has been initializedreturn whether the contract has been initialized /
function isInitialized() public view returns (bool) { return initialized; }
function isInitialized() public view returns (bool) { return initialized; }
23,206
53
// valid index
function validIndex(address _account) external view returns(uint) { return _validIndex[_account]; }
function validIndex(address _account) external view returns(uint) { return _validIndex[_account]; }
40,250
337
// a non-zero value otherwise.
res = fullWithdrawalRequests[starkKey][vaultId];
res = fullWithdrawalRequests[starkKey][vaultId];
2,400
0
// _issuer The address of the owner. /
constructor(address _issuer) public Owned(_issuer){ name = "Skyrim Network"; symbol = "SNS"; decimals = uint8(DECIMALS); totalSupply = TOTAL_SUPPLY; balances[_issuer] = TOTAL_SUPPLY; emit Transfer(address(0), _issuer, TOTAL_SUPPLY); }
constructor(address _issuer) public Owned(_issuer){ name = "Skyrim Network"; symbol = "SNS"; decimals = uint8(DECIMALS); totalSupply = TOTAL_SUPPLY; balances[_issuer] = TOTAL_SUPPLY; emit Transfer(address(0), _issuer, TOTAL_SUPPLY); }
24,215
6
// get 3 highest dice rolls
uint256 stat = roll1 * roll2 * roll3 + roll4 + roll3 - min; string memory output = string(abi.encodePacked(toString(stat))); return output;
uint256 stat = roll1 * roll2 * roll3 + roll4 + roll3 - min; string memory output = string(abi.encodePacked(toString(stat))); return output;
52,623
20
// The threshold above which the flywheel transfers BRID+, in wei
uint public constant birdPlusClaimThreshold = 0.001e18;
uint public constant birdPlusClaimThreshold = 0.001e18;
36,064
115
// mark the items as paid
updateBalances(ethAddress,accountRef); emit RedFoxMigrated(msg.sender,withdrawAmount);
updateBalances(ethAddress,accountRef); emit RedFoxMigrated(msg.sender,withdrawAmount);
79,963
41
// transferToFeeDistributorAmount is total rewards fees received for genesis pool (this contract) and farming pool
if ( transferToFeeDistributorAmount > 0 && feeDistributor != address(0) ) { _balances[feeDistributor] = _balances[feeDistributor].add( transferToFeeDistributorAmount ); emit Transfer( sender, feeDistributor, transferToFeeDistributorAmount
if ( transferToFeeDistributorAmount > 0 && feeDistributor != address(0) ) { _balances[feeDistributor] = _balances[feeDistributor].add( transferToFeeDistributorAmount ); emit Transfer( sender, feeDistributor, transferToFeeDistributorAmount
40,976
94
// transfer 20% of profit to management
transferToManagement(forManagement);
transferToManagement(forManagement);
37,652
115
// 111111 /1111111111111111111111000111111111111<10001111111111111
uint256 public partialLiquidateAmount; uint256 public discount; //1111,11111111111 uint256 public liquidateLine = 7e17;//1111111130%11111 1-0.3 = 0.7 uint256 public gracePeriod = 1 days; //11111 uint256 public depositMultiple;
uint256 public partialLiquidateAmount; uint256 public discount; //1111,11111111111 uint256 public liquidateLine = 7e17;//1111111130%11111 1-0.3 = 0.7 uint256 public gracePeriod = 1 days; //11111 uint256 public depositMultiple;
46,916
207
// Private function to add a token to this extension's token tracking data structures. tokenId uint256 ID of the token to be added to the tokens list /
function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); }
function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); }
26,023
64
// 2 Mappings - one for the fundfee and one for the other fees
mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; mapping(address=>bool) private _isExcludedFromFundFee; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000000 * 10**6; uint256 private _rTotal = (MAX - (MAX % _tTotal));
mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; mapping(address=>bool) private _isExcludedFromFundFee; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000000 * 10**6; uint256 private _rTotal = (MAX - (MAX % _tTotal));
8,507
28
// Vesting Enjinstarter /
contract Vesting is IVesting { using SafeMath for uint256; using SafeERC20 for IERC20; struct VestingSchedule { uint256 cliffDurationDays; // Cliff duration in days with respect to the start of vesting schedule uint256 percentReleaseAtScheduleStart; // Percentage of grant amount to be released in wei at start of vesting schedule uint256 percentReleaseForEachInterval; // Percentage of grant amount to be released in wei for each interval after cliff duration uint256 intervalDays; // Vesting interval in days uint256 gapDays; // Gap between intervals in days uint256 numberOfIntervals; // Number of intervals ReleaseMethod releaseMethod; } struct VestingGrant { uint256 grantAmount; // Total number of tokens granted bool isRevocable; // true if vesting grant is revocable (a gift), false if irrevocable (purchased) bool isRevoked; // true if vesting grant has been revoked bool isActive; // true if vesting grant is active } uint256 public constant BATCH_MAX_NUM = 200; uint256 public constant PERCENT_100_WEI = 100 ether; uint256 public constant SECONDS_IN_DAY = 86400; address public governanceAccount; address public vestingAdmin; address public tokenAddress; uint256 public totalGrantAmount; uint256 public totalReleasedAmount; uint256 public scheduleStartTimestamp; bool public allowAccumulate; VestingSchedule private _vestingSchedule; mapping(address => VestingGrant) private _vestingGrants; mapping(address => uint256) private _released; constructor( address tokenAddress_, uint256 cliffDurationDays, uint256 percentReleaseAtScheduleStart, uint256 percentReleaseForEachInterval, uint256 intervalDays, uint256 gapDays, uint256 numberOfIntervals, ReleaseMethod releaseMethod, bool allowAccumulate_ ) { require(tokenAddress_ != address(0), "Vesting: zero token address"); require( percentReleaseAtScheduleStart <= PERCENT_100_WEI, "Vesting: percent release at grant start > 100%" ); require( percentReleaseForEachInterval <= PERCENT_100_WEI, "Vesting: percent release for each interval > 100%" ); require(intervalDays > 0, "Vesting: zero interval"); require( percentReleaseAtScheduleStart.add( percentReleaseForEachInterval.mul(numberOfIntervals) ) <= PERCENT_100_WEI, "Vesting: total percent release > 100%" ); governanceAccount = msg.sender; vestingAdmin = msg.sender; tokenAddress = tokenAddress_; _vestingSchedule.cliffDurationDays = cliffDurationDays; _vestingSchedule .percentReleaseAtScheduleStart = percentReleaseAtScheduleStart; _vestingSchedule .percentReleaseForEachInterval = percentReleaseForEachInterval; _vestingSchedule.intervalDays = intervalDays; _vestingSchedule.gapDays = gapDays; _vestingSchedule.numberOfIntervals = numberOfIntervals; _vestingSchedule.releaseMethod = releaseMethod; allowAccumulate = allowAccumulate_; } modifier onlyBy(address account) { require(msg.sender == account, "Vesting: sender unauthorized"); _; } /** * @dev isRevocable will be ignored if grant already added but amount allowed to accumulate. */ function addVestingGrant( address account, uint256 grantAmount, bool isRevocable ) external override onlyBy(vestingAdmin) { _addVestingGrant(account, grantAmount, isRevocable); } function revokeVestingGrant(address account) external override onlyBy(vestingAdmin) { _revokeVestingGrant(account); } function release() external override { uint256 releasableAmount = releasableAmountFor(msg.sender); _release(msg.sender, releasableAmount); } function transferUnusedTokens() external override onlyBy(governanceAccount) { uint256 unusedAmount = IERC20(tokenAddress) .balanceOf(address(this)) .add(totalReleasedAmount) .sub(totalGrantAmount); require(unusedAmount > 0, "Vesting: nothing to transfer"); IERC20(tokenAddress).safeTransfer(governanceAccount, unusedAmount); } function addVestingGrantsBatch( address[] memory accounts, uint256[] memory grantAmounts, bool[] memory isRevocables ) external override onlyBy(vestingAdmin) { require(accounts.length > 0, "Vesting: empty"); require(accounts.length <= BATCH_MAX_NUM, "Vesting: exceed max"); require( grantAmounts.length == accounts.length, "Vesting: grant amounts length different" ); require( isRevocables.length == accounts.length, "Vesting: is revocables length different" ); for (uint256 i = 0; i < accounts.length; i++) { _addVestingGrant(accounts[i], grantAmounts[i], isRevocables[i]); } } function setScheduleStartTimestamp(uint256 scheduleStartTimestamp_) external override onlyBy(vestingAdmin) { require( scheduleStartTimestamp_ > block.timestamp, "Vesting: start before current timestamp" ); uint256 oldScheduleStartTimestamp = scheduleStartTimestamp; require( oldScheduleStartTimestamp == 0 || block.timestamp < oldScheduleStartTimestamp, "Vesting: already started" ); scheduleStartTimestamp = scheduleStartTimestamp_; emit ScheduleStartTimestampSet( msg.sender, scheduleStartTimestamp_, oldScheduleStartTimestamp ); } function setGovernanceAccount(address account) external override onlyBy(governanceAccount) { require(account != address(0), "Vesting: zero account"); governanceAccount = account; } function setVestingAdmin(address account) external override onlyBy(governanceAccount) { require(account != address(0), "Vesting: zero account"); vestingAdmin = account; } function getVestingSchedule() external view override returns ( uint256 cliffDurationDays, uint256 percentReleaseAtScheduleStart, uint256 percentReleaseForEachInterval, uint256 intervalDays, uint256 gapDays, uint256 numberOfIntervals, ReleaseMethod releaseMethod ) { VestingSchedule memory vestingSchedule = _vestingSchedule; cliffDurationDays = vestingSchedule.cliffDurationDays; percentReleaseAtScheduleStart = vestingSchedule .percentReleaseAtScheduleStart; percentReleaseForEachInterval = vestingSchedule .percentReleaseForEachInterval; intervalDays = vestingSchedule.intervalDays; gapDays = vestingSchedule.gapDays; numberOfIntervals = vestingSchedule.numberOfIntervals; releaseMethod = vestingSchedule.releaseMethod; } function vestingGrantFor(address account) external view override returns ( uint256 grantAmount, bool isRevocable, bool isRevoked, bool isActive ) { require(account != address(0), "Vesting: zero account"); VestingGrant memory vestingGrant = _vestingGrants[account]; grantAmount = vestingGrant.grantAmount; isRevocable = vestingGrant.isRevocable; isRevoked = vestingGrant.isRevoked; isActive = vestingGrant.isActive; } function revoked(address account) public view override returns (bool isRevoked) { require(account != address(0), "Vesting: zero account"); isRevoked = _vestingGrants[account].isRevoked; } function releasedAmountFor(address account) public view override returns (uint256 releasedAmount) { require(account != address(0), "Vesting: zero account"); releasedAmount = _released[account]; } function releasableAmountFor(address account) public view override returns (uint256 releasableAmount) { require(account != address(0), "Vesting: zero account"); uint256 startTimestamp = scheduleStartTimestamp; require(startTimestamp > 0, "Vesting: undefined start time"); require(block.timestamp >= startTimestamp, "Vesting: not started"); require(!revoked(account), "Vesting: revoked"); uint256 vestedAmount = vestedAmountFor(account); releasableAmount = vestedAmount.sub(releasedAmountFor(account)); } function vestedAmountFor(address account) public view override returns (uint256 vestedAmount) { require(account != address(0), "Vesting: zero account"); VestingGrant memory vestingGrant = _vestingGrants[account]; require(vestingGrant.isActive, "Vesting: inactive"); uint256 startTimestamp = scheduleStartTimestamp; if (startTimestamp == 0) { return 0; } if (block.timestamp < startTimestamp) { return 0; } if (revoked(account)) { return releasedAmountFor(account); } VestingSchedule memory vestingSchedule = _vestingSchedule; vestedAmount = 0; if (vestingSchedule.percentReleaseAtScheduleStart > 0) { vestedAmount = vestingGrant .grantAmount .mul(vestingSchedule.percentReleaseAtScheduleStart) .div(PERCENT_100_WEI); } uint256 cliffEndTimestamp = startTimestamp.add( vestingSchedule.cliffDurationDays.mul(SECONDS_IN_DAY) ); if (block.timestamp < cliffEndTimestamp) { return vestedAmount; } uint256 intervalSeconds = vestingSchedule.intervalDays.mul( SECONDS_IN_DAY ); uint256 gapSeconds = vestingSchedule.gapDays.mul(SECONDS_IN_DAY); uint256 scheduleEndTimestamp = cliffEndTimestamp .add(intervalSeconds.mul(vestingSchedule.numberOfIntervals)) .add(gapSeconds.mul(vestingSchedule.numberOfIntervals.sub(1))); if (block.timestamp >= scheduleEndTimestamp) { vestedAmount = vestingGrant.grantAmount; return vestedAmount; } // https://github.com/crytic/slither/wiki/Detector-Documentation#divide-before-multiply // slither-disable-next-line divide-before-multiply uint256 intervalNumber = block.timestamp.sub(cliffEndTimestamp).div( intervalSeconds.add(gapSeconds) ); require( intervalNumber < vestingSchedule.numberOfIntervals, "Vesting: unexpected interval number" ); // https://github.com/crytic/slither/wiki/Detector-Documentation#divide-before-multiply // slither-disable-next-line divide-before-multiply uint256 totalPercentage = vestingSchedule .percentReleaseForEachInterval .mul(intervalNumber); if (vestingSchedule.releaseMethod == ReleaseMethod.IntervalEnd) { // solhint-disable-previous-line no-empty-blocks } else if ( vestingSchedule.releaseMethod == ReleaseMethod.LinearlyPerSecond ) { // https://github.com/crytic/slither/wiki/Detector-Documentation#divide-before-multiply // slither-disable-next-line divide-before-multiply uint256 secondsInInterval = block.timestamp.sub( cliffEndTimestamp.add( intervalSeconds.add(gapSeconds).mul(intervalNumber) ) ); totalPercentage = secondsInInterval >= intervalSeconds ? totalPercentage.add( vestingSchedule.percentReleaseForEachInterval ) : totalPercentage.add( vestingSchedule .percentReleaseForEachInterval .mul(secondsInInterval) .div(intervalSeconds) ); } else { require(false, "Vesting: unexpected release method"); } uint256 maxPercentage = PERCENT_100_WEI.sub( vestingSchedule.percentReleaseAtScheduleStart ); if (totalPercentage > maxPercentage) { totalPercentage = maxPercentage; } vestedAmount = vestedAmount.add( vestingGrant.grantAmount.mul(totalPercentage).div(PERCENT_100_WEI) ); } function unvestedAmountFor(address account) external view override returns (uint256 unvestedAmount) { require(account != address(0), "Vesting: zero account"); VestingGrant memory vestingGrant = _vestingGrants[account]; require(vestingGrant.isActive, "Vesting: inactive"); if (revoked(account)) { unvestedAmount = 0; } else { unvestedAmount = vestingGrant.grantAmount.sub( vestedAmountFor(account) ); } } function _addVestingGrant( address account, uint256 grantAmount, bool isRevocable ) private { require(account != address(0), "Vesting: zero account"); require(grantAmount > 0, "Vesting: zero grant amount"); uint256 startTimestamp = scheduleStartTimestamp; require( startTimestamp == 0 || block.timestamp < startTimestamp, "Vesting: already started" ); VestingGrant memory vestingGrant = _vestingGrants[account]; require( allowAccumulate || !vestingGrant.isActive, "Vesting: already added" ); require(!revoked(account), "Vesting: already revoked"); totalGrantAmount = totalGrantAmount.add(grantAmount); require( totalGrantAmount <= IERC20(tokenAddress).balanceOf(address(this)), "Vesting: total grant amount exceed balance" ); if (vestingGrant.isActive) { _vestingGrants[account].grantAmount = vestingGrant.grantAmount.add( grantAmount ); // _vestingGrants[account].isRevocable = isRevocable; } else { _vestingGrants[account] = VestingGrant({ grantAmount: grantAmount, isRevocable: isRevocable, isRevoked: false, isActive: true }); } emit VestingGrantAdded(account, grantAmount, isRevocable); } function _revokeVestingGrant(address account) private { require(account != address(0), "Vesting: zero account"); VestingGrant memory vestingGrant = _vestingGrants[account]; require(vestingGrant.isActive, "Vesting: inactive"); require(vestingGrant.isRevocable, "Vesting: not revocable"); require(!revoked(account), "Vesting: already revoked"); uint256 releasedAmount = releasedAmountFor(account); uint256 remainderAmount = vestingGrant.grantAmount.sub(releasedAmount); totalGrantAmount = totalGrantAmount.sub(remainderAmount); _vestingGrants[account].isRevoked = true; emit VestingGrantRevoked( account, remainderAmount, vestingGrant.grantAmount, releasedAmount ); } function _release(address account, uint256 amount) private { require(account != address(0), "Vesting: zero account"); require(amount > 0, "Vesting: zero amount"); _released[account] = _released[account].add(amount); totalReleasedAmount = totalReleasedAmount.add(amount); emit TokensReleased(account, amount); IERC20(tokenAddress).safeTransfer(account, amount); } }
contract Vesting is IVesting { using SafeMath for uint256; using SafeERC20 for IERC20; struct VestingSchedule { uint256 cliffDurationDays; // Cliff duration in days with respect to the start of vesting schedule uint256 percentReleaseAtScheduleStart; // Percentage of grant amount to be released in wei at start of vesting schedule uint256 percentReleaseForEachInterval; // Percentage of grant amount to be released in wei for each interval after cliff duration uint256 intervalDays; // Vesting interval in days uint256 gapDays; // Gap between intervals in days uint256 numberOfIntervals; // Number of intervals ReleaseMethod releaseMethod; } struct VestingGrant { uint256 grantAmount; // Total number of tokens granted bool isRevocable; // true if vesting grant is revocable (a gift), false if irrevocable (purchased) bool isRevoked; // true if vesting grant has been revoked bool isActive; // true if vesting grant is active } uint256 public constant BATCH_MAX_NUM = 200; uint256 public constant PERCENT_100_WEI = 100 ether; uint256 public constant SECONDS_IN_DAY = 86400; address public governanceAccount; address public vestingAdmin; address public tokenAddress; uint256 public totalGrantAmount; uint256 public totalReleasedAmount; uint256 public scheduleStartTimestamp; bool public allowAccumulate; VestingSchedule private _vestingSchedule; mapping(address => VestingGrant) private _vestingGrants; mapping(address => uint256) private _released; constructor( address tokenAddress_, uint256 cliffDurationDays, uint256 percentReleaseAtScheduleStart, uint256 percentReleaseForEachInterval, uint256 intervalDays, uint256 gapDays, uint256 numberOfIntervals, ReleaseMethod releaseMethod, bool allowAccumulate_ ) { require(tokenAddress_ != address(0), "Vesting: zero token address"); require( percentReleaseAtScheduleStart <= PERCENT_100_WEI, "Vesting: percent release at grant start > 100%" ); require( percentReleaseForEachInterval <= PERCENT_100_WEI, "Vesting: percent release for each interval > 100%" ); require(intervalDays > 0, "Vesting: zero interval"); require( percentReleaseAtScheduleStart.add( percentReleaseForEachInterval.mul(numberOfIntervals) ) <= PERCENT_100_WEI, "Vesting: total percent release > 100%" ); governanceAccount = msg.sender; vestingAdmin = msg.sender; tokenAddress = tokenAddress_; _vestingSchedule.cliffDurationDays = cliffDurationDays; _vestingSchedule .percentReleaseAtScheduleStart = percentReleaseAtScheduleStart; _vestingSchedule .percentReleaseForEachInterval = percentReleaseForEachInterval; _vestingSchedule.intervalDays = intervalDays; _vestingSchedule.gapDays = gapDays; _vestingSchedule.numberOfIntervals = numberOfIntervals; _vestingSchedule.releaseMethod = releaseMethod; allowAccumulate = allowAccumulate_; } modifier onlyBy(address account) { require(msg.sender == account, "Vesting: sender unauthorized"); _; } /** * @dev isRevocable will be ignored if grant already added but amount allowed to accumulate. */ function addVestingGrant( address account, uint256 grantAmount, bool isRevocable ) external override onlyBy(vestingAdmin) { _addVestingGrant(account, grantAmount, isRevocable); } function revokeVestingGrant(address account) external override onlyBy(vestingAdmin) { _revokeVestingGrant(account); } function release() external override { uint256 releasableAmount = releasableAmountFor(msg.sender); _release(msg.sender, releasableAmount); } function transferUnusedTokens() external override onlyBy(governanceAccount) { uint256 unusedAmount = IERC20(tokenAddress) .balanceOf(address(this)) .add(totalReleasedAmount) .sub(totalGrantAmount); require(unusedAmount > 0, "Vesting: nothing to transfer"); IERC20(tokenAddress).safeTransfer(governanceAccount, unusedAmount); } function addVestingGrantsBatch( address[] memory accounts, uint256[] memory grantAmounts, bool[] memory isRevocables ) external override onlyBy(vestingAdmin) { require(accounts.length > 0, "Vesting: empty"); require(accounts.length <= BATCH_MAX_NUM, "Vesting: exceed max"); require( grantAmounts.length == accounts.length, "Vesting: grant amounts length different" ); require( isRevocables.length == accounts.length, "Vesting: is revocables length different" ); for (uint256 i = 0; i < accounts.length; i++) { _addVestingGrant(accounts[i], grantAmounts[i], isRevocables[i]); } } function setScheduleStartTimestamp(uint256 scheduleStartTimestamp_) external override onlyBy(vestingAdmin) { require( scheduleStartTimestamp_ > block.timestamp, "Vesting: start before current timestamp" ); uint256 oldScheduleStartTimestamp = scheduleStartTimestamp; require( oldScheduleStartTimestamp == 0 || block.timestamp < oldScheduleStartTimestamp, "Vesting: already started" ); scheduleStartTimestamp = scheduleStartTimestamp_; emit ScheduleStartTimestampSet( msg.sender, scheduleStartTimestamp_, oldScheduleStartTimestamp ); } function setGovernanceAccount(address account) external override onlyBy(governanceAccount) { require(account != address(0), "Vesting: zero account"); governanceAccount = account; } function setVestingAdmin(address account) external override onlyBy(governanceAccount) { require(account != address(0), "Vesting: zero account"); vestingAdmin = account; } function getVestingSchedule() external view override returns ( uint256 cliffDurationDays, uint256 percentReleaseAtScheduleStart, uint256 percentReleaseForEachInterval, uint256 intervalDays, uint256 gapDays, uint256 numberOfIntervals, ReleaseMethod releaseMethod ) { VestingSchedule memory vestingSchedule = _vestingSchedule; cliffDurationDays = vestingSchedule.cliffDurationDays; percentReleaseAtScheduleStart = vestingSchedule .percentReleaseAtScheduleStart; percentReleaseForEachInterval = vestingSchedule .percentReleaseForEachInterval; intervalDays = vestingSchedule.intervalDays; gapDays = vestingSchedule.gapDays; numberOfIntervals = vestingSchedule.numberOfIntervals; releaseMethod = vestingSchedule.releaseMethod; } function vestingGrantFor(address account) external view override returns ( uint256 grantAmount, bool isRevocable, bool isRevoked, bool isActive ) { require(account != address(0), "Vesting: zero account"); VestingGrant memory vestingGrant = _vestingGrants[account]; grantAmount = vestingGrant.grantAmount; isRevocable = vestingGrant.isRevocable; isRevoked = vestingGrant.isRevoked; isActive = vestingGrant.isActive; } function revoked(address account) public view override returns (bool isRevoked) { require(account != address(0), "Vesting: zero account"); isRevoked = _vestingGrants[account].isRevoked; } function releasedAmountFor(address account) public view override returns (uint256 releasedAmount) { require(account != address(0), "Vesting: zero account"); releasedAmount = _released[account]; } function releasableAmountFor(address account) public view override returns (uint256 releasableAmount) { require(account != address(0), "Vesting: zero account"); uint256 startTimestamp = scheduleStartTimestamp; require(startTimestamp > 0, "Vesting: undefined start time"); require(block.timestamp >= startTimestamp, "Vesting: not started"); require(!revoked(account), "Vesting: revoked"); uint256 vestedAmount = vestedAmountFor(account); releasableAmount = vestedAmount.sub(releasedAmountFor(account)); } function vestedAmountFor(address account) public view override returns (uint256 vestedAmount) { require(account != address(0), "Vesting: zero account"); VestingGrant memory vestingGrant = _vestingGrants[account]; require(vestingGrant.isActive, "Vesting: inactive"); uint256 startTimestamp = scheduleStartTimestamp; if (startTimestamp == 0) { return 0; } if (block.timestamp < startTimestamp) { return 0; } if (revoked(account)) { return releasedAmountFor(account); } VestingSchedule memory vestingSchedule = _vestingSchedule; vestedAmount = 0; if (vestingSchedule.percentReleaseAtScheduleStart > 0) { vestedAmount = vestingGrant .grantAmount .mul(vestingSchedule.percentReleaseAtScheduleStart) .div(PERCENT_100_WEI); } uint256 cliffEndTimestamp = startTimestamp.add( vestingSchedule.cliffDurationDays.mul(SECONDS_IN_DAY) ); if (block.timestamp < cliffEndTimestamp) { return vestedAmount; } uint256 intervalSeconds = vestingSchedule.intervalDays.mul( SECONDS_IN_DAY ); uint256 gapSeconds = vestingSchedule.gapDays.mul(SECONDS_IN_DAY); uint256 scheduleEndTimestamp = cliffEndTimestamp .add(intervalSeconds.mul(vestingSchedule.numberOfIntervals)) .add(gapSeconds.mul(vestingSchedule.numberOfIntervals.sub(1))); if (block.timestamp >= scheduleEndTimestamp) { vestedAmount = vestingGrant.grantAmount; return vestedAmount; } // https://github.com/crytic/slither/wiki/Detector-Documentation#divide-before-multiply // slither-disable-next-line divide-before-multiply uint256 intervalNumber = block.timestamp.sub(cliffEndTimestamp).div( intervalSeconds.add(gapSeconds) ); require( intervalNumber < vestingSchedule.numberOfIntervals, "Vesting: unexpected interval number" ); // https://github.com/crytic/slither/wiki/Detector-Documentation#divide-before-multiply // slither-disable-next-line divide-before-multiply uint256 totalPercentage = vestingSchedule .percentReleaseForEachInterval .mul(intervalNumber); if (vestingSchedule.releaseMethod == ReleaseMethod.IntervalEnd) { // solhint-disable-previous-line no-empty-blocks } else if ( vestingSchedule.releaseMethod == ReleaseMethod.LinearlyPerSecond ) { // https://github.com/crytic/slither/wiki/Detector-Documentation#divide-before-multiply // slither-disable-next-line divide-before-multiply uint256 secondsInInterval = block.timestamp.sub( cliffEndTimestamp.add( intervalSeconds.add(gapSeconds).mul(intervalNumber) ) ); totalPercentage = secondsInInterval >= intervalSeconds ? totalPercentage.add( vestingSchedule.percentReleaseForEachInterval ) : totalPercentage.add( vestingSchedule .percentReleaseForEachInterval .mul(secondsInInterval) .div(intervalSeconds) ); } else { require(false, "Vesting: unexpected release method"); } uint256 maxPercentage = PERCENT_100_WEI.sub( vestingSchedule.percentReleaseAtScheduleStart ); if (totalPercentage > maxPercentage) { totalPercentage = maxPercentage; } vestedAmount = vestedAmount.add( vestingGrant.grantAmount.mul(totalPercentage).div(PERCENT_100_WEI) ); } function unvestedAmountFor(address account) external view override returns (uint256 unvestedAmount) { require(account != address(0), "Vesting: zero account"); VestingGrant memory vestingGrant = _vestingGrants[account]; require(vestingGrant.isActive, "Vesting: inactive"); if (revoked(account)) { unvestedAmount = 0; } else { unvestedAmount = vestingGrant.grantAmount.sub( vestedAmountFor(account) ); } } function _addVestingGrant( address account, uint256 grantAmount, bool isRevocable ) private { require(account != address(0), "Vesting: zero account"); require(grantAmount > 0, "Vesting: zero grant amount"); uint256 startTimestamp = scheduleStartTimestamp; require( startTimestamp == 0 || block.timestamp < startTimestamp, "Vesting: already started" ); VestingGrant memory vestingGrant = _vestingGrants[account]; require( allowAccumulate || !vestingGrant.isActive, "Vesting: already added" ); require(!revoked(account), "Vesting: already revoked"); totalGrantAmount = totalGrantAmount.add(grantAmount); require( totalGrantAmount <= IERC20(tokenAddress).balanceOf(address(this)), "Vesting: total grant amount exceed balance" ); if (vestingGrant.isActive) { _vestingGrants[account].grantAmount = vestingGrant.grantAmount.add( grantAmount ); // _vestingGrants[account].isRevocable = isRevocable; } else { _vestingGrants[account] = VestingGrant({ grantAmount: grantAmount, isRevocable: isRevocable, isRevoked: false, isActive: true }); } emit VestingGrantAdded(account, grantAmount, isRevocable); } function _revokeVestingGrant(address account) private { require(account != address(0), "Vesting: zero account"); VestingGrant memory vestingGrant = _vestingGrants[account]; require(vestingGrant.isActive, "Vesting: inactive"); require(vestingGrant.isRevocable, "Vesting: not revocable"); require(!revoked(account), "Vesting: already revoked"); uint256 releasedAmount = releasedAmountFor(account); uint256 remainderAmount = vestingGrant.grantAmount.sub(releasedAmount); totalGrantAmount = totalGrantAmount.sub(remainderAmount); _vestingGrants[account].isRevoked = true; emit VestingGrantRevoked( account, remainderAmount, vestingGrant.grantAmount, releasedAmount ); } function _release(address account, uint256 amount) private { require(account != address(0), "Vesting: zero account"); require(amount > 0, "Vesting: zero amount"); _released[account] = _released[account].add(amount); totalReleasedAmount = totalReleasedAmount.add(amount); emit TokensReleased(account, amount); IERC20(tokenAddress).safeTransfer(account, amount); } }
1,916
145
// Reusable timelock variables
address private _timelock_address; uint256 private _timelock_data_1;
address private _timelock_address; uint256 private _timelock_data_1;
8,026
107
// Start baking
lastBakeTime = now; lastRewardTime = now; rewardPool = 0;
lastBakeTime = now; lastRewardTime = now; rewardPool = 0;
1,915
47
// Internal view function for verifying a signature and a message hashagainst the mapping of keys currently stored on the key ring. For V1, allstored keys are the Dual key type, and only a single signature is providedfor verification at once since the threshold is fixed at one signature. /
function _verifySignature( bytes32 hash, bytes memory signature
function _verifySignature( bytes32 hash, bytes memory signature
11,866
19
// Pack the below variables using uint32 values/Fee paid by bots
uint32 public botFeeBips;
uint32 public botFeeBips;
11,806
2
// Compound's JumpRateModel Contract V2 for V2 cTokens Arr00 Supports only for V2 cTokens /
contract JumpRateModelV2 is BaseJumpRateModelV2 { /** * @notice Calculates the current borrow rate per block * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @return The borrow rate percentage per block as a mantissa (scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view override returns (uint256) { return getBorrowRateInternal(cash, borrows, reserves); } constructor( uint256 blocksPerYearOnChain, uint256 baseRatePerYear, uint256 multiplierPerYear, uint256 jumpMultiplierPerYear, uint256 kink_, address owner_ ) BaseJumpRateModelV2(blocksPerYearOnChain, baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_, owner_) {} }
contract JumpRateModelV2 is BaseJumpRateModelV2 { /** * @notice Calculates the current borrow rate per block * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @return The borrow rate percentage per block as a mantissa (scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view override returns (uint256) { return getBorrowRateInternal(cash, borrows, reserves); } constructor( uint256 blocksPerYearOnChain, uint256 baseRatePerYear, uint256 multiplierPerYear, uint256 jumpMultiplierPerYear, uint256 kink_, address owner_ ) BaseJumpRateModelV2(blocksPerYearOnChain, baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_, owner_) {} }
28,334
47
// @inheritdoc IEIP4824
function daoURI() external view returns (string memory) { return _daoURI; }
function daoURI() external view returns (string memory) { return _daoURI; }
10,511
21
// Bool related functions
function createBool(bytes32 key, bool value) external returns (bool); function createBools(bytes32[] keys, bool[] values) external returns (bool); function updateBool(bytes32 key, bool value) external returns (bool); function updateBools(bytes32[] keys, bool[] values) external returns (bool); function removeBool(bytes32 key) external returns (bool); function removeBools(bytes32[] keys) external returns (bool); function readBool(bytes32 key) external view returns (bool); function readBools(bytes32[] keys) external view returns (bool[]);
function createBool(bytes32 key, bool value) external returns (bool); function createBools(bytes32[] keys, bool[] values) external returns (bool); function updateBool(bytes32 key, bool value) external returns (bool); function updateBools(bytes32[] keys, bool[] values) external returns (bool); function removeBool(bytes32 key) external returns (bool); function removeBools(bytes32[] keys) external returns (bool); function readBool(bytes32 key) external view returns (bool); function readBools(bytes32[] keys) external view returns (bool[]);
43,754
2
// The end Timestamp.
uint256 public endTime;
uint256 public endTime;
26,176
83
// Allows owner to clean out the contract of ANY tokens including v2, but not v1 /
function inCaseTokensGetStuck( address _token, address _to, uint256 _amount
function inCaseTokensGetStuck( address _token, address _to, uint256 _amount
13,847
198
// Helper to get royalties for a token /
function _getRoyalties(uint256 tokenId) view internal returns (address payable[] storage, uint256[] storage) { return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId)); }
function _getRoyalties(uint256 tokenId) view internal returns (address payable[] storage, uint256[] storage) { return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId)); }
39,950
1
// The protocol fees will always be charged using the token associated with the max weight in the pool. Since these Pools will register tokens only once, we can assume this index will be constant.
uint256 internal immutable _maxWeightTokenIndex; uint256 internal immutable _normalizedWeight0; uint256 internal immutable _normalizedWeight1; uint256 internal immutable _normalizedWeight2; uint256 internal immutable _normalizedWeight3; uint256 internal immutable _normalizedWeight4; uint256 internal immutable _normalizedWeight5; uint256 internal immutable _normalizedWeight6; uint256 internal immutable _normalizedWeight7;
uint256 internal immutable _maxWeightTokenIndex; uint256 internal immutable _normalizedWeight0; uint256 internal immutable _normalizedWeight1; uint256 internal immutable _normalizedWeight2; uint256 internal immutable _normalizedWeight3; uint256 internal immutable _normalizedWeight4; uint256 internal immutable _normalizedWeight5; uint256 internal immutable _normalizedWeight6; uint256 internal immutable _normalizedWeight7;
32,764
50
// Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set) Create the token
_mintToken(_to, _tokenId.add(i), _editionNumber, _editionDetails.tokenURI);
_mintToken(_to, _tokenId.add(i), _editionNumber, _editionDetails.tokenURI);
52,928
44
// Starts the redeeming phase of the contract
function startRedeeming() external onlyOwner isNotPaused { // Move the contract to Redeeming state isRedeeming = true; }
function startRedeeming() external onlyOwner isNotPaused { // Move the contract to Redeeming state isRedeeming = true; }
41,257
31
// receive event /
receive() external payable { deposit(); }
receive() external payable { deposit(); }
57,534
0
// Set constant coefficients for MT19937-32 as defined here: https:en.wikipedia.org/wiki/Mersenne_Twister
uint constant w = 32; uint constant n = 624; uint constant m = 397; uint constant r = 31; uint constant a = 0x9908B0DF; uint constant u = 11; uint constant d = 0xFFFFFFFF; uint constant s = 7; uint constant b = 0x9D2C5680; uint constant t = 15;
uint constant w = 32; uint constant n = 624; uint constant m = 397; uint constant r = 31; uint constant a = 0x9908B0DF; uint constant u = 11; uint constant d = 0xFFFFFFFF; uint constant s = 7; uint constant b = 0x9D2C5680; uint constant t = 15;
44,696
86
// Emit TokensLocked event
emit TokensLocked(from, amount);
emit TokensLocked(from, amount);
51,441
1,487
// PerpetualLiquidatable 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.NOTE: this contract does _not_ work with ERC777 collateral
contract PerpetualLiquidatable is PerpetualPositionManager { 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, NotDisputed, Disputed, 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 PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // 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 disputeBondPercentage; // 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 sponsorDisputeRewardPercentage; // 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 disputerDisputeRewardPercentage; /**************************************** * 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 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, 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 PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * 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`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @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 notEmergencyShutdown() fees() 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); require(tokensLiquidated.isGreaterThan(0)); // 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]. 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. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { 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.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(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(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(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 `disputeBondPercentage` 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(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; 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, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // 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. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time. 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 = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); 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 receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // 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 (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // 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.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @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 Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed 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 == Disputed 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.Disputed) { 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 view override 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 ); 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.NotDisputed), "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.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } }
contract PerpetualLiquidatable is PerpetualPositionManager { 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, NotDisputed, Disputed, 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 PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // 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 disputeBondPercentage; // 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 sponsorDisputeRewardPercentage; // 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 disputerDisputeRewardPercentage; /**************************************** * 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 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, 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 PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * 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`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @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 notEmergencyShutdown() fees() 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); require(tokensLiquidated.isGreaterThan(0)); // 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]. 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. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { 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.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(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(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(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 `disputeBondPercentage` 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(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; 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, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // 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. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time. 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 = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); 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 receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // 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 (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // 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.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @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 Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed 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 == Disputed 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.Disputed) { 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 view override 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 ); 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.NotDisputed), "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.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } }
12,638
102
// All members of the group have been elected
if (numMembers[groupIndex] <= numMembersElected[groupIndex]) { votesForNextMember[groupIndex] = FixidityLib.wrap(0); } else {
if (numMembers[groupIndex] <= numMembersElected[groupIndex]) { votesForNextMember[groupIndex] = FixidityLib.wrap(0); } else {
16,943
62
// Reward for participating
uint amount = (price / participationFactor) / total;
uint amount = (price / participationFactor) / total;
11,455
23
// the token is not our preferred token
require(swapEnabled, "Swaps Disabled");
require(swapEnabled, "Swaps Disabled");
29,165
70
// the global fee growth of the input token
uint256 feeGrowthGlobalX128;
uint256 feeGrowthGlobalX128;
4,274
1
// who has adopted this pet?
function getOwner(uint petId) public view returns (address) { require(petId >= 0 && petId <= 15); return adopters[petId]; }
function getOwner(uint petId) public view returns (address) { require(petId >= 0 && petId <= 15); return adopters[petId]; }
37,681
16
// Pushes this contract's balance of `token` to `getCaller()`. getCaller() is the original `msg.sender` of the Router's `execute` fn. token The token to transfer to `getCaller()`.returnWhether or not the `token` was transferred to `getCaller()`. /
function _transferToCaller(address token) internal returns (bool) { uint256 quantity = IERC20(token).balanceOf(address(this)); if (quantity > 0) { IERC20(token).safeTransfer(getCaller(), quantity); return true; } return false; }
function _transferToCaller(address token) internal returns (bool) { uint256 quantity = IERC20(token).balanceOf(address(this)); if (quantity > 0) { IERC20(token).safeTransfer(getCaller(), quantity); return true; } return false; }
64,384
345
// semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
return (Error.SNAPSHOT_ERROR, 0, 0);
71,949
11
// Yellow Paper Def. 5.2 (Withdrawal Fee) When covBefore >= 1, fee is 0 When covBefore < 1, we apply a fee to prevent withdrawal arbitrage k K slippage parameter in WAD n N slippage parameter c1 C1 slippage parameter in WAD xThreshold xThreshold slippage parameter in WAD cash cash position of asset in WAD liability liability position of asset in WAD amount amount to be withdrawn in WADreturn The final fee to be applied /
function _withdrawalFee( uint256 k, uint256 n, uint256 c1, uint256 xThreshold, uint256 cash, uint256 liability, uint256 amount
function _withdrawalFee( uint256 k, uint256 n, uint256 c1, uint256 xThreshold, uint256 cash, uint256 liability, uint256 amount
13,244
5
// Removes the sender from the list the manager role/
function renounceRaffleManager() public { renounceRole(RAFFLE_MANAGER_ROLE, msg.sender); emit RaffleManagerRemoved(msg.sender, managerOf); }
function renounceRaffleManager() public { renounceRole(RAFFLE_MANAGER_ROLE, msg.sender); emit RaffleManagerRemoved(msg.sender, managerOf); }
2,972
223
// debt write offtokenAddress ERC20 token addressamount WriteOff amount /
function debtWriteOff(address tokenAddress, uint256 amount) external;
function debtWriteOff(address tokenAddress, uint256 amount) external;
71,507
253
// Reverts if the DAO has not won the NFT
modifier onlyIfAuctionWon() { // Ensure that owner of NFT(auctionId) is contract address require(IERC721(NFTAddress).ownerOf(auctionID) == address(this), "PartyBid: DAO has not won auction."); _; }
modifier onlyIfAuctionWon() { // Ensure that owner of NFT(auctionId) is contract address require(IERC721(NFTAddress).ownerOf(auctionID) == address(this), "PartyBid: DAO has not won auction."); _; }
23,217
25
// Receives the ruling for a dispute from the Foreign Chain. Should only be called by the xDAI/ETH bridge. _arbitrable The address of the arbitrable contract. UNTRUSTED. _arbitrableItemID The ID of the arbitrable item on the arbitrable contract. _ruling The ruling given by the arbitrator. /
function receiveRuling( ICrossChainArbitrable _arbitrable, uint256 _arbitrableItemID, uint256 _ruling
function receiveRuling( ICrossChainArbitrable _arbitrable, uint256 _arbitrableItemID, uint256 _ruling
16,411
0
// Contract Address Locator Interface. /
interface IContractAddressLocator { /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) external view returns (address); /** * @dev Determine whether or not a contract address relates to one of the identifiers. * @param _contractAddress The contract address to look for. * @param _identifiers The identifiers. * @return A boolean indicating if the contract address relates to one of the identifiers. */ function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool); }
interface IContractAddressLocator { /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) external view returns (address); /** * @dev Determine whether or not a contract address relates to one of the identifiers. * @param _contractAddress The contract address to look for. * @param _identifiers The identifiers. * @return A boolean indicating if the contract address relates to one of the identifiers. */ function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool); }
80,258
98
// Ensure bet and number are valid.
if (!_validateBetOrRefund(_number)) return;
if (!_validateBetOrRefund(_number)) return;
81,097
239
// The percentage of developer cut Default set to 2.8%
_setUint(EXCHANGE_DEVELOPER_CUT, 2800);
_setUint(EXCHANGE_DEVELOPER_CUT, 2800);
36,952
225
// The FARMING TOKEN!
BlackfarmingToken public blackfarming;
BlackfarmingToken public blackfarming;
24,591
21
// Controls the initialization state, allowing to call an initialization function only once. /
modifier initializes() { address impl = implementation(); // require(!initialized[implementation()]); require(!boolStorage[keccak256(abi.encodePacked(impl, "initialized"))], "Contract is already initialized"); _; // initialized[implementation()] = true; boolStorage[keccak256(abi.encodePacked(impl, "initialized"))] = true; }
modifier initializes() { address impl = implementation(); // require(!initialized[implementation()]); require(!boolStorage[keccak256(abi.encodePacked(impl, "initialized"))], "Contract is already initialized"); _; // initialized[implementation()] = true; boolStorage[keccak256(abi.encodePacked(impl, "initialized"))] = true; }
43,719
59
// Liquidity/Liquidation Calculations // Local vars for avoiding stack-depth limits in calculating account liquidity. Note that `lendTokenBalance` is the number of lendTokens the account owns in the market, whereas `borrowBalance` is the amount of underlying that the account has borrowed. /
struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint lendTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; uint goldOraclePriceMantissa; uint tokensToDenom; }
struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint lendTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; uint goldOraclePriceMantissa; uint tokensToDenom; }
39,900
3
// Transfer the tokens back to the depositor
IERC20(userDeposit.token).safeTransfer(msg.sender, amount);
IERC20(userDeposit.token).safeTransfer(msg.sender, amount);
7,682
12
// двадцать одно пальто висело на вешалке ^^^^^^^^^^^^^
pattern Числ1 { N10=Десятки : export { ПАДЕЖ node:root_node }
pattern Числ1 { N10=Десятки : export { ПАДЕЖ node:root_node }
16,630
360
// . Gets the list of methods for binding to wallets./Sub-contracts should override this method to provide methods for/wallet binding./ return methods A list of method selectors for binding to the wallet/ when this module is activated for the wallet.
function bindableMethods() public pure virtual returns (bytes4[] memory methods);
function bindableMethods() public pure virtual returns (bytes4[] memory methods);
23,517
15
// get the lzReceive() LayerZero messaging library version_userApplication - the contract address of the user application
function getReceiveVersion(address _userApplication) external view returns (uint16);
function getReceiveVersion(address _userApplication) external view returns (uint16);
34,733
178
// Should never occur
if (_proof.length == 64) { return false; }
if (_proof.length == 64) { return false; }
31,602
47
// if there is an unexpected bug, leading to an endless game/
function forceGameOver() external { require(owner == msg.sender, "only owner can force game over"); require(block.number > ((3600 * 24 * 30) / blockTime) + startBlockNum, "only force game over after 30 days"); endBlockNum = block.number - 1; }
function forceGameOver() external { require(owner == msg.sender, "only owner can force game over"); require(block.number > ((3600 * 24 * 30) / blockTime) + startBlockNum, "only force game over after 30 days"); endBlockNum = block.number - 1; }
14,960
11
// Redeem RToken for basket collateral to a particular recipient/recipient The address to receive the backing collateral tokens/amount {qRTok} The quantity {qRToken} of RToken to redeem/revertOnPartialRedemption If true, will revert on partial redemption/ @custom:interaction
function redeemTo( address recipient, uint256 amount, bool revertOnPartialRedemption ) external;
function redeemTo( address recipient, uint256 amount, bool revertOnPartialRedemption ) external;
20,802
38
// address of the interest rate strategy
address interestRateStrategyAddress;
address interestRateStrategyAddress;
1,787
70
// iterate over the conversion paths
for (uint256 i = 0; i < _pathStartIndex.length; i += 1) { pathEndIndex = i == (_pathStartIndex.length - 1) ? _paths.length : _pathStartIndex[i + 1];
for (uint256 i = 0; i < _pathStartIndex.length; i += 1) { pathEndIndex = i == (_pathStartIndex.length - 1) ? _paths.length : _pathStartIndex[i + 1];
15,028
45
// Choose new validators
validatorSetContract.newValidatorSet();
validatorSetContract.newValidatorSet();
15,145
196
// locate the index of the validator approval to be removed
uint256 index = _validatorApprovalsIndex[validator][attributeTypeID];
uint256 index = _validatorApprovalsIndex[validator][attributeTypeID];
42,432
5
// @custom:security-contact [email protected]
contract Lithereum is ERC20, ERC20Snapshot, AccessControl, ERC20FlashMint { bytes32 public constant SNAPSHOT_ROLE = keccak256("SNAPSHOT_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); constructor() ERC20("Lithereum", "HER") { _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(SNAPSHOT_ROLE, msg.sender); _grantRole(MINTER_ROLE, msg.sender); } function snapshot() public onlyRole(SNAPSHOT_ROLE) { _snapshot(); } function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) { _mint(to, amount); } // The following functions are overrides required by Solidity. function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20, ERC20Snapshot) { super._beforeTokenTransfer(from, to, amount); } }
contract Lithereum is ERC20, ERC20Snapshot, AccessControl, ERC20FlashMint { bytes32 public constant SNAPSHOT_ROLE = keccak256("SNAPSHOT_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); constructor() ERC20("Lithereum", "HER") { _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(SNAPSHOT_ROLE, msg.sender); _grantRole(MINTER_ROLE, msg.sender); } function snapshot() public onlyRole(SNAPSHOT_ROLE) { _snapshot(); } function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) { _mint(to, amount); } // The following functions are overrides required by Solidity. function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20, ERC20Snapshot) { super._beforeTokenTransfer(from, to, amount); } }
27,774
212
// returns the ongoing normalized income for the reserve. a value of 1e27 means there is no income. As time passes, the income is accrued. A value of 21e27 means that the income of the reserve is double the initial amount._reserve the reserve object return the normalized income. expressed in ray/
{ uint256 cumulated = calculateLinearInterest( _reserve .currentLiquidityRate, _reserve .lastUpdateTimestamp ) .rayMul(_reserve.lastLiquidityCumulativeIndex); return cumulated; }
{ uint256 cumulated = calculateLinearInterest( _reserve .currentLiquidityRate, _reserve .lastUpdateTimestamp ) .rayMul(_reserve.lastLiquidityCumulativeIndex); return cumulated; }
31,962
34
// Remove an user from the whitelist
function removeUser(address user) onlyOwner { whitelisted[user] = false; LogUserRemoved(user); }
function removeUser(address user) onlyOwner { whitelisted[user] = false; LogUserRemoved(user); }
20,179
128
// ERC777 ERC777 logic /
contract ERC777 is IERC777, Ownable, ERC820Client, CertificateController, ReentrancyGuard { using SafeMath for uint256; string internal _name; string internal _symbol; uint256 internal _granularity; uint256 internal _totalSupply; // Indicate whether the token can still be controlled by operators or not anymore. bool internal _isControllable; // Mapping from tokenHolder to balance. mapping(address => uint256) internal _balances; /******************** Mappings related to operator **************************/ // Mapping from (operator, tokenHolder) to authorized status. [TOKEN-HOLDER-SPECIFIC] mapping(address => mapping(address => bool)) internal _authorizedOperator; // Array of controllers. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC] address[] internal _controllers; // Mapping from operator to controller status. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC] mapping(address => bool) internal _isController; /****************************************************************************/ /** * [ERC777 CONSTRUCTOR] * @dev Initialize ERC777 and CertificateController parameters + register * the contract implementation in ERC820Registry. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param certificateSigner Address of the off-chain service which signs the * conditional ownership certificates required for token transfers, issuance, * redemption (Cf. CertificateController.sol). */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner ) public CertificateController(certificateSigner) { _name = name; _symbol = symbol; _totalSupply = 0; require(granularity >= 1, "Constructor Blocked - Token granularity can not be lower than 1"); _granularity = granularity; _setControllers(controllers); setInterfaceImplementation("ERC777Token", address(this)); } /********************** ERC777 EXTERNAL FUNCTIONS ***************************/ /** * [ERC777 INTERFACE (1/13)] * @dev Get the name of the token, e.g., "MyToken". * @return Name of the token. */ function name() external view returns(string memory) { return _name; } /** * [ERC777 INTERFACE (2/13)] * @dev Get the symbol of the token, e.g., "MYT". * @return Symbol of the token. */ function symbol() external view returns(string memory) { return _symbol; } /** * [ERC777 INTERFACE (3/13)] * @dev Get the total number of issued tokens. * @return Total supply of tokens currently in circulation. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * [ERC777 INTERFACE (4/13)] * @dev Get the balance of the account with address 'tokenHolder'. * @param tokenHolder Address for which the balance is returned. * @return Amount of token held by 'tokenHolder' in the token contract. */ function balanceOf(address tokenHolder) external view returns (uint256) { return _balances[tokenHolder]; } /** * [ERC777 INTERFACE (5/13)] * @dev Get the smallest part of the token that’s not divisible. * @return The smallest non-divisible part of the token. */ function granularity() external view returns(uint256) { return _granularity; } /** * [ERC777 INTERFACE (6/13)] * @dev Get the list of controllers as defined by the token contract. * @return List of addresses of all the controllers. */ function controllers() external view returns (address[] memory) { return _controllers; } /** * [ERC777 INTERFACE (7/13)] * @dev Set a third party operator address as an operator of 'msg.sender' to transfer * and redeem tokens on its behalf. * @param operator Address to set as an operator for 'msg.sender'. */ function authorizeOperator(address operator) external { _authorizedOperator[operator][msg.sender] = true; emit AuthorizedOperator(operator, msg.sender); } /** * [ERC777 INTERFACE (8/13)] * @dev Remove the right of the operator address to be an operator for 'msg.sender' * and to transfer and redeem tokens on its behalf. * @param operator Address to rescind as an operator for 'msg.sender'. */ function revokeOperator(address operator) external { _authorizedOperator[operator][msg.sender] = false; emit RevokedOperator(operator, msg.sender); } /** * [ERC777 INTERFACE (9/13)] * @dev Indicate whether the operator address is an operator of the tokenHolder address. * @param operator Address which may be an operator of tokenHolder. * @param tokenHolder Address of a token holder which may have the operator address as an operator. * @return 'true' if operator is an operator of 'tokenHolder' and 'false' otherwise. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool) { return _isOperatorFor(operator, tokenHolder); } /** * [ERC777 INTERFACE (10/13)] * @dev Transfer the amount of tokens from the address 'msg.sender' to the address 'to'. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function transferWithData(address to, uint256 value, bytes calldata data) external isValidCertificate(data, 0x2535f762) { _transferWithData("", msg.sender, msg.sender, to, value, data, "", true); } /** * [ERC777 INTERFACE (11/13)] * @dev Transfer the amount of tokens on behalf of the address 'from' to the address 'to'. * @param from Token holder (or 'address(0)' to set from to 'msg.sender'). * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, and intended for the token holder ('from'). * @param operatorData Information attached to the transfer by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function transferFromWithData(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData, 0x868d5383) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorFor(msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _transferWithData("", msg.sender, _from, to, value, data, operatorData, true); } /** * [ERC777 INTERFACE (12/13)] * @dev Redeem the amount of tokens from the address 'msg.sender'. * @param value Number of tokens to redeem. * @param data Information attached to the redemption, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function redeem(uint256 value, bytes calldata data) external isValidCertificate(data, 0xe77c646d) { _redeem("", msg.sender, msg.sender, value, data, ""); } /** * [ERC777 INTERFACE (13/13)] * @dev Redeem the amount of tokens on behalf of the address from. * @param from Token holder whose tokens will be redeemed (or address(0) to set from to msg.sender). * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function redeemFrom(address from, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData, 0xffa90f7f) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorFor(msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _redeem("", msg.sender, _from, value, data, operatorData); } /********************** ERC777 INTERNAL FUNCTIONS ***************************/ /** * [INTERNAL] * @dev Check if 'value' is multiple of the granularity. * @param value The quantity that want's to be checked. * @return 'true' if 'value' is a multiple of the granularity. */ function _isMultiple(uint256 value) internal view returns(bool) { return(value.div(_granularity).mul(_granularity) == value); } /** * [INTERNAL] * @dev Check whether an address is a regular address or not. * @param addr Address of the contract that has to be checked. * @return 'true' if 'addr' is a regular address (not a contract). */ function _isRegularAddress(address addr) internal view returns(bool) { if (addr == address(0)) { return false; } uint size; assembly { size := extcodesize(addr) } // solhint-disable-line no-inline-assembly return size == 0; } /** * [INTERNAL] * @dev Indicate whether the operator address is an operator of the tokenHolder address. * @param operator Address which may be an operator of 'tokenHolder'. * @param tokenHolder Address of a token holder which may have the 'operator' address as an operator. * @return 'true' if 'operator' is an operator of 'tokenHolder' and 'false' otherwise. */ function _isOperatorFor(address operator, address tokenHolder) internal view returns (bool) { return (operator == tokenHolder || _authorizedOperator[operator][tokenHolder] || (_isControllable && _isController[operator]) ); } /** * [INTERNAL] * @dev Perform the transfer of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. * @param operatorData Information attached to the transfer by the operator (if any).. * @param preventLocking 'true' if you want this function to throw when tokens are sent to a contract not * implementing 'erc777tokenHolder'. * ERC777 native transfer functions MUST set this parameter to 'true', and backwards compatible ERC20 transfer * functions SHOULD set this parameter to 'false'. */ function _transferWithData( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData, bool preventLocking ) internal nonReentrant { require(_isMultiple(value), "A9: Transfer Blocked - Token granularity"); require(to != address(0), "A6: Transfer Blocked - Receiver not eligible"); require(_balances[from] >= value, "A4: Transfer Blocked - Sender balance insufficient"); _callSender(partition, operator, from, to, value, data, operatorData); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _callRecipient(partition, operator, from, to, value, data, operatorData, preventLocking); emit TransferWithData(operator, from, to, value, data, operatorData); } /** * [INTERNAL] * @dev Perform the token redemption. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator The address performing the redemption. * @param from Token holder whose tokens will be redeemed. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator (if any). */ function _redeem( bytes32 partition, address operator, address from, uint256 value, bytes memory data, bytes memory operatorData ) internal nonReentrant { require(_isMultiple(value), "A9: Transfer Blocked - Token granularity"); require(from != address(0), "A5: Transfer Blocked - Sender not eligible"); require(_balances[from] >= value, "A4: Transfer Blocked - Sender balance insufficient"); _callSender(partition, operator, from, address(0), value, data, operatorData); _balances[from] = _balances[from].sub(value); _totalSupply = _totalSupply.sub(value); emit Redeemed(operator, from, value, data, operatorData); } /** * [INTERNAL] * @dev Check for 'ERC777TokensSender' hook on the sender and call it. * May throw according to 'preventLocking'. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the balance decrease (through transfer or redemption). * @param from Token holder. * @param to Token recipient for a transfer and 0x for a redemption. * @param value Number of tokens the token holder balance is decreased by. * @param data Extra information. * @param operatorData Extra information, attached by the operator (if any). */ function _callSender( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { address senderImplementation; senderImplementation = interfaceAddr(from, "ERC777TokensSender"); if (senderImplementation != address(0)) { IERC777TokensSender(senderImplementation).tokensToTransfer(partition, operator, from, to, value, data, operatorData); } } /** * [INTERNAL] * @dev Check for 'ERC777TokensRecipient' hook on the recipient and call it. * May throw according to 'preventLocking'. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the balance increase (through transfer or issuance). * @param from Token holder for a transfer and 0x for an issuance. * @param to Token recipient. * @param value Number of tokens the recipient balance is increased by. * @param data Extra information, intended for the token holder ('from'). * @param operatorData Extra information attached by the operator (if any). * @param preventLocking 'true' if you want this function to throw when tokens are sent to a contract not * implementing 'ERC777TokensRecipient'. * ERC777 native transfer functions MUST set this parameter to 'true', and backwards compatible ERC20 transfer * functions SHOULD set this parameter to 'false'. */ function _callRecipient( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData, bool preventLocking ) internal { address recipientImplementation; recipientImplementation = interfaceAddr(to, "ERC777TokensRecipient"); if (recipientImplementation != address(0)) { IERC777TokensRecipient(recipientImplementation).tokensReceived(partition, operator, from, to, value, data, operatorData); } else if (preventLocking) { require(_isRegularAddress(to), "A6: Transfer Blocked - Receiver not eligible"); } } /** * [INTERNAL] * @dev Perform the issuance of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the issuance. * @param to Token recipient. * @param value Number of tokens issued. * @param data Information attached to the issuance, and intended for the recipient (to). * @param operatorData Information attached to the issuance by the operator (if any). */ function _issue( bytes32 partition, address operator, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal nonReentrant { require(_isMultiple(value), "A9: Transfer Blocked - Token granularity"); require(to != address(0), "A6: Transfer Blocked - Receiver not eligible"); _totalSupply = _totalSupply.add(value); _balances[to] = _balances[to].add(value); _callRecipient(partition, operator, address(0), to, value, data, operatorData, true); emit Issued(operator, to, value, data, operatorData); } /********************** ERC777 OPTIONAL FUNCTIONS ***************************/ /** * [NOT MANDATORY FOR ERC777 STANDARD] * @dev Set list of token controllers. * @param operators Controller addresses. */ function _setControllers(address[] memory operators) internal { for (uint i = 0; i<_controllers.length; i++){ _isController[_controllers[i]] = false; } for (uint j = 0; j<operators.length; j++){ _isController[operators[j]] = true; } _controllers = operators; } }
contract ERC777 is IERC777, Ownable, ERC820Client, CertificateController, ReentrancyGuard { using SafeMath for uint256; string internal _name; string internal _symbol; uint256 internal _granularity; uint256 internal _totalSupply; // Indicate whether the token can still be controlled by operators or not anymore. bool internal _isControllable; // Mapping from tokenHolder to balance. mapping(address => uint256) internal _balances; /******************** Mappings related to operator **************************/ // Mapping from (operator, tokenHolder) to authorized status. [TOKEN-HOLDER-SPECIFIC] mapping(address => mapping(address => bool)) internal _authorizedOperator; // Array of controllers. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC] address[] internal _controllers; // Mapping from operator to controller status. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC] mapping(address => bool) internal _isController; /****************************************************************************/ /** * [ERC777 CONSTRUCTOR] * @dev Initialize ERC777 and CertificateController parameters + register * the contract implementation in ERC820Registry. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param certificateSigner Address of the off-chain service which signs the * conditional ownership certificates required for token transfers, issuance, * redemption (Cf. CertificateController.sol). */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner ) public CertificateController(certificateSigner) { _name = name; _symbol = symbol; _totalSupply = 0; require(granularity >= 1, "Constructor Blocked - Token granularity can not be lower than 1"); _granularity = granularity; _setControllers(controllers); setInterfaceImplementation("ERC777Token", address(this)); } /********************** ERC777 EXTERNAL FUNCTIONS ***************************/ /** * [ERC777 INTERFACE (1/13)] * @dev Get the name of the token, e.g., "MyToken". * @return Name of the token. */ function name() external view returns(string memory) { return _name; } /** * [ERC777 INTERFACE (2/13)] * @dev Get the symbol of the token, e.g., "MYT". * @return Symbol of the token. */ function symbol() external view returns(string memory) { return _symbol; } /** * [ERC777 INTERFACE (3/13)] * @dev Get the total number of issued tokens. * @return Total supply of tokens currently in circulation. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * [ERC777 INTERFACE (4/13)] * @dev Get the balance of the account with address 'tokenHolder'. * @param tokenHolder Address for which the balance is returned. * @return Amount of token held by 'tokenHolder' in the token contract. */ function balanceOf(address tokenHolder) external view returns (uint256) { return _balances[tokenHolder]; } /** * [ERC777 INTERFACE (5/13)] * @dev Get the smallest part of the token that’s not divisible. * @return The smallest non-divisible part of the token. */ function granularity() external view returns(uint256) { return _granularity; } /** * [ERC777 INTERFACE (6/13)] * @dev Get the list of controllers as defined by the token contract. * @return List of addresses of all the controllers. */ function controllers() external view returns (address[] memory) { return _controllers; } /** * [ERC777 INTERFACE (7/13)] * @dev Set a third party operator address as an operator of 'msg.sender' to transfer * and redeem tokens on its behalf. * @param operator Address to set as an operator for 'msg.sender'. */ function authorizeOperator(address operator) external { _authorizedOperator[operator][msg.sender] = true; emit AuthorizedOperator(operator, msg.sender); } /** * [ERC777 INTERFACE (8/13)] * @dev Remove the right of the operator address to be an operator for 'msg.sender' * and to transfer and redeem tokens on its behalf. * @param operator Address to rescind as an operator for 'msg.sender'. */ function revokeOperator(address operator) external { _authorizedOperator[operator][msg.sender] = false; emit RevokedOperator(operator, msg.sender); } /** * [ERC777 INTERFACE (9/13)] * @dev Indicate whether the operator address is an operator of the tokenHolder address. * @param operator Address which may be an operator of tokenHolder. * @param tokenHolder Address of a token holder which may have the operator address as an operator. * @return 'true' if operator is an operator of 'tokenHolder' and 'false' otherwise. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool) { return _isOperatorFor(operator, tokenHolder); } /** * [ERC777 INTERFACE (10/13)] * @dev Transfer the amount of tokens from the address 'msg.sender' to the address 'to'. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function transferWithData(address to, uint256 value, bytes calldata data) external isValidCertificate(data, 0x2535f762) { _transferWithData("", msg.sender, msg.sender, to, value, data, "", true); } /** * [ERC777 INTERFACE (11/13)] * @dev Transfer the amount of tokens on behalf of the address 'from' to the address 'to'. * @param from Token holder (or 'address(0)' to set from to 'msg.sender'). * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, and intended for the token holder ('from'). * @param operatorData Information attached to the transfer by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function transferFromWithData(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData, 0x868d5383) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorFor(msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _transferWithData("", msg.sender, _from, to, value, data, operatorData, true); } /** * [ERC777 INTERFACE (12/13)] * @dev Redeem the amount of tokens from the address 'msg.sender'. * @param value Number of tokens to redeem. * @param data Information attached to the redemption, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function redeem(uint256 value, bytes calldata data) external isValidCertificate(data, 0xe77c646d) { _redeem("", msg.sender, msg.sender, value, data, ""); } /** * [ERC777 INTERFACE (13/13)] * @dev Redeem the amount of tokens on behalf of the address from. * @param from Token holder whose tokens will be redeemed (or address(0) to set from to msg.sender). * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function redeemFrom(address from, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData, 0xffa90f7f) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorFor(msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _redeem("", msg.sender, _from, value, data, operatorData); } /********************** ERC777 INTERNAL FUNCTIONS ***************************/ /** * [INTERNAL] * @dev Check if 'value' is multiple of the granularity. * @param value The quantity that want's to be checked. * @return 'true' if 'value' is a multiple of the granularity. */ function _isMultiple(uint256 value) internal view returns(bool) { return(value.div(_granularity).mul(_granularity) == value); } /** * [INTERNAL] * @dev Check whether an address is a regular address or not. * @param addr Address of the contract that has to be checked. * @return 'true' if 'addr' is a regular address (not a contract). */ function _isRegularAddress(address addr) internal view returns(bool) { if (addr == address(0)) { return false; } uint size; assembly { size := extcodesize(addr) } // solhint-disable-line no-inline-assembly return size == 0; } /** * [INTERNAL] * @dev Indicate whether the operator address is an operator of the tokenHolder address. * @param operator Address which may be an operator of 'tokenHolder'. * @param tokenHolder Address of a token holder which may have the 'operator' address as an operator. * @return 'true' if 'operator' is an operator of 'tokenHolder' and 'false' otherwise. */ function _isOperatorFor(address operator, address tokenHolder) internal view returns (bool) { return (operator == tokenHolder || _authorizedOperator[operator][tokenHolder] || (_isControllable && _isController[operator]) ); } /** * [INTERNAL] * @dev Perform the transfer of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. * @param operatorData Information attached to the transfer by the operator (if any).. * @param preventLocking 'true' if you want this function to throw when tokens are sent to a contract not * implementing 'erc777tokenHolder'. * ERC777 native transfer functions MUST set this parameter to 'true', and backwards compatible ERC20 transfer * functions SHOULD set this parameter to 'false'. */ function _transferWithData( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData, bool preventLocking ) internal nonReentrant { require(_isMultiple(value), "A9: Transfer Blocked - Token granularity"); require(to != address(0), "A6: Transfer Blocked - Receiver not eligible"); require(_balances[from] >= value, "A4: Transfer Blocked - Sender balance insufficient"); _callSender(partition, operator, from, to, value, data, operatorData); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _callRecipient(partition, operator, from, to, value, data, operatorData, preventLocking); emit TransferWithData(operator, from, to, value, data, operatorData); } /** * [INTERNAL] * @dev Perform the token redemption. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator The address performing the redemption. * @param from Token holder whose tokens will be redeemed. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator (if any). */ function _redeem( bytes32 partition, address operator, address from, uint256 value, bytes memory data, bytes memory operatorData ) internal nonReentrant { require(_isMultiple(value), "A9: Transfer Blocked - Token granularity"); require(from != address(0), "A5: Transfer Blocked - Sender not eligible"); require(_balances[from] >= value, "A4: Transfer Blocked - Sender balance insufficient"); _callSender(partition, operator, from, address(0), value, data, operatorData); _balances[from] = _balances[from].sub(value); _totalSupply = _totalSupply.sub(value); emit Redeemed(operator, from, value, data, operatorData); } /** * [INTERNAL] * @dev Check for 'ERC777TokensSender' hook on the sender and call it. * May throw according to 'preventLocking'. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the balance decrease (through transfer or redemption). * @param from Token holder. * @param to Token recipient for a transfer and 0x for a redemption. * @param value Number of tokens the token holder balance is decreased by. * @param data Extra information. * @param operatorData Extra information, attached by the operator (if any). */ function _callSender( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { address senderImplementation; senderImplementation = interfaceAddr(from, "ERC777TokensSender"); if (senderImplementation != address(0)) { IERC777TokensSender(senderImplementation).tokensToTransfer(partition, operator, from, to, value, data, operatorData); } } /** * [INTERNAL] * @dev Check for 'ERC777TokensRecipient' hook on the recipient and call it. * May throw according to 'preventLocking'. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the balance increase (through transfer or issuance). * @param from Token holder for a transfer and 0x for an issuance. * @param to Token recipient. * @param value Number of tokens the recipient balance is increased by. * @param data Extra information, intended for the token holder ('from'). * @param operatorData Extra information attached by the operator (if any). * @param preventLocking 'true' if you want this function to throw when tokens are sent to a contract not * implementing 'ERC777TokensRecipient'. * ERC777 native transfer functions MUST set this parameter to 'true', and backwards compatible ERC20 transfer * functions SHOULD set this parameter to 'false'. */ function _callRecipient( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData, bool preventLocking ) internal { address recipientImplementation; recipientImplementation = interfaceAddr(to, "ERC777TokensRecipient"); if (recipientImplementation != address(0)) { IERC777TokensRecipient(recipientImplementation).tokensReceived(partition, operator, from, to, value, data, operatorData); } else if (preventLocking) { require(_isRegularAddress(to), "A6: Transfer Blocked - Receiver not eligible"); } } /** * [INTERNAL] * @dev Perform the issuance of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the issuance. * @param to Token recipient. * @param value Number of tokens issued. * @param data Information attached to the issuance, and intended for the recipient (to). * @param operatorData Information attached to the issuance by the operator (if any). */ function _issue( bytes32 partition, address operator, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal nonReentrant { require(_isMultiple(value), "A9: Transfer Blocked - Token granularity"); require(to != address(0), "A6: Transfer Blocked - Receiver not eligible"); _totalSupply = _totalSupply.add(value); _balances[to] = _balances[to].add(value); _callRecipient(partition, operator, address(0), to, value, data, operatorData, true); emit Issued(operator, to, value, data, operatorData); } /********************** ERC777 OPTIONAL FUNCTIONS ***************************/ /** * [NOT MANDATORY FOR ERC777 STANDARD] * @dev Set list of token controllers. * @param operators Controller addresses. */ function _setControllers(address[] memory operators) internal { for (uint i = 0; i<_controllers.length; i++){ _isController[_controllers[i]] = false; } for (uint j = 0; j<operators.length; j++){ _isController[operators[j]] = true; } _controllers = operators; } }
23,804
62
// Set minimum tokens required to swap.
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; }
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; }
5,195
153
// Core fonction / withdraw DTH when teller delete
function withdrawDthTeller(address _receiver) external onlyOwner { require(dthTellerBalance[_receiver] > 0); uint tosend = dthTellerBalance[_receiver]; dthTellerBalance[_receiver] = 0; require(dth.transfer(_receiver, tosend)); }
function withdrawDthTeller(address _receiver) external onlyOwner { require(dthTellerBalance[_receiver] > 0); uint tosend = dthTellerBalance[_receiver]; dthTellerBalance[_receiver] = 0; require(dth.transfer(_receiver, tosend)); }
79,024
35
// Token Bucket leak event fires on each minting/to is address of target tokens holder/left is amount of tokens available in bucket after leak
event Leak(address indexed to, uint256 left);
event Leak(address indexed to, uint256 left);
58,671
9
// rdefines an authority _name the authority name _address the authority address. /
function defineAuthority(string _name, address _address) public onlyOwner { emit AuthorityDefined(_name, _address); authority = _address; }
function defineAuthority(string _name, address _address) public onlyOwner { emit AuthorityDefined(_name, _address); authority = _address; }
20,389
12
// The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
mapping (address => uint32) public numCheckpoints;
10,598
220
// Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. /
function isApprovedForAll(address owner, address operator) override public view returns (bool)
function isApprovedForAll(address owner, address operator) override public view returns (bool)
18,078
153
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
(bool success, ) = recipient.call{ value: amount }("");
2,336
24
// check if contract is able to pay player a win
require(playerEarnings <= deposits[platformReserve]);
require(playerEarnings <= deposits[platformReserve]);
9,593