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 |
|---|---|---|---|---|
152 | // Simulate the effects of minting shares at the current block, given current on-chain conditions. shares amount of shares to mintreturn assets that will be deposited / | function previewMint(uint256 shares) public view override returns (uint256 assets) {
(uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);
assets = _previewMint(shares, _totalAssets, _totalSupply);
}
| function previewMint(uint256 shares) public view override returns (uint256 assets) {
(uint256 _totalAssets, uint256 _totalSupply) = _getTotalAssetsAndTotalSupply(true);
assets = _previewMint(shares, _totalAssets, _totalSupply);
}
| 42,299 |
24 | // it will white list multiple members | // @param _user {address[]} of users to whitelist
// @return true if successful
function addToWhiteListMultiple(address[] _users) external onlyOwner() returns (bool) {
for (uint i = 0; i < _users.length; ++i) {
if (whiteList[_users[i]] != true) {
whiteList[_users[i]] = true;
totalWhiteListed++;
}
}
LogWhiteListedMultiple(totalWhiteListed);
return true;
}
| // @param _user {address[]} of users to whitelist
// @return true if successful
function addToWhiteListMultiple(address[] _users) external onlyOwner() returns (bool) {
for (uint i = 0; i < _users.length; ++i) {
if (whiteList[_users[i]] != true) {
whiteList[_users[i]] = true;
totalWhiteListed++;
}
}
LogWhiteListedMultiple(totalWhiteListed);
return true;
}
| 15,336 |
43 | // Tracking status of wallets | mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public _isExcludedFromFee;
| mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public _isExcludedFromFee;
| 36,157 |
567 | // Cancel the liquidated LUSD debt with the LUSD in the stability pool | activePoolCached.decreaseLUSDDebt(_debtToOffset);
_decreaseLUSD(_debtToOffset);
| activePoolCached.decreaseLUSDDebt(_debtToOffset);
_decreaseLUSD(_debtToOffset);
| 68,835 |
93 | // return LSD token to the user | lsdToken.transfer(msg.sender, _veLSDAmount);
| lsdToken.transfer(msg.sender, _veLSDAmount);
| 34,524 |
39 | // Adds a new gateway rule newRule - the address describing the new rule / | function gatewayRules(address newRule) internal {
//get current index
uint16 index = gatewayRuleIndex();
index += 1;
addressStorage[keccak256(abi.encodePacked(gatewayRules1,index))] = newRule;
//increase index
uint16Storage[keccak256(treasuryRuleIndex1)] = index;
}
| function gatewayRules(address newRule) internal {
//get current index
uint16 index = gatewayRuleIndex();
index += 1;
addressStorage[keccak256(abi.encodePacked(gatewayRules1,index))] = newRule;
//increase index
uint16Storage[keccak256(treasuryRuleIndex1)] = index;
}
| 28,759 |
93 | // Transfer ZORA fee to recipient | (, uint256 zoraFee) = zoraFeeForAmount(quantity);
| (, uint256 zoraFee) = zoraFeeForAmount(quantity);
| 26,593 |
5 | // Emitted when pendingAdmin is accepted, which means admin is updated/ | event NewAdmin(address oldAdmin, address newAdmin);
| event NewAdmin(address oldAdmin, address newAdmin);
| 25,670 |
130 | // (seconds since last interaction / vesting term remaining) | uint percentVested = percentVestedFor( _recipient );
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _recipient ]; // delete user info
emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data
return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due
} else { // if unfinished
| uint percentVested = percentVestedFor( _recipient );
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _recipient ]; // delete user info
emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data
return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due
} else { // if unfinished
| 13,241 |
38 | // Calculate COMP accrued by a supplier and possibly transfer it to them cToken The market in which the supplier is interacting supplier The address of the supplier to distribute COMP to / | function distributeSupplierComp(address cToken, address supplier) internal {
CompMarketState storage supplyState = compSupplyState[cToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]});
compSupplierIndex[cToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = CToken(cToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(compAccrued[supplier], supplierDelta);
compAccrued[supplier] = supplierAccrued;
emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa);
}
| function distributeSupplierComp(address cToken, address supplier) internal {
CompMarketState storage supplyState = compSupplyState[cToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]});
compSupplierIndex[cToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = CToken(cToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(compAccrued[supplier], supplierDelta);
compAccrued[supplier] = supplierAccrued;
emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa);
}
| 7,694 |
246 | // FUNCTIONS / constructor | constructor( IxBackendIface _b
, IxPaymentsIface _pay
, EnsOwnerProxy _ensOwnerPx
, BBFarmIface _bbFarm0
, CommAuctionIface _commAuction
| constructor( IxBackendIface _b
, IxPaymentsIface _pay
, EnsOwnerProxy _ensOwnerPx
, BBFarmIface _bbFarm0
, CommAuctionIface _commAuction
| 4,111 |
2 | // Modifier to use in the initializer function of a contract./ | modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
| modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
| 29,121 |
52 | // Locks the contract for owner for the amount of time provided | function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
| function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
| 1,968 |
6 | // creates a new CommunityToken | function createNewToken(address a, string memory description) public onlyOwner
| function createNewToken(address a, string memory description) public onlyOwner
| 45,218 |
11 | // Require that there is enough Ether in the transaction | require(msg.value >= _product.price);
| require(msg.value >= _product.price);
| 36,810 |
28 | // Basic | string public name;
string public symbol;
uint8 public decimals = 0;
uint256 public totalSupply;
| string public name;
string public symbol;
uint8 public decimals = 0;
uint256 public totalSupply;
| 26,800 |
40 | // Check how many numbers match (correct number not position) | uint8 matchingNumbers = getMatchingNumbers(playerTickets[msg.sender][_lotteryId][i].numbers,
allLotteries[_lotteryId].winningNumbers);
| uint8 matchingNumbers = getMatchingNumbers(playerTickets[msg.sender][_lotteryId][i].numbers,
allLotteries[_lotteryId].winningNumbers);
| 30,042 |
18 | // swap router used to convert LOCKED into BURNABLE tokens | IUniswapV2Router02 public swapRouter;
| IUniswapV2Router02 public swapRouter;
| 42,532 |
8 | // If sender is not the owner and isTradable is false, then throw exception | if (sender != owner() && !isTradable) {
require(isTradable, "Transfers are not allowed at the moment");
}
| if (sender != owner() && !isTradable) {
require(isTradable, "Transfers are not allowed at the moment");
}
| 28,234 |
204 | // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. | return string(abi.encodePacked(baseURI,"?id=", tokenId.toString()));
| return string(abi.encodePacked(baseURI,"?id=", tokenId.toString()));
| 38,889 |
156 | // Ensure that each `to` address is a contract and is not this contract. | for (uint256 i = 0; i < calls.length; i++) {
if (calls[i].value == 0) {
_ensureValidGenericCallTarget(calls[i].to);
}
| for (uint256 i = 0; i < calls.length; i++) {
if (calls[i].value == 0) {
_ensureValidGenericCallTarget(calls[i].to);
}
| 7,915 |
66 | // return the amount of wei raised. / | function weiRaised() public view returns (uint256) {
return _weiRaised;
}
| function weiRaised() public view returns (uint256) {
return _weiRaised;
}
| 28,399 |
217 | // ------------------------------ STRUCTS ------------------------------ //Store user asset informations | struct NftRecord {
mapping(address => uint256) holdings;
address[] tokens;
address reserve;
uint256 lockTimestamp;
}
| struct NftRecord {
mapping(address => uint256) holdings;
address[] tokens;
address reserve;
uint256 lockTimestamp;
}
| 62,742 |
4 | // } else { NFTMetadata memory metadata = NFTMetadata(uri, true); _nftMetadata[nftId] = metadata; } |
address payable owner = payable(owner());
owner.transfer(msg.value);
|
address payable owner = payable(owner());
owner.transfer(msg.value);
| 22,920 |
2 | // Mint for team and marketing | _mint(operations, (maxSupply * 5) / 100); // 5%
_mint(marketmaker, (maxSupply * 10) / 100); // 10%
| _mint(operations, (maxSupply * 5) / 100); // 5%
_mint(marketmaker, (maxSupply * 10) / 100); // 10%
| 37,251 |
60 | // require that at least `amount` tokens are unlocked before transfer is possible also permit if minting tokens (coming from 0x0) / | function _beforeTokenTransfer(address from, address /*to*/, uint256 amount) internal virtual override {
require(from == address(0x0) || amount <= balanceUnlocked(from), ERROR_INSUFFICIENT_UNLOCKED);
}
| function _beforeTokenTransfer(address from, address /*to*/, uint256 amount) internal virtual override {
require(from == address(0x0) || amount <= balanceUnlocked(from), ERROR_INSUFFICIENT_UNLOCKED);
}
| 39,447 |
2 | // Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens ownedE.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC asset The address of the underlying asset to withdraw amount The underlying amount to be withdrawn- Send the value type(uint256).max in order to withdraw the whole aToken balance to The address that will receive the underlying, same as msg.sender if the userwants to receive it on his own wallet, or a different address if the beneficiary is adifferent walletreturn The final amount withdrawn / | ) external returns (uint256){
require(asset != address(0x0), "asset cannot be burn address");
ITestToken(asset).mint(to, amount);
ITestToken(aTokens[asset]).burn(msg.sender, amount);
return amount;
}
| ) external returns (uint256){
require(asset != address(0x0), "asset cannot be burn address");
ITestToken(asset).mint(to, amount);
ITestToken(aTokens[asset]).burn(msg.sender, amount);
return amount;
}
| 2,113 |
194 | // adding seperate function setupContractId since initialize is already called with old implementation | function setupContractId()
external
only(DEFAULT_ADMIN_ROLE)
| function setupContractId()
external
only(DEFAULT_ADMIN_ROLE)
| 40,955 |
37 | // Add/remove any number of addresses whose funds get reflected/reflectCuts ReflectCut[] | function reflectCut(
SLib.ReflectCut_[] calldata reflectCuts
| function reflectCut(
SLib.ReflectCut_[] calldata reflectCuts
| 2,643 |
104 | // only owner address can set minBet / | {
minBet = newMinimumBet;
}
| {
minBet = newMinimumBet;
}
| 9,793 |
67 | // Check the signature length | if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
| if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
| 594 |
219 | // How many fractional bits are there? / | uint256 constant private REAL_FBITS = 40;
| uint256 constant private REAL_FBITS = 40;
| 9,901 |
47 | // Internal function to remove a token ID from the list of a given address_from address representing the previous owner of the given token ID_tokenId uint256 ID of the token to be removed from the tokens list of the given address/ | function removeToken(address _from, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _from);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = balanceOf(_from).sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
tokenOwner[_tokenId] = 0;
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
totalTokens = totalTokens.sub(1);
}
| function removeToken(address _from, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _from);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = balanceOf(_from).sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
tokenOwner[_tokenId] = 0;
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
totalTokens = totalTokens.sub(1);
}
| 57,765 |
27 | // Base contract for Chaotic. Holds all common structs, events and base variables./cuilichen | contract BaseFight is OwnerBase {
event FighterReady(uint32 season);
// data of fighter
struct Fighter {
uint tokenID;
address hometown;
address owner;
uint16 power;
}
mapping (uint => Fighter) public soldiers; // key is (season * 1000 + index)
// time for matches
mapping (uint32 => uint64 ) public matchTime;// key is season
mapping (uint32 => uint64 ) public seedFromCOO; // key is season
mapping (uint32 => uint8 ) public finished; // key is season
//
uint32[] seasonIDs;
/// @dev get base infomation of the seasons
function getSeasonInfo(uint32[99] _seasons) view public returns (uint length,uint[99] matchTimes, uint[99] results) {
for (uint i = 0; i < _seasons.length; i++) {
uint32 _season = _seasons[i];
if(_season >0){
matchTimes[i] = matchTime[_season];
results[i] = finished[_season];
}else{
length = i;
break;
}
}
}
/// @dev check seed form coo
function checkCooSeed(uint32 _season) public view returns (uint64) {
require(finished[_season] > 0);
return seedFromCOO[_season];
}
/// @dev set a fighter for a season, prepare for combat.
function createSeason(uint32 _season, uint64 fightTime, uint64 _seedFromCOO, address[8] _home, uint[8] _tokenID, uint16[8] _power, address[8] _owner) external onlyCOO {
require(matchTime[_season] <= 0);
require(fightTime > 0);
require(_seedFromCOO > 0);
seasonIDs.push(_season);// a new season
matchTime[_season] = fightTime;
seedFromCOO[_season] = _seedFromCOO;
for (uint i = 0; i < 8; i++) {
Fighter memory soldier = Fighter({
hometown:_home[i],
owner:_owner[i],
tokenID:_tokenID[i],
power: _power[i]
});
uint key = _season * 1000 + i;
soldiers[key] = soldier;
}
//fire the event
emit FighterReady(_season);
}
/// @dev process a fight
function _localFight(uint32 _season, uint32 _seed) internal returns (uint8 winner)
{
require(finished[_season] == 0);//make sure a season just match once.
uint[] memory powers = new uint[](8);
uint sumPower = 0;
uint8 i = 0;
uint key = 0;
Fighter storage soldier = soldiers[0];
for (i = 0; i < 8; i++) {
key = _season * 1000 + i;
soldier = soldiers[key];
powers[i] = soldier.power;
sumPower = sumPower + soldier.power;
}
uint sumValue = 0;
uint tmpPower = 0;
for (i = 0; i < 8; i++) {
tmpPower = powers[i] ** 5;//
sumValue += tmpPower;
powers[i] = sumValue;
}
uint singleDeno = sumPower ** 5;
uint randomVal = _getRandom(_seed);
winner = 0;
uint shoot = sumValue * randomVal * 10000000000 / singleDeno / 0xffffffff;
for (i = 0; i < 8; i++) {
tmpPower = powers[i];
if (shoot <= tmpPower * 10000000000 / singleDeno) {
winner = i;
break;
}
}
finished[_season] = uint8(100 + winner);
return winner;
}
/// @dev give a seed and get a random value between 0 and 0xffffffff.
/// @param _seed an uint32 value from users
function _getRandom(uint32 _seed) pure internal returns(uint32) {
return uint32(keccak256(_seed));
}
}
| contract BaseFight is OwnerBase {
event FighterReady(uint32 season);
// data of fighter
struct Fighter {
uint tokenID;
address hometown;
address owner;
uint16 power;
}
mapping (uint => Fighter) public soldiers; // key is (season * 1000 + index)
// time for matches
mapping (uint32 => uint64 ) public matchTime;// key is season
mapping (uint32 => uint64 ) public seedFromCOO; // key is season
mapping (uint32 => uint8 ) public finished; // key is season
//
uint32[] seasonIDs;
/// @dev get base infomation of the seasons
function getSeasonInfo(uint32[99] _seasons) view public returns (uint length,uint[99] matchTimes, uint[99] results) {
for (uint i = 0; i < _seasons.length; i++) {
uint32 _season = _seasons[i];
if(_season >0){
matchTimes[i] = matchTime[_season];
results[i] = finished[_season];
}else{
length = i;
break;
}
}
}
/// @dev check seed form coo
function checkCooSeed(uint32 _season) public view returns (uint64) {
require(finished[_season] > 0);
return seedFromCOO[_season];
}
/// @dev set a fighter for a season, prepare for combat.
function createSeason(uint32 _season, uint64 fightTime, uint64 _seedFromCOO, address[8] _home, uint[8] _tokenID, uint16[8] _power, address[8] _owner) external onlyCOO {
require(matchTime[_season] <= 0);
require(fightTime > 0);
require(_seedFromCOO > 0);
seasonIDs.push(_season);// a new season
matchTime[_season] = fightTime;
seedFromCOO[_season] = _seedFromCOO;
for (uint i = 0; i < 8; i++) {
Fighter memory soldier = Fighter({
hometown:_home[i],
owner:_owner[i],
tokenID:_tokenID[i],
power: _power[i]
});
uint key = _season * 1000 + i;
soldiers[key] = soldier;
}
//fire the event
emit FighterReady(_season);
}
/// @dev process a fight
function _localFight(uint32 _season, uint32 _seed) internal returns (uint8 winner)
{
require(finished[_season] == 0);//make sure a season just match once.
uint[] memory powers = new uint[](8);
uint sumPower = 0;
uint8 i = 0;
uint key = 0;
Fighter storage soldier = soldiers[0];
for (i = 0; i < 8; i++) {
key = _season * 1000 + i;
soldier = soldiers[key];
powers[i] = soldier.power;
sumPower = sumPower + soldier.power;
}
uint sumValue = 0;
uint tmpPower = 0;
for (i = 0; i < 8; i++) {
tmpPower = powers[i] ** 5;//
sumValue += tmpPower;
powers[i] = sumValue;
}
uint singleDeno = sumPower ** 5;
uint randomVal = _getRandom(_seed);
winner = 0;
uint shoot = sumValue * randomVal * 10000000000 / singleDeno / 0xffffffff;
for (i = 0; i < 8; i++) {
tmpPower = powers[i];
if (shoot <= tmpPower * 10000000000 / singleDeno) {
winner = i;
break;
}
}
finished[_season] = uint8(100 + winner);
return winner;
}
/// @dev give a seed and get a random value between 0 and 0xffffffff.
/// @param _seed an uint32 value from users
function _getRandom(uint32 _seed) pure internal returns(uint32) {
return uint32(keccak256(_seed));
}
}
| 46,081 |
7 | // Dev address. Set to owner's address to revoke. | address private devAddress;
event OrnamentCreated(uint256 indexed tokenId);
event TokenUpdated(uint256 tokenId);
| address private devAddress;
event OrnamentCreated(uint256 indexed tokenId);
event TokenUpdated(uint256 tokenId);
| 21,800 |
44 | // returns the native fee the UA pays to cover fees | function estimateFees(uint16 _chainId, address _ua, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParams) external view override returns (uint nativeFee, uint zroFee) {
uint16 chainId = _chainId;
address ua = _ua;
uint payloadSize = _payload.length;
bytes memory adapterParam = _adapterParams;
ApplicationConfiguration memory uaConfig = getAppConfig(chainId, ua);
// Relayer Fee
uint relayerFee;
{
if (adapterParam.length == 0) {
bytes memory defaultAdaptorParam = defaultAdapterParams[chainId][uaConfig.outboundProofType];
relayerFee = ILayerZeroRelayer(uaConfig.relayer).getPrice(chainId, uaConfig.outboundProofType, ua, payloadSize, defaultAdaptorParam);
} else {
relayerFee = ILayerZeroRelayer(uaConfig.relayer).getPrice(chainId, uaConfig.outboundProofType, ua, payloadSize, adapterParam);
}
}
// Oracle Fee
uint oracleFee = ILayerZeroOracle(uaConfig.oracle).getPrice(chainId, uaConfig.outboundProofType);
// LayerZero Fee
{
uint protocolFee = treasuryContract.getFees(_payInZRO, relayerFee, oracleFee);
_payInZRO ? zroFee = protocolFee : nativeFee = protocolFee;
}
// return the sum of fees
nativeFee = nativeFee.add(relayerFee).add(oracleFee);
}
| function estimateFees(uint16 _chainId, address _ua, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParams) external view override returns (uint nativeFee, uint zroFee) {
uint16 chainId = _chainId;
address ua = _ua;
uint payloadSize = _payload.length;
bytes memory adapterParam = _adapterParams;
ApplicationConfiguration memory uaConfig = getAppConfig(chainId, ua);
// Relayer Fee
uint relayerFee;
{
if (adapterParam.length == 0) {
bytes memory defaultAdaptorParam = defaultAdapterParams[chainId][uaConfig.outboundProofType];
relayerFee = ILayerZeroRelayer(uaConfig.relayer).getPrice(chainId, uaConfig.outboundProofType, ua, payloadSize, defaultAdaptorParam);
} else {
relayerFee = ILayerZeroRelayer(uaConfig.relayer).getPrice(chainId, uaConfig.outboundProofType, ua, payloadSize, adapterParam);
}
}
// Oracle Fee
uint oracleFee = ILayerZeroOracle(uaConfig.oracle).getPrice(chainId, uaConfig.outboundProofType);
// LayerZero Fee
{
uint protocolFee = treasuryContract.getFees(_payInZRO, relayerFee, oracleFee);
_payInZRO ? zroFee = protocolFee : nativeFee = protocolFee;
}
// return the sum of fees
nativeFee = nativeFee.add(relayerFee).add(oracleFee);
}
| 36,189 |
15 | // Seller can cancel the contract escrow and return all the funds to buyer | function cancel() external payable
| function cancel() external payable
| 40,735 |
1 | // Returns the subtraction of two unsigned integers, reverting onoverflow (when the result is negative). Counterpart to Solidity's `-` operator. Requirements:- Subtraction cannot overflow. / | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
| function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
| 487 |
19 | // ------------------ADMIN FUNCTIONS / Starts Auction AuctionInfo The Struct Of Auction InfoMerkleRoots The Merkle Roots For The Auction DiscountAmounts The Discount Amounts For The Auction ([80,90] = 20% Discount, 10% Discount) / | function __StartAuction(Params memory AuctionInfo, bytes32[] calldata MerkleRoots, uint[] calldata DiscountAmounts) external onlyAdmin returns (uint SaleIndex)
| function __StartAuction(Params memory AuctionInfo, bytes32[] calldata MerkleRoots, uint[] calldata DiscountAmounts) external onlyAdmin returns (uint SaleIndex)
| 19,840 |
4 | // Maximum Tokens available per transaction/purchase | uint256 private _maxMintAmount = 20;
| uint256 private _maxMintAmount = 20;
| 20,830 |
17 | // Deposits tokens in proportion to the Optimizer's current ticks. amount0Desired Max amount of token0 to deposit amount1Desired Max amount of token1 to deposit to address that plp should be transferedreturn shares mintedreturn amount0 Amount of token0 depositedreturn amount1 Amount of token1 deposited / | function deposit(uint256 amount0Desired, uint256 amount1Desired, address to) external returns (uint256 shares, uint256 amount0,uint256 amount1);
| function deposit(uint256 amount0Desired, uint256 amount1Desired, address to) external returns (uint256 shares, uint256 amount0,uint256 amount1);
| 26,472 |
70 | // Moves tokens `amount` from `sender` to `recipient`. | * This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| * This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 27,128 |
86 | // Main entry point for buying into the Pre-Sale. Contract Receives $ETH | receive() external payable {
// Prevent owner from buying tokens, but allow them to add pre-sale ETH to the contract for Uniswap liquidity
// Validations.
require(
msg.sender != address(0),
"ManysCrowdsale: beneficiary is the zero address"
);
require(isOpen(), "ManysCrowdsale: sale did not start yet.");
//require(!hasEnded(), "TacosCrowdsale: sale is over.");
// require(
// weiRaised < _totalCapForCurrentRound(),
// "TacosCrowdsale: The cap for the current round has been filled."
// );
// require(
// _allowedInCurrentRound(msg.sender),
// "TacosCrowdsale: Address not allowed for this round."
// );
// require(
// contributions[msg.sender] < CAP_PER_ADDRESS,
// "TacosCrowdsale: Individual cap has been filled."
// );
// If we've passed most validations, let's get them $MANYs
_buyTokens(msg.sender);
}
| receive() external payable {
// Prevent owner from buying tokens, but allow them to add pre-sale ETH to the contract for Uniswap liquidity
// Validations.
require(
msg.sender != address(0),
"ManysCrowdsale: beneficiary is the zero address"
);
require(isOpen(), "ManysCrowdsale: sale did not start yet.");
//require(!hasEnded(), "TacosCrowdsale: sale is over.");
// require(
// weiRaised < _totalCapForCurrentRound(),
// "TacosCrowdsale: The cap for the current round has been filled."
// );
// require(
// _allowedInCurrentRound(msg.sender),
// "TacosCrowdsale: Address not allowed for this round."
// );
// require(
// contributions[msg.sender] < CAP_PER_ADDRESS,
// "TacosCrowdsale: Individual cap has been filled."
// );
// If we've passed most validations, let's get them $MANYs
_buyTokens(msg.sender);
}
| 23,953 |
58 | // conect to tht contract | function buyTHT(uint256 _value) private
| function buyTHT(uint256 _value) private
| 1,831 |
12 | // Use first coin from pool and if that is empty (due to error) fall back to second coin | address preferredCoinAddress = coins[0];
if (preferredCoinAddress == address(0)) {
preferredCoinAddress = coins[1];
}
| address preferredCoinAddress = coins[0];
if (preferredCoinAddress == address(0)) {
preferredCoinAddress = coins[1];
}
| 65,099 |
184 | // return A unit amount of terminal inflation supply Weekly compound rate based on number of weeks / | function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) {
// rate = (1 + weekly rate) ^ num of weeks
uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks);
// return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks
return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit()));
}
| function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) {
// rate = (1 + weekly rate) ^ num of weeks
uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks);
// return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks
return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit()));
}
| 5,740 |
136 | // Array with all token ids, used for enumeration | uint256[] private _allTokens;
| uint256[] private _allTokens;
| 17,693 |
287 | // ACTION: DEPOSIT OR WITHDRAW | ProcessInfo memory processInfo;
if (totalPendingDeposit > pendingWithdrawalAmount) { // DEPOSIT
| ProcessInfo memory processInfo;
if (totalPendingDeposit > pendingWithdrawalAmount) { // DEPOSIT
| 1,331 |
8 | // Are you in the Buddy List? Check if `forBuddiesOnly` is enabled to determine if this actually gets you anything. | function isAddressInBuddyList(address a, bytes32[] memory buddyMerkleProof) public view returns (bool) {
bytes32 l = keccak256(abi.encodePacked(a));
return MerkleProof.verify(buddyMerkleProof, BuddiesMerkleRoot, l);
}
| function isAddressInBuddyList(address a, bytes32[] memory buddyMerkleProof) public view returns (bool) {
bytes32 l = keccak256(abi.encodePacked(a));
return MerkleProof.verify(buddyMerkleProof, BuddiesMerkleRoot, l);
}
| 14,233 |
16 | // Get Boxes Left Supply / | function getBoxesLeftSupply() public view returns (uint256) {
return boxesMaxSupply - totalBoxesLength;
}
| function getBoxesLeftSupply() public view returns (uint256) {
return boxesMaxSupply - totalBoxesLength;
}
| 37,740 |
9 | // Returns the instant value for `variable` in the sample pointed to by `index`. / | function _getInstantValue(IPriceOracle.Variable variable, uint256 index) internal view returns (int256) {
bytes32 sample = _getSample(index);
_require(sample.timestamp() > 0, Errors.ORACLE_NOT_INITIALIZED);
return sample.instant(variable);
}
| function _getInstantValue(IPriceOracle.Variable variable, uint256 index) internal view returns (int256) {
bytes32 sample = _getSample(index);
_require(sample.timestamp() > 0, Errors.ORACLE_NOT_INITIALIZED);
return sample.instant(variable);
}
| 32,870 |
16 | // This function provides compounding in secondschi Accumulated interest rate over timeratePerSecond Interest rate accumulation per second in RAD(10ˆ27)lastUpdated When the interest rate was last updatedpie Total sum of all amounts accumulating under one interest rate, divided by that rate return The new accumulated rate, as well as the difference between the debt calculated with the old and new accumulated rates. | function compounding(uint chi, uint ratePerSecond, uint lastUpdated, uint pie) public view returns (uint, uint) {
require(block.timestamp >= lastUpdated, "tinlake-math/invalid-timestamp");
require(chi != 0);
// instead of a interestBearingAmount we use a accumulated interest rate index (chi)
uint updatedChi = _chargeInterest(chi ,ratePerSecond, lastUpdated, block.timestamp);
return (updatedChi, safeSub(rmul(updatedChi, pie), rmul(chi, pie)));
}
| function compounding(uint chi, uint ratePerSecond, uint lastUpdated, uint pie) public view returns (uint, uint) {
require(block.timestamp >= lastUpdated, "tinlake-math/invalid-timestamp");
require(chi != 0);
// instead of a interestBearingAmount we use a accumulated interest rate index (chi)
uint updatedChi = _chargeInterest(chi ,ratePerSecond, lastUpdated, block.timestamp);
return (updatedChi, safeSub(rmul(updatedChi, pie), rmul(chi, pie)));
}
| 12,503 |
50 | // angel investors wallet | address public angelInvestorsWallet;
| address public angelInvestorsWallet;
| 73,174 |
19 | // Bump version | CHANGELOG.setVersion("1.2.0");
| CHANGELOG.setVersion("1.2.0");
| 4,195 |
27 | // message unnecessarily. For custom revert reasons use {tryDiv}. Counterpart to Solidity's `/` operator. Note: this function uses a`revert` opcode (which leaves remaining gas untouched) while Solidityuses an invalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero. / | function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
| function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
| 108 |
89 | // Make the donation | _donate(
_kittyId,
trustAmount,
fosterAmount,
kitties[_kittyId].trustAddress,
kitties[_kittyId].fosterAddress
);
| _donate(
_kittyId,
trustAmount,
fosterAmount,
kitties[_kittyId].trustAddress,
kitties[_kittyId].fosterAddress
);
| 51,127 |
64 | // Stake UNI-V2-LP ( ETH-BSKT Pair ) token | function stake(uint256 amount) public updateReward(_msgSender()) checkStart {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(_msgSender(), amount);
}
| function stake(uint256 amount) public updateReward(_msgSender()) checkStart {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(_msgSender(), amount);
}
| 47,021 |
54 | // Returns true if `_operator` is an approved operator for `_owner`, false otherwise. _owner The address that owns the NFTs. _operator The address that acts on behalf of the owner.return True if approved for all, false otherwise. / | function isApprovedForAll(
| function isApprovedForAll(
| 8,273 |
6 | // Check if KYC is required for address _address Address to check / | function isKYCRequired(address _address) external view returns(bool) {
return KYCRequired[_address];
}
| function isKYCRequired(address _address) external view returns(bool) {
return KYCRequired[_address];
}
| 28,187 |
40 | // use executeRequest in the body instead? (more gas due to all the checks, but less code duplication) | _refundCreator(task);
unchecked {
--takenTasks;
}
| _refundCreator(task);
unchecked {
--takenTasks;
}
| 11,788 |
27 | // case 2: R>1 | payQuote = _RAboveBuyBaseToken(buyBaseAmount, _BASE_BALANCE_, newBaseTarget);
newRStatus = Types.RStatus.ABOVE_ONE;
| payQuote = _RAboveBuyBaseToken(buyBaseAmount, _BASE_BALANCE_, newBaseTarget);
newRStatus = Types.RStatus.ABOVE_ONE;
| 2,358 |
139 | // https:docs.peri.finance/contracts/source/interfaces/itradingrewards | interface ITradingRewards {
/* ========== VIEWS ========== */
function getAvailableRewards() external view returns (uint);
function getUnassignedRewards() external view returns (uint);
function getRewardsToken() external view returns (address);
function getPeriodController() external view returns (address);
function getCurrentPeriod() external view returns (uint);
function getPeriodIsClaimable(uint periodID) external view returns (bool);
function getPeriodIsFinalized(uint periodID) external view returns (bool);
function getPeriodRecordedFees(uint periodID) external view returns (uint);
function getPeriodTotalRewards(uint periodID) external view returns (uint);
function getPeriodAvailableRewards(uint periodID) external view returns (uint);
function getUnaccountedFeesForAccountForPeriod(address account, uint periodID) external view returns (uint);
function getAvailableRewardsForAccountForPeriod(address account, uint periodID) external view returns (uint);
function getAvailableRewardsForAccountForPeriods(address account, uint[] calldata periodIDs)
external
view
returns (uint totalRewards);
/* ========== MUTATIVE FUNCTIONS ========== */
function claimRewardsForPeriod(uint periodID) external;
function claimRewardsForPeriods(uint[] calldata periodIDs) external;
/* ========== RESTRICTED FUNCTIONS ========== */
function recordExchangeFeeForAccount(uint usdFeeAmount, address account) external;
function closeCurrentPeriodWithRewards(uint rewards) external;
function recoverTokens(address tokenAddress, address recoverAddress) external;
function recoverUnassignedRewardTokens(address recoverAddress) external;
function recoverAssignedRewardTokensAndDestroyPeriod(address recoverAddress, uint periodID) external;
function setPeriodController(address newPeriodController) external;
}
| interface ITradingRewards {
/* ========== VIEWS ========== */
function getAvailableRewards() external view returns (uint);
function getUnassignedRewards() external view returns (uint);
function getRewardsToken() external view returns (address);
function getPeriodController() external view returns (address);
function getCurrentPeriod() external view returns (uint);
function getPeriodIsClaimable(uint periodID) external view returns (bool);
function getPeriodIsFinalized(uint periodID) external view returns (bool);
function getPeriodRecordedFees(uint periodID) external view returns (uint);
function getPeriodTotalRewards(uint periodID) external view returns (uint);
function getPeriodAvailableRewards(uint periodID) external view returns (uint);
function getUnaccountedFeesForAccountForPeriod(address account, uint periodID) external view returns (uint);
function getAvailableRewardsForAccountForPeriod(address account, uint periodID) external view returns (uint);
function getAvailableRewardsForAccountForPeriods(address account, uint[] calldata periodIDs)
external
view
returns (uint totalRewards);
/* ========== MUTATIVE FUNCTIONS ========== */
function claimRewardsForPeriod(uint periodID) external;
function claimRewardsForPeriods(uint[] calldata periodIDs) external;
/* ========== RESTRICTED FUNCTIONS ========== */
function recordExchangeFeeForAccount(uint usdFeeAmount, address account) external;
function closeCurrentPeriodWithRewards(uint rewards) external;
function recoverTokens(address tokenAddress, address recoverAddress) external;
function recoverUnassignedRewardTokens(address recoverAddress) external;
function recoverAssignedRewardTokensAndDestroyPeriod(address recoverAddress, uint periodID) external;
function setPeriodController(address newPeriodController) external;
}
| 40,386 |
156 | // Library for fixed point arithmetic on uints / | library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
| library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
| 15,082 |
3 | // Note: We are not using careful math here as we're performing a division that cannot fail | return exp.mantissa / expScale;
| return exp.mantissa / expScale;
| 21,767 |
227 | // Function to mint tokens/to address to which new minted tokens are sent/amount of tokens to send / return A boolean that indicates if the operation was successful. | function mint(address to, uint256 amount) public isMinter() returns (bool) {
_mint(to, amount);
return true;
}
| function mint(address to, uint256 amount) public isMinter() returns (bool) {
_mint(to, amount);
return true;
}
| 668 |
40 | // Minus 1y locked tokens | remainingTokens = remainingTokens.sub(totalSupplyLocked1Y);
| remainingTokens = remainingTokens.sub(totalSupplyLocked1Y);
| 23,715 |
354 | // // Called by anyone to poke the timestamp of a given account. This allows users toeffectively 'claim' any new timeMultiplier, but will revert if there is no change there. / | function reviewTimestamp(address _account) external {
_reviewWeightedTimestamp(_account);
}
| function reviewTimestamp(address _account) external {
_reviewWeightedTimestamp(_account);
}
| 58,007 |
314 | // Withdraw a specific amount of underlying tokens from strategies in the withdrawal stack./underlyingAmount The amount of underlying tokens to pull into float./Automatically removes depleted strategies from the withdrawal stack. | function pullFromWithdrawalStack(uint256 underlyingAmount) internal {
// We will update this variable as we pull from strategies.
uint256 amountLeftToPull = underlyingAmount;
// We'll start at the tip of the stack and traverse backwards.
uint256 currentIndex = withdrawalStack.length - 1;
// Iterate in reverse so we pull from the stack in a "last in, first out" manner.
// Will revert due to underflow if we empty the stack before pulling the desired amount.
for (; ; currentIndex--) {
// Get the strategy at the current stack index.
Strategy strategy = withdrawalStack[currentIndex];
// Get the balance of the strategy before we withdraw from it.
uint256 strategyBalance = getStrategyData[strategy].balance;
// If the strategy is currently untrusted or was already depleted:
if (!getStrategyData[strategy].trusted || strategyBalance == 0) {
// Remove it from the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, strategy);
// Move onto the next strategy.
continue;
}
// We want to pull as much as we can from the strategy, but no more than we need.
uint256 amountToPull = strategyBalance > amountLeftToPull ? amountLeftToPull : strategyBalance;
unchecked {
// Compute the balance of the strategy that will remain after we withdraw.
// Cannot underflow as we cap the amount to pull at the strategy's balance.
uint256 strategyBalanceAfterWithdrawal = strategyBalance - amountToPull;
// Without this the next harvest would count the withdrawal as a loss.
getStrategyData[strategy].balance = strategyBalanceAfterWithdrawal.safeCastTo248();
// Adjust our goal based on how much we can pull from the strategy.
// Cannot underflow as we cap the amount to pull at the amount left to pull.
amountLeftToPull -= amountToPull;
emit StrategyWithdrawal(msg.sender, strategy, amountToPull);
// Withdraw from the strategy and revert if returns an error code.
require(strategy.redeemUnderlying(amountToPull) == 0, "REDEEM_FAILED");
// If we fully depleted the strategy:
if (strategyBalanceAfterWithdrawal == 0) {
// Remove it from the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, strategy);
}
}
// If we've pulled all we need, exit the loop.
if (amountLeftToPull == 0) break;
}
unchecked {
// Account for the withdrawals done in the loop above.
// Cannot underflow as the balances of some strategies cannot exceed the sum of all.
totalStrategyHoldings -= underlyingAmount;
}
// Cache the Vault's balance of ETH.
uint256 ethBalance = address(this).balance;
// If the Vault's underlying token is WETH compatible and we have some ETH, wrap it into WETH.
if (ethBalance != 0 && underlyingIsWETH) WETH(payable(address(UNDERLYING))).deposit{value: ethBalance}();
}
| function pullFromWithdrawalStack(uint256 underlyingAmount) internal {
// We will update this variable as we pull from strategies.
uint256 amountLeftToPull = underlyingAmount;
// We'll start at the tip of the stack and traverse backwards.
uint256 currentIndex = withdrawalStack.length - 1;
// Iterate in reverse so we pull from the stack in a "last in, first out" manner.
// Will revert due to underflow if we empty the stack before pulling the desired amount.
for (; ; currentIndex--) {
// Get the strategy at the current stack index.
Strategy strategy = withdrawalStack[currentIndex];
// Get the balance of the strategy before we withdraw from it.
uint256 strategyBalance = getStrategyData[strategy].balance;
// If the strategy is currently untrusted or was already depleted:
if (!getStrategyData[strategy].trusted || strategyBalance == 0) {
// Remove it from the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, strategy);
// Move onto the next strategy.
continue;
}
// We want to pull as much as we can from the strategy, but no more than we need.
uint256 amountToPull = strategyBalance > amountLeftToPull ? amountLeftToPull : strategyBalance;
unchecked {
// Compute the balance of the strategy that will remain after we withdraw.
// Cannot underflow as we cap the amount to pull at the strategy's balance.
uint256 strategyBalanceAfterWithdrawal = strategyBalance - amountToPull;
// Without this the next harvest would count the withdrawal as a loss.
getStrategyData[strategy].balance = strategyBalanceAfterWithdrawal.safeCastTo248();
// Adjust our goal based on how much we can pull from the strategy.
// Cannot underflow as we cap the amount to pull at the amount left to pull.
amountLeftToPull -= amountToPull;
emit StrategyWithdrawal(msg.sender, strategy, amountToPull);
// Withdraw from the strategy and revert if returns an error code.
require(strategy.redeemUnderlying(amountToPull) == 0, "REDEEM_FAILED");
// If we fully depleted the strategy:
if (strategyBalanceAfterWithdrawal == 0) {
// Remove it from the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, strategy);
}
}
// If we've pulled all we need, exit the loop.
if (amountLeftToPull == 0) break;
}
unchecked {
// Account for the withdrawals done in the loop above.
// Cannot underflow as the balances of some strategies cannot exceed the sum of all.
totalStrategyHoldings -= underlyingAmount;
}
// Cache the Vault's balance of ETH.
uint256 ethBalance = address(this).balance;
// If the Vault's underlying token is WETH compatible and we have some ETH, wrap it into WETH.
if (ethBalance != 0 && underlyingIsWETH) WETH(payable(address(UNDERLYING))).deposit{value: ethBalance}();
}
| 21,485 |
168 | // calculates the next token ID based on value of _currentTokenIDreturn uint256 for the next token ID / | function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
| function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
| 61,212 |
90 | // Check proof validity. | require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");
| require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");
| 13,798 |
25 | // If there exists ERC-20 tickets and the caller prefers these unstaked tickets. | bool _shouldUnstakeTickets = _preferUnstakedTickets &&
_tickets != ITickets(address(0));
if (_shouldUnstakeTickets) {
| bool _shouldUnstakeTickets = _preferUnstakedTickets &&
_tickets != ITickets(address(0));
if (_shouldUnstakeTickets) {
| 35,710 |
213 | // Mint plots / | function mintPlots(uint256[] memory plotIDs, bytes memory signature) external payable onlyNotContract {
require(openMint, "mint not open");
require(_verifyMintSignature(msg.sender, plotIDs, MINT_PLOTS_CALL_HASH_TYPE, signature), "invalid minting signature");
require(plotIDs.length <= txMaxPlots, "mint too many at a time");
require(mintedPlotCount[msg.sender] + plotIDs.length <= maxPlotOneAddr, "mint too many by one address");
uint256[3] memory incNumbers;
for (uint256 i = 0; i < plotIDs.length; i++) {
require(plotIDs[i] < totalMaxSupply, "plot id overrange");
Model m = ModelsInScene[plotIDs[i]%SCENE_PLOT_NUMBER];
incNumbers[uint256(m)] += 1;
}
require(msg.value >= superLargePrice*incNumbers[0]+grandePrice*incNumbers[1]+standardPrice*incNumbers[2], "not enough ether sent");
modelMintCount[0] += incNumbers[0];
modelMintCount[1] += incNumbers[1];
modelMintCount[2] += incNumbers[2];
mintedPlotCount[msg.sender] += plotIDs.length;
for (uint256 i = 0; i < plotIDs.length; i++) {
_safeMint(msg.sender, plotIDs[i]);
}
}
| function mintPlots(uint256[] memory plotIDs, bytes memory signature) external payable onlyNotContract {
require(openMint, "mint not open");
require(_verifyMintSignature(msg.sender, plotIDs, MINT_PLOTS_CALL_HASH_TYPE, signature), "invalid minting signature");
require(plotIDs.length <= txMaxPlots, "mint too many at a time");
require(mintedPlotCount[msg.sender] + plotIDs.length <= maxPlotOneAddr, "mint too many by one address");
uint256[3] memory incNumbers;
for (uint256 i = 0; i < plotIDs.length; i++) {
require(plotIDs[i] < totalMaxSupply, "plot id overrange");
Model m = ModelsInScene[plotIDs[i]%SCENE_PLOT_NUMBER];
incNumbers[uint256(m)] += 1;
}
require(msg.value >= superLargePrice*incNumbers[0]+grandePrice*incNumbers[1]+standardPrice*incNumbers[2], "not enough ether sent");
modelMintCount[0] += incNumbers[0];
modelMintCount[1] += incNumbers[1];
modelMintCount[2] += incNumbers[2];
mintedPlotCount[msg.sender] += plotIDs.length;
for (uint256 i = 0; i < plotIDs.length; i++) {
_safeMint(msg.sender, plotIDs[i]);
}
}
| 33,762 |
89 | // Function for getting rewards percentage by owner / | function getSwapFee() public view returns(uint256){
return _bridgeFee;
}
| function getSwapFee() public view returns(uint256){
return _bridgeFee;
}
| 24,947 |
24 | // get metadata of the token | function getTokenMetaData(uint _tokenId) public view returns(string memory) {
string memory tokenMetaData = tokenURI(_tokenId);
return tokenMetaData;
}
| function getTokenMetaData(uint _tokenId) public view returns(string memory) {
string memory tokenMetaData = tokenURI(_tokenId);
return tokenMetaData;
}
| 37,153 |
112 | // Subtract 256 bit number from 512 bit number | assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
| assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
| 27,569 |
10 | // Utility library of inline functions on addressesdevelop@teller.finance / | library AddressLib {
address public constant ADDRESS_EMPTY = address(0x0);
/**
* @dev Checks if this address is all 0s
* @param self The address this function was called on
* @return boolean
*/
function isEmpty(address self) internal pure returns (bool) {
return self == ADDRESS_EMPTY;
}
/**
* @dev Checks if this address is the same as another address
* @param self The address this function was called on
* @param other Address to check against itself
* @return boolean
*/
function isEqualTo(address self, address other) internal pure returns (bool) {
return self == other;
}
/**
* @dev Checks if this address is different to another address
* @param self The address this function was called on
* @param other Address to check against itself
* @return boolean
*/
function isNotEqualTo(address self, address other) internal pure returns (bool) {
return self != other;
}
/**
* @dev Checks if this address is not all 0s
* @param self The address this function was called on
* @return boolean
*/
function isNotEmpty(address self) internal pure returns (bool) {
return self != ADDRESS_EMPTY;
}
/**
* @dev Throws an error if address is all 0s
* @param self The address this function was called on
* @param message Error message if address is all 0s
*/
function requireNotEmpty(address self, string memory message) internal pure {
require(isNotEmpty(self), message);
}
/**
* @dev Throws an error if address is not all 0s
* @param self The address this function was called on
* @param message Error message if address is not all 0s
*/
function requireEmpty(address self, string memory message) internal pure {
require(isEmpty(self), message);
}
/**
* @dev Throws an error if address is not the same as another address
* @param self The address this function was called on
* @param other The address to check against itself
* @param message Error message if addresses are not the same
*/
function requireEqualTo(
address self,
address other,
string memory message
) internal pure {
require(isEqualTo(self, other), message);
}
/**
* @dev Throws an error if address is the same as another address
* @param self The address this function was called on
* @param other The address to check against itself
* @param message Error message if addresses are the same
*/
function requireNotEqualTo(
address self,
address other,
string memory message
) internal pure {
require(isNotEqualTo(self, other), message);
}
}
| library AddressLib {
address public constant ADDRESS_EMPTY = address(0x0);
/**
* @dev Checks if this address is all 0s
* @param self The address this function was called on
* @return boolean
*/
function isEmpty(address self) internal pure returns (bool) {
return self == ADDRESS_EMPTY;
}
/**
* @dev Checks if this address is the same as another address
* @param self The address this function was called on
* @param other Address to check against itself
* @return boolean
*/
function isEqualTo(address self, address other) internal pure returns (bool) {
return self == other;
}
/**
* @dev Checks if this address is different to another address
* @param self The address this function was called on
* @param other Address to check against itself
* @return boolean
*/
function isNotEqualTo(address self, address other) internal pure returns (bool) {
return self != other;
}
/**
* @dev Checks if this address is not all 0s
* @param self The address this function was called on
* @return boolean
*/
function isNotEmpty(address self) internal pure returns (bool) {
return self != ADDRESS_EMPTY;
}
/**
* @dev Throws an error if address is all 0s
* @param self The address this function was called on
* @param message Error message if address is all 0s
*/
function requireNotEmpty(address self, string memory message) internal pure {
require(isNotEmpty(self), message);
}
/**
* @dev Throws an error if address is not all 0s
* @param self The address this function was called on
* @param message Error message if address is not all 0s
*/
function requireEmpty(address self, string memory message) internal pure {
require(isEmpty(self), message);
}
/**
* @dev Throws an error if address is not the same as another address
* @param self The address this function was called on
* @param other The address to check against itself
* @param message Error message if addresses are not the same
*/
function requireEqualTo(
address self,
address other,
string memory message
) internal pure {
require(isEqualTo(self, other), message);
}
/**
* @dev Throws an error if address is the same as another address
* @param self The address this function was called on
* @param other The address to check against itself
* @param message Error message if addresses are the same
*/
function requireNotEqualTo(
address self,
address other,
string memory message
) internal pure {
require(isNotEqualTo(self, other), message);
}
}
| 26,107 |
18 | // require(block.timestamp >= _revealTime, "Reveal time not reached"); | return _revealTime;
| return _revealTime;
| 3,652 |
127 | // $Z / 1 one token | if (getOneTokenUsd() > 1 * 10 ** 9) {
setReserveRatio(reserveRatio.sub(reserveStepSize));
} else {
| if (getOneTokenUsd() > 1 * 10 ** 9) {
setReserveRatio(reserveRatio.sub(reserveStepSize));
} else {
| 26,484 |
22 | // A logout is a prerequisite to withdrawing the deposited OSTafter the holding period. A validator that is logged out has nomore voting power starting from the current meta-block height plustwo._validatorIndex The unique index of the validator that shall be logged out. return `true` if the logout succeeded. / | function logout(
uint256 _validatorIndex
)
external
returns (bool success_)
| function logout(
uint256 _validatorIndex
)
external
returns (bool success_)
| 50,558 |
40 | // forceDecrementVotes does not increment nonvoting account balance, so we can't double count | _decrementNonvotingAccountBalance(account, maxSlash.sub(difference));
_incrementNonvotingAccountBalance(reporter, reward);
| _decrementNonvotingAccountBalance(account, maxSlash.sub(difference));
_incrementNonvotingAccountBalance(reporter, reward);
| 17,724 |
124 | // sending all the tokens to Owner | _balanceOf[owner] = _totalSupply;
| _balanceOf[owner] = _totalSupply;
| 1,566 |
71 | // Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if both sides are fully funded. _itemID The ID of the item which request to fund. _side The recipient of the contribution. / | function fundAppeal(bytes32 _itemID, Party _side) external payable {
require(_side > Party.None, "Invalid side.");
Item storage item = items[_itemID];
require(item.status > Status.Registered, "The item must have a pending request.");
uint256 lastRequestIndex = item.requestCount - 1;
Request storage request = item.requests[lastRequestIndex];
DisputeData storage disputeData = requestsDisputeData[_itemID][lastRequestIndex];
require(
disputeData.status == DisputeStatus.AwaitingRuling,
"A dispute must have been raised to fund an appeal."
);
ArbitrationParams storage arbitrationParams = arbitrationParamsChanges[request.arbitrationParamsIndex];
IArbitrator arbitrator = arbitrationParams.arbitrator;
uint256 lastRoundIndex = disputeData.roundCount - 1;
Round storage round = disputeData.rounds[lastRoundIndex];
require(round.sideFunded != _side, "Side already fully funded.");
uint256 multiplier;
{
(uint256 appealPeriodStart, uint256 appealPeriodEnd) = arbitrator.appealPeriod(disputeData.disputeID);
require(
block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd,
"Contributions must be made within the appeal period."
);
Party winner = Party(arbitrator.currentRuling(disputeData.disputeID));
if (winner == Party.None) {
multiplier = sharedStakeMultiplier;
} else if (_side == winner) {
multiplier = winnerStakeMultiplier;
} else {
multiplier = loserStakeMultiplier;
require(
block.timestamp < (appealPeriodStart + appealPeriodEnd) / 2,
"The loser must contribute during the first half of the appeal period."
);
}
}
uint256 appealCost = arbitrator.appealCost(disputeData.disputeID, arbitrationParams.arbitratorExtraData);
uint256 totalCost = appealCost.addCap(appealCost.mulCap(multiplier) / MULTIPLIER_DIVISOR);
contribute(_itemID, lastRequestIndex, lastRoundIndex, uint256(_side), msg.sender, msg.value, totalCost);
if (round.amountPaid[uint256(_side)] >= totalCost) {
if (round.sideFunded == Party.None) {
round.sideFunded = _side;
} else {
// Resets the value because both sides are funded.
round.sideFunded = Party.None;
// Raise appeal if both sides are fully funded.
arbitrator.appeal.value(appealCost)(disputeData.disputeID, arbitrationParams.arbitratorExtraData);
disputeData.roundCount++;
round.feeRewards = round.feeRewards.subCap(appealCost);
}
}
}
| function fundAppeal(bytes32 _itemID, Party _side) external payable {
require(_side > Party.None, "Invalid side.");
Item storage item = items[_itemID];
require(item.status > Status.Registered, "The item must have a pending request.");
uint256 lastRequestIndex = item.requestCount - 1;
Request storage request = item.requests[lastRequestIndex];
DisputeData storage disputeData = requestsDisputeData[_itemID][lastRequestIndex];
require(
disputeData.status == DisputeStatus.AwaitingRuling,
"A dispute must have been raised to fund an appeal."
);
ArbitrationParams storage arbitrationParams = arbitrationParamsChanges[request.arbitrationParamsIndex];
IArbitrator arbitrator = arbitrationParams.arbitrator;
uint256 lastRoundIndex = disputeData.roundCount - 1;
Round storage round = disputeData.rounds[lastRoundIndex];
require(round.sideFunded != _side, "Side already fully funded.");
uint256 multiplier;
{
(uint256 appealPeriodStart, uint256 appealPeriodEnd) = arbitrator.appealPeriod(disputeData.disputeID);
require(
block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd,
"Contributions must be made within the appeal period."
);
Party winner = Party(arbitrator.currentRuling(disputeData.disputeID));
if (winner == Party.None) {
multiplier = sharedStakeMultiplier;
} else if (_side == winner) {
multiplier = winnerStakeMultiplier;
} else {
multiplier = loserStakeMultiplier;
require(
block.timestamp < (appealPeriodStart + appealPeriodEnd) / 2,
"The loser must contribute during the first half of the appeal period."
);
}
}
uint256 appealCost = arbitrator.appealCost(disputeData.disputeID, arbitrationParams.arbitratorExtraData);
uint256 totalCost = appealCost.addCap(appealCost.mulCap(multiplier) / MULTIPLIER_DIVISOR);
contribute(_itemID, lastRequestIndex, lastRoundIndex, uint256(_side), msg.sender, msg.value, totalCost);
if (round.amountPaid[uint256(_side)] >= totalCost) {
if (round.sideFunded == Party.None) {
round.sideFunded = _side;
} else {
// Resets the value because both sides are funded.
round.sideFunded = Party.None;
// Raise appeal if both sides are fully funded.
arbitrator.appeal.value(appealCost)(disputeData.disputeID, arbitrationParams.arbitratorExtraData);
disputeData.roundCount++;
round.feeRewards = round.feeRewards.subCap(appealCost);
}
}
}
| 81,103 |
80 | // SafeMath : it's from openzeppelin. Math operations with safety checks that throw on error / | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Subtracts two 32 bit numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub_32(uint32 a, uint32 b) internal pure returns (uint32) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Adds two 32 bit numbers, throws on overflow.
*/
function add_32(uint32 a, uint32 b) internal pure returns (uint32 c) {
c = a + b;
assert(c >= a);
return c;
}
} | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Subtracts two 32 bit numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub_32(uint32 a, uint32 b) internal pure returns (uint32) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Adds two 32 bit numbers, throws on overflow.
*/
function add_32(uint32 a, uint32 b) internal pure returns (uint32 c) {
c = a + b;
assert(c >= a);
return c;
}
} | 46,591 |
16 | // Sets user as KYC verified. | * Emits a {UserKycVerified} event.
*
* Requirements:
*
* - `_account` should be a registered as user.
*/
function userKycVerified(address _account) public onlyOwner {
require(_isUser(_account), "not a user");
setAttribute(_account, KYC_AML_VERIFIED, 1);
emit UserKycVerified(_account);
}
| * Emits a {UserKycVerified} event.
*
* Requirements:
*
* - `_account` should be a registered as user.
*/
function userKycVerified(address _account) public onlyOwner {
require(_isUser(_account), "not a user");
setAttribute(_account, KYC_AML_VERIFIED, 1);
emit UserKycVerified(_account);
}
| 54,713 |
13 | // Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa/self The mapping containing all tick information for initialized ticks/tick The tick that will be updated/tickCurrent The current tick/liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)/feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0/feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1/secondsPerLiquidityCumulativeX128 The all-time seconds per max(1, liquidity) of the pool/tickCumulative The ticktime elapsed since the pool was first initialized/time The current block timestamp | function update(
mapping(int24 => Tick.Info) storage self,
int24 tick,
int24 tickCurrent,
int128 liquidityDelta,
uint256 feeGrowthGlobal0X128,
uint256 feeGrowthGlobal1X128,
uint160 secondsPerLiquidityCumulativeX128,
int56 tickCumulative,
uint32 time,
| function update(
mapping(int24 => Tick.Info) storage self,
int24 tick,
int24 tickCurrent,
int128 liquidityDelta,
uint256 feeGrowthGlobal0X128,
uint256 feeGrowthGlobal1X128,
uint160 secondsPerLiquidityCumulativeX128,
int56 tickCumulative,
uint32 time,
| 264 |
68 | // set the contract status & emit result | emit Finalized(partyStatus, totalSpent, _ethFee, totalContributedToParty);
| emit Finalized(partyStatus, totalSpent, _ethFee, totalContributedToParty);
| 59,877 |
16 | // Start and stop sale | function setSaleActive(bool val) public onlyOwner {
saleActive = val;
}
| function setSaleActive(bool val) public onlyOwner {
saleActive = val;
}
| 40,039 |
4 | // Execute any action on behalf of strategy./Regular call is executed. If any of extcall fails, transaction should revert./destinations addresses to call/calldatas calldatas to execute | function multicall(
address[] calldata destinations,
bytes[] calldata calldatas
) external;
| function multicall(
address[] calldata destinations,
bytes[] calldata calldatas
) external;
| 23,414 |
66 | // Decrease allowance of spender/_spender Spender of the tokens/_value Amount of tokens that can be spent by spender/ return true/false | function approveLess(address _spender, uint256 _value) public returns (bool) {
uint previous = _allowance[msg.sender][_spender];
uint newAllowance = previous.sub(_value);
_allowance[msg.sender][_spender] = newAllowance;
emit Approval(msg.sender, _spender, newAllowance);
return true;
}
| function approveLess(address _spender, uint256 _value) public returns (bool) {
uint previous = _allowance[msg.sender][_spender];
uint newAllowance = previous.sub(_value);
_allowance[msg.sender][_spender] = newAllowance;
emit Approval(msg.sender, _spender, newAllowance);
return true;
}
| 64,876 |
18 | // https:etherscan.io/address/0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f | address internal constant GHO_TOKEN = 0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f;
| address internal constant GHO_TOKEN = 0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f;
| 15,717 |
6 | // Fired in withdrawEarlyFees()receiver the receiver of the early withdrawal fees tokenReceived the token received amountReceived amount of the token received / | event WithdrawFees(
| event WithdrawFees(
| 33,980 |
4 | // Returns the division of two unsigned integers, with a division by zero flag. _Available since v3.4._ / | function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
| function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
| 7,154 |
52 | // Calculate nextSetUnits such that the USD value of new Set is equal to the USD value of the Set being rebalanced out of | uint256[] memory nextSetUnits = new uint256[](1);
uint256 potentialNextUnit = 0;
uint256 naturalUnitMultiplier = 1;
uint256 nextNaturalUnit;
| uint256[] memory nextSetUnits = new uint256[](1);
uint256 potentialNextUnit = 0;
uint256 naturalUnitMultiplier = 1;
uint256 nextNaturalUnit;
| 52,021 |
177 | // Tries to fetch the decimals of a token, if not existent, fails with a require statementtoken An instance of IERC20return The decimals of a token / | function tryDecimals(IERC20 token) internal view returns (uint8) {
// solhint-disable-line private-vars-leading-underscore
bytes memory payload = abi.encodeWithSignature("decimals()");
// solhint-disable avoid-low-level-calls
(bool success, bytes memory returnData) = address(token).staticcall(payload);
require(success, "RequiredDecimals: required decimals");
uint8 decimals = abi.decode(returnData, (uint8));
require(decimals < _MAX_TOKEN_DECIMALS, "RequiredDecimals: token decimals should be lower than 38");
return decimals;
}
| function tryDecimals(IERC20 token) internal view returns (uint8) {
// solhint-disable-line private-vars-leading-underscore
bytes memory payload = abi.encodeWithSignature("decimals()");
// solhint-disable avoid-low-level-calls
(bool success, bytes memory returnData) = address(token).staticcall(payload);
require(success, "RequiredDecimals: required decimals");
uint8 decimals = abi.decode(returnData, (uint8));
require(decimals < _MAX_TOKEN_DECIMALS, "RequiredDecimals: token decimals should be lower than 38");
return decimals;
}
| 62,050 |
1 | // Constructor _boxBaseAddress boxBase address / | constructor(address _boxBaseAddress) {
boxBase = _boxBaseAddress;
}
| constructor(address _boxBaseAddress) {
boxBase = _boxBaseAddress;
}
| 46,550 |
374 | // Internal function to get the draft config for a given term_termId Identification number of the term querying the draft config of return Draft config for the given term/ | function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) {
(IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId);
return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct });
}
| function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) {
(IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId);
return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct });
}
| 19,594 |
20 | // Add a verified address to the Security Token whitelist _whitelistAddress Address attempting to join ST whitelistreturn bool success / | function addToWhitelist(address _whitelistAddress) public returns (bool success);
| function addToWhitelist(address _whitelistAddress) public returns (bool success);
| 34,582 |
5 | // Allows the core system and CCIP to burn tokens. / | function burn(address target, uint256 amount) external override {
if (
msg.sender != OwnableStorage.getOwner() &&
msg.sender != AssociatedSystem.load(_CCIP_CHAINLINK_TOKEN_POOL).proxy
) {
revert AccessError.Unauthorized(msg.sender);
}
_burn(target, amount);
}
| function burn(address target, uint256 amount) external override {
if (
msg.sender != OwnableStorage.getOwner() &&
msg.sender != AssociatedSystem.load(_CCIP_CHAINLINK_TOKEN_POOL).proxy
) {
revert AccessError.Unauthorized(msg.sender);
}
_burn(target, amount);
}
| 25,557 |
0 | // Internal state to the contract | string private greeting;
| string private greeting;
| 24,954 |
173 | // Rate for each tier (no of tokens for 1 ETH)Max wei for each tier | struct Tier {
uint256 rate;
uint256 max;
}
| struct Tier {
uint256 rate;
uint256 max;
}
| 20,539 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.