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 |
|---|---|---|---|---|
12 | // Add. | function fAdd(uint x, uint y) internal pure returns (uint) {
return x.add(y);
}
| function fAdd(uint x, uint y) internal pure returns (uint) {
return x.add(y);
}
| 64,838 |
67 | // Actually perform the safeTransferFrom. _from The current owner of the NFT. _to The new owner. _tokenId The NFT to transfer. _data Additional data with no specified format, sent in call to `_to`. / | function _safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
| function _safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
| 10,036 |
1 | // SBCWrapperProxy Upgradeable version of the underlying SBCWrapper. / | contract SBCWrapperProxy is EIP1967Proxy {
constructor(
address _admin,
SBCToken _token,
SBCDepositContract _depositContract
) {
_setAdmin(_admin);
_setImplementation(address(new SBCWrapper(_token, _depositContract)));
}
}
| contract SBCWrapperProxy is EIP1967Proxy {
constructor(
address _admin,
SBCToken _token,
SBCDepositContract _depositContract
) {
_setAdmin(_admin);
_setImplementation(address(new SBCWrapper(_token, _depositContract)));
}
}
| 19,208 |
114 | // Referral program 1,3% + Bounty program: 1,1%. Distribute 2,4% of final total supply of tokens (FTST24/1000) after endICODate to the wallet [G]. | uint256 tokensG = FTST.mul(24).div(1000);
token.mint(walletG, tokensG);
token.finishMinting();
finished = true;
| uint256 tokensG = FTST.mul(24).div(1000);
token.mint(walletG, tokensG);
token.finishMinting();
finished = true;
| 44,356 |
3 | // Retrieves the timestamp of the last batch submitted by the sequencer.return _lastSequencerTimestamp Last sequencer batch timestamp. / | function getLastSequencerTimestamp() external view returns (uint256 _lastSequencerTimestamp);
| function getLastSequencerTimestamp() external view returns (uint256 _lastSequencerTimestamp);
| 15,600 |
152 | // OpenSea contract info getter / | function contractURI() public view returns (string memory) {
return contract_uri;
}
| function contractURI() public view returns (string memory) {
return contract_uri;
}
| 43,132 |
1 | // ============ ERC20 Interface ============ |
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
|
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
| 22,245 |
64 | // profit = formular.getTakerProfitLoss(orders[orderID].number,orders[orderID].openPrice,currentPrice, ContractType.LONG); | profit = order.number.mul(currentPrice- order.openPrice).div(PRICE_DECIMALS);
| profit = order.number.mul(currentPrice- order.openPrice).div(PRICE_DECIMALS);
| 6,637 |
70 | // ERC-1271 must return this magic value when `isValidSignature` is called. | bytes4 internal constant _ERC_1271_MAGIC_VALUE = bytes4(0x20c13b0b);
| bytes4 internal constant _ERC_1271_MAGIC_VALUE = bytes4(0x20c13b0b);
| 31,271 |
89 | // Unstakes CBWC NFTs | function unStakeCBWC(uint256[] calldata _tokenIds)
external
isStakingLive
isTokenOwner(_tokenIds)
checkInputLength(_tokenIds)
| function unStakeCBWC(uint256[] calldata _tokenIds)
external
isStakingLive
isTokenOwner(_tokenIds)
checkInputLength(_tokenIds)
| 20,780 |
12 | // Retrieve a `severity` for a given `region` and `season` , provided by `oracle`.season year (e.g. 2021). region region code in bytes32 oracle oracle address return Severity .If Severity is the default value then it means that the oracle didn't provide any submission for `region` and `season` / | function getSubmission(
| function getSubmission(
| 11,057 |
4 | // Returns is a given address has cross ledger operator rights._operator The address of the operator return bool / | function isCrossLedgerOperator(address _operator)
| function isCrossLedgerOperator(address _operator)
| 9,375 |
66 | // `callHotel` Call hotel in the index, the hotel can onlybe called by its manager. Effectively proxies a hotel call.Emits HotelCalled on success.hotel Hotel's addressdata Encoded method call to be done on Hotel contract. / | function callHotel(address hotel, bytes data) external {
// Ensure hotel address is valid
require(hotel != address(0));
// Ensure we know about the hotel at all
require(hotelsIndex[hotel] != uint(0));
// Ensure that the caller is the hotel's rightful owner
require(hotelsByManager[msg.sender][hotelsByManagerIndex[hotel]] != address(0));
Hotel hotelInstance = Hotel(hotel);
// Ensure we are calling only our own hotels
require(hotelInstance.index() == address(this));
require(hotel.call(data));
emit HotelCalled(hotel);
}
| function callHotel(address hotel, bytes data) external {
// Ensure hotel address is valid
require(hotel != address(0));
// Ensure we know about the hotel at all
require(hotelsIndex[hotel] != uint(0));
// Ensure that the caller is the hotel's rightful owner
require(hotelsByManager[msg.sender][hotelsByManagerIndex[hotel]] != address(0));
Hotel hotelInstance = Hotel(hotel);
// Ensure we are calling only our own hotels
require(hotelInstance.index() == address(this));
require(hotel.call(data));
emit HotelCalled(hotel);
}
| 41,016 |
39 | // Used to remove routers that can transact crosschain _router Router address to remove / | function unapproveRouter(address _router) external onlyOwnerOrRouter {
// Sanity check: not empty
if (_router == address(0)) revert RoutersFacet__unapproveRouter_routerEmpty();
// Sanity check: needs removal
RouterConfig memory config = s.routerConfigs[_router];
if (!config.approved) revert RoutersFacet__unapproveRouter_notAdded();
// Update approvals in config mapping
delete s.routerConfigs[_router].approved;
delete s.routerConfigs[_router].portalApproved;
// Emit event
emit RouterRemoved(_router, msg.sender);
}
| function unapproveRouter(address _router) external onlyOwnerOrRouter {
// Sanity check: not empty
if (_router == address(0)) revert RoutersFacet__unapproveRouter_routerEmpty();
// Sanity check: needs removal
RouterConfig memory config = s.routerConfigs[_router];
if (!config.approved) revert RoutersFacet__unapproveRouter_notAdded();
// Update approvals in config mapping
delete s.routerConfigs[_router].approved;
delete s.routerConfigs[_router].portalApproved;
// Emit event
emit RouterRemoved(_router, msg.sender);
}
| 23,800 |
41 | // Returns asset description._symbol asset symbol. return asset description. / | function description(bytes32 _symbol) constant returns(string) {
return assets[_symbol].description;
}
| function description(bytes32 _symbol) constant returns(string) {
return assets[_symbol].description;
}
| 21,426 |
3 | // Allows governance to pull tokens out of this contract(it should never hold tokens) _token The address of the token _amount The amount to withdraw _to The address to send to / | function governanceRecoverUnsupported(
IERC20 _token,
uint256 _amount,
address _to
| function governanceRecoverUnsupported(
IERC20 _token,
uint256 _amount,
address _to
| 34,800 |
777 | // check if owner is still owner | if (getOwner(_cdpId) != holder.owner) return (false, 0);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
| if (getOwner(_cdpId) != holder.owner) return (false, 0);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
| 55,110 |
9 | // default values | purchaseWindow = _purchaseWindow;
commodityPrice = _commodityPrice;
eth_usd_consumer_address = _eth_usd_consumer_address;
eth_pricer = IChainlinkPriceConsumer(_eth_usd_consumer_address);
tier_to_tierDetails[Tier.tier1] = TierDetails( // Initialize tiers
87500 * 1e18, // 1e18 being the number of decimals of tokens. Not to be confused with sd59x18_decimals
0,
2 weeks,
100 ether
| purchaseWindow = _purchaseWindow;
commodityPrice = _commodityPrice;
eth_usd_consumer_address = _eth_usd_consumer_address;
eth_pricer = IChainlinkPriceConsumer(_eth_usd_consumer_address);
tier_to_tierDetails[Tier.tier1] = TierDetails( // Initialize tiers
87500 * 1e18, // 1e18 being the number of decimals of tokens. Not to be confused with sd59x18_decimals
0,
2 weeks,
100 ether
| 9,055 |
247 | // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) | emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
| emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
| 3,641 |
60 | // An array containing the Dungeon struct, which contains all the dungeons in existance. The ID for each dungeon is the index of this array. / | Dungeon[] public dungeons;
| Dungeon[] public dungeons;
| 44,084 |
23 | // Return CR at `epoch`, given it's set. | cumulativeReward = _cumulativeRewardsByPool[poolId][epoch];
if (_isCumulativeRewardSet(cumulativeReward)) {
return cumulativeReward;
}
| cumulativeReward = _cumulativeRewardsByPool[poolId][epoch];
if (_isCumulativeRewardSet(cumulativeReward)) {
return cumulativeReward;
}
| 41,826 |
44 | // use internal fn instead of modifier to avoid stack depth compiler errors | _validSplitHash(split, accounts, percentAllocations, distributorFee);
_distributeETH(
split,
accounts,
percentAllocations,
distributorFee,
distributorAddress
);
| _validSplitHash(split, accounts, percentAllocations, distributorFee);
_distributeETH(
split,
accounts,
percentAllocations,
distributorFee,
distributorAddress
);
| 24,799 |
143 | // CalcBPD / | function calcBPD(
uint256 start,
uint256 end,
uint256 shares
| function calcBPD(
uint256 start,
uint256 end,
uint256 shares
| 37,889 |
192 | // Adjust the holder value to ensure rewards are split fairly! | _isholder = wrapperdb(dbcontract).isHolder(msg.sender);
if (_isholder == false) {
wrapperdb(dbcontract).manageHolderAddresses(true, msg.sender); ///Sets user as a holder!
wrapperdb(dbcontract).manageNumHolders(2); ///Bump the holder value
}
| _isholder = wrapperdb(dbcontract).isHolder(msg.sender);
if (_isholder == false) {
wrapperdb(dbcontract).manageHolderAddresses(true, msg.sender); ///Sets user as a holder!
wrapperdb(dbcontract).manageNumHolders(2); ///Bump the holder value
}
| 38,374 |
9 | // increasing claimable tokens | total += diff;
records[beneficiary].total += uint120(diff);
| total += diff;
records[beneficiary].total += uint120(diff);
| 8,536 |
0 | // This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program.If not, see <http:www.gnu.org/licenses/>. | library BConst {
uint public constant BONE = 10**18;
uint public constant MIN_BOUND_TOKENS = 2;
uint public constant MAX_BOUND_TOKENS = 8;
uint public constant DEFAULT_FEE = BONE * 3 / 1000; // 0.3%
uint public constant MIN_FEE = BONE / 10**6;
uint public constant MAX_FEE = BONE / 10;
uint public constant DEFAULT_COLLECTED_FEE = BONE / 2000; // 0.05%
uint public constant MAX_COLLECTED_FEE = BONE / 200; // 0.5%
uint public constant DEFAULT_EXIT_FEE = 0;
uint public constant MAX_EXIT_FEE = BONE / 1000; // 0.1%
uint public constant MIN_WEIGHT = BONE;
uint public constant MAX_WEIGHT = BONE * 50;
uint public constant MAX_TOTAL_WEIGHT = BONE * 50;
uint public constant MIN_BALANCE = BONE / 10**12;
uint public constant DEFAULT_INIT_POOL_SUPPLY = BONE * 100;
uint public constant MIN_INIT_POOL_SUPPLY = BONE / 1000;
uint public constant MAX_INIT_POOL_SUPPLY = BONE * 10**18;
uint public constant MIN_BPOW_BASE = 1 wei;
uint public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei;
uint public constant BPOW_PRECISION = BONE / 10**10;
uint public constant MAX_IN_RATIO = BONE / 2;
uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
}
| library BConst {
uint public constant BONE = 10**18;
uint public constant MIN_BOUND_TOKENS = 2;
uint public constant MAX_BOUND_TOKENS = 8;
uint public constant DEFAULT_FEE = BONE * 3 / 1000; // 0.3%
uint public constant MIN_FEE = BONE / 10**6;
uint public constant MAX_FEE = BONE / 10;
uint public constant DEFAULT_COLLECTED_FEE = BONE / 2000; // 0.05%
uint public constant MAX_COLLECTED_FEE = BONE / 200; // 0.5%
uint public constant DEFAULT_EXIT_FEE = 0;
uint public constant MAX_EXIT_FEE = BONE / 1000; // 0.1%
uint public constant MIN_WEIGHT = BONE;
uint public constant MAX_WEIGHT = BONE * 50;
uint public constant MAX_TOTAL_WEIGHT = BONE * 50;
uint public constant MIN_BALANCE = BONE / 10**12;
uint public constant DEFAULT_INIT_POOL_SUPPLY = BONE * 100;
uint public constant MIN_INIT_POOL_SUPPLY = BONE / 1000;
uint public constant MAX_INIT_POOL_SUPPLY = BONE * 10**18;
uint public constant MIN_BPOW_BASE = 1 wei;
uint public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei;
uint public constant BPOW_PRECISION = BONE / 10**10;
uint public constant MAX_IN_RATIO = BONE / 2;
uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
}
| 39,392 |
191 | // 请求预言机方法 | function _requestURL(address from, string memory apiURL, string memory postParam, uint256 tokenId, bytes memory extraData) private returns(bytes32 _id) {
_id = aggregate.getPostUrl{value: oraclePrice}(apiURL, postParam);
requestIdToData[_id] = RequestData(from, tokenId);
emit LogRequest(_id, from, tokenId, oraclePrice, extraData);
}
| function _requestURL(address from, string memory apiURL, string memory postParam, uint256 tokenId, bytes memory extraData) private returns(bytes32 _id) {
_id = aggregate.getPostUrl{value: oraclePrice}(apiURL, postParam);
requestIdToData[_id] = RequestData(from, tokenId);
emit LogRequest(_id, from, tokenId, oraclePrice, extraData);
}
| 11,567 |
107 | // Returns the number of decimals used to get its user representation.For example, if `decimals` equals `2`, a balance of `505` tokens shouldbe displayed to a user as `5,05` (`505 / 102`). Tokens usually opt for a value of 18, imitating the relationship between | * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
// Present in ERC777
function decimals() public view returns (uint8) {
return _decimals;
}
| * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
// Present in ERC777
function decimals() public view returns (uint8) {
return _decimals;
}
| 6,851 |
236 | // TODO: Add locked stakes too? |
getReward();
|
getReward();
| 24,096 |
20 | // A library for performing overflow-/underflow-safe addition and subtraction on uint32. | library BoringMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
| library BoringMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
| 8,980 |
5 | // Generate the token SVG art of a specified frame _id for which we want art _frame for which we want artreturn animated SVG art of token _id at _frame. / | function tokenFrame(uint256 _id, uint256 _frame)
public
view
returns (string memory)
| function tokenFrame(uint256 _id, uint256 _frame)
public
view
returns (string memory)
| 33,787 |
4 | // Returns the addition of two unsigned integers, reverting onoverflow. Counterpart to Solidity's `+` operator. Requirements:- Addition cannot overflow. / | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
| function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
| 21,920 |
119 | // base contract for option pool / | abstract contract OptionPoolBase is IOptionPool, PausablePool{
using SafeERC20 for IERC20;
using SafeERC20 for IOption;
using SafeMath for uint;
using SafeMath for address;
using Address for address payable;
uint public collateral; // collaterals in this pool
mapping (address => uint256) internal _premiumBalance; // tracking pooler's claimable premium
IOption [] internal _options; // all option contracts
address internal _owner; // owner of this contract
IERC20 immutable public USDTContract; // USDT asset contract address
UniswapInterface immutable public uniswapRouter; // Uniswap ETH Price quote
CDFDataInterface public cdfDataContract; // cdf data contract;
uint public utilizationRate; // utilization rate of the pool in percent
uint public maxUtilizationRate; // max utilization rate of the pool in percent
uint64 public sigma; // current sigma
uint private _sigmaSoldOptions; // sum total options sold in a period
uint private _sigmaTotalOptions; // sum total options issued
uint private _nextSigmaUpdate; // expected next sigma updating time;
// tracking pooler's collateral with
// the token contract of the pooler;
IPoolerToken public poolerTokenContract;
bool poolerTokenOnce;
// round limit
uint public roundLimit;
// number of options
uint immutable internal _numOptions;
/**
* @dev Modifier to make a function callable only buy owner
*/
modifier onlyOwner() {
require(msg.sender == _owner, "OptionPoolBase: need owner");
_;
}
/**
* @dev Modifier to make a function callable only buy poolerTokenContract
*/
modifier onlyPoolerTokenContract() {
require(msg.sender == address(poolerTokenContract), "OptionPoolBase: need poolerTokenContract");
_;
}
/**
* @dev settle debug log
*/
event SettleLog (string name, uint strikePrice, uint etherPrice, uint totalProfit, uint totalOptionSold, uint premiumShare);
/**
* @dev sigma update log
*/
event SigmaUpdate(uint sigma, uint rate);
/**
* @dev ownership transfer event log
*/
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev sigma set log
*/
event SigmaSet(uint sigma);
/**
* @dev abstract function for current option supply per slot
*/
function _slotSupply(uint etherPrice) internal virtual returns(uint);
/**
* @dev abstract function to calculate option gain
*/
function _calcProfits(uint settlePrice, uint strikePrice, uint optionAmount) internal pure virtual returns(uint256 gain);
/**
* @dev abstract function to send back option profits
*/
function _sendProfits(address payable account, uint256 amount) internal virtual;
/**
* @dev abstract function to get total pledged collateral
*/
function _totalPledged() internal view virtual returns (uint);
constructor(IERC20 USDTContract_, UniswapInterface uniswapRouter_, CDFDataInterface cdfDataContract_, uint numOptions) public {
_owner = msg.sender;
USDTContract = USDTContract_;
uniswapRouter = uniswapRouter_;
cdfDataContract = cdfDataContract_;
utilizationRate = 50; // default utilization rate is 50
maxUtilizationRate = 75; // default max utilization rate is 50
_nextSigmaUpdate = block.timestamp + 3600;
roundLimit = 1000;
sigma = 70;
_numOptions = numOptions;
}
/**
* @dev Returns the owner of this contract
*/
function owner() external override view returns (address) {
return _owner;
}
/**
* @dev transfer ownership
*/
function transferOwnership(address newOwner) external override onlyOwner {
require(newOwner != address(0), "owner zero");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/**
*@dev pooler & buyer pausing
*/
function pausePooler() external override onlyOwner { _pausePooler(); }
function unpausePooler() external override onlyOwner { _unpausePooler(); }
function pauseBuyer() external override onlyOwner { _pauseBuyer(); }
function unpauseBuyer() external override onlyOwner { _unpauseBuyer(); }
/**
* @notice check remaining options for the option contract
*/
function optionsLeft(IOption optionContract) external override view returns (uint256){
return optionContract.balanceOf(address(this));
}
/**
* @notice buy options via USDT, pool receive premium
*/
function buy(uint amount, IOption optionContract, uint round) external override whenBuyerNotPaused returns(bool) {
// if the option has expired settle first
if (block.timestamp >= optionContract.expiryDate()) { // expired
update();
}
// check if option current round is the given round
if (optionContract.getRound() != round) {
return false;
}
// check remaing options
require(optionContract.balanceOf(address(this)) >= amount, "soldout");
// calculate premium cost
uint premium = premiumCost(amount, optionContract);
require(premium > 0, "option to buy too less");
// transfer premium USDTs to this pool
USDTContract.safeTransferFrom(msg.sender, address(this), premium);
// transfer options to msg.sender
optionContract.safeTransfer(msg.sender, amount);
// credit premium to option contract
optionContract.addPremium(premium);
// sigma: count sold options
_sigmaSoldOptions = _sigmaSoldOptions.add(amount);
return true;
}
/**
* @dev convert sigma to index, sigma will be rounded to nearest index
*/
function _sigmaToIndex() private view returns(uint) {
// sigma to index
require(sigma >=15 && sigma <=145, "invalid sigma");
uint sigmaIndex = sigma / 5;
return sigmaIndex;
}
/**
* @notice check option cost for given amount of option
*/
function premiumCost(uint amount, IOption optionContract) public override view returns(uint) {
// notice the CDF is already multiplied by cdfDataContract.Amplifier()
uint cdf = cdfDataContract.CDF(optionContract.getDuration(), _sigmaToIndex());
// note the price is for 1ETH = 1e18
return amount * optionContract.strikePrice() * cdf / (1 ether) / cdfDataContract.Amplifier();
}
/**
* @notice list all options
*/
function listOptions() external override view returns (IOption []memory) {
return _options;
}
/**
* @notice get current utilization rate
*/
function currentUtilizationRate() external override view returns (uint256) {
return _totalPledged().mul(100).div(collateral);
}
/**
* @notice update of options, triggered by anyone periodically
*/
function update() public override {
// update call options
uint etherPrice = getEtherPrice();
// prevent divide by 0;
require(etherPrice > 0, "invalid price");
// settle all options
for (uint i = 0;i< _options.length;i++) {
if (block.timestamp >= _options[i].expiryDate()) { // expired
_settleOption(_options[i], etherPrice);
}
}
// calculate supply for a slot after settlement,
// notice we must settle options before option reset, otherwise
// we cannot get a correct slot supply due to COLLATERAL WRITE DOWN
// when multiple options settles at once.
uint slotSupply = _slotSupply(etherPrice);
for (uint i = 0;i< _options.length;i++) {
if (block.timestamp >= _options[i].expiryDate()) {
// reset option with new slot supply
_options[i].resetOption(etherPrice, slotSupply);
// sigma: count newly issued options
_sigmaTotalOptions = _sigmaTotalOptions.add(_options[i].totalSupply());
}
}
// should update sigma while sigma period expired
if (block.timestamp > _nextSigmaUpdate) {
updateSigma();
}
}
/**
* @dev function to update sigma value periodically
*/
function updateSigma() internal {
// sigma: metrics updates hourly
if (_sigmaTotalOptions > 0) {
// update sigma
uint rate = _sigmaSoldOptions.mul(100).div(_sigmaTotalOptions);
// sigma range [15, 145]
if (rate > 90 && sigma < 145) {
sigma += 5;
emit SigmaUpdate(sigma, rate);
} else if (rate < 50 && sigma > 15) {
sigma -= 5;
emit SigmaUpdate(sigma, rate);
}
}
// clear metrics
_sigmaTotalOptions = 0;
_sigmaSoldOptions = 0;
// rebuild sold/total metrics
for (uint i = 0;i< _options.length;i++) {
// sum all issued options and sold options
uint supply = _options[i].totalSupply();
uint sold = supply.sub(_options[i].balanceOf(address(this)));
// sigma: set current metrics
_sigmaTotalOptions = _sigmaTotalOptions.add(supply);
_sigmaSoldOptions = _sigmaSoldOptions.add(sold);
}
// set next update time to one hour later
_nextSigmaUpdate = block.timestamp + 3600;
}
/**
* @notice adjust sigma manually
*/
function adjustSigma(uint64 newSigma) external override onlyOwner {
require (newSigma % 5 == 0, "sigma needs 5*N");
require (newSigma >= 15 && newSigma <= 145, "sigma not in range [15,145]");
sigma = newSigma;
emit SigmaSet(sigma);
}
/**
* @notice poolers claim premium USDTs;
*/
function claimPremium() external override whenPoolerNotPaused {
// settle un-distributed premiums in rounds to _premiumBalance;
_settlePremium(msg.sender);
// send USDTs premium back to senders's address
uint amountUSDTPremium = _premiumBalance[msg.sender];
_premiumBalance[msg.sender] = 0; // zero premium blance
// extra check the amount is not 0;
if (amountUSDTPremium > 0) {
USDTContract.safeTransfer(msg.sender, amountUSDTPremium);
}
}
/**
* @notice settle premium in rounds while pooler token tranfsers.
*/
function settlePremiumByPoolerToken(address account) external override onlyPoolerTokenContract returns(bool) {
return _settlePremium(account);
}
/**
* @dev settle option contract
*/
function _settleOption(IOption option, uint settlePrice) internal {
uint totalSupply = option.totalSupply();
uint strikePrice = option.strikePrice();
// ignore 0 supply && 0 strikePrice option
if (totalSupply == 0 || strikePrice == 0) {
return;
}
// count total sold options
uint totalOptionSold = totalSupply.sub(option.balanceOf(address(this)));
// calculate total gain
uint totalProfits = _calcProfits(settlePrice, strikePrice, totalOptionSold);
// substract ethers from collateral
// buyer's gain is pooler's loss
collateral = collateral.sub(totalProfits);
// settle preimum share
uint premiumShare;
if (poolerTokenContract.totalSupply() > 0) {
premiumShare = option.totalPremiums()
.mul(1e18) // mul share with 1e18 to prevent from underflow
.div(poolerTokenContract.totalSupply());
// set premium share to round for pooler
option.setRoundPremiumShare(option.getRound(), premiumShare);
}
// log
emit SettleLog(option.name(), strikePrice, settlePrice, totalProfits, totalOptionSold, premiumShare);
}
/**
* @notice settle premium in rounds to _premiumBalance,
* settle premium happens before any token exchange such as ERC20-transfer,mint,burn,
* and manually claimPremium;
*
* @return false means the rounds has terminated due to gas limit
*/
function _settlePremium(address account) internal returns(bool) {
uint accountCollateral = poolerTokenContract.balanceOf(account);
// at any time we find a pooler with 0 collateral, we can mark the previous rounds settled
// to avoid meaningless round loops below.
if (accountCollateral == 0) {
for (uint i = 0; i < _options.length; i++) {
if (_options[i].getRound() > 0) {
// all settled rounds before current round marked settled, which also means
// new collateral will make money immediately at current round.
_options[i].setSettledPremiumRound(_options[i].getRound() - 1, account);
}
}
return true;
}
// at this stage, the account has collaterals
uint roundsCounter;
for (uint i = 0; i < _options.length; i++) {
// shift premium from settled rounds with rounds control
uint maxRound = _options[i].getRound();
for (uint r = _options[i].getSettledPremiumRound(account) + 1; r < maxRound; r++) {
uint roundPremium = _options[i].getRoundPremiumShare(r)
.mul(accountCollateral)
.div(1e18); // remember to div by 1e18
// shift un-distributed premiums to _premiumBalance
_premiumBalance[account] = _premiumBalance[account].add(roundPremium);
// mark this round premium claimed
_options[i].setSettledPremiumRound(r, account);
// @dev BLOCK GAS LIMIT PROBLEM
// poolers needs to submit multiple transactions to claim ALL premiums in all rounds
// due to gas limit.
roundsCounter++;
if (roundsCounter >= roundLimit) {
return false;
}
}
}
return true;
}
/**
* @notice net-withdraw amount;
*/
function NWA() public view override returns (uint) {
// get minimum collateral
uint minCollateral = _totalPledged() * 100 / maxUtilizationRate;
if (minCollateral > collateral) {
return 0;
}
// net withdrawable amount
return collateral.sub(minCollateral);
}
/**
* @notice poolers sum premium USDTs;
*/
function checkPremium(address account) external override view returns(uint256) {
uint accountCollateral = poolerTokenContract.balanceOf(account);
// if the account has 0 value pooled
if (accountCollateral == 0) {
return 0;
}
uint premium;
for (uint i = 0; i < _options.length; i++) {
uint maxRound = _options[i].getRound();
for (uint r = _options[i].getSettledPremiumRound(account) + 1; r < maxRound; r++) {
uint roundPremium = _options[i].getRoundPremiumShare(r)
.mul(accountCollateral)
.div(1e18); // remember to div by 1e18
premium = premium.add(roundPremium);
}
}
// add un-distributed premium with _premiumBalance
return premium + _premiumBalance[account];
}
/**
* @notice buyers claim all option profits
*/
function claimProfits() external override whenBuyerNotPaused {
uint roundsCounter;
uint accountProfits;
// sum all profits from all options
for (uint i = 0; i < _options.length; i++) {
// sum all profits from all un-claimed rounds
uint r = _options[i].popUnclaimedProfitsRound(msg.sender);
while (r!= 0) {
uint settlePrice = _options[i].getRoundSettlePrice(r);
uint strikePrice = _options[i].getRoundStrikePrice(r);
uint optionAmount = _options[i].getRoundBalanceOf(r, msg.sender);
// accumulate gain in rounds
accountProfits = accountProfits.add(_calcProfits(settlePrice, strikePrice, optionAmount));
// @dev break for BLOCK GAS LIMIT
// poolers needs to submit multiple transactions to claim profits in all rounds.
roundsCounter++;
if (roundsCounter >= roundLimit) {
break;
}
// pop next round
r = _options[i].popUnclaimedProfitsRound(msg.sender);
}
}
// extra check the amount is not 0;
if (accountProfits > 0) {
_sendProfits(msg.sender, accountProfits);
}
}
/**
* @notice check claimable buyer's profits
*/
function checkProfits(address account) external override view returns (uint256 profits) {
// sum all profits from all options
for (uint i = 0; i < _options.length; i++) {
uint optionProfits = checkOptionProfits(_options[i], account);
profits = profits.add(optionProfits);
}
return profits;
}
/**
* @notice check profits in an option
*/
function checkOptionProfits(IOption option, address account) internal view returns (uint256 amount) {
// sum all profits from all un-claimed rounds
uint [] memory rounds = option.getUnclaimedProfitsRounds(msg.sender);
for (uint i=0;i<rounds.length;i++) {
uint settlePrice = option.getRoundSettlePrice(rounds[i]);
uint strikePrice = option.getRoundStrikePrice(rounds[i]);
uint optionAmount = option.getRoundBalanceOf(rounds[i], account);
// accumulate gain in rounds
amount = amount.add(_calcProfits(settlePrice, strikePrice, optionAmount));
}
return amount;
}
/**
* @notice set new option contract to option pool with different duration
*/
function setOption(IOption option) external override onlyOwner {
require(_options.length <= _numOptions, "options exceeded");
require(option.getDuration() > 0, "duration is 0");
require(option.totalSupply() == 0, "totalSupply != 0");
require(option.getPool() == address(this), "owner mismatch");
// the duration must be in the set
bool durationValid;
for (uint i=0;i<cdfDataContract.numDurations();i++) {
if (option.getDuration() == cdfDataContract.Durations(i)) {
durationValid = true;
break;
}
}
require (durationValid, "duration invalid");
// the option must not be set more than once
for (uint i = 0;i< _options.length;i++) {
require(_options[i] != option, "duplicated");
}
_options.push(option);
}
/**
* @notice set pooler token once
*/
function setPoolerToken(IPoolerToken poolerToken) external override onlyOwner {
require (!poolerTokenOnce, "already set");
require(poolerToken.getPool() == address(this), "owner mismatch");
poolerTokenContract = poolerToken;
poolerTokenOnce = true;
}
/**
* @notice set utilization rate by owner
*/
function setUtilizationRate(uint rate) external override onlyOwner {
require(rate >=0 && rate <= 100, "rate[0,100]");
utilizationRate = rate;
}
/**
* @notice set max utilization rate by owner
*/
function setMaxUtilizationRate(uint maxrate) external override onlyOwner {
require(maxrate >=0 && maxrate <= 100, "rate[0,100]");
require(maxrate > utilizationRate, "less than rate");
maxUtilizationRate = maxrate;
}
/**
* @dev set round limit to avoid gas exceedes block gasLimit
*/
function setRoundLimit(uint limit) external override onlyOwner {
require(roundLimit > 0, "roundLimit 0");
roundLimit = limit;
}
/**
* @dev get the price of ETH from uniswap
*/
function getEtherPrice() public view returns(uint) {
address[] memory addrs = new address[](2);
addrs[0] = address(USDTContract);
addrs[1] = uniswapRouter.WETH.address;
uint[] memory amounts = uniswapRouter.getAmountsIn((1 ether), addrs);
return amounts[0];
}
}
| abstract contract OptionPoolBase is IOptionPool, PausablePool{
using SafeERC20 for IERC20;
using SafeERC20 for IOption;
using SafeMath for uint;
using SafeMath for address;
using Address for address payable;
uint public collateral; // collaterals in this pool
mapping (address => uint256) internal _premiumBalance; // tracking pooler's claimable premium
IOption [] internal _options; // all option contracts
address internal _owner; // owner of this contract
IERC20 immutable public USDTContract; // USDT asset contract address
UniswapInterface immutable public uniswapRouter; // Uniswap ETH Price quote
CDFDataInterface public cdfDataContract; // cdf data contract;
uint public utilizationRate; // utilization rate of the pool in percent
uint public maxUtilizationRate; // max utilization rate of the pool in percent
uint64 public sigma; // current sigma
uint private _sigmaSoldOptions; // sum total options sold in a period
uint private _sigmaTotalOptions; // sum total options issued
uint private _nextSigmaUpdate; // expected next sigma updating time;
// tracking pooler's collateral with
// the token contract of the pooler;
IPoolerToken public poolerTokenContract;
bool poolerTokenOnce;
// round limit
uint public roundLimit;
// number of options
uint immutable internal _numOptions;
/**
* @dev Modifier to make a function callable only buy owner
*/
modifier onlyOwner() {
require(msg.sender == _owner, "OptionPoolBase: need owner");
_;
}
/**
* @dev Modifier to make a function callable only buy poolerTokenContract
*/
modifier onlyPoolerTokenContract() {
require(msg.sender == address(poolerTokenContract), "OptionPoolBase: need poolerTokenContract");
_;
}
/**
* @dev settle debug log
*/
event SettleLog (string name, uint strikePrice, uint etherPrice, uint totalProfit, uint totalOptionSold, uint premiumShare);
/**
* @dev sigma update log
*/
event SigmaUpdate(uint sigma, uint rate);
/**
* @dev ownership transfer event log
*/
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev sigma set log
*/
event SigmaSet(uint sigma);
/**
* @dev abstract function for current option supply per slot
*/
function _slotSupply(uint etherPrice) internal virtual returns(uint);
/**
* @dev abstract function to calculate option gain
*/
function _calcProfits(uint settlePrice, uint strikePrice, uint optionAmount) internal pure virtual returns(uint256 gain);
/**
* @dev abstract function to send back option profits
*/
function _sendProfits(address payable account, uint256 amount) internal virtual;
/**
* @dev abstract function to get total pledged collateral
*/
function _totalPledged() internal view virtual returns (uint);
constructor(IERC20 USDTContract_, UniswapInterface uniswapRouter_, CDFDataInterface cdfDataContract_, uint numOptions) public {
_owner = msg.sender;
USDTContract = USDTContract_;
uniswapRouter = uniswapRouter_;
cdfDataContract = cdfDataContract_;
utilizationRate = 50; // default utilization rate is 50
maxUtilizationRate = 75; // default max utilization rate is 50
_nextSigmaUpdate = block.timestamp + 3600;
roundLimit = 1000;
sigma = 70;
_numOptions = numOptions;
}
/**
* @dev Returns the owner of this contract
*/
function owner() external override view returns (address) {
return _owner;
}
/**
* @dev transfer ownership
*/
function transferOwnership(address newOwner) external override onlyOwner {
require(newOwner != address(0), "owner zero");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/**
*@dev pooler & buyer pausing
*/
function pausePooler() external override onlyOwner { _pausePooler(); }
function unpausePooler() external override onlyOwner { _unpausePooler(); }
function pauseBuyer() external override onlyOwner { _pauseBuyer(); }
function unpauseBuyer() external override onlyOwner { _unpauseBuyer(); }
/**
* @notice check remaining options for the option contract
*/
function optionsLeft(IOption optionContract) external override view returns (uint256){
return optionContract.balanceOf(address(this));
}
/**
* @notice buy options via USDT, pool receive premium
*/
function buy(uint amount, IOption optionContract, uint round) external override whenBuyerNotPaused returns(bool) {
// if the option has expired settle first
if (block.timestamp >= optionContract.expiryDate()) { // expired
update();
}
// check if option current round is the given round
if (optionContract.getRound() != round) {
return false;
}
// check remaing options
require(optionContract.balanceOf(address(this)) >= amount, "soldout");
// calculate premium cost
uint premium = premiumCost(amount, optionContract);
require(premium > 0, "option to buy too less");
// transfer premium USDTs to this pool
USDTContract.safeTransferFrom(msg.sender, address(this), premium);
// transfer options to msg.sender
optionContract.safeTransfer(msg.sender, amount);
// credit premium to option contract
optionContract.addPremium(premium);
// sigma: count sold options
_sigmaSoldOptions = _sigmaSoldOptions.add(amount);
return true;
}
/**
* @dev convert sigma to index, sigma will be rounded to nearest index
*/
function _sigmaToIndex() private view returns(uint) {
// sigma to index
require(sigma >=15 && sigma <=145, "invalid sigma");
uint sigmaIndex = sigma / 5;
return sigmaIndex;
}
/**
* @notice check option cost for given amount of option
*/
function premiumCost(uint amount, IOption optionContract) public override view returns(uint) {
// notice the CDF is already multiplied by cdfDataContract.Amplifier()
uint cdf = cdfDataContract.CDF(optionContract.getDuration(), _sigmaToIndex());
// note the price is for 1ETH = 1e18
return amount * optionContract.strikePrice() * cdf / (1 ether) / cdfDataContract.Amplifier();
}
/**
* @notice list all options
*/
function listOptions() external override view returns (IOption []memory) {
return _options;
}
/**
* @notice get current utilization rate
*/
function currentUtilizationRate() external override view returns (uint256) {
return _totalPledged().mul(100).div(collateral);
}
/**
* @notice update of options, triggered by anyone periodically
*/
function update() public override {
// update call options
uint etherPrice = getEtherPrice();
// prevent divide by 0;
require(etherPrice > 0, "invalid price");
// settle all options
for (uint i = 0;i< _options.length;i++) {
if (block.timestamp >= _options[i].expiryDate()) { // expired
_settleOption(_options[i], etherPrice);
}
}
// calculate supply for a slot after settlement,
// notice we must settle options before option reset, otherwise
// we cannot get a correct slot supply due to COLLATERAL WRITE DOWN
// when multiple options settles at once.
uint slotSupply = _slotSupply(etherPrice);
for (uint i = 0;i< _options.length;i++) {
if (block.timestamp >= _options[i].expiryDate()) {
// reset option with new slot supply
_options[i].resetOption(etherPrice, slotSupply);
// sigma: count newly issued options
_sigmaTotalOptions = _sigmaTotalOptions.add(_options[i].totalSupply());
}
}
// should update sigma while sigma period expired
if (block.timestamp > _nextSigmaUpdate) {
updateSigma();
}
}
/**
* @dev function to update sigma value periodically
*/
function updateSigma() internal {
// sigma: metrics updates hourly
if (_sigmaTotalOptions > 0) {
// update sigma
uint rate = _sigmaSoldOptions.mul(100).div(_sigmaTotalOptions);
// sigma range [15, 145]
if (rate > 90 && sigma < 145) {
sigma += 5;
emit SigmaUpdate(sigma, rate);
} else if (rate < 50 && sigma > 15) {
sigma -= 5;
emit SigmaUpdate(sigma, rate);
}
}
// clear metrics
_sigmaTotalOptions = 0;
_sigmaSoldOptions = 0;
// rebuild sold/total metrics
for (uint i = 0;i< _options.length;i++) {
// sum all issued options and sold options
uint supply = _options[i].totalSupply();
uint sold = supply.sub(_options[i].balanceOf(address(this)));
// sigma: set current metrics
_sigmaTotalOptions = _sigmaTotalOptions.add(supply);
_sigmaSoldOptions = _sigmaSoldOptions.add(sold);
}
// set next update time to one hour later
_nextSigmaUpdate = block.timestamp + 3600;
}
/**
* @notice adjust sigma manually
*/
function adjustSigma(uint64 newSigma) external override onlyOwner {
require (newSigma % 5 == 0, "sigma needs 5*N");
require (newSigma >= 15 && newSigma <= 145, "sigma not in range [15,145]");
sigma = newSigma;
emit SigmaSet(sigma);
}
/**
* @notice poolers claim premium USDTs;
*/
function claimPremium() external override whenPoolerNotPaused {
// settle un-distributed premiums in rounds to _premiumBalance;
_settlePremium(msg.sender);
// send USDTs premium back to senders's address
uint amountUSDTPremium = _premiumBalance[msg.sender];
_premiumBalance[msg.sender] = 0; // zero premium blance
// extra check the amount is not 0;
if (amountUSDTPremium > 0) {
USDTContract.safeTransfer(msg.sender, amountUSDTPremium);
}
}
/**
* @notice settle premium in rounds while pooler token tranfsers.
*/
function settlePremiumByPoolerToken(address account) external override onlyPoolerTokenContract returns(bool) {
return _settlePremium(account);
}
/**
* @dev settle option contract
*/
function _settleOption(IOption option, uint settlePrice) internal {
uint totalSupply = option.totalSupply();
uint strikePrice = option.strikePrice();
// ignore 0 supply && 0 strikePrice option
if (totalSupply == 0 || strikePrice == 0) {
return;
}
// count total sold options
uint totalOptionSold = totalSupply.sub(option.balanceOf(address(this)));
// calculate total gain
uint totalProfits = _calcProfits(settlePrice, strikePrice, totalOptionSold);
// substract ethers from collateral
// buyer's gain is pooler's loss
collateral = collateral.sub(totalProfits);
// settle preimum share
uint premiumShare;
if (poolerTokenContract.totalSupply() > 0) {
premiumShare = option.totalPremiums()
.mul(1e18) // mul share with 1e18 to prevent from underflow
.div(poolerTokenContract.totalSupply());
// set premium share to round for pooler
option.setRoundPremiumShare(option.getRound(), premiumShare);
}
// log
emit SettleLog(option.name(), strikePrice, settlePrice, totalProfits, totalOptionSold, premiumShare);
}
/**
* @notice settle premium in rounds to _premiumBalance,
* settle premium happens before any token exchange such as ERC20-transfer,mint,burn,
* and manually claimPremium;
*
* @return false means the rounds has terminated due to gas limit
*/
function _settlePremium(address account) internal returns(bool) {
uint accountCollateral = poolerTokenContract.balanceOf(account);
// at any time we find a pooler with 0 collateral, we can mark the previous rounds settled
// to avoid meaningless round loops below.
if (accountCollateral == 0) {
for (uint i = 0; i < _options.length; i++) {
if (_options[i].getRound() > 0) {
// all settled rounds before current round marked settled, which also means
// new collateral will make money immediately at current round.
_options[i].setSettledPremiumRound(_options[i].getRound() - 1, account);
}
}
return true;
}
// at this stage, the account has collaterals
uint roundsCounter;
for (uint i = 0; i < _options.length; i++) {
// shift premium from settled rounds with rounds control
uint maxRound = _options[i].getRound();
for (uint r = _options[i].getSettledPremiumRound(account) + 1; r < maxRound; r++) {
uint roundPremium = _options[i].getRoundPremiumShare(r)
.mul(accountCollateral)
.div(1e18); // remember to div by 1e18
// shift un-distributed premiums to _premiumBalance
_premiumBalance[account] = _premiumBalance[account].add(roundPremium);
// mark this round premium claimed
_options[i].setSettledPremiumRound(r, account);
// @dev BLOCK GAS LIMIT PROBLEM
// poolers needs to submit multiple transactions to claim ALL premiums in all rounds
// due to gas limit.
roundsCounter++;
if (roundsCounter >= roundLimit) {
return false;
}
}
}
return true;
}
/**
* @notice net-withdraw amount;
*/
function NWA() public view override returns (uint) {
// get minimum collateral
uint minCollateral = _totalPledged() * 100 / maxUtilizationRate;
if (minCollateral > collateral) {
return 0;
}
// net withdrawable amount
return collateral.sub(minCollateral);
}
/**
* @notice poolers sum premium USDTs;
*/
function checkPremium(address account) external override view returns(uint256) {
uint accountCollateral = poolerTokenContract.balanceOf(account);
// if the account has 0 value pooled
if (accountCollateral == 0) {
return 0;
}
uint premium;
for (uint i = 0; i < _options.length; i++) {
uint maxRound = _options[i].getRound();
for (uint r = _options[i].getSettledPremiumRound(account) + 1; r < maxRound; r++) {
uint roundPremium = _options[i].getRoundPremiumShare(r)
.mul(accountCollateral)
.div(1e18); // remember to div by 1e18
premium = premium.add(roundPremium);
}
}
// add un-distributed premium with _premiumBalance
return premium + _premiumBalance[account];
}
/**
* @notice buyers claim all option profits
*/
function claimProfits() external override whenBuyerNotPaused {
uint roundsCounter;
uint accountProfits;
// sum all profits from all options
for (uint i = 0; i < _options.length; i++) {
// sum all profits from all un-claimed rounds
uint r = _options[i].popUnclaimedProfitsRound(msg.sender);
while (r!= 0) {
uint settlePrice = _options[i].getRoundSettlePrice(r);
uint strikePrice = _options[i].getRoundStrikePrice(r);
uint optionAmount = _options[i].getRoundBalanceOf(r, msg.sender);
// accumulate gain in rounds
accountProfits = accountProfits.add(_calcProfits(settlePrice, strikePrice, optionAmount));
// @dev break for BLOCK GAS LIMIT
// poolers needs to submit multiple transactions to claim profits in all rounds.
roundsCounter++;
if (roundsCounter >= roundLimit) {
break;
}
// pop next round
r = _options[i].popUnclaimedProfitsRound(msg.sender);
}
}
// extra check the amount is not 0;
if (accountProfits > 0) {
_sendProfits(msg.sender, accountProfits);
}
}
/**
* @notice check claimable buyer's profits
*/
function checkProfits(address account) external override view returns (uint256 profits) {
// sum all profits from all options
for (uint i = 0; i < _options.length; i++) {
uint optionProfits = checkOptionProfits(_options[i], account);
profits = profits.add(optionProfits);
}
return profits;
}
/**
* @notice check profits in an option
*/
function checkOptionProfits(IOption option, address account) internal view returns (uint256 amount) {
// sum all profits from all un-claimed rounds
uint [] memory rounds = option.getUnclaimedProfitsRounds(msg.sender);
for (uint i=0;i<rounds.length;i++) {
uint settlePrice = option.getRoundSettlePrice(rounds[i]);
uint strikePrice = option.getRoundStrikePrice(rounds[i]);
uint optionAmount = option.getRoundBalanceOf(rounds[i], account);
// accumulate gain in rounds
amount = amount.add(_calcProfits(settlePrice, strikePrice, optionAmount));
}
return amount;
}
/**
* @notice set new option contract to option pool with different duration
*/
function setOption(IOption option) external override onlyOwner {
require(_options.length <= _numOptions, "options exceeded");
require(option.getDuration() > 0, "duration is 0");
require(option.totalSupply() == 0, "totalSupply != 0");
require(option.getPool() == address(this), "owner mismatch");
// the duration must be in the set
bool durationValid;
for (uint i=0;i<cdfDataContract.numDurations();i++) {
if (option.getDuration() == cdfDataContract.Durations(i)) {
durationValid = true;
break;
}
}
require (durationValid, "duration invalid");
// the option must not be set more than once
for (uint i = 0;i< _options.length;i++) {
require(_options[i] != option, "duplicated");
}
_options.push(option);
}
/**
* @notice set pooler token once
*/
function setPoolerToken(IPoolerToken poolerToken) external override onlyOwner {
require (!poolerTokenOnce, "already set");
require(poolerToken.getPool() == address(this), "owner mismatch");
poolerTokenContract = poolerToken;
poolerTokenOnce = true;
}
/**
* @notice set utilization rate by owner
*/
function setUtilizationRate(uint rate) external override onlyOwner {
require(rate >=0 && rate <= 100, "rate[0,100]");
utilizationRate = rate;
}
/**
* @notice set max utilization rate by owner
*/
function setMaxUtilizationRate(uint maxrate) external override onlyOwner {
require(maxrate >=0 && maxrate <= 100, "rate[0,100]");
require(maxrate > utilizationRate, "less than rate");
maxUtilizationRate = maxrate;
}
/**
* @dev set round limit to avoid gas exceedes block gasLimit
*/
function setRoundLimit(uint limit) external override onlyOwner {
require(roundLimit > 0, "roundLimit 0");
roundLimit = limit;
}
/**
* @dev get the price of ETH from uniswap
*/
function getEtherPrice() public view returns(uint) {
address[] memory addrs = new address[](2);
addrs[0] = address(USDTContract);
addrs[1] = uniswapRouter.WETH.address;
uint[] memory amounts = uniswapRouter.getAmountsIn((1 ether), addrs);
return amounts[0];
}
}
| 18,459 |
12 | // Minimum number of days that a border can be removed for | uint256 public minDaysToRemove = 1;
| uint256 public minDaysToRemove = 1;
| 16,958 |
41 | // uint256 public constant rate = 1000; |
uint256 public constant soldPercent = 60;
uint256 public constant partnersPercent = 5;
uint256 public constant companyPercent = 35;
uint256 public constant softcap = 2000 * 1 ether;
uint256 public constant presalecap = 2500 * 1 ether;
uint256 public constant hardcap = 10000 * 1 ether;
uint256 public constant startPresale = 1532304000; // 2018-07-23 00:00
|
uint256 public constant soldPercent = 60;
uint256 public constant partnersPercent = 5;
uint256 public constant companyPercent = 35;
uint256 public constant softcap = 2000 * 1 ether;
uint256 public constant presalecap = 2500 * 1 ether;
uint256 public constant hardcap = 10000 * 1 ether;
uint256 public constant startPresale = 1532304000; // 2018-07-23 00:00
| 49,860 |
45 | // Settle outstanding bad debt | settleDebt();
| settleDebt();
| 28,352 |
7 | // Get total net token value. / | function getNetTokenValueOf(address _targetToken, uint256 _amount)
public
view
returns (uint256 netTokenValue)
| function getNetTokenValueOf(address _targetToken, uint256 _amount)
public
view
returns (uint256 netTokenValue)
| 185 |
65 | // checks if crowdsale target is reached | function targetReached() internal view returns (bool) {
return (tokensSold >= crowdsaleTarget);
}
| function targetReached() internal view returns (bool) {
return (tokensSold >= crowdsaleTarget);
}
| 14,584 |
24 | // Returns the number of timestamps/reports for a specific data ID _id is ID of the specific data feedreturn uint256 of the number of the timestamps/reports for the inputted data ID / | function getTimestampCountById(bytes32 _id) external view returns(uint256){
return reports[_id].timestamps.length;
}
| function getTimestampCountById(bytes32 _id) external view returns(uint256){
return reports[_id].timestamps.length;
}
| 23,806 |
211 | // Transfers ownership of the contract to a new account (`newOwner`).Can only be called by the current owner. / | function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
| function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
| 219 |
55 | // Burns `_amount` tokens from `_owner`/_owner The address that will lose the tokens/_amount The quantity of tokens to burn/ return True if the tokens are burned correctly | function burn(address _owner, uint _amount) external onlyOwner returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
emit Transfer(_owner, address(0), _amount);
return true;
}
| function burn(address _owner, uint _amount) external onlyOwner returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
emit Transfer(_owner, address(0), _amount);
return true;
}
| 11,392 |
18 | // Transfer the total number of tokens from grantor into the account's holdings. | _transfer(grantor, beneficiary, totalAmount);
| _transfer(grantor, beneficiary, totalAmount);
| 52,954 |
0 | // this recreates the message that was signed on the client | bytes32 message = prefixed(keccak256(abi.encodePacked(msg.sender, amount, nonce, this)));
require(recoverSigner(message, signature) == owner, string(abi.encodePacked('signature do not match, message',message,' and signature is ',signature,'this',this)));
payable(msg.sender).transfer(amount);
| bytes32 message = prefixed(keccak256(abi.encodePacked(msg.sender, amount, nonce, this)));
require(recoverSigner(message, signature) == owner, string(abi.encodePacked('signature do not match, message',message,' and signature is ',signature,'this',this)));
payable(msg.sender).transfer(amount);
| 25,989 |
17 | // Map the challengeId to the challenge string, which is the address of the owner | challenges[challengeId] = toAsciiString(owner);
| challenges[challengeId] = toAsciiString(owner);
| 5,795 |
3 | // Check that the execution is not being performed through a delegate call. This allows a function to becallable on the implementing contract but not through proxies. / | modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
| modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
| 2,080 |
100 | // Used internally, mostly by children implementations, see sync()Updates smart contract state (`yieldRewardsPerToken`, `lastYieldDistribution`) / | function _sync() internal virtual {
// check bound conditions and if these are not met -
// exit silently, without emitting an event
if (lastYieldDistribution >= endBlock) {
return;
}
if (blockNumber() <= lastYieldDistribution) {
return;
}
// if locking weight is zero - update only `lastYieldDistribution` and exit
if (usersLockingAmount == 0) {
lastYieldDistribution = blockNumber();
return;
}
// to calculate the reward we need to know how many blocks passed, and reward per block
uint256 currentBlock = blockNumber() > endBlock ? endBlock : blockNumber();
uint256 blocksPassed = currentBlock - lastYieldDistribution;
// calculate the reward
uint256 highReward = blocksPassed * highPerBlock;
// update rewards per weight and `lastYieldDistribution`
yieldRewardsPerToken += rewardToToken(highReward, usersLockingAmount);
lastYieldDistribution = currentBlock;
// emit an event
emit Synchronized(msg.sender, yieldRewardsPerToken, lastYieldDistribution);
}
| function _sync() internal virtual {
// check bound conditions and if these are not met -
// exit silently, without emitting an event
if (lastYieldDistribution >= endBlock) {
return;
}
if (blockNumber() <= lastYieldDistribution) {
return;
}
// if locking weight is zero - update only `lastYieldDistribution` and exit
if (usersLockingAmount == 0) {
lastYieldDistribution = blockNumber();
return;
}
// to calculate the reward we need to know how many blocks passed, and reward per block
uint256 currentBlock = blockNumber() > endBlock ? endBlock : blockNumber();
uint256 blocksPassed = currentBlock - lastYieldDistribution;
// calculate the reward
uint256 highReward = blocksPassed * highPerBlock;
// update rewards per weight and `lastYieldDistribution`
yieldRewardsPerToken += rewardToToken(highReward, usersLockingAmount);
lastYieldDistribution = currentBlock;
// emit an event
emit Synchronized(msg.sender, yieldRewardsPerToken, lastYieldDistribution);
}
| 46,966 |
41 | // Get current count of minted tokens/ return Returns number | function tokenCount() external view virtual returns (uint256) {
return _tokenIds.current();
}
| function tokenCount() external view virtual returns (uint256) {
return _tokenIds.current();
}
| 27,578 |
404 | // amount user is asking to withdraw after a that period expires | uint112 thawing;
| uint112 thawing;
| 82,819 |
225 | // tokenInfo | struct TokenInfo {
Character character;
string cid;
string tag;
mapping(string => string) attrs;
}
| struct TokenInfo {
Character character;
string cid;
string tag;
mapping(string => string) attrs;
}
| 31,056 |
59 | // as a sanity check, make sure it has the function and there is no error otherwise could brick governance | Incentivizer(incentivizer).getPriorVotes(guardian, block.number - 1);
require(msg.sender == address(timelock), "GovernorAlpha::!timelock");
incentivizers.push(incentivizer);
| Incentivizer(incentivizer).getPriorVotes(guardian, block.number - 1);
require(msg.sender == address(timelock), "GovernorAlpha::!timelock");
incentivizers.push(incentivizer);
| 66,668 |
266 | // --------------------------------------------------------------------------------- | uint index = indices[j][--i];
PriceSheet memory sheet = pair.sheets[index];
| uint index = indices[j][--i];
PriceSheet memory sheet = pair.sheets[index];
| 30,543 |
27 | // Emitted when someone other than the owner is trying to call an only owner function. | error OnlyOwner();
event OperatorFilterRegistryAddressUpdated(address newRegistry);
IOperatorFilterRegistry public operatorFilterRegistry;
| error OnlyOwner();
event OperatorFilterRegistryAddressUpdated(address newRegistry);
IOperatorFilterRegistry public operatorFilterRegistry;
| 24,558 |
53 | // expecting fixed length proofs | if (_proof.length != PROOF_LEN)
revert("invalid proof length");
| if (_proof.length != PROOF_LEN)
revert("invalid proof length");
| 20,869 |
2 | // Restricts a function so it can only be executed through governance proposals. For example, governanceparameter setters in {GovernorSettings} are protected using this modifier. The governance executing address may be different from the Governor's own address, for example it could be atimelock. This can be customized by modules by overriding {_executor}. The executor is only able to invoke thesefunctions during the execution of the governor's {execute} function, and not under any other circumstances. Thus,for example, additional timelock proposers are not able to change governance parameters without going through thegovernance protocol (since v4.6). / | modifier onlyGovernance() {
require(_msgSender() == _executor(), "Governor: onlyGovernance");
if (_executor() != address(this)) {
bytes32 msgDataHash = keccak256(_msgData());
| modifier onlyGovernance() {
require(_msgSender() == _executor(), "Governor: onlyGovernance");
if (_executor() != address(this)) {
bytes32 msgDataHash = keccak256(_msgData());
| 6,524 |
25 | // If this matrix position is empty, set the value to the generated random number. | value = random;
| value = random;
| 2,625 |
166 | // Get order info, fillable amount, and signature validity for an RFQ order./Fillable amount is determined using balances and allowances of the maker./order The RFQ order./signature The order signature./ return orderInfo Info about the order./ return actualFillableTakerTokenAmount How much of the order is fillable/ based on maker funds, in taker tokens./ return isSignatureValid Whether the signature is valid. | function getRfqOrderRelevantState(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature
)
external
view
returns (
LibNativeOrder.OrderInfo memory orderInfo,
uint128 actualFillableTakerTokenAmount,
bool isSignatureValid
| function getRfqOrderRelevantState(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature
)
external
view
returns (
LibNativeOrder.OrderInfo memory orderInfo,
uint128 actualFillableTakerTokenAmount,
bool isSignatureValid
| 70,864 |
71 | // Max transaction amount, only applied in limited mode | uint256 public maxTransferAmount;
| uint256 public maxTransferAmount;
| 31,798 |
15 | // Add _privilleged_operators | function addOperator(address operator) public {
require(msg.sender == owner, "Only contract creator is allowed to do this.");
_privilleged_operators[operator] = true;
emit OperatorCh(operator, true);
}
| function addOperator(address operator) public {
require(msg.sender == owner, "Only contract creator is allowed to do this.");
_privilleged_operators[operator] = true;
emit OperatorCh(operator, true);
}
| 44,470 |
214 | // wallet => whitelisted_addr => effective_since | mapping(address => mapping(address => uint)) public effectiveTimeMap;
event Whitelisted(
address wallet,
address addr,
bool whitelisted,
uint effectiveTime
);
event DappWhitelisted(
| mapping(address => mapping(address => uint)) public effectiveTimeMap;
event Whitelisted(
address wallet,
address addr,
bool whitelisted,
uint effectiveTime
);
event DappWhitelisted(
| 48,239 |
75 | // Fallback function to receive funds for the execution of transactions. / | function () public payable {}
/** @dev Gets the sum of contract funds that are used for the execution of transactions.
* @return Contract balance without reserved ETH.
*/
function getExpendableFunds() public view returns (uint) {
return address(this).balance.subCap(reservedETH);
}
| function () public payable {}
/** @dev Gets the sum of contract funds that are used for the execution of transactions.
* @return Contract balance without reserved ETH.
*/
function getExpendableFunds() public view returns (uint) {
return address(this).balance.subCap(reservedETH);
}
| 42,891 |
287 | // The amount of blocks the cooldown period takes | uint40 unstakeCooldown;
| uint40 unstakeCooldown;
| 47,973 |
26 | // Donate to Category | function donate(
string memory category,
address token,
uint256 amount
| function donate(
string memory category,
address token,
uint256 amount
| 25,860 |
133 | // Whitelist OpenSea proxy contract for easy trading. | ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
| ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
| 50,046 |
193 | // Deletes the token with the provided ID. _tokenId uint256 ID of the token. / | function deleteToken(uint256 _tokenId) external onlyTokenOwner(_tokenId) {
_burn(msg.sender, _tokenId);
}
| function deleteToken(uint256 _tokenId) external onlyTokenOwner(_tokenId) {
_burn(msg.sender, _tokenId);
}
| 2,510 |
89 | // Fire an event to tell the world of the newly staked tokens | emit Stake(_user, _value);
return true;
| emit Stake(_user, _value);
return true;
| 32,603 |
14 | // Variable used to keep track of the level count. |
uint levels = 0;
|
uint levels = 0;
| 13,884 |
279 | // The ending heldToken balance of the vault should be the starting heldToken balance minus the available heldToken amount | assert(
MarginCommon.getPositionBalanceImpl(state, transaction.positionId)
== transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken)
);
return payout;
| assert(
MarginCommon.getPositionBalanceImpl(state, transaction.positionId)
== transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken)
);
return payout;
| 5,720 |
156 | // Returns the win percent when going high on the given number | function getHighWinPercent(uint number) public pure returns (uint) {
require(number >= 1 && number < NUM_DICE_SIDES);
if (number == 1) {
return 100;
} else if (number == 2) {
return 110;
} else if (number == 3) {
return 120;
} else if (number == 4) {
return 130;
} else if (number == 5) {
return 140;
} else if (number == 6) {
return 150;
} else if (number == 7) {
return 180;
} else if (number == 8) {
return 200;
} else if (number == 9) {
return 300;
} else if (number == 10) {
return 300;
} else if (number == 11) {
return 500;
} else if (number == 12) {
return 1200;
}
}
| function getHighWinPercent(uint number) public pure returns (uint) {
require(number >= 1 && number < NUM_DICE_SIDES);
if (number == 1) {
return 100;
} else if (number == 2) {
return 110;
} else if (number == 3) {
return 120;
} else if (number == 4) {
return 130;
} else if (number == 5) {
return 140;
} else if (number == 6) {
return 150;
} else if (number == 7) {
return 180;
} else if (number == 8) {
return 200;
} else if (number == 9) {
return 300;
} else if (number == 10) {
return 300;
} else if (number == 11) {
return 500;
} else if (number == 12) {
return 1200;
}
}
| 20,275 |
23 | // get proposal info proposal id / | function getProposalInfo(uint256 proposalId)
public
view
returns (
address resourceId,
address proposer,
uint8 proposalType,
uint256 blockNumberInterval,
uint8 status,
address[] memory agreeVoters,
| function getProposalInfo(uint256 proposalId)
public
view
returns (
address resourceId,
address proposer,
uint8 proposalType,
uint256 blockNumberInterval,
uint8 status,
address[] memory agreeVoters,
| 37,196 |
13 | // Swap WETH for Hog | pair.swap(amount0Out, amount1Out, bar, new bytes(0));
| pair.swap(amount0Out, amount1Out, bar, new bytes(0));
| 43,875 |
658 | // Takes a portfolio state and writes it to storage./This method should only be called directly by the nToken. Account updates to portfolios should happen via/ the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library./ return updated variables to update the account context with/ hasDebt: whether or not the portfolio has negative fCash assets/ portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio/ uint8: the length of the storage array/ uint40: the new nextSettleTime for the portfolio | function storeAssets(PortfolioState memory portfolioState, address account)
internal
returns (
bool,
bytes32,
uint8,
uint40
)
| function storeAssets(PortfolioState memory portfolioState, address account)
internal
returns (
bool,
bytes32,
uint8,
uint40
)
| 11,066 |
11 | // Multisig smart contract address to which funds will be sent | address payable public wallet = 0x1eFD3738e4Cb360ea0FB5FA6aB0cd49BBba516e2;
address public owner;
| address payable public wallet = 0x1eFD3738e4Cb360ea0FB5FA6aB0cd49BBba516e2;
address public owner;
| 13,874 |
13 | // Allow only ScalingFunds agents to call the modified function / | modifier onlyScalingFundsAgent {
require(
super.hasRole(SCALINGFUNDS_AGENT, msg.sender),
"Caller does not have SCALINGFUNDS_AGENT role"
);
_;
}
| modifier onlyScalingFundsAgent {
require(
super.hasRole(SCALINGFUNDS_AGENT, msg.sender),
"Caller does not have SCALINGFUNDS_AGENT role"
);
_;
}
| 9,699 |
693 | // Pause Router liquidation enabled states | bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01;
bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02;
bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04;
bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08;
| bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01;
bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02;
bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04;
bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08;
| 65,134 |
100 | // This function changes the freezing period of account which was currently in locking state. | function _changeFreezeBlock(address account, uint256 _block) external onlyOwner() {
_boughtBlock[account] = _block;
blacklisted[account]=0;
}
| function _changeFreezeBlock(address account, uint256 _block) external onlyOwner() {
_boughtBlock[account] = _block;
blacklisted[account]=0;
}
| 28,527 |
14 | // Removes a value from a set. O(1). Returns true if the value was removed from the set, that is if it waspresent. / | function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
| function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
| 7,583 |
151 | // Allows to set the last withdrawn validator id./_validatorId validator id. | function setLastWithdrawnValidatorId(uint256 _validatorId) external;
| function setLastWithdrawnValidatorId(uint256 _validatorId) external;
| 50,181 |
0 | // ++++++++++++ External functions ++++++++++++++++++++++ | function addReporter(address account) external onlyOwner {
_requireAccountNotReporter(account);
reporters[account] = true;
emit ReporterAdded(account);
}
| function addReporter(address account) external onlyOwner {
_requireAccountNotReporter(account);
reporters[account] = true;
emit ReporterAdded(account);
}
| 25,198 |
15 | // a divided by b | function div(uint a, uint b) internal pure returns (uint c) {
assert(b != 0);
c = a / b;
}
| function div(uint a, uint b) internal pure returns (uint c) {
assert(b != 0);
c = a / b;
}
| 49,747 |
298 | // lock 95% of reward if it comes from bonus time | function _harvest(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
uint256 pending =
user.amount.mul(pool.accGovTokenPerShare).div(1e12).sub(
user.rewardDebt
);
uint256 masterBal = govToken.balanceOf(address(this));
if (pending > masterBal) {
pending = masterBal;
}
if (pending > 0) {
govToken.transfer(msg.sender, pending);
uint256 lockAmount = 0;
if (user.rewardDebtAtBlock <= FINISH_BONUS_AT_BLOCK) {
lockAmount = pending.mul(PERCENT_LOCK_BONUS_REWARD).div(
100
);
govToken.lock(msg.sender, lockAmount);
}
user.rewardDebtAtBlock = block.number;
emit SendHokkFiTokenReward(msg.sender, _pid, pending, lockAmount);
}
user.rewardDebt = user.amount.mul(pool.accGovTokenPerShare).div(1e12);
if (_pid == 0) {
IStaking(stakingContract).claimRewards(msg.sender, msg.sender, user.amount);
}
}
}
| function _harvest(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
uint256 pending =
user.amount.mul(pool.accGovTokenPerShare).div(1e12).sub(
user.rewardDebt
);
uint256 masterBal = govToken.balanceOf(address(this));
if (pending > masterBal) {
pending = masterBal;
}
if (pending > 0) {
govToken.transfer(msg.sender, pending);
uint256 lockAmount = 0;
if (user.rewardDebtAtBlock <= FINISH_BONUS_AT_BLOCK) {
lockAmount = pending.mul(PERCENT_LOCK_BONUS_REWARD).div(
100
);
govToken.lock(msg.sender, lockAmount);
}
user.rewardDebtAtBlock = block.number;
emit SendHokkFiTokenReward(msg.sender, _pid, pending, lockAmount);
}
user.rewardDebt = user.amount.mul(pool.accGovTokenPerShare).div(1e12);
if (_pid == 0) {
IStaking(stakingContract).claimRewards(msg.sender, msg.sender, user.amount);
}
}
}
| 50,653 |
93 | // Replace list | s_authorizedSenderList = senders;
emit AuthorizedSendersChanged(senders, msg.sender);
| s_authorizedSenderList = senders;
emit AuthorizedSendersChanged(senders, msg.sender);
| 31,039 |
1,062 | // Deploys a new `DesignatedVoting` contract. ownerAddress defines who will own the deployed instance of the designatedVoting contract.return designatedVoting a new DesignatedVoting contract. / | function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) {
require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted");
DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender);
designatedVotingContracts[msg.sender] = designatedVoting;
return designatedVoting;
}
| function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) {
require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted");
DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender);
designatedVotingContracts[msg.sender] = designatedVoting;
return designatedVoting;
}
| 30,496 |
240 | // An upper limit on maxSupply, necessary for maintaining ERC20Votes compatibility | uint256 public constant MAX_ALLOWABLE_SUPPLY = 2**224 - 1;
| uint256 public constant MAX_ALLOWABLE_SUPPLY = 2**224 - 1;
| 78,497 |
985 | // The Governor is sent all tokens | _mint(msg.sender, 100000000 ether); // 100,000,000 GDAI
| _mint(msg.sender, 100000000 ether); // 100,000,000 GDAI
| 84,796 |
46 | // Creates `tAmount` tokens and assigns them to `account`, increasingthe total supply. | * Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - the caller must have minter role.
*/
function mint(address account, uint256 amountIn) public onlyRole(MINTER_ROLE) {
// Indicates if rate should be deducted from burn
bool isRated = true;
// If account belongs to _isExcludedFromRate account then remove the rate
if (_isExcludedFromRate[_msgSender()] || _isExcludedFromRate[account]) {
isRated = false;
}
_mint(account, amountIn);
}
| * Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - the caller must have minter role.
*/
function mint(address account, uint256 amountIn) public onlyRole(MINTER_ROLE) {
// Indicates if rate should be deducted from burn
bool isRated = true;
// If account belongs to _isExcludedFromRate account then remove the rate
if (_isExcludedFromRate[_msgSender()] || _isExcludedFromRate[account]) {
isRated = false;
}
_mint(account, amountIn);
}
| 30,810 |
48 | // If Chainlink is live and Tellor is working, compare prices. Switch to Chainlink if prices are within 5%, and return Chainlink price. | if (_bothOraclesSimilarPrice(chainlinkResponse, tellorResponse)) {
_changeStatus(Status.chainlinkWorking);
return _storeChainlinkPrice(chainlinkResponse);
}
| if (_bothOraclesSimilarPrice(chainlinkResponse, tellorResponse)) {
_changeStatus(Status.chainlinkWorking);
return _storeChainlinkPrice(chainlinkResponse);
}
| 4,350 |
184 | // Remove the currentRequestId/onDeckRequestId from the requestQ array containing the rest of the 50 requests | self.requestQ[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0;
| self.requestQ[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0;
| 15,417 |
17 | // Encodes rebalance stable borrow rate parameters from standard input to compact representation of 1 bytes32 asset The address of the underlying asset borrowed user The address of the user to be rebalancedreturn compact representation of rebalance stable borrow rate parameters / | function encodeRebalanceStableBorrowRate(
address asset,
address user
| function encodeRebalanceStableBorrowRate(
address asset,
address user
| 18,638 |
92 | // Removes `memberToRemove` from the shared role, `roleId`. Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of themanaging role for `roleId`. roleId the SharedRole membership to modify. memberToRemove the current SharedRole member to remove. / | function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
| function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
| 6,611 |
104 | // ExecutionLib Contains the logic for executing a scheduled transaction. / | library ExecutionLib {
struct ExecutionData {
address toAddress; /// The destination of the transaction.
bytes callData; /// The bytecode that will be sent with the transaction.
uint callValue; /// The wei value that will be sent with the transaction.
uint callGas; /// The amount of gas to be sent with the transaction.
uint gasPrice; /// The gasPrice that should be set for the transaction.
}
/**
* @dev Send the transaction according to the parameters outlined in ExecutionData.
* @param self The ExecutionData object.
*/
function sendTransaction(ExecutionData storage self)
internal returns (bool)
{
/// Should never actually reach this require check, but here in case.
require(self.gasPrice <= tx.gasprice);
/* solium-disable security/no-call-value */
return self.toAddress.call.value(self.callValue).gas(self.callGas)(self.callData);
}
/**
* Returns the maximum possible gas consumption that a transaction request
* may consume. The EXTRA_GAS value represents the overhead involved in
* request execution.
*/
function CALL_GAS_CEILING(uint EXTRA_GAS)
internal view returns (uint)
{
return block.gaslimit - EXTRA_GAS;
}
/*
* @dev Validation: ensure that the callGas is not above the total possible gas
* for a call.
*/
function validateCallGas(uint callGas, uint EXTRA_GAS)
internal view returns (bool)
{
return callGas < CALL_GAS_CEILING(EXTRA_GAS);
}
/*
* @dev Validation: ensure that the toAddress is not set to the empty address.
*/
function validateToAddress(address toAddress)
internal pure returns (bool)
{
return toAddress != 0x0;
}
}
| library ExecutionLib {
struct ExecutionData {
address toAddress; /// The destination of the transaction.
bytes callData; /// The bytecode that will be sent with the transaction.
uint callValue; /// The wei value that will be sent with the transaction.
uint callGas; /// The amount of gas to be sent with the transaction.
uint gasPrice; /// The gasPrice that should be set for the transaction.
}
/**
* @dev Send the transaction according to the parameters outlined in ExecutionData.
* @param self The ExecutionData object.
*/
function sendTransaction(ExecutionData storage self)
internal returns (bool)
{
/// Should never actually reach this require check, but here in case.
require(self.gasPrice <= tx.gasprice);
/* solium-disable security/no-call-value */
return self.toAddress.call.value(self.callValue).gas(self.callGas)(self.callData);
}
/**
* Returns the maximum possible gas consumption that a transaction request
* may consume. The EXTRA_GAS value represents the overhead involved in
* request execution.
*/
function CALL_GAS_CEILING(uint EXTRA_GAS)
internal view returns (uint)
{
return block.gaslimit - EXTRA_GAS;
}
/*
* @dev Validation: ensure that the callGas is not above the total possible gas
* for a call.
*/
function validateCallGas(uint callGas, uint EXTRA_GAS)
internal view returns (bool)
{
return callGas < CALL_GAS_CEILING(EXTRA_GAS);
}
/*
* @dev Validation: ensure that the toAddress is not set to the empty address.
*/
function validateToAddress(address toAddress)
internal pure returns (bool)
{
return toAddress != 0x0;
}
}
| 15,981 |
73 | // Push '0' to the end of the 4 bytes just pushed - this will be the length of the STORES action | mstore(add(0x24, add(ptr, mload(ptr))), 0)
| mstore(add(0x24, add(ptr, mload(ptr))), 0)
| 60,705 |
29 | // Emit an event inidicating a new validator has been registered, allowing for offchain listeners to track the validator registry | emit NewValidator(data.operator, data.pubkey, data.withdrawal_credentials, data.signature, data.deposit_data_root);
unchecked {
++i;
}
| emit NewValidator(data.operator, data.pubkey, data.withdrawal_credentials, data.signature, data.deposit_data_root);
unchecked {
++i;
}
| 44,864 |
7 | // Define an internal function '_addConsumer' to add this role, called by 'addConsumer' | function _addCustomer(address account) internal {
grantRole(CUSTOMER_ROLE, account);
}
| function _addCustomer(address account) internal {
grantRole(CUSTOMER_ROLE, account);
}
| 5,198 |
13 | // Finally update ticket total | raffleTicketsBought += amount;
| raffleTicketsBought += amount;
| 31,240 |
104 | // Update the promoter pledged balance [SmAC contracts calls only]. | function updatePledged(address promoter, uint256 amount) external returns(bool);
| function updatePledged(address promoter, uint256 amount) external returns(bool);
| 27,983 |
46 | // allows the owner to send vested tokens to participants/self Stored vesting from vesting contract/token the token contract that is being withdrawn/_beneficiary registered address to send the tokens to | function sendTokens(VestingStorage storage self,CrowdsaleToken token, address _beneficiary) public returns (bool) {
require(now > self.startTime);
require(msg.sender == self.owner);
require(self.isToken);
bool ok;
bool err;
uint256 _withdrawAmount;
if((now < self.endTime) && (self.holdingAmount[_beneficiary][1] > 0)){
// if there is a bonus and it's before the endTime, cancel the bonus
_withdrawAmount = calculateWithdrawal(self, _beneficiary);
uint256 _bonusAmount = self.holdingAmount[_beneficiary][1];
self.holdingAmount[msg.sender][1] = 0;
ok = token.burnToken(_bonusAmount);
} else {
if(now > self.endTime){
// if it's past the endTime then send everything left
_withdrawAmount = self.holdingAmount[_beneficiary][0] + self.holdingAmount[_beneficiary][1];
(ok, _withdrawAmount) = _withdrawAmount.minus(self.hasWithdrawn[_beneficiary]);
require(!err);
self.holdingAmount[_beneficiary][0] = 0;
self.holdingAmount[_beneficiary][1] = 0;
} else {
// if we're here then it's before the endTime and no bonus, need to calculate
_withdrawAmount = calculateWithdrawal(self, _beneficiary);
}
}
self.hasWithdrawn[_beneficiary] += _withdrawAmount;
// transfer tokens to the beneficiary
ok = token.transfer(_beneficiary, _withdrawAmount);
require(ok);
LogTokensWithdrawn(_beneficiary,_withdrawAmount);
return true;
}
| function sendTokens(VestingStorage storage self,CrowdsaleToken token, address _beneficiary) public returns (bool) {
require(now > self.startTime);
require(msg.sender == self.owner);
require(self.isToken);
bool ok;
bool err;
uint256 _withdrawAmount;
if((now < self.endTime) && (self.holdingAmount[_beneficiary][1] > 0)){
// if there is a bonus and it's before the endTime, cancel the bonus
_withdrawAmount = calculateWithdrawal(self, _beneficiary);
uint256 _bonusAmount = self.holdingAmount[_beneficiary][1];
self.holdingAmount[msg.sender][1] = 0;
ok = token.burnToken(_bonusAmount);
} else {
if(now > self.endTime){
// if it's past the endTime then send everything left
_withdrawAmount = self.holdingAmount[_beneficiary][0] + self.holdingAmount[_beneficiary][1];
(ok, _withdrawAmount) = _withdrawAmount.minus(self.hasWithdrawn[_beneficiary]);
require(!err);
self.holdingAmount[_beneficiary][0] = 0;
self.holdingAmount[_beneficiary][1] = 0;
} else {
// if we're here then it's before the endTime and no bonus, need to calculate
_withdrawAmount = calculateWithdrawal(self, _beneficiary);
}
}
self.hasWithdrawn[_beneficiary] += _withdrawAmount;
// transfer tokens to the beneficiary
ok = token.transfer(_beneficiary, _withdrawAmount);
require(ok);
LogTokensWithdrawn(_beneficiary,_withdrawAmount);
return true;
}
| 12,809 |
4 | // Limit Admires per NFT | require(
s.info[invokerId].admired !=
getMatrix() + s.info[invokerId].expand_level &&
block.timestamp < s.info[invokerId].can_admire_after,
"Max Admires Reached"
);
require(msg.sender == _ownerOf(invokerId), "No Ownership");
require(_ownerOf(invokerId) != _ownerOf(targetId), "Not Allowed");
IERC20 currency = getERC20();
require(
| require(
s.info[invokerId].admired !=
getMatrix() + s.info[invokerId].expand_level &&
block.timestamp < s.info[invokerId].can_admire_after,
"Max Admires Reached"
);
require(msg.sender == _ownerOf(invokerId), "No Ownership");
require(_ownerOf(invokerId) != _ownerOf(targetId), "Not Allowed");
IERC20 currency = getERC20();
require(
| 27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XtrINxawzMEAAUVeGi5upo7SEAcF6dxPaSzXYpBHgUlcIAZtyd1/UyNG5qCq63gHGYopjamVyZKUMow8NcCe1dUemWlgFAbtdGcytILXngauK9UYC5dJUHKBqTsLAm+NrKpXCG1WpngMpL3b8i67os1+YTADc360rf5vkPQ7rZon2nXVAAAAAASUVORK5CYII=";
| 4,014 |
6 | // define a function to renounce ownership | function renounceOwnership() public onlyOwner {
emit TransferOwnership(origOwner, address(0));
origOwner = payable(address(0));
}
| function renounceOwnership() public onlyOwner {
emit TransferOwnership(origOwner, address(0));
origOwner = payable(address(0));
}
| 2,182 |
103 | // ============ External ============ //Change base asset oracle in case current one fails or is deprecated. Only contractowner is allowed to change. _newBaseOracleAddress Address of new oracle to pull data from / | function changeBaseOracle(
IOracle _newBaseOracleAddress
)
external
timeLockUpgrade
| function changeBaseOracle(
IOracle _newBaseOracleAddress
)
external
timeLockUpgrade
| 24,139 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.