Unnamed: 0
int64 0
7.36k
| comments
stringlengths 3
35.2k
| code_string
stringlengths 1
527k
| code
stringlengths 1
527k
| __index_level_0__
int64 0
88.6k
|
---|---|---|---|---|
9 | // Gets the weighted average of two samples and their respective weights sample1 The first encoded sample sample2 The second encoded sample weight1 The weight of the first sample weight2 The weight of the second samplereturn weightedAverageId The weighted average idreturn weightedAverageVolatility The weighted average volatilityreturn weightedAverageBinCrossed The weighted average bin crossed / | function getWeightedAverage(bytes32 sample1, bytes32 sample2, uint40 weight1, uint40 weight2)
internal
pure
returns (uint64 weightedAverageId, uint64 weightedAverageVolatility, uint64 weightedAverageBinCrossed)
| function getWeightedAverage(bytes32 sample1, bytes32 sample2, uint40 weight1, uint40 weight2)
internal
pure
returns (uint64 weightedAverageId, uint64 weightedAverageVolatility, uint64 weightedAverageBinCrossed)
| 28,833 |
460 | // The given timestamp must not be greater than `block.timestamp + 1 hour` and at most `optOutPeriod(booster)` seconds old. | uint64 _now = uint64(block.timestamp);
uint64 _optOutPeriod = uint64(optOutPeriod);
bool notTooFarInFuture = payload.timestamp <= _now + 1 hours;
bool belowMaxAge = true;
| uint64 _now = uint64(block.timestamp);
uint64 _optOutPeriod = uint64(optOutPeriod);
bool notTooFarInFuture = payload.timestamp <= _now + 1 hours;
bool belowMaxAge = true;
| 5,357 |
37 | // Maintain a sell quota as the net of all daily buys and sells, plus a predefined threshold | if (_sellThreshold > 0) {
uint256 blockTimestamp = block.timestamp;
if (_sellQuota.blockMetric == 0 || _sellQuota.blockMetric < blockTimestamp - 1 days) {
_sellQuota.blockMetric = blockTimestamp;
_sellQuota.amount = int256(_sellThreshold);
emit SellQuotaChanged(_sellQuota.blockMetric, _sellQuota.amount);
}
| if (_sellThreshold > 0) {
uint256 blockTimestamp = block.timestamp;
if (_sellQuota.blockMetric == 0 || _sellQuota.blockMetric < blockTimestamp - 1 days) {
_sellQuota.blockMetric = blockTimestamp;
_sellQuota.amount = int256(_sellThreshold);
emit SellQuotaChanged(_sellQuota.blockMetric, _sellQuota.amount);
}
| 37,156 |
8 | // Check horizontally | for(uint i = 0; i<7; i++){
for(uint j = 0; j<4; j++){
if(_board[i][j] != 0 && _board[i][j] == _board[i][j+1] && _board[i][j] == _board[i][j+2] && _board[i][j] == _board[i][j+3]){
return true;
}
| for(uint i = 0; i<7; i++){
for(uint j = 0; j<4; j++){
if(_board[i][j] != 0 && _board[i][j] == _board[i][j+1] && _board[i][j] == _board[i][j+2] && _board[i][j] == _board[i][j+3]){
return true;
}
| 13,297 |
8 | // called before any token transfer; includes (batched) minting and burning / | ) internal override(ERC1155, ERC1155Supply) {
super._beforeTokenTransfer(operator, from, to, nftIds, amounts, data);
}
| ) internal override(ERC1155, ERC1155Supply) {
super._beforeTokenTransfer(operator, from, to, nftIds, amounts, data);
}
| 25,324 |
96 | // To test with JS and compare with actual encoder. Maintaining for reference. | // t = function() { return IEVMScriptExecutor.at('0x4bcdd59d6c77774ee7317fc1095f69ec84421e49').contract.execScript.getData(...[].slice.call(arguments)).slice(10).match(/.{1,64}/g) }
// run = function() { return ScriptHelpers.new().then(sh => { sh.abiEncode.call(...[].slice.call(arguments)).then(a => console.log(a.slice(2).match(/.{1,64}/g)) ) }) }
// This is truly not beautiful but lets no daydream to the day solidity gets reflection features
function abiEncode(bytes _a, bytes _b, address[] _c) public pure returns (bytes d) {
return encode(_a, _b, _c);
}
| // t = function() { return IEVMScriptExecutor.at('0x4bcdd59d6c77774ee7317fc1095f69ec84421e49').contract.execScript.getData(...[].slice.call(arguments)).slice(10).match(/.{1,64}/g) }
// run = function() { return ScriptHelpers.new().then(sh => { sh.abiEncode.call(...[].slice.call(arguments)).then(a => console.log(a.slice(2).match(/.{1,64}/g)) ) }) }
// This is truly not beautiful but lets no daydream to the day solidity gets reflection features
function abiEncode(bytes _a, bytes _b, address[] _c) public pure returns (bytes d) {
return encode(_a, _b, _c);
}
| 2,970 |
0 | // Store address of Smart Wallet Upgrade Beacon Controller as a constant. | address private constant _SMART_WALLET_UPGRADE_BEACON_CONTROLLER = address(
0x00000000002226C940b74d674B85E4bE05539663
);
| address private constant _SMART_WALLET_UPGRADE_BEACON_CONTROLLER = address(
0x00000000002226C940b74d674B85E4bE05539663
);
| 1,677 |
4 | // Proves that an account contained particular info (nonce, balance, codehash) at a particular block.encodedProof the encoded AccountInfoProof / | function _prove(bytes calldata encodedProof) internal view override returns (Fact memory) {
AccountInfoProof calldata proof = parseAccountInfoProof(encodedProof);
(
bool exists,
CoreTypes.BlockHeaderData memory head,
CoreTypes.AccountData memory acc
) = verifyAccountAtBlock(proof.account, proof.accountProof, proof.header, proof.blockProof);
require(exists, "Account does not exist at block");
if (proof.info == AccountInfo.StorageRoot) {
return
Fact(
proof.account,
FactSigs.accountStorageFactSig(head.Number, acc.StorageRoot),
""
);
} else if (proof.info == AccountInfo.CodeHash) {
return
Fact(proof.account, FactSigs.accountCodeHashFactSig(head.Number, acc.CodeHash), "");
} else if (proof.info == AccountInfo.Balance) {
return
Fact(
proof.account,
FactSigs.accountBalanceFactSig(head.Number),
abi.encodePacked(acc.Balance)
);
} else if (proof.info == AccountInfo.Nonce) {
return
Fact(
proof.account,
FactSigs.accountNonceFactSig(head.Number),
abi.encodePacked(acc.Nonce)
);
} else if (proof.info == AccountInfo.RawHeader) {
return Fact(proof.account, FactSigs.accountFactSig(head.Number), abi.encode(acc));
} else {
revert("Unknown account info requested");
}
}
| function _prove(bytes calldata encodedProof) internal view override returns (Fact memory) {
AccountInfoProof calldata proof = parseAccountInfoProof(encodedProof);
(
bool exists,
CoreTypes.BlockHeaderData memory head,
CoreTypes.AccountData memory acc
) = verifyAccountAtBlock(proof.account, proof.accountProof, proof.header, proof.blockProof);
require(exists, "Account does not exist at block");
if (proof.info == AccountInfo.StorageRoot) {
return
Fact(
proof.account,
FactSigs.accountStorageFactSig(head.Number, acc.StorageRoot),
""
);
} else if (proof.info == AccountInfo.CodeHash) {
return
Fact(proof.account, FactSigs.accountCodeHashFactSig(head.Number, acc.CodeHash), "");
} else if (proof.info == AccountInfo.Balance) {
return
Fact(
proof.account,
FactSigs.accountBalanceFactSig(head.Number),
abi.encodePacked(acc.Balance)
);
} else if (proof.info == AccountInfo.Nonce) {
return
Fact(
proof.account,
FactSigs.accountNonceFactSig(head.Number),
abi.encodePacked(acc.Nonce)
);
} else if (proof.info == AccountInfo.RawHeader) {
return Fact(proof.account, FactSigs.accountFactSig(head.Number), abi.encode(acc));
} else {
revert("Unknown account info requested");
}
}
| 21,072 |
60 | // обновляем анкету коровы | user[keccak256(gamer) & keccak256(num_cow)].cow_live = false;
| user[keccak256(gamer) & keccak256(num_cow)].cow_live = false;
| 67,409 |
242 | // _INTERFACE_ID_ERC2981 | _registerInterface(0x2a55205a);
| _registerInterface(0x2a55205a);
| 23,047 |
83 | // Hook that is called before any transfer of tokens. This includesminting and burning. Calling conditions: - when `from` and `to` are both non-zero, `amount` of `from`'s tokenswill be to transferred to `to`.- when `from` is zero, `amount` tokens will be minted for `to`.- when `to` is zero, `amount` of `from`'s tokens will be burned.- `from` and `to` are never both zero. To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks]. / | // function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
| // function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
| 46,909 |
4 | // Set a multiplier for how many tokens to earn each time a block passes. | function setRate(uint256 _rate) external onlyOwner {
rate = _rate;
}
| function setRate(uint256 _rate) external onlyOwner {
rate = _rate;
}
| 74,940 |
23 | // RequirePlatform | requirePlatform();
privilegedMinterAddress = _privilegedMinterAddress;
| requirePlatform();
privilegedMinterAddress = _privilegedMinterAddress;
| 26,717 |
40 | // Validate external call params | if (_orderCreation.externalCall.length > 0) {
ExternalCall memory externalCall = abi.decode(
_orderCreation.externalCall,
(ExternalCall)
);
if (externalCall.executionFee > _orderCreation.takeAmount) revert ProposedFeeTooHigh();
if (
externalCall.data.length > 0 &&
externalCall.fallbackAddress.length != dstAddressLength
) revert WrongAddressLength();
| if (_orderCreation.externalCall.length > 0) {
ExternalCall memory externalCall = abi.decode(
_orderCreation.externalCall,
(ExternalCall)
);
if (externalCall.executionFee > _orderCreation.takeAmount) revert ProposedFeeTooHigh();
if (
externalCall.data.length > 0 &&
externalCall.fallbackAddress.length != dstAddressLength
) revert WrongAddressLength();
| 13,512 |
80 | // add y^16(20! / 16!) | z = (z * y) / FIXED_1;
res += z * 0x0000000000001ab8;
| z = (z * y) / FIXED_1;
res += z * 0x0000000000001ab8;
| 2,513 |
150 | // Updates category details/_categoryId Category id that needs to be updated/_name Category name/_memberRoleToVote Voting Layer sequence in which the voting has to be performed./_allowedToCreateProposal Member roles allowed to create the proposal/_majorityVotePerc Majority Vote threshold for Each voting layer/_quorumPerc minimum threshold percentage required in voting to calculate result/_closingTime Vote closing time for Each voting layer/_actionHash hash of details containing the action that has to be performed after proposal is accepted/_contractAddress address of contract to call after proposal is accepted/_contractName name of contract to be called after proposal is accepted/_incentives rewards to distributed after proposal is accepted | function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
| function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
| 22,197 |
7 | // The basis points offered by coupon holders to have their coupons redeemed -- default is 200 bps (2%) E.g., offers[_user] = 500 indicates that _user will pay 500 basis points (5%) to the caller | mapping(address => uint256) private offers;
| mapping(address => uint256) private offers;
| 31,943 |
100 | // Get a page of open trades for a specified token symbol - max 30 per page | function getTrades(string calldata symbol, uint256 pageNum, uint256 perPage) external view returns (string memory){
// Check for max per page
require(perPage <= 30, "30 is the max page size");
string memory page = '{ "trades":[';
require(pageNum > 0, "Page number starts from 1");
// Create indexes
uint256 startIndex = pageNum.sub(1);
uint256 phantomEndIndex = startIndex.add(perPage);
uint256 endIndex = 0;
// Find the end of the array
if(phantomEndIndex > _openTrades[symbol].length){ endIndex = _openTrades[symbol].length; }
else{ endIndex = phantomEndIndex; }
// Build the page (json)
for(uint256 i=startIndex; i<endIndex;i++){
// Check for deleted row
if(_openTrades[symbol][i].valid){
page = _buildTrade(symbol, page, i);
}
// If not add to index (if possible)
else { if((endIndex + 1) < _openTrades[symbol].length) { endIndex++; }}
}
page = strConcat(page, "]},");
return page;
}
| function getTrades(string calldata symbol, uint256 pageNum, uint256 perPage) external view returns (string memory){
// Check for max per page
require(perPage <= 30, "30 is the max page size");
string memory page = '{ "trades":[';
require(pageNum > 0, "Page number starts from 1");
// Create indexes
uint256 startIndex = pageNum.sub(1);
uint256 phantomEndIndex = startIndex.add(perPage);
uint256 endIndex = 0;
// Find the end of the array
if(phantomEndIndex > _openTrades[symbol].length){ endIndex = _openTrades[symbol].length; }
else{ endIndex = phantomEndIndex; }
// Build the page (json)
for(uint256 i=startIndex; i<endIndex;i++){
// Check for deleted row
if(_openTrades[symbol][i].valid){
page = _buildTrade(symbol, page, i);
}
// If not add to index (if possible)
else { if((endIndex + 1) < _openTrades[symbol].length) { endIndex++; }}
}
page = strConcat(page, "]},");
return page;
}
| 50,712 |
27 | // Migrate lp token to another lp contract. | function replaceMigrate(uint256 _pid) public onlyOwner {
PoolInfo storage pool = poolInfo[_pid];
IMigrator migrator = pool.migrator;
require(address(migrator) != address(0), "migrate: no migrator");
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
(IERC20 newLpToken, uint mintBal) = migrator.replaceMigrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
emit ReplaceMigrate(address(migrator), _pid, bal);
}
| function replaceMigrate(uint256 _pid) public onlyOwner {
PoolInfo storage pool = poolInfo[_pid];
IMigrator migrator = pool.migrator;
require(address(migrator) != address(0), "migrate: no migrator");
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
(IERC20 newLpToken, uint mintBal) = migrator.replaceMigrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
emit ReplaceMigrate(address(migrator), _pid, bal);
}
| 26,114 |
5 | // revoke Role adding controle Requirements: - PAUSER_ROLE can't be revoked, it can only be renounced./ | function revokeRole(bytes32 role, address account) public override {
if(role == PAUSER_ROLE)
require(false, "PAUSER_ROLE can't be revoked, it can only be renounced");
super.revokeRole(role,account);
}
| function revokeRole(bytes32 role, address account) public override {
if(role == PAUSER_ROLE)
require(false, "PAUSER_ROLE can't be revoked, it can only be renounced");
super.revokeRole(role,account);
}
| 11,112 |
25 | // low level token purchase function | function buyTokens(address beneficiary) payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
| function buyTokens(address beneficiary) payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
| 2,289 |
66 | // Modifier to make a function callable only for owner and saleAgent when the contract is paused. / | modifier onlyWhenNotPaused() {
if(owner != msg.sender && saleAgent != msg.sender) {
require (!paused);
}
_;
}
| modifier onlyWhenNotPaused() {
if(owner != msg.sender && saleAgent != msg.sender) {
require (!paused);
}
_;
}
| 6,505 |
40 | // if we're not yet working on this operation, switch over and reset the confirmation status. | if (! isOperationActive(_operation)) {
| if (! isOperationActive(_operation)) {
| 13,087 |
378 | // Reveal a previously committed vote for `identifier` at `time`. The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`that `commitVote()` was called with. Only the committer can reveal their vote. identifier voted on in the commit phase. EG BTC/USD price pair. time specifies the unix timestamp of the price is being voted on. price voted on during the commit phase. salt value used to hide the commitment price during the commit phase. / | function revealVote(
| function revealVote(
| 9,936 |
5 | // Constants/ "Magic" prefix. When prepended to some arbitrary bytecode and used to create a contract, the appended bytecode will be deployed as given. | bytes13 internal constant DEPLOY_CODE_PREFIX = 0x600D380380600D6000396000f3;
| bytes13 internal constant DEPLOY_CODE_PREFIX = 0x600D380380600D6000396000f3;
| 69,047 |
143 | // get the length of supported tokens/ return The quantity of tokens added | function getTokenAddressesLength() external view returns (uint256);
| function getTokenAddressesLength() external view returns (uint256);
| 11,433 |
34 | // Tiers filled | wait = true;
endTime = swapTime;
WaitStarted(endTime);
| wait = true;
endTime = swapTime;
WaitStarted(endTime);
| 40,546 |
332 | // Construct the LongShortPair params Constructor params used to initialize the LSP. Key-valued object with the following structure: - `pairName`: Name of the long short pair contract. - `expirationTimestamp`: Unix timestamp of when the contract will expire. - `collateralPerPair`: How many units of collateral are required to mint one pair of synthetic tokens. - `priceIdentifier`: Price identifier, registered in the DVM for the long short pair. - `longToken`: Token used as long in the LSP. Mint and burn rights needed by this contract. - `shortToken`: Token used as short in the LSP. Mint and burn rights needed by this contract. - | constructor(ConstructorParams memory params) Testable(params.timerAddress) {
finder = params.finder;
require(bytes(params.pairName).length > 0, "Pair name cant be empty");
require(params.expirationTimestamp > getCurrentTime(), "Expiration timestamp in past");
require(params.collateralPerPair > 0, "Collateral per pair cannot be 0");
require(_getIdentifierWhitelist().isIdentifierSupported(params.priceIdentifier), "Identifier not registered");
require(address(_getOptimisticOracle()) != address(0), "Invalid finder");
require(address(params.financialProductLibrary) != address(0), "Invalid FinancialProductLibrary");
require(_getCollateralWhitelist().isOnWhitelist(address(params.collateralToken)), "Collateral not whitelisted");
require(params.optimisticOracleLivenessTime > 0, "OO liveness cannot be 0");
require(params.optimisticOracleLivenessTime < 5200 weeks, "OO liveness too large");
pairName = params.pairName;
expirationTimestamp = params.expirationTimestamp;
collateralPerPair = params.collateralPerPair;
priceIdentifier = params.priceIdentifier;
enableEarlyExpiration = params.enableEarlyExpiration;
longToken = params.longToken;
shortToken = params.shortToken;
collateralToken = params.collateralToken;
financialProductLibrary = params.financialProductLibrary;
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Ancillary data + additional stamped information should be less than ancillary data limit. Consider early
// expiration ancillary data, if enableEarlyExpiration is set.
customAncillaryData = params.customAncillaryData;
require(
optimisticOracle
.stampAncillaryData(
(enableEarlyExpiration ? getEarlyExpirationAncillaryData() : customAncillaryData),
address(this)
)
.length <= optimisticOracle.ancillaryBytesLimit(),
"Ancillary Data too long"
);
proposerReward = params.proposerReward;
optimisticOracleLivenessTime = params.optimisticOracleLivenessTime;
optimisticOracleProposerBond = params.optimisticOracleProposerBond;
}
| constructor(ConstructorParams memory params) Testable(params.timerAddress) {
finder = params.finder;
require(bytes(params.pairName).length > 0, "Pair name cant be empty");
require(params.expirationTimestamp > getCurrentTime(), "Expiration timestamp in past");
require(params.collateralPerPair > 0, "Collateral per pair cannot be 0");
require(_getIdentifierWhitelist().isIdentifierSupported(params.priceIdentifier), "Identifier not registered");
require(address(_getOptimisticOracle()) != address(0), "Invalid finder");
require(address(params.financialProductLibrary) != address(0), "Invalid FinancialProductLibrary");
require(_getCollateralWhitelist().isOnWhitelist(address(params.collateralToken)), "Collateral not whitelisted");
require(params.optimisticOracleLivenessTime > 0, "OO liveness cannot be 0");
require(params.optimisticOracleLivenessTime < 5200 weeks, "OO liveness too large");
pairName = params.pairName;
expirationTimestamp = params.expirationTimestamp;
collateralPerPair = params.collateralPerPair;
priceIdentifier = params.priceIdentifier;
enableEarlyExpiration = params.enableEarlyExpiration;
longToken = params.longToken;
shortToken = params.shortToken;
collateralToken = params.collateralToken;
financialProductLibrary = params.financialProductLibrary;
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Ancillary data + additional stamped information should be less than ancillary data limit. Consider early
// expiration ancillary data, if enableEarlyExpiration is set.
customAncillaryData = params.customAncillaryData;
require(
optimisticOracle
.stampAncillaryData(
(enableEarlyExpiration ? getEarlyExpirationAncillaryData() : customAncillaryData),
address(this)
)
.length <= optimisticOracle.ancillaryBytesLimit(),
"Ancillary Data too long"
);
proposerReward = params.proposerReward;
optimisticOracleLivenessTime = params.optimisticOracleLivenessTime;
optimisticOracleProposerBond = params.optimisticOracleProposerBond;
}
| 72,742 |
7 | // checks if the instance of market maker contract is open for public/_token address address of the CC token. | modifier marketOpen(address _token) {
require(MarketMaker(currencyMap[_token].mmAddress).isOpenForPublic());
_;
}
| modifier marketOpen(address _token) {
require(MarketMaker(currencyMap[_token].mmAddress).isOpenForPublic());
_;
}
| 17,613 |
19 | // update reserves and, on the first call per block, price accumulators | function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= 0xffffffffffffffffffffffffffff && balance1 <= 0xffffffffffffffffffffffffffff, 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
| function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= 0xffffffffffffffffffffffffffff && balance1 <= 0xffffffffffffffffffffffffffff, 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
| 34,950 |
72 | // same as restake but for layer 1 stakes | // @param sessionID {uint256} - id of the stake
// @param stakingDays {uint256} - number of days to be staked
// @param topup {uint256} - amount of AXN to be added as topup to the stake
function restakeV1(
uint256 sessionId,
uint256 stakingDays,
uint256 topup
) external pausable {
require(sessionId <= lastSessionIdV1, 'Staking: Invalid sessionId');
require(stakingDays != 0, 'Staking: Staking days < 1');
require(stakingDays <= 5555, 'Staking: Staking days > 5555');
Session storage session = sessionDataOf[msg.sender][sessionId];
require(
session.shares == 0 && session.withdrawn == false,
'Staking: Stake withdrawn'
);
(
uint256 amount,
uint256 start,
uint256 end,
uint256 shares,
uint256 firstPayout
) = stakingV1.sessionDataOf(msg.sender, sessionId);
// Unstaked in v1 / doesn't exist
require(shares != 0, 'Staking: Stake withdrawn');
uint256 actualEnd = now;
require(end <= actualEnd, 'Staking: Stake not mature');
uint256 sessionStakingDays = (end - start) / stepTimestamp;
uint256 lastPayout = sessionStakingDays + firstPayout;
uint256 amountOut =
unstakeV1Internal(
sessionId,
amount,
start,
end,
actualEnd,
shares,
firstPayout,
lastPayout
);
if (topup != 0) {
IToken(addresses.mainToken).burn(msg.sender, topup);
amountOut = amountOut.add(topup);
}
stakeInternal(amountOut, stakingDays, msg.sender);
}
| // @param sessionID {uint256} - id of the stake
// @param stakingDays {uint256} - number of days to be staked
// @param topup {uint256} - amount of AXN to be added as topup to the stake
function restakeV1(
uint256 sessionId,
uint256 stakingDays,
uint256 topup
) external pausable {
require(sessionId <= lastSessionIdV1, 'Staking: Invalid sessionId');
require(stakingDays != 0, 'Staking: Staking days < 1');
require(stakingDays <= 5555, 'Staking: Staking days > 5555');
Session storage session = sessionDataOf[msg.sender][sessionId];
require(
session.shares == 0 && session.withdrawn == false,
'Staking: Stake withdrawn'
);
(
uint256 amount,
uint256 start,
uint256 end,
uint256 shares,
uint256 firstPayout
) = stakingV1.sessionDataOf(msg.sender, sessionId);
// Unstaked in v1 / doesn't exist
require(shares != 0, 'Staking: Stake withdrawn');
uint256 actualEnd = now;
require(end <= actualEnd, 'Staking: Stake not mature');
uint256 sessionStakingDays = (end - start) / stepTimestamp;
uint256 lastPayout = sessionStakingDays + firstPayout;
uint256 amountOut =
unstakeV1Internal(
sessionId,
amount,
start,
end,
actualEnd,
shares,
firstPayout,
lastPayout
);
if (topup != 0) {
IToken(addresses.mainToken).burn(msg.sender, topup);
amountOut = amountOut.add(topup);
}
stakeInternal(amountOut, stakingDays, msg.sender);
}
| 24,274 |
349 | // Set royalty basis points | function setRoyaltyBasisPoints(uint256 _basisPoints) public onlyOwner {
royaltyBasisPoints = _basisPoints;
emit RoyaltyBasisPoints(_basisPoints);
}
| function setRoyaltyBasisPoints(uint256 _basisPoints) public onlyOwner {
royaltyBasisPoints = _basisPoints;
emit RoyaltyBasisPoints(_basisPoints);
}
| 29,826 |
277 | // The main minting function | function mint(uint256 amount) public payable {
require(isSaleActive, "Sale must be active to mint NFT");
require(amount <= MAX_NFT, "Amount must be less than MAX_NFT");
require(totalSupply().add(amount) <= MAX_NFT, "Total supply + amount must be less than MAX_NFT");
require(nftPrice.mul(amount) == msg.value, "Ether value sent is not correct");
require(amount <= maxNftPurchase, "Can't mint more than 50");
for(uint counter = 0; counter < amount; counter++) {
uint mintIndex = totalSupply();
if(totalSupply() < MAX_NFT) {
_safeMint(msg.sender, mintIndex);
}
}
// If we haven't set the starting index and it is either
// 1. the last saleable token or
// 2. the first token to be sold after the end of pre-sale
// set the starting index block
if(startingIndexBlock == 0 && (totalSupply() == MAX_NFT || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
| function mint(uint256 amount) public payable {
require(isSaleActive, "Sale must be active to mint NFT");
require(amount <= MAX_NFT, "Amount must be less than MAX_NFT");
require(totalSupply().add(amount) <= MAX_NFT, "Total supply + amount must be less than MAX_NFT");
require(nftPrice.mul(amount) == msg.value, "Ether value sent is not correct");
require(amount <= maxNftPurchase, "Can't mint more than 50");
for(uint counter = 0; counter < amount; counter++) {
uint mintIndex = totalSupply();
if(totalSupply() < MAX_NFT) {
_safeMint(msg.sender, mintIndex);
}
}
// If we haven't set the starting index and it is either
// 1. the last saleable token or
// 2. the first token to be sold after the end of pre-sale
// set the starting index block
if(startingIndexBlock == 0 && (totalSupply() == MAX_NFT || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
| 21,459 |
133 | // Establish path from Ether to token. | (address[] memory path, ) = _createPathAndAmounts(
_WETH, address(tokenReceived), false
);
| (address[] memory path, ) = _createPathAndAmounts(
_WETH, address(tokenReceived), false
);
| 29,254 |
23 | // Circuit Breaker Storage Library Library for storing and manipulating state related to circuit breakers. The intent of circuit breakers is to halt trading of a given token if its value changes drastically -in either direction - with respect to other tokens in the pool. For instance, a stablecoin might de-pegand go to zero. With no safeguards, arbitrageurs could drain the pool by selling large amounts of thetoken to the pool at inflated internal prices. The circuit breaker mechanism establishes a "safe trading range" for each token, expressed in terms ofthe BPT price. Both lower and upper bounds can be set, | library CircuitBreakerStorageLib {
using ValueCompression for uint256;
using FixedPoint for uint256;
using WordCodec for bytes32;
// Store circuit breaker information per token
// When the circuit breaker is set, the caller passes in the lower and upper bounds (expressed as percentages),
// the current BPT price, and the normalized weight. The weight is bound by 1e18, and fits in ~60 bits, so there
// is no need for compression. We store the weight in 64 bits, just to use round numbers for all the bit lengths.
//
// We then store the current BPT price, and compute and cache the adjusted lower and upper bounds at the current
// weight. When multiplied by the stored BPT price, the adjusted bounds define the BPT price trading range: the
// "runtime" BPT prices can be directly compared to these BPT price bounds.
//
// Since the price bounds need to be adjusted for the token weight, in general these adjusted bounds would be
// computed every time. However, if the weight of the token has not changed since the circuit breaker was set,
// the adjusted bounds cache can still be used, avoiding a heavy computation.
//
// [ 32 bits | 32 bits | 96 bits | 64 bits | 16 bits | 16 bits |
// [ adjusted upper bound | adjusted lower bound | BPT price | reference weight | upper bound | lower bound |
// |MSB LSB|
uint256 private constant _LOWER_BOUND_OFFSET = 0;
uint256 private constant _UPPER_BOUND_OFFSET = _LOWER_BOUND_OFFSET + _BOUND_WIDTH;
uint256 private constant _REFERENCE_WEIGHT_OFFSET = _UPPER_BOUND_OFFSET + _BOUND_WIDTH;
uint256 private constant _BPT_PRICE_OFFSET = _REFERENCE_WEIGHT_OFFSET + _REFERENCE_WEIGHT_WIDTH;
uint256 private constant _ADJUSTED_LOWER_BOUND_OFFSET = _BPT_PRICE_OFFSET + _BPT_PRICE_WIDTH;
uint256 private constant _ADJUSTED_UPPER_BOUND_OFFSET = _ADJUSTED_LOWER_BOUND_OFFSET + _ADJUSTED_BOUND_WIDTH;
uint256 private constant _REFERENCE_WEIGHT_WIDTH = 64;
uint256 private constant _BPT_PRICE_WIDTH = 96;
uint256 private constant _BOUND_WIDTH = 16;
uint256 private constant _ADJUSTED_BOUND_WIDTH = 32;
// We allow the bounds to range over two orders of magnitude: 0.1 - 10. The maximum upper bound is set to 10.0
// in 18-decimal floating point, since this fits in 64 bits, and can be shifted down to 16 bit precision without
// much loss. Since compression would lose a lot of precision for values close to 0, we also constrain the lower
// bound to a minimum value >> 0.
//
// Since the adjusted bounds are (bound percentage)**(1 - weight), and weights are stored normalized, the
// maximum normalized weight is 1 - minimumWeight, which is 0.99 ~ 1. Therefore the adjusted bounds are likewise
// constrained to 10**1 ~ 10. So we can use this as the maximum value of both the raw percentage and
// weight-adjusted percentage bounds.
uint256 private constant _MIN_BOUND_PERCENTAGE = 1e17; // 0.1 in 18-decimal fixed point
uint256 private constant _MAX_BOUND_PERCENTAGE = 10e18; // 10.0 in 18-decimal fixed point
// Since we know the bounds fit into 64 bits, simply shifting them down to fit in 16 bits is not only faster than
// the compression and decompression operations, but generally less lossy.
uint256 private constant _BOUND_SHIFT_BITS = 64 - _BOUND_WIDTH;
/**
* @notice Returns the BPT price, reference weight, and the lower and upper percentage bounds for a given token.
* @dev If an upper or lower bound value is zero, it means there is no circuit breaker in that direction for the
* given token.
* @param circuitBreakerState - The bytes32 state of the token of interest.
*/
function getCircuitBreakerFields(bytes32 circuitBreakerState)
internal
pure
returns (
uint256 bptPrice,
uint256 referenceWeight,
uint256 lowerBound,
uint256 upperBound
)
{
bptPrice = circuitBreakerState.decodeUint(_BPT_PRICE_OFFSET, _BPT_PRICE_WIDTH);
referenceWeight = circuitBreakerState.decodeUint(_REFERENCE_WEIGHT_OFFSET, _REFERENCE_WEIGHT_WIDTH);
// Decompress the bounds by shifting left.
lowerBound = circuitBreakerState.decodeUint(_LOWER_BOUND_OFFSET, _BOUND_WIDTH) << _BOUND_SHIFT_BITS;
upperBound = circuitBreakerState.decodeUint(_UPPER_BOUND_OFFSET, _BOUND_WIDTH) << _BOUND_SHIFT_BITS;
}
/**
* @notice Returns a dynamic lower or upper BPT price bound for a given token, at the current weight.
* @dev The current BPT price of the token can be directly compared to this value, to determine whether
* the breaker should be tripped. If a bound is 0, it means there is no circuit breaker in that direction
* for this token: there might be a lower bound, but no upper bound. If the current BPT price is less than
* the lower bound, or greater than the non-zero upper bound, the transaction should revert.
*
* These BPT price bounds are dynamically adjusted by a non-linear factor dependent on the weight.
* In general: lower/upper BPT price bound = bptPrice * "weight adjustment". The weight adjustment is
* given as: (boundaryPercentage)**(1 - weight).
*
* For instance, given the 80/20 BAL/WETH pool with a 90% lower bound, the weight complement would be
* (1 - 0.8) = 0.2, so the lower adjusted bound would be (0.9 ** 0.2) ~ 0.9791. For the WETH token at 20%,
* the bound would be (0.9 ** 0.8) ~ 0.9192.
*
* With unequal weights (assuming a balanced pool), the balance of a higher-weight token will respond less
* to a proportional change in spot price than a lower weight token, which we might call "balance inertia".
*
* If the external price drops, all else being equal, the pool would be arbed until the percent drop in spot
* price equaled the external price drop. Since during this process the *internal* pool price would be
* above market, the arbers would sell cheap tokens to our poor unwitting pool at inflated prices, raising
* the balance of the depreciating token, and lowering the balance of another token (WETH in this example).
*
* Using weighted math, and assuming for simplicity that the sum of all weights is 1, you can compute the
* amountIn ratio for the arb trade as: (1/priceRatio) ** (1 - weight). For our 0.9 ratio and a weight of
* 0.8, this is ~ 1.0213. So if you had 8000 tokens before, the ending balance would be 8000*1.0213 ~ 8170.
* Note that the higher the weight, the lower this ratio is. That means the counterparty token is going
* out proportionally faster than the arb token is coming in: hence the non-linear relationship between
* spot price and BPT price.
*
* If we call the initial balance B0, and set k = (1/priceRatio) ** (1 - weight), the post-arb balance is
* given by: B1 = k * B0. Since the BPTPrice0 = totalSupply*weight/B0, and BPTPrice1 = totalSupply*weight/B1,
* we can combine these equations to compute the BPT price ratio BPTPrice1/BPTPrice0 = 1/k; BPT1 = BPT0/k.
* So we see that the "conversion factor" between the spot price ratio and BPT Price ratio can be written
* as above BPT1 = BPT0 * (1/k), or more simply: (BPT price) * (priceRatio)**(1 - weight).
*
* Another way to think of it is in terms of "BPT Value". Assuming a balanced pool, a token with a weight
* of 80% represents 80% of the value of the BPT. An uncorrelated drop in that token's value would drop
* the value of LP shares much faster than a similar drop in the value of a 20% token. Whatever the value
* of the bound percentage, as the adjustment factor - B ** (1 - weight) - approaches 1, less adjustment
* is necessary: it tracks the relative price movement more closely. Intuitively, this is wny we use the
* complement of the weight. Higher weight = lower exponent = adjustment factor closer to 1.0 = "faster"
* tracking of value changes.
*
* If the value of the weight has not changed, we can use the cached adjusted bounds stored when the breaker
* was set. Otherwise, we need to calculate them.
*
* As described in the general comments above, the weight adjustment calculation attempts to isolate changes
* in the balance due to arbitrageurs responding to external prices, from internal price changes caused by
* weight changes. There is a non-linear relationship between "spot" price changes and BPT price changes.
* This calculation transforms one into the other.
* @param circuitBreakerState - The bytes32 state of the token of interest.
* @param currentWeight - The token's current normalized weight.
* @param isLowerBound - Flag indicating whether this is the lower bound.
* @return - lower or upper bound BPT price, which can be directly compared against the current BPT price.
*/
function getBptPriceBound(
bytes32 circuitBreakerState,
uint256 currentWeight,
bool isLowerBound
) internal pure returns (uint256) {
uint256 bound = circuitBreakerState.decodeUint(
isLowerBound ? _LOWER_BOUND_OFFSET : _UPPER_BOUND_OFFSET,
_BOUND_WIDTH
) << _BOUND_SHIFT_BITS;
if (bound == 0) {
return 0;
}
// Retrieve the BPT price and reference weight passed in when the circuit breaker was set.
uint256 bptPrice = circuitBreakerState.decodeUint(_BPT_PRICE_OFFSET, _BPT_PRICE_WIDTH);
uint256 referenceWeight = circuitBreakerState.decodeUint(_REFERENCE_WEIGHT_OFFSET, _REFERENCE_WEIGHT_WIDTH);
uint256 boundRatio;
if (currentWeight == referenceWeight) {
// If the weight hasn't changed since the circuit breaker was set, we can use the precomputed
// adjusted bounds.
boundRatio = circuitBreakerState
.decodeUint(
isLowerBound ? _ADJUSTED_LOWER_BOUND_OFFSET : _ADJUSTED_UPPER_BOUND_OFFSET,
_ADJUSTED_BOUND_WIDTH
)
.decompress(_ADJUSTED_BOUND_WIDTH, _MAX_BOUND_PERCENTAGE);
} else {
// The weight has changed, so we retrieve the raw percentage bounds and do the full calculation.
// Decompress the bounds by shifting left.
boundRatio = CircuitBreakerLib.calcAdjustedBound(bound, currentWeight, isLowerBound);
}
// Use the adjusted bounds (either cached or computed) to calculate the BPT price bounds.
return CircuitBreakerLib.calcBptPriceBoundary(boundRatio, bptPrice, isLowerBound);
}
/**
* @notice Sets the reference BPT price, normalized weight, and upper and lower bounds for a token.
* @dev If a bound is zero, it means there is no circuit breaker in that direction for the given token.
* @param bptPrice: The BPT price of the token at the time the circuit breaker is set. The BPT Price
* of a token is generally given by: supply * weight / balance.
* @param referenceWeight: This is the current normalized weight of the token.
* @param lowerBound: The value of the lower bound, expressed as a percentage.
* @param upperBound: The value of the upper bound, expressed as a percentage.
*/
function setCircuitBreaker(
uint256 bptPrice,
uint256 referenceWeight,
uint256 lowerBound,
uint256 upperBound
) internal pure returns (bytes32) {
// It's theoretically not required for the lower bound to be < 1, but it wouldn't make much sense otherwise:
// the circuit breaker would immediately trip. Note that this explicitly allows setting either to 0, disabling
// the circuit breaker for the token in that direction.
_require(
lowerBound == 0 || (lowerBound >= _MIN_BOUND_PERCENTAGE && lowerBound <= FixedPoint.ONE),
Errors.INVALID_CIRCUIT_BREAKER_BOUNDS
);
_require(upperBound <= _MAX_BOUND_PERCENTAGE, Errors.INVALID_CIRCUIT_BREAKER_BOUNDS);
_require(upperBound == 0 || upperBound >= lowerBound, Errors.INVALID_CIRCUIT_BREAKER_BOUNDS);
// Set the reference parameters: BPT price of the token, and the reference weight.
bytes32 circuitBreakerState = bytes32(0).insertUint(bptPrice, _BPT_PRICE_OFFSET, _BPT_PRICE_WIDTH).insertUint(
referenceWeight,
_REFERENCE_WEIGHT_OFFSET,
_REFERENCE_WEIGHT_WIDTH
);
// Add the lower and upper percentage bounds. Compress by shifting right.
circuitBreakerState = circuitBreakerState
.insertUint(lowerBound >> _BOUND_SHIFT_BITS, _LOWER_BOUND_OFFSET, _BOUND_WIDTH)
.insertUint(upperBound >> _BOUND_SHIFT_BITS, _UPPER_BOUND_OFFSET, _BOUND_WIDTH);
// Precompute and store the adjusted bounds, used to convert percentage bounds to BPT price bounds.
// If the weight has not changed since the breaker was set, we can use the precomputed values directly,
// and avoid a heavy computation.
uint256 adjustedLowerBound = CircuitBreakerLib.calcAdjustedBound(lowerBound, referenceWeight, true);
uint256 adjustedUpperBound = CircuitBreakerLib.calcAdjustedBound(upperBound, referenceWeight, false);
// Finally, insert these computed adjusted bounds, and return the complete set of fields.
return
circuitBreakerState
.insertUint(
adjustedLowerBound.compress(_ADJUSTED_BOUND_WIDTH, _MAX_BOUND_PERCENTAGE),
_ADJUSTED_LOWER_BOUND_OFFSET,
_ADJUSTED_BOUND_WIDTH
)
.insertUint(
adjustedUpperBound.compress(_ADJUSTED_BOUND_WIDTH, _MAX_BOUND_PERCENTAGE),
_ADJUSTED_UPPER_BOUND_OFFSET,
_ADJUSTED_BOUND_WIDTH
);
}
/**
* @notice Update the cached adjusted bounds, given a new weight.
* @dev This might be used when weights are adjusted, pre-emptively updating the cache to improve performance
* of operations after the weight change completes. Note that this does not update the BPT price: this is still
* relative to the last call to `setCircuitBreaker`. The intent is only to optimize the automatic bounds
* adjustments due to changing weights.
*/
function updateAdjustedBounds(bytes32 circuitBreakerState, uint256 newReferenceWeight)
internal
pure
returns (bytes32)
{
uint256 adjustedLowerBound = CircuitBreakerLib.calcAdjustedBound(
circuitBreakerState.decodeUint(_LOWER_BOUND_OFFSET, _BOUND_WIDTH) << _BOUND_SHIFT_BITS,
newReferenceWeight,
true
);
uint256 adjustedUpperBound = CircuitBreakerLib.calcAdjustedBound(
circuitBreakerState.decodeUint(_UPPER_BOUND_OFFSET, _BOUND_WIDTH) << _BOUND_SHIFT_BITS,
newReferenceWeight,
false
);
// Replace the reference weight.
bytes32 result = circuitBreakerState.insertUint(
newReferenceWeight,
_REFERENCE_WEIGHT_OFFSET,
_REFERENCE_WEIGHT_WIDTH
);
// Update the cached adjusted bounds.
return
result
.insertUint(
adjustedLowerBound.compress(_ADJUSTED_BOUND_WIDTH, _MAX_BOUND_PERCENTAGE),
_ADJUSTED_LOWER_BOUND_OFFSET,
_ADJUSTED_BOUND_WIDTH
)
.insertUint(
adjustedUpperBound.compress(_ADJUSTED_BOUND_WIDTH, _MAX_BOUND_PERCENTAGE),
_ADJUSTED_UPPER_BOUND_OFFSET,
_ADJUSTED_BOUND_WIDTH
);
}
} | library CircuitBreakerStorageLib {
using ValueCompression for uint256;
using FixedPoint for uint256;
using WordCodec for bytes32;
// Store circuit breaker information per token
// When the circuit breaker is set, the caller passes in the lower and upper bounds (expressed as percentages),
// the current BPT price, and the normalized weight. The weight is bound by 1e18, and fits in ~60 bits, so there
// is no need for compression. We store the weight in 64 bits, just to use round numbers for all the bit lengths.
//
// We then store the current BPT price, and compute and cache the adjusted lower and upper bounds at the current
// weight. When multiplied by the stored BPT price, the adjusted bounds define the BPT price trading range: the
// "runtime" BPT prices can be directly compared to these BPT price bounds.
//
// Since the price bounds need to be adjusted for the token weight, in general these adjusted bounds would be
// computed every time. However, if the weight of the token has not changed since the circuit breaker was set,
// the adjusted bounds cache can still be used, avoiding a heavy computation.
//
// [ 32 bits | 32 bits | 96 bits | 64 bits | 16 bits | 16 bits |
// [ adjusted upper bound | adjusted lower bound | BPT price | reference weight | upper bound | lower bound |
// |MSB LSB|
uint256 private constant _LOWER_BOUND_OFFSET = 0;
uint256 private constant _UPPER_BOUND_OFFSET = _LOWER_BOUND_OFFSET + _BOUND_WIDTH;
uint256 private constant _REFERENCE_WEIGHT_OFFSET = _UPPER_BOUND_OFFSET + _BOUND_WIDTH;
uint256 private constant _BPT_PRICE_OFFSET = _REFERENCE_WEIGHT_OFFSET + _REFERENCE_WEIGHT_WIDTH;
uint256 private constant _ADJUSTED_LOWER_BOUND_OFFSET = _BPT_PRICE_OFFSET + _BPT_PRICE_WIDTH;
uint256 private constant _ADJUSTED_UPPER_BOUND_OFFSET = _ADJUSTED_LOWER_BOUND_OFFSET + _ADJUSTED_BOUND_WIDTH;
uint256 private constant _REFERENCE_WEIGHT_WIDTH = 64;
uint256 private constant _BPT_PRICE_WIDTH = 96;
uint256 private constant _BOUND_WIDTH = 16;
uint256 private constant _ADJUSTED_BOUND_WIDTH = 32;
// We allow the bounds to range over two orders of magnitude: 0.1 - 10. The maximum upper bound is set to 10.0
// in 18-decimal floating point, since this fits in 64 bits, and can be shifted down to 16 bit precision without
// much loss. Since compression would lose a lot of precision for values close to 0, we also constrain the lower
// bound to a minimum value >> 0.
//
// Since the adjusted bounds are (bound percentage)**(1 - weight), and weights are stored normalized, the
// maximum normalized weight is 1 - minimumWeight, which is 0.99 ~ 1. Therefore the adjusted bounds are likewise
// constrained to 10**1 ~ 10. So we can use this as the maximum value of both the raw percentage and
// weight-adjusted percentage bounds.
uint256 private constant _MIN_BOUND_PERCENTAGE = 1e17; // 0.1 in 18-decimal fixed point
uint256 private constant _MAX_BOUND_PERCENTAGE = 10e18; // 10.0 in 18-decimal fixed point
// Since we know the bounds fit into 64 bits, simply shifting them down to fit in 16 bits is not only faster than
// the compression and decompression operations, but generally less lossy.
uint256 private constant _BOUND_SHIFT_BITS = 64 - _BOUND_WIDTH;
/**
* @notice Returns the BPT price, reference weight, and the lower and upper percentage bounds for a given token.
* @dev If an upper or lower bound value is zero, it means there is no circuit breaker in that direction for the
* given token.
* @param circuitBreakerState - The bytes32 state of the token of interest.
*/
function getCircuitBreakerFields(bytes32 circuitBreakerState)
internal
pure
returns (
uint256 bptPrice,
uint256 referenceWeight,
uint256 lowerBound,
uint256 upperBound
)
{
bptPrice = circuitBreakerState.decodeUint(_BPT_PRICE_OFFSET, _BPT_PRICE_WIDTH);
referenceWeight = circuitBreakerState.decodeUint(_REFERENCE_WEIGHT_OFFSET, _REFERENCE_WEIGHT_WIDTH);
// Decompress the bounds by shifting left.
lowerBound = circuitBreakerState.decodeUint(_LOWER_BOUND_OFFSET, _BOUND_WIDTH) << _BOUND_SHIFT_BITS;
upperBound = circuitBreakerState.decodeUint(_UPPER_BOUND_OFFSET, _BOUND_WIDTH) << _BOUND_SHIFT_BITS;
}
/**
* @notice Returns a dynamic lower or upper BPT price bound for a given token, at the current weight.
* @dev The current BPT price of the token can be directly compared to this value, to determine whether
* the breaker should be tripped. If a bound is 0, it means there is no circuit breaker in that direction
* for this token: there might be a lower bound, but no upper bound. If the current BPT price is less than
* the lower bound, or greater than the non-zero upper bound, the transaction should revert.
*
* These BPT price bounds are dynamically adjusted by a non-linear factor dependent on the weight.
* In general: lower/upper BPT price bound = bptPrice * "weight adjustment". The weight adjustment is
* given as: (boundaryPercentage)**(1 - weight).
*
* For instance, given the 80/20 BAL/WETH pool with a 90% lower bound, the weight complement would be
* (1 - 0.8) = 0.2, so the lower adjusted bound would be (0.9 ** 0.2) ~ 0.9791. For the WETH token at 20%,
* the bound would be (0.9 ** 0.8) ~ 0.9192.
*
* With unequal weights (assuming a balanced pool), the balance of a higher-weight token will respond less
* to a proportional change in spot price than a lower weight token, which we might call "balance inertia".
*
* If the external price drops, all else being equal, the pool would be arbed until the percent drop in spot
* price equaled the external price drop. Since during this process the *internal* pool price would be
* above market, the arbers would sell cheap tokens to our poor unwitting pool at inflated prices, raising
* the balance of the depreciating token, and lowering the balance of another token (WETH in this example).
*
* Using weighted math, and assuming for simplicity that the sum of all weights is 1, you can compute the
* amountIn ratio for the arb trade as: (1/priceRatio) ** (1 - weight). For our 0.9 ratio and a weight of
* 0.8, this is ~ 1.0213. So if you had 8000 tokens before, the ending balance would be 8000*1.0213 ~ 8170.
* Note that the higher the weight, the lower this ratio is. That means the counterparty token is going
* out proportionally faster than the arb token is coming in: hence the non-linear relationship between
* spot price and BPT price.
*
* If we call the initial balance B0, and set k = (1/priceRatio) ** (1 - weight), the post-arb balance is
* given by: B1 = k * B0. Since the BPTPrice0 = totalSupply*weight/B0, and BPTPrice1 = totalSupply*weight/B1,
* we can combine these equations to compute the BPT price ratio BPTPrice1/BPTPrice0 = 1/k; BPT1 = BPT0/k.
* So we see that the "conversion factor" between the spot price ratio and BPT Price ratio can be written
* as above BPT1 = BPT0 * (1/k), or more simply: (BPT price) * (priceRatio)**(1 - weight).
*
* Another way to think of it is in terms of "BPT Value". Assuming a balanced pool, a token with a weight
* of 80% represents 80% of the value of the BPT. An uncorrelated drop in that token's value would drop
* the value of LP shares much faster than a similar drop in the value of a 20% token. Whatever the value
* of the bound percentage, as the adjustment factor - B ** (1 - weight) - approaches 1, less adjustment
* is necessary: it tracks the relative price movement more closely. Intuitively, this is wny we use the
* complement of the weight. Higher weight = lower exponent = adjustment factor closer to 1.0 = "faster"
* tracking of value changes.
*
* If the value of the weight has not changed, we can use the cached adjusted bounds stored when the breaker
* was set. Otherwise, we need to calculate them.
*
* As described in the general comments above, the weight adjustment calculation attempts to isolate changes
* in the balance due to arbitrageurs responding to external prices, from internal price changes caused by
* weight changes. There is a non-linear relationship between "spot" price changes and BPT price changes.
* This calculation transforms one into the other.
* @param circuitBreakerState - The bytes32 state of the token of interest.
* @param currentWeight - The token's current normalized weight.
* @param isLowerBound - Flag indicating whether this is the lower bound.
* @return - lower or upper bound BPT price, which can be directly compared against the current BPT price.
*/
function getBptPriceBound(
bytes32 circuitBreakerState,
uint256 currentWeight,
bool isLowerBound
) internal pure returns (uint256) {
uint256 bound = circuitBreakerState.decodeUint(
isLowerBound ? _LOWER_BOUND_OFFSET : _UPPER_BOUND_OFFSET,
_BOUND_WIDTH
) << _BOUND_SHIFT_BITS;
if (bound == 0) {
return 0;
}
// Retrieve the BPT price and reference weight passed in when the circuit breaker was set.
uint256 bptPrice = circuitBreakerState.decodeUint(_BPT_PRICE_OFFSET, _BPT_PRICE_WIDTH);
uint256 referenceWeight = circuitBreakerState.decodeUint(_REFERENCE_WEIGHT_OFFSET, _REFERENCE_WEIGHT_WIDTH);
uint256 boundRatio;
if (currentWeight == referenceWeight) {
// If the weight hasn't changed since the circuit breaker was set, we can use the precomputed
// adjusted bounds.
boundRatio = circuitBreakerState
.decodeUint(
isLowerBound ? _ADJUSTED_LOWER_BOUND_OFFSET : _ADJUSTED_UPPER_BOUND_OFFSET,
_ADJUSTED_BOUND_WIDTH
)
.decompress(_ADJUSTED_BOUND_WIDTH, _MAX_BOUND_PERCENTAGE);
} else {
// The weight has changed, so we retrieve the raw percentage bounds and do the full calculation.
// Decompress the bounds by shifting left.
boundRatio = CircuitBreakerLib.calcAdjustedBound(bound, currentWeight, isLowerBound);
}
// Use the adjusted bounds (either cached or computed) to calculate the BPT price bounds.
return CircuitBreakerLib.calcBptPriceBoundary(boundRatio, bptPrice, isLowerBound);
}
/**
* @notice Sets the reference BPT price, normalized weight, and upper and lower bounds for a token.
* @dev If a bound is zero, it means there is no circuit breaker in that direction for the given token.
* @param bptPrice: The BPT price of the token at the time the circuit breaker is set. The BPT Price
* of a token is generally given by: supply * weight / balance.
* @param referenceWeight: This is the current normalized weight of the token.
* @param lowerBound: The value of the lower bound, expressed as a percentage.
* @param upperBound: The value of the upper bound, expressed as a percentage.
*/
function setCircuitBreaker(
uint256 bptPrice,
uint256 referenceWeight,
uint256 lowerBound,
uint256 upperBound
) internal pure returns (bytes32) {
// It's theoretically not required for the lower bound to be < 1, but it wouldn't make much sense otherwise:
// the circuit breaker would immediately trip. Note that this explicitly allows setting either to 0, disabling
// the circuit breaker for the token in that direction.
_require(
lowerBound == 0 || (lowerBound >= _MIN_BOUND_PERCENTAGE && lowerBound <= FixedPoint.ONE),
Errors.INVALID_CIRCUIT_BREAKER_BOUNDS
);
_require(upperBound <= _MAX_BOUND_PERCENTAGE, Errors.INVALID_CIRCUIT_BREAKER_BOUNDS);
_require(upperBound == 0 || upperBound >= lowerBound, Errors.INVALID_CIRCUIT_BREAKER_BOUNDS);
// Set the reference parameters: BPT price of the token, and the reference weight.
bytes32 circuitBreakerState = bytes32(0).insertUint(bptPrice, _BPT_PRICE_OFFSET, _BPT_PRICE_WIDTH).insertUint(
referenceWeight,
_REFERENCE_WEIGHT_OFFSET,
_REFERENCE_WEIGHT_WIDTH
);
// Add the lower and upper percentage bounds. Compress by shifting right.
circuitBreakerState = circuitBreakerState
.insertUint(lowerBound >> _BOUND_SHIFT_BITS, _LOWER_BOUND_OFFSET, _BOUND_WIDTH)
.insertUint(upperBound >> _BOUND_SHIFT_BITS, _UPPER_BOUND_OFFSET, _BOUND_WIDTH);
// Precompute and store the adjusted bounds, used to convert percentage bounds to BPT price bounds.
// If the weight has not changed since the breaker was set, we can use the precomputed values directly,
// and avoid a heavy computation.
uint256 adjustedLowerBound = CircuitBreakerLib.calcAdjustedBound(lowerBound, referenceWeight, true);
uint256 adjustedUpperBound = CircuitBreakerLib.calcAdjustedBound(upperBound, referenceWeight, false);
// Finally, insert these computed adjusted bounds, and return the complete set of fields.
return
circuitBreakerState
.insertUint(
adjustedLowerBound.compress(_ADJUSTED_BOUND_WIDTH, _MAX_BOUND_PERCENTAGE),
_ADJUSTED_LOWER_BOUND_OFFSET,
_ADJUSTED_BOUND_WIDTH
)
.insertUint(
adjustedUpperBound.compress(_ADJUSTED_BOUND_WIDTH, _MAX_BOUND_PERCENTAGE),
_ADJUSTED_UPPER_BOUND_OFFSET,
_ADJUSTED_BOUND_WIDTH
);
}
/**
* @notice Update the cached adjusted bounds, given a new weight.
* @dev This might be used when weights are adjusted, pre-emptively updating the cache to improve performance
* of operations after the weight change completes. Note that this does not update the BPT price: this is still
* relative to the last call to `setCircuitBreaker`. The intent is only to optimize the automatic bounds
* adjustments due to changing weights.
*/
function updateAdjustedBounds(bytes32 circuitBreakerState, uint256 newReferenceWeight)
internal
pure
returns (bytes32)
{
uint256 adjustedLowerBound = CircuitBreakerLib.calcAdjustedBound(
circuitBreakerState.decodeUint(_LOWER_BOUND_OFFSET, _BOUND_WIDTH) << _BOUND_SHIFT_BITS,
newReferenceWeight,
true
);
uint256 adjustedUpperBound = CircuitBreakerLib.calcAdjustedBound(
circuitBreakerState.decodeUint(_UPPER_BOUND_OFFSET, _BOUND_WIDTH) << _BOUND_SHIFT_BITS,
newReferenceWeight,
false
);
// Replace the reference weight.
bytes32 result = circuitBreakerState.insertUint(
newReferenceWeight,
_REFERENCE_WEIGHT_OFFSET,
_REFERENCE_WEIGHT_WIDTH
);
// Update the cached adjusted bounds.
return
result
.insertUint(
adjustedLowerBound.compress(_ADJUSTED_BOUND_WIDTH, _MAX_BOUND_PERCENTAGE),
_ADJUSTED_LOWER_BOUND_OFFSET,
_ADJUSTED_BOUND_WIDTH
)
.insertUint(
adjustedUpperBound.compress(_ADJUSTED_BOUND_WIDTH, _MAX_BOUND_PERCENTAGE),
_ADJUSTED_UPPER_BOUND_OFFSET,
_ADJUSTED_BOUND_WIDTH
);
}
} | 22,112 |
115 | // Add time lock, only locker can add/ | function _addTimeLock(address account, uint amount, uint expiresAt) internal {
require(amount > 0, "Time Lock: lock amount must be greater than 0");
require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now");
_timeLocks[account].push(TimeLock(amount, expiresAt));
emit TimeLocked(account);
}
| function _addTimeLock(address account, uint amount, uint expiresAt) internal {
require(amount > 0, "Time Lock: lock amount must be greater than 0");
require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now");
_timeLocks[account].push(TimeLock(amount, expiresAt));
emit TimeLocked(account);
}
| 4,354 |
24 | // modifier used to keep track of the dynamic rewards for user each time a deposit or withdraw is made | modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = calculateRewards(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
| modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = calculateRewards(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
| 22,557 |
129 | // ensure all the arrays in the vault are valid | require(_vault.shortOtokens.length <= 1, "MarginCalculator: Too many short otokens in the vault");
require(_vault.longOtokens.length <= 1, "MarginCalculator: Too many long otokens in the vault");
require(_vault.collateralAssets.length <= 1, "MarginCalculator: Too many collateral assets in the vault");
require(
_vault.shortOtokens.length == _vault.shortAmounts.length,
"MarginCalculator: Short asset and amount mismatch"
);
require(
_vault.longOtokens.length == _vault.longAmounts.length,
| require(_vault.shortOtokens.length <= 1, "MarginCalculator: Too many short otokens in the vault");
require(_vault.longOtokens.length <= 1, "MarginCalculator: Too many long otokens in the vault");
require(_vault.collateralAssets.length <= 1, "MarginCalculator: Too many collateral assets in the vault");
require(
_vault.shortOtokens.length == _vault.shortAmounts.length,
"MarginCalculator: Short asset and amount mismatch"
);
require(
_vault.longOtokens.length == _vault.longAmounts.length,
| 24,411 |
0 | // / | uint public feePercentage;
bool public buysAllowed = true;
| uint public feePercentage;
bool public buysAllowed = true;
| 19,387 |
17 | // Emitted when the validator set is updated./nonce Nonce./powerThreshold New voting power threshold./validatorSetHash Hash of new validator set./ See `updateValidatorSet`. | event ValidatorSetUpdatedEvent(uint256 indexed nonce, uint256 powerThreshold, bytes32 validatorSetHash);
| event ValidatorSetUpdatedEvent(uint256 indexed nonce, uint256 powerThreshold, bytes32 validatorSetHash);
| 52,773 |
105 | // {RoleAdminChanged} not being emitted signaling this. _Available since v3.1._/ | event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
| event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
| 36,189 |
18 | // have we got proven consensus? | if(witnessCount >= acceptanceTreshold) {
break;
}
| if(witnessCount >= acceptanceTreshold) {
break;
}
| 10,902 |
81 | // Set max delay time for each token/tokens list of tokens to set max delay/maxDelays list of max delay times to set to | function setMaxDelayTimes(address[] calldata tokens, uint[] calldata maxDelays) external onlyGov {
require(tokens.length == maxDelays.length, 'tokens & maxDelays length mismatched');
for (uint idx = 0; idx < tokens.length; idx++) {
maxDelayTimes[tokens[idx]] = maxDelays[idx];
emit SetMaxDelayTime(tokens[idx], maxDelays[idx]);
}
}
| function setMaxDelayTimes(address[] calldata tokens, uint[] calldata maxDelays) external onlyGov {
require(tokens.length == maxDelays.length, 'tokens & maxDelays length mismatched');
for (uint idx = 0; idx < tokens.length; idx++) {
maxDelayTimes[tokens[idx]] = maxDelays[idx];
emit SetMaxDelayTime(tokens[idx], maxDelays[idx]);
}
}
| 22,766 |
2 | // Array of ERC20 interfaces for balancer flashloan | IERC20[] public globalTokens;
| IERC20[] public globalTokens;
| 21,147 |
120 | // - shift information to the left by a specified number of bits_val - value to be shifted_shift - number of bits to shift return - `_val` shifted `_shift` bits to the left, i.e. multiplied by 2`_shift` | function shiftLeft(uint _val, uint _shift) private pure returns (uint) {
return _val * uint(2)**_shift;
}
| function shiftLeft(uint _val, uint _shift) private pure returns (uint) {
return _val * uint(2)**_shift;
}
| 19,782 |
577 | // Converts an internal asset cash value to its underlying token value./ar exchange rate object between asset and underlying/assetBalance amount to convert to underlying | function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance)
internal
pure
returns (int256)
| function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance)
internal
pure
returns (int256)
| 3,749 |
20 | // Allows to create market after successful funding/ return Market address | function createMarket()
public
timedTransitions
atStage(Stages.AuctionSuccessful)
returns (Market)
| function createMarket()
public
timedTransitions
atStage(Stages.AuctionSuccessful)
returns (Market)
| 32,311 |
116 | // Attempt to transfer the total Dai balance to the caller. | _transferMax(_DAI, msg.sender, true);
| _transferMax(_DAI, msg.sender, true);
| 16,731 |
6 | // calculate the trailing zeros on the binary representation of the number | if (d << 128 == 0) {
d >>= 128;
s += 128;
}
| if (d << 128 == 0) {
d >>= 128;
s += 128;
}
| 9,748 |
22 | // transfer erc1155 to seller | IERC1155(token).safeTransferFrom(address(this), seller, id, 1, new bytes(0x0));
ended = true;
| IERC1155(token).safeTransferFrom(address(this), seller, id, 1, new bytes(0x0));
ended = true;
| 3,743 |
24 | // ---------------------------------- External Functions---------------------------------- | function setCycleStatusTo_allocateWinner() public onlyWhenInitialising{
cycleStatus = CycleStatus.allocateWinner;
}
| function setCycleStatusTo_allocateWinner() public onlyWhenInitialising{
cycleStatus = CycleStatus.allocateWinner;
}
| 6,106 |
140 | // reverse-for-loops with unsigned integer/ solium-disable-next-line security/no-modify-for-iter-var / take last decimal digit | bstr[i] = bytes1(uint8(ASCII_ZERO + (j % 10)));
| bstr[i] = bytes1(uint8(ASCII_ZERO + (j % 10)));
| 31,706 |
98 | // Performs transfer from an included account to an excluded account.(included and excluded from receiving reward.) / | function _transferToExcluded(address sender, address recipient, ValuesFromAmount memory values) private {
_reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount;
_tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount;
_reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount;
}
| function _transferToExcluded(address sender, address recipient, ValuesFromAmount memory values) private {
_reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount;
_tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount;
_reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount;
}
| 20,625 |
14 | // 提交人命令清单,数组单向增加 | mapping(address => uint256[]) submitterCmds;
| mapping(address => uint256[]) submitterCmds;
| 35,148 |
251 | // reset lockup | totalLockedUpRewards = totalLockedUpRewards.sub(user.rewardLockedUp);
user.rewardLockedUp = 0;
user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval);
| totalLockedUpRewards = totalLockedUpRewards.sub(user.rewardLockedUp);
user.rewardLockedUp = 0;
user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval);
| 24,602 |
271 | // initialize storage variables on a new G-UNI pool, only called once/_name name of Vault (immutable)/_symbol symbol of Vault (immutable)/_pool address of Uniswap V3 pool (immutable)/_managerFeeBPS proportion of fees earned that go to manager treasury/_lowerTick initial lowerTick (only changeable with executiveRebalance)/_lowerTick initial upperTick (only changeable with executiveRebalance)/_manager_ address of manager (ownership can be transferred) | function initialize(
string memory _name,
string memory _symbol,
address _pool,
uint16 _managerFeeBPS,
int24 _lowerTick,
int24 _upperTick,
address _manager_
| function initialize(
string memory _name,
string memory _symbol,
address _pool,
uint16 _managerFeeBPS,
int24 _lowerTick,
int24 _upperTick,
address _manager_
| 61,510 |
0 | // int public num = 129; | int public people = 0;
| int public people = 0;
| 46,515 |
4 | // UpgradeabilityStorage This contract holds all the necessary state variables to support the upgrade functionality / | contract UpgradeabilityStorage {
// Version name of the current implementation
string internal _version;
// Address of the current implementation
address internal _implementation;
/**
* @dev Tells the version name of the current implementation
* @return string representing the name of the current version
*/
function version() public view returns (string) {
return _version;
}
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view returns (address) {
return _implementation;
}
}
| contract UpgradeabilityStorage {
// Version name of the current implementation
string internal _version;
// Address of the current implementation
address internal _implementation;
/**
* @dev Tells the version name of the current implementation
* @return string representing the name of the current version
*/
function version() public view returns (string) {
return _version;
}
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view returns (address) {
return _implementation;
}
}
| 20,506 |
14 | // Returns the integer division of two unsigned integers, reverting with custom message ondivision by zero. The result is rounded towards zero. CAUTION: This function is deprecated because it requires allocating memory for the error | * 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 Solidity
* uses 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;
}
| * 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 Solidity
* uses 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;
}
| 1,144 |
25 | // Returns x1/z1x2/z2=(x1x2)/(z1z2), in projective coordinates on P¹(𝔽ₙ) | function projectiveMul(uint256 x1, uint256 z1, uint256 x2, uint256 z2)
| function projectiveMul(uint256 x1, uint256 z1, uint256 x2, uint256 z2)
| 30,376 |
622 | // A list of all of the vaults. The last element of the list is the vault that is currently being used for/ deposits and withdraws. Vaults before the last element are considered inactive and are expected to be cleared. | Vault.List private _vaults;
| Vault.List private _vaults;
| 35,759 |
437 | // Returns the downcasted int120 from int256, reverting onoverflow (when the input is less than smallest int120 orgreater than largest int120). Counterpart to Solidity's `int120` operator. Requirements: - input must fit into 120 bits / | function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
| function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
| 36,511 |
66 | // _____ _ _ | struct RoundData{
//tracks ownership of the territories
//encoded in 8bit such that 0=noncolonized and the remaining 255 values reference a team
//32 territories fit each entry, for a total of 3232, there are only 3231 territories
//the one that corresponds to the nonexisting ID=0 remains empty
uint256[101] owners;
mapping(address=>uint16) teamXaddr; //return team by address
//keep track of the rolls to split the pot
mapping(uint16=>uint256) validrollsXteam; // number of valid rolls by team
mapping(address=>uint256) validrollsXaddr; //valid rolls by address
mapping(uint16=>uint256) teampotshare; //money that each team gets at the end of the round is stored here
mapping(uint16=>bytes32) nationnameXteam;
uint256 pot;
//1xRGB for map display color
mapping(uint16=>uint256) colorXteam;
//track which colors are registered
mapping(uint256=>bool) iscolorregistered;
mapping(bytes32=>bool) isnameregistered; //avoid duplicate nation names within a same round
//counter
uint16 teamcnt;
//timers
uint256 roundstart;
//these settings can be modified by admin to balance if required, will get into effect when a new round is started
uint16 beginterritories; //number of territories to claim at createnation
uint16 maxroll;// = 6;
uint256 trucetime;
uint256 price;
uint256 maxextensiontruce;
bytes32 winner;
}
| struct RoundData{
//tracks ownership of the territories
//encoded in 8bit such that 0=noncolonized and the remaining 255 values reference a team
//32 territories fit each entry, for a total of 3232, there are only 3231 territories
//the one that corresponds to the nonexisting ID=0 remains empty
uint256[101] owners;
mapping(address=>uint16) teamXaddr; //return team by address
//keep track of the rolls to split the pot
mapping(uint16=>uint256) validrollsXteam; // number of valid rolls by team
mapping(address=>uint256) validrollsXaddr; //valid rolls by address
mapping(uint16=>uint256) teampotshare; //money that each team gets at the end of the round is stored here
mapping(uint16=>bytes32) nationnameXteam;
uint256 pot;
//1xRGB for map display color
mapping(uint16=>uint256) colorXteam;
//track which colors are registered
mapping(uint256=>bool) iscolorregistered;
mapping(bytes32=>bool) isnameregistered; //avoid duplicate nation names within a same round
//counter
uint16 teamcnt;
//timers
uint256 roundstart;
//these settings can be modified by admin to balance if required, will get into effect when a new round is started
uint16 beginterritories; //number of territories to claim at createnation
uint16 maxroll;// = 6;
uint256 trucetime;
uint256 price;
uint256 maxextensiontruce;
bytes32 winner;
}
| 12,515 |
22 | // Update reward variables of the given pool. _pid The index of the pool. See `poolInfo`.return pool Returns the pool that was updated. / | function updatePool(uint256 _pid) public returns (PoolInfo memory pool) {
pool = poolInfo[_pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 rewardsTotal = rewardsSchedule.getRewardsForBlockRange(pool.lastRewardBlock, block.number);
uint256 poolReward = rewardsTotal.mul(pool.allocPoint) / totalAllocPoint;
pool.accRewardsPerShare = pool.accRewardsPerShare.add((poolReward.mul(ACC_REWARDS_PRECISION) / lpSupply).to128());
}
pool.lastRewardBlock = block.number.to64();
poolInfo[_pid] = pool;
emit LogUpdatePool(_pid, pool.lastRewardBlock, lpSupply, pool.accRewardsPerShare);
}
}
| function updatePool(uint256 _pid) public returns (PoolInfo memory pool) {
pool = poolInfo[_pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 rewardsTotal = rewardsSchedule.getRewardsForBlockRange(pool.lastRewardBlock, block.number);
uint256 poolReward = rewardsTotal.mul(pool.allocPoint) / totalAllocPoint;
pool.accRewardsPerShare = pool.accRewardsPerShare.add((poolReward.mul(ACC_REWARDS_PRECISION) / lpSupply).to128());
}
pool.lastRewardBlock = block.number.to64();
poolInfo[_pid] = pool;
emit LogUpdatePool(_pid, pool.lastRewardBlock, lpSupply, pool.accRewardsPerShare);
}
}
| 17,340 |
43 | // Auction finishes successfully above the reserve/Transfer contract funds to initialized wallet. | function finalize() public nonReentrant {
require(
hasAdminRole(msg.sender) ||
wallet == msg.sender ||
hasSmartContractRole(msg.sender) ||
finalizeTimeExpired(),
"BatchAuction: Sender must be admin"
);
require(
!marketStatus.finalized,
"BatchAuction: Auction has already finalized"
);
require(
block.timestamp > marketInfo.endTime,
"BatchAuction: Auction has not finished yet"
);
if (auctionSuccessful()) {
/// @dev Successful auction
/// @dev Transfer contributed tokens to wallet.
_safeTokenPayment(
paymentCurrency,
wallet,
uint256(marketStatus.commitmentsTotal)
);
} else {
/// @dev Failed auction
/// @dev Return auction tokens back to wallet.
_safeTokenPayment(auctionToken, wallet, marketInfo.totalTokens);
}
marketStatus.finalized = true;
startReleaseTime = block.timestamp;
emit AuctionFinalized();
}
| function finalize() public nonReentrant {
require(
hasAdminRole(msg.sender) ||
wallet == msg.sender ||
hasSmartContractRole(msg.sender) ||
finalizeTimeExpired(),
"BatchAuction: Sender must be admin"
);
require(
!marketStatus.finalized,
"BatchAuction: Auction has already finalized"
);
require(
block.timestamp > marketInfo.endTime,
"BatchAuction: Auction has not finished yet"
);
if (auctionSuccessful()) {
/// @dev Successful auction
/// @dev Transfer contributed tokens to wallet.
_safeTokenPayment(
paymentCurrency,
wallet,
uint256(marketStatus.commitmentsTotal)
);
} else {
/// @dev Failed auction
/// @dev Return auction tokens back to wallet.
_safeTokenPayment(auctionToken, wallet, marketInfo.totalTokens);
}
marketStatus.finalized = true;
startReleaseTime = block.timestamp;
emit AuctionFinalized();
}
| 60,408 |
40 | // Destroys `amount` tokens from `account`, reducing thetotal supply. Emits a {Transfer} event with `to` set to the zero address. Requirements: - `account` cannot be the zero address.- `account` must have at least `amount` tokens. / | function _burn(address account, uint256 amount) internal virtual {
| function _burn(address account, uint256 amount) internal virtual {
| 2,199 |
6 | // Treasury address | address public treasury;
| address public treasury;
| 34,224 |
8 | // STORAGE //A mapping from car IDs to the address that owns them. All cars have/some valid owner address. | mapping (uint256 => address) public carIndexToOwner;
| mapping (uint256 => address) public carIndexToOwner;
| 46,420 |
22 | // Add share of fees | amount0 = burned0.add(fees0.mul(shares).div(totalSupply));
amount1 = burned1.add(fees1.mul(shares).div(totalSupply));
| amount0 = burned0.add(fees0.mul(shares).div(totalSupply));
amount1 = burned1.add(fees1.mul(shares).div(totalSupply));
| 23,312 |
152 | // Gas-optimized version of the `getPriorVotes` function -it accepts IDs of checkpoints to look for votes data as of the given block in(if the checkpoints miss the data, it get searched through all checkpoints recorded) Call (off-chain) the `findCheckpoints` function to get needed IDs account The address of the account to get votes for blockNumber The block number to get votes at userCheckpointId ID of the checkpoint to look for the user data first userCheckpointId ID of the checkpoint to look for the shared data firstreturn The number of votes the account had as of the given block / | function _getPriorVotes(
address account,
uint256 blockNumber,
uint32 userCheckpointId,
uint32 sharedCheckpointId
| function _getPriorVotes(
address account,
uint256 blockNumber,
uint32 userCheckpointId,
uint32 sharedCheckpointId
| 32,037 |
79 | // | function transferFrom(
address sender,
address recipient,
uint256 amount////////////////////////////////////////////////////////////////////////////////////////////////////////
| function transferFrom(
address sender,
address recipient,
uint256 amount////////////////////////////////////////////////////////////////////////////////////////////////////////
| 44,892 |
70 | // Internal function to set the ACO Pool maximum number of open ACOs allowed. newMaximumOpenAco Value of the new ACO Pool maximum number of open ACOs allowed. / | function _setAcoPoolMaximumOpenAco(uint256 newMaximumOpenAco) internal virtual {
emit SetAcoPoolMaximumOpenAco(acoPoolMaximumOpenAco, newMaximumOpenAco);
acoPoolMaximumOpenAco = newMaximumOpenAco;
}
| function _setAcoPoolMaximumOpenAco(uint256 newMaximumOpenAco) internal virtual {
emit SetAcoPoolMaximumOpenAco(acoPoolMaximumOpenAco, newMaximumOpenAco);
acoPoolMaximumOpenAco = newMaximumOpenAco;
}
| 36,365 |
223 | // external token transfer from a specific account_externalToken the token contract_from the account to spend token from_to the destination address_value the amount of tokens to transfer return bool which represents success/ | function externalTokenTransferFrom(
StandardToken _externalToken,
address _from,
address _to,
uint _value
)
public onlyOwner returns(bool)
| function externalTokenTransferFrom(
StandardToken _externalToken,
address _from,
address _to,
uint _value
)
public onlyOwner returns(bool)
| 20,617 |
21 | // High level token purchase function / | function() payable {
buyTokens(msg.sender);
}
| function() payable {
buyTokens(msg.sender);
}
| 32,405 |
149 | // Convex Finance Yield Bearing Vault/joeysantoro | contract ConvexERC4626 is ERC4626, RewardsClaimer {
using SafeTransferLib for ERC20;
/// @notice The Convex Booster contract (for deposit/withdraw)
IConvexBooster public immutable convexBooster;
/// @notice The Convex Rewards contract (for claiming rewards)
IConvexBaseRewardPool public immutable convexRewards;
/// @notice Convex token
ERC20 CVX = ERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B);
uint256 public immutable pid;
/**
@notice Creates a new Vault that accepts a specific underlying token.
@param _asset The ERC20 compliant token the Vault should accept.
@param _name The name for the vault token.
@param _symbol The symbol for the vault token.
@param _convexBooster The Convex Booster contract (for deposit/withdraw).
@param _convexRewards The Convex Rewards contract (for claiming rewards).
@param _rewardsDestination the address to send CRV and CVX.
@param _rewardTokens the rewards tokens to send out.
*/
constructor(
ERC20 _asset,
string memory _name,
string memory _symbol,
IConvexBooster _convexBooster,
IConvexBaseRewardPool _convexRewards,
address _rewardsDestination,
ERC20[] memory _rewardTokens
)
ERC4626(_asset, _name, _symbol)
RewardsClaimer(_rewardsDestination, _rewardTokens)
{
convexBooster = _convexBooster;
convexRewards = _convexRewards;
pid = _convexRewards.pid();
_asset.approve(address(_convexBooster), type(uint256).max);
}
function updateRewardTokens() public {
uint256 len = convexRewards.extraRewardsLength();
require(len < 5, "exceed max rewards");
delete rewardTokens;
bool cvxReward;
for (uint256 i = 0; i < len; i++) {
rewardTokens.push(convexRewards.extraRewards(i).rewardToken());
if (convexRewards.extraRewards(i).rewardToken() == CVX) cvxReward = true;
}
if (!cvxReward) rewardTokens.push(CVX);
rewardTokens.push(convexRewards.rewardToken());
}
function afterDeposit(uint256 amount, uint256) internal override {
require(convexBooster.deposit(pid, amount, true), "deposit error");
}
function beforeWithdraw(uint256 amount, uint256) internal override {
require(convexRewards.withdrawAndUnwrap(amount, false), "withdraw error");
}
function beforeClaim() internal override {
require(convexRewards.getReward(address(this), true), "rewards error");
}
/// @notice Calculates the total amount of underlying tokens the Vault holds.
/// @return The total amount of underlying tokens the Vault holds.
function totalAssets() public view override returns (uint256) {
return convexRewards.balanceOf(address(this));
}
} | contract ConvexERC4626 is ERC4626, RewardsClaimer {
using SafeTransferLib for ERC20;
/// @notice The Convex Booster contract (for deposit/withdraw)
IConvexBooster public immutable convexBooster;
/// @notice The Convex Rewards contract (for claiming rewards)
IConvexBaseRewardPool public immutable convexRewards;
/// @notice Convex token
ERC20 CVX = ERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B);
uint256 public immutable pid;
/**
@notice Creates a new Vault that accepts a specific underlying token.
@param _asset The ERC20 compliant token the Vault should accept.
@param _name The name for the vault token.
@param _symbol The symbol for the vault token.
@param _convexBooster The Convex Booster contract (for deposit/withdraw).
@param _convexRewards The Convex Rewards contract (for claiming rewards).
@param _rewardsDestination the address to send CRV and CVX.
@param _rewardTokens the rewards tokens to send out.
*/
constructor(
ERC20 _asset,
string memory _name,
string memory _symbol,
IConvexBooster _convexBooster,
IConvexBaseRewardPool _convexRewards,
address _rewardsDestination,
ERC20[] memory _rewardTokens
)
ERC4626(_asset, _name, _symbol)
RewardsClaimer(_rewardsDestination, _rewardTokens)
{
convexBooster = _convexBooster;
convexRewards = _convexRewards;
pid = _convexRewards.pid();
_asset.approve(address(_convexBooster), type(uint256).max);
}
function updateRewardTokens() public {
uint256 len = convexRewards.extraRewardsLength();
require(len < 5, "exceed max rewards");
delete rewardTokens;
bool cvxReward;
for (uint256 i = 0; i < len; i++) {
rewardTokens.push(convexRewards.extraRewards(i).rewardToken());
if (convexRewards.extraRewards(i).rewardToken() == CVX) cvxReward = true;
}
if (!cvxReward) rewardTokens.push(CVX);
rewardTokens.push(convexRewards.rewardToken());
}
function afterDeposit(uint256 amount, uint256) internal override {
require(convexBooster.deposit(pid, amount, true), "deposit error");
}
function beforeWithdraw(uint256 amount, uint256) internal override {
require(convexRewards.withdrawAndUnwrap(amount, false), "withdraw error");
}
function beforeClaim() internal override {
require(convexRewards.getReward(address(this), true), "rewards error");
}
/// @notice Calculates the total amount of underlying tokens the Vault holds.
/// @return The total amount of underlying tokens the Vault holds.
function totalAssets() public view override returns (uint256) {
return convexRewards.balanceOf(address(this));
}
} | 40,949 |
19 | // you return the tkenID | return voucher.tokenId;
| return voucher.tokenId;
| 33,267 |
17 | // Check block existing | require(
!blockExisting[blockHash],
"Relay block failed: block already relayed"
);
| require(
!blockExisting[blockHash],
"Relay block failed: block already relayed"
);
| 17,476 |
218 | // Stores a new beacon in the EIP1967 beacon slot. / | function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
| function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
| 5,123 |
21 | // ERC20 balance | assertEq(erc20.balanceOf(address(tokenOwner)), 10 ether);
assertEq(erc20.balanceOf(address(multiwrap)), 0);
| assertEq(erc20.balanceOf(address(tokenOwner)), 10 ether);
assertEq(erc20.balanceOf(address(multiwrap)), 0);
| 4,901 |
164 | // Allows the owner to update configuration variables / | function configUnlock(
| function configUnlock(
| 32,258 |
260 | // calculates the health factor from the corresponding balancescollateralBalanceETH the total collateral balance in ETHborrowBalanceETH the total borrow balance in ETHtotalFeesETH the total fees in ETHliquidationThreshold the avg liquidation threshold/ | ) internal pure returns (uint256) {
if (borrowBalanceETH == 0) return uint256(-1);
return
(collateralBalanceETH.mul(liquidationThreshold).div(100)).wadDiv(
borrowBalanceETH.add(totalFeesETH)
);
}
| ) internal pure returns (uint256) {
if (borrowBalanceETH == 0) return uint256(-1);
return
(collateralBalanceETH.mul(liquidationThreshold).div(100)).wadDiv(
borrowBalanceETH.add(totalFeesETH)
);
}
| 6,911 |
24 | // INSTANT CASHBACK base cashback + 1% for each deposit >= 3 AVAX | if(msg.value >= 3 ether) {
user.cashbackBonus = user.cashbackBonus + 10;
}
| if(msg.value >= 3 ether) {
user.cashbackBonus = user.cashbackBonus + 10;
}
| 5,666 |
36 | // Sets the reference to the market oracle. marketOracle_ The address of the market oracle contract. / | function setMarketOracle(IOracle marketOracle_)
external
onlyOwner
| function setMarketOracle(IOracle marketOracle_)
external
onlyOwner
| 26,411 |
24 | // send message to deBridge gate | {
deBridgeGate.send{value: msg.value}(
| {
deBridgeGate.send{value: msg.value}(
| 7,963 |
12 | // Calculates the last block number according to available funds / | function getFinalBlockNumber() public view returns (uint256) {
//in case reward token == stake token
uint256 sameTokenAmount = address(rewardToken) == address(stakeToken)
? stakeTotalShares * pricePerShare()
: 0;
uint256 firstBlock = stakeTotalShares == 0
? block.number
: lastRewardBlock;
uint256 contractBalance = rewardToken.balanceOf(address(this)) -
sameTokenAmount;
return
firstBlock +
(contractBalance - totalPendingReward) /
rewardPerBlock;
}
| function getFinalBlockNumber() public view returns (uint256) {
//in case reward token == stake token
uint256 sameTokenAmount = address(rewardToken) == address(stakeToken)
? stakeTotalShares * pricePerShare()
: 0;
uint256 firstBlock = stakeTotalShares == 0
? block.number
: lastRewardBlock;
uint256 contractBalance = rewardToken.balanceOf(address(this)) -
sameTokenAmount;
return
firstBlock +
(contractBalance - totalPendingReward) /
rewardPerBlock;
}
| 3,987 |
51 | // The contract takes the ERC20 coin address from which this contract will work and from the owner (Team wallet) who owns the funds. | function Allocation(IRightAndRoles _rightAndRoles,ERC20Basic _token, uint256 _unlockPart1, uint256 _unlockPart2) GuidedByRoles(_rightAndRoles) public{
unlockPart1 = _unlockPart1;
unlockPart2 = _unlockPart2;
token = _token;
}
| function Allocation(IRightAndRoles _rightAndRoles,ERC20Basic _token, uint256 _unlockPart1, uint256 _unlockPart2) GuidedByRoles(_rightAndRoles) public{
unlockPart1 = _unlockPart1;
unlockPart2 = _unlockPart2;
token = _token;
}
| 61,874 |
36 | // Transfer token to a specified address. to The address to transfer to. value The amount to be transferred. / | function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
// Normal Transfer
_transfer(msg.sender, to, value);
return true;
}
| function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
// Normal Transfer
_transfer(msg.sender, to, value);
return true;
}
| 19,913 |
10 | // called once by the factory at time of deployment | function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'Moonswap: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
| function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'Moonswap: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
| 1,063 |
59 | // Internal functions //Updates account info and reverts if daily limit is breached/account Address of account./amount Amount of tokens account needing to transfer./ return boolean. | function _enforceLimit(address account, uint amount)
internal
| function _enforceLimit(address account, uint amount)
internal
| 10,860 |
24 | // Handle the receipt of multiple ERC1155 token types An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updatedThis function MAY throw to revert and reject the transferReturn of other amount than the magic value WILL result in the transaction being revertedNote: The token contract address is always the message sender _operatorThe address which called the `safeBatchTransferFrom` function _fromThe address which previously owned the token _ids An array containing ids of each token being transferred _amounts An array containing amounts of each token being transferred _dataAdditional | function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4);
| function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4);
| 11,503 |
41 | // Chamge allowed margin tokens | function allowMarginToken(address token, bool alw) public onlyOwner
| function allowMarginToken(address token, bool alw) public onlyOwner
| 43,108 |
4 | // functions callable by HolyRedeemer yield distributor | function harvestYield(uint256 amount) external; // pool would transfer amount tokens from caller as it's profits
| function harvestYield(uint256 amount) external; // pool would transfer amount tokens from caller as it's profits
| 50,770 |
361 | // Circular linked list | struct Node {
StakeData data;
uint prev;
uint next;
}
| struct Node {
StakeData data;
uint prev;
uint next;
}
| 8,653 |
52 | // calculate support amount in USD | uint supportedAmount = msg.value.mul(rate.ETH_USD_rate()).div(10**18);
| uint supportedAmount = msg.value.mul(rate.ETH_USD_rate()).div(10**18);
| 37,375 |
0 | // exchanges like ApeSwap renamed uniswapV2Call | bytes memory payload = abi.encodePacked(this.uniswapV2Call.selector, input[4:]);
(bool success,) = address(this).delegatecall(payload);
require(success, "uniswapV2Call failed");
| bytes memory payload = abi.encodePacked(this.uniswapV2Call.selector, input[4:]);
(bool success,) = address(this).delegatecall(payload);
require(success, "uniswapV2Call failed");
| 35,171 |
298 | // {ERC721} token factory ("NFTFactory"), including: address of creator => NFT contract address | mapping(address => NFT[]) nftMap;
| mapping(address => NFT[]) nftMap;
| 15,671 |
53 | // override ERC721RestrictApprove | function addLocalContractAllowList(
address transferer
| function addLocalContractAllowList(
address transferer
| 15,867 |
33 | // FarmRewards solace.fi Rewards farmers with [SOLACE](./SOLACE). Rewards were accumulated by farmers for participating in farms. Rewards will be unlocked linearly over six months and can be redeemed for [SOLACE](./SOLACE) by paying $0.03/[SOLACE](./SOLACE). / | contract FarmRewards is IFarmRewards, ReentrancyGuard, Governable {
/// @notice xSOLACE Token.
address public override xsolace;
/// @notice receiver for payments
address public override receiver;
/// @notice timestamp that rewards start vesting
uint256 constant public override vestingStart = 1638316800; // midnight UTC before December 1, 2021
/// @notice timestamp that rewards finish vesting
uint256 constant public override vestingEnd = 1651363200; // midnight UTC before May 1, 2022
uint256 public override solacePerXSolace;
/// @notice The stablecoins that can be used for payment.
mapping(address => bool) public override tokenInSupported;
/// @notice Total farmed rewards of a farmer.
mapping(address => uint256) public override farmedRewards;
/// @notice Redeemed rewards of a farmer.
mapping(address => uint256) public override redeemedRewards;
/**
* @notice Constructs the `FarmRewards` contract.
* @param governance_ The address of the [governor](/docs/protocol/governance).
* @param xsolace_ Address of [**xSOLACE**](./xSOLACE).
* @param receiver_ Address to send proceeds.
* @param solacePerXSolace_ The amount of [**SOLACE**](./SOLACE) for one [**xSOLACE**](./xSOLACE).
*/
constructor(address governance_, address xsolace_, address receiver_, uint256 solacePerXSolace_) Governable(governance_) {
require(xsolace_ != address(0x0), "zero address xsolace");
require(receiver_ != address(0x0), "zero address receiver");
xsolace = xsolace_;
receiver = receiver_;
solacePerXSolace = solacePerXSolace_;
}
/***************************************
VIEW FUNCTIONS
***************************************/
/**
* @notice Calculates the amount of token in needed for an amount of [**xSOLACE**](./xSOLACE) out.
* @param tokenIn The token to pay with.
* @param amountOut The amount of [**xSOLACE**](./xSOLACE) wanted.
* @return amountIn The amount of `tokenIn` needed.
*/
function calculateAmountIn(address tokenIn, uint256 amountOut) external view override returns (uint256 amountIn) {
// check token support
require(tokenInSupported[tokenIn], "token in not supported");
// calculate xsolace out @ $0.03/SOLACE
uint256 pricePerSolace = 3 * (10 ** (ERC20(tokenIn).decimals() - 2)); // usd/solace
uint256 pricePerXSolace = pricePerSolace * solacePerXSolace / 1 ether; // usd/xsolace
amountIn = amountOut * pricePerXSolace / 1 ether;
return amountIn;
}
/**
* @notice Calculates the amount of [**xSOLACE**](./xSOLACE) out for an amount of token in.
* @param tokenIn The token to pay with.
* @param amountIn The amount of `tokenIn` in.
* @return amountOut The amount of [**xSOLACE**](./xSOLACE) out.
*/
function calculateAmountOut(address tokenIn, uint256 amountIn) external view override returns (uint256 amountOut) {
// check token support
require(tokenInSupported[tokenIn], "token in not supported");
// calculate xsolace out @ $0.03/SOLACE
uint256 pricePerSolace = 3 * (10 ** (ERC20(tokenIn).decimals() - 2)); // usd/solace
uint256 pricePerXSolace = pricePerSolace * solacePerXSolace / 1 ether; // usd/xsolace
amountOut = amountIn * 1 ether / pricePerXSolace;
return amountOut;
}
/**
* @notice The amount of [**xSOLACE**](./xSOLACE) that a farmer has vested.
* Does not include the amount they've already redeemed.
* @param farmer The farmer to query.
* @return amount The amount of vested [**xSOLACE**](./xSOLACE).
*/
function purchaseableVestedXSolace(address farmer) public view override returns (uint256 amount) {
uint256 timestamp = block.timestamp;
uint256 totalRewards = farmedRewards[farmer];
uint256 totalVestedAmount = (timestamp >= vestingEnd)
? totalRewards // fully vested
: (totalRewards * (timestamp - vestingStart) / (vestingEnd - vestingStart)); // partially vested
amount = totalVestedAmount - redeemedRewards[farmer];
return amount;
}
/***************************************
MUTATOR FUNCTIONS
***************************************/
/**
* @notice Deposit tokens to redeem rewards.
* @param tokenIn The token to use as payment.
* @param amountIn The max amount to pay.
*/
function redeem(address tokenIn, uint256 amountIn) external override nonReentrant {
// accounting
amountIn = _redeem(tokenIn, amountIn, msg.sender);
// pull tokens
SafeERC20.safeTransferFrom(IERC20(tokenIn), msg.sender, receiver, amountIn);
}
/**
* @notice Deposit tokens to redeem rewards.
* @param tokenIn The token to use as payment.
* @param amountIn The max amount to pay.
* @param depositor The farmer that deposits.
* @param deadline Time the transaction must go through before.
* @param v secp256k1 signature
* @param r secp256k1 signature
* @param s secp256k1 signature
*/
function redeemSigned(address tokenIn, uint256 amountIn, address depositor, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override nonReentrant {
// permit
ERC20Permit(tokenIn).permit(depositor, address(this), amountIn, deadline, v, r, s);
// accounting
amountIn = _redeem(tokenIn, amountIn, depositor);
// pull tokens
SafeERC20.safeTransferFrom(IERC20(tokenIn), depositor, receiver, amountIn);
}
/**
* @notice Redeems a farmers rewards.
* @param tokenIn The token to use as payment.
* @param amountIn The max amount to pay.
* @param depositor The farmer that deposits.
* @return actualAmountIn The amount of tokens used.
*/
function _redeem(address tokenIn, uint256 amountIn, address depositor) internal returns (uint256 actualAmountIn) {
// check token support
require(tokenInSupported[tokenIn], "token in not supported");
// calculate xsolace out @ $0.03/SOLACE
uint256 pricePerSolace = 3 * (10 ** (ERC20(tokenIn).decimals() - 2)); // usd/solace
uint256 pricePerXSolace = pricePerSolace * solacePerXSolace / 1 ether; // usd/xsolace
uint256 xsolaceOut = amountIn * 1 ether / pricePerXSolace;
// verify xsolace rewards
uint256 vestedXSolace_ = purchaseableVestedXSolace(depositor);
if(xsolaceOut > vestedXSolace_) {
xsolaceOut = vestedXSolace_;
// calculate amount in for max solace
actualAmountIn = xsolaceOut * pricePerXSolace / 1 ether;
} else {
actualAmountIn = amountIn;
}
// reward
SafeERC20.safeTransfer(IERC20(xsolace), depositor, xsolaceOut);
// record
redeemedRewards[depositor] += xsolaceOut;
return actualAmountIn;
}
/***************************************
GOVERNANCE FUNCTIONS
***************************************/
/**
* @notice Adds support for tokens. Should be stablecoins.
* Can only be called by the current [**governor**](/docs/protocol/governance).
* @param tokens The tokens to add support for.
*/
function supportTokens(address[] calldata tokens) external override onlyGovernance {
for(uint256 i = 0; i < tokens.length; ++i) {
address token = tokens[i];
require(token != address(0x0), "zero address token");
tokenInSupported[token] = true;
}
}
/**
* @notice Sets the recipient for proceeds.
* Can only be called by the current [**governor**](/docs/protocol/governance).
* @param receiver_ The new recipient.
*/
function setReceiver(address payable receiver_) external override onlyGovernance {
require(receiver_ != address(0x0), "zero address receiver");
receiver = receiver_;
emit ReceiverSet(receiver_);
}
/**
* @notice Returns excess [**xSOLACE**](./xSOLACE).
* Can only be called by the current [**governor**](/docs/protocol/governance).
* @param amount Amount to send. Will be sent from this contract to `receiver`.
*/
function returnXSolace(uint256 amount) external override onlyGovernance {
SafeERC20.safeTransfer(IERC20(xsolace), receiver, amount);
}
/**
* @notice Sets the rewards that farmers have earned.
* Can only be called by the current [**governor**](/docs/protocol/governance).
* @param farmers Array of farmers to set.
* @param rewards Array of rewards to set.
*/
function setFarmedRewards(address[] calldata farmers, uint256[] calldata rewards) external override onlyGovernance {
require(farmers.length == rewards.length, "length mismatch");
for(uint256 i = 0; i < farmers.length; i++) {
farmedRewards[farmers[i]] = rewards[i];
}
}
}
| contract FarmRewards is IFarmRewards, ReentrancyGuard, Governable {
/// @notice xSOLACE Token.
address public override xsolace;
/// @notice receiver for payments
address public override receiver;
/// @notice timestamp that rewards start vesting
uint256 constant public override vestingStart = 1638316800; // midnight UTC before December 1, 2021
/// @notice timestamp that rewards finish vesting
uint256 constant public override vestingEnd = 1651363200; // midnight UTC before May 1, 2022
uint256 public override solacePerXSolace;
/// @notice The stablecoins that can be used for payment.
mapping(address => bool) public override tokenInSupported;
/// @notice Total farmed rewards of a farmer.
mapping(address => uint256) public override farmedRewards;
/// @notice Redeemed rewards of a farmer.
mapping(address => uint256) public override redeemedRewards;
/**
* @notice Constructs the `FarmRewards` contract.
* @param governance_ The address of the [governor](/docs/protocol/governance).
* @param xsolace_ Address of [**xSOLACE**](./xSOLACE).
* @param receiver_ Address to send proceeds.
* @param solacePerXSolace_ The amount of [**SOLACE**](./SOLACE) for one [**xSOLACE**](./xSOLACE).
*/
constructor(address governance_, address xsolace_, address receiver_, uint256 solacePerXSolace_) Governable(governance_) {
require(xsolace_ != address(0x0), "zero address xsolace");
require(receiver_ != address(0x0), "zero address receiver");
xsolace = xsolace_;
receiver = receiver_;
solacePerXSolace = solacePerXSolace_;
}
/***************************************
VIEW FUNCTIONS
***************************************/
/**
* @notice Calculates the amount of token in needed for an amount of [**xSOLACE**](./xSOLACE) out.
* @param tokenIn The token to pay with.
* @param amountOut The amount of [**xSOLACE**](./xSOLACE) wanted.
* @return amountIn The amount of `tokenIn` needed.
*/
function calculateAmountIn(address tokenIn, uint256 amountOut) external view override returns (uint256 amountIn) {
// check token support
require(tokenInSupported[tokenIn], "token in not supported");
// calculate xsolace out @ $0.03/SOLACE
uint256 pricePerSolace = 3 * (10 ** (ERC20(tokenIn).decimals() - 2)); // usd/solace
uint256 pricePerXSolace = pricePerSolace * solacePerXSolace / 1 ether; // usd/xsolace
amountIn = amountOut * pricePerXSolace / 1 ether;
return amountIn;
}
/**
* @notice Calculates the amount of [**xSOLACE**](./xSOLACE) out for an amount of token in.
* @param tokenIn The token to pay with.
* @param amountIn The amount of `tokenIn` in.
* @return amountOut The amount of [**xSOLACE**](./xSOLACE) out.
*/
function calculateAmountOut(address tokenIn, uint256 amountIn) external view override returns (uint256 amountOut) {
// check token support
require(tokenInSupported[tokenIn], "token in not supported");
// calculate xsolace out @ $0.03/SOLACE
uint256 pricePerSolace = 3 * (10 ** (ERC20(tokenIn).decimals() - 2)); // usd/solace
uint256 pricePerXSolace = pricePerSolace * solacePerXSolace / 1 ether; // usd/xsolace
amountOut = amountIn * 1 ether / pricePerXSolace;
return amountOut;
}
/**
* @notice The amount of [**xSOLACE**](./xSOLACE) that a farmer has vested.
* Does not include the amount they've already redeemed.
* @param farmer The farmer to query.
* @return amount The amount of vested [**xSOLACE**](./xSOLACE).
*/
function purchaseableVestedXSolace(address farmer) public view override returns (uint256 amount) {
uint256 timestamp = block.timestamp;
uint256 totalRewards = farmedRewards[farmer];
uint256 totalVestedAmount = (timestamp >= vestingEnd)
? totalRewards // fully vested
: (totalRewards * (timestamp - vestingStart) / (vestingEnd - vestingStart)); // partially vested
amount = totalVestedAmount - redeemedRewards[farmer];
return amount;
}
/***************************************
MUTATOR FUNCTIONS
***************************************/
/**
* @notice Deposit tokens to redeem rewards.
* @param tokenIn The token to use as payment.
* @param amountIn The max amount to pay.
*/
function redeem(address tokenIn, uint256 amountIn) external override nonReentrant {
// accounting
amountIn = _redeem(tokenIn, amountIn, msg.sender);
// pull tokens
SafeERC20.safeTransferFrom(IERC20(tokenIn), msg.sender, receiver, amountIn);
}
/**
* @notice Deposit tokens to redeem rewards.
* @param tokenIn The token to use as payment.
* @param amountIn The max amount to pay.
* @param depositor The farmer that deposits.
* @param deadline Time the transaction must go through before.
* @param v secp256k1 signature
* @param r secp256k1 signature
* @param s secp256k1 signature
*/
function redeemSigned(address tokenIn, uint256 amountIn, address depositor, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override nonReentrant {
// permit
ERC20Permit(tokenIn).permit(depositor, address(this), amountIn, deadline, v, r, s);
// accounting
amountIn = _redeem(tokenIn, amountIn, depositor);
// pull tokens
SafeERC20.safeTransferFrom(IERC20(tokenIn), depositor, receiver, amountIn);
}
/**
* @notice Redeems a farmers rewards.
* @param tokenIn The token to use as payment.
* @param amountIn The max amount to pay.
* @param depositor The farmer that deposits.
* @return actualAmountIn The amount of tokens used.
*/
function _redeem(address tokenIn, uint256 amountIn, address depositor) internal returns (uint256 actualAmountIn) {
// check token support
require(tokenInSupported[tokenIn], "token in not supported");
// calculate xsolace out @ $0.03/SOLACE
uint256 pricePerSolace = 3 * (10 ** (ERC20(tokenIn).decimals() - 2)); // usd/solace
uint256 pricePerXSolace = pricePerSolace * solacePerXSolace / 1 ether; // usd/xsolace
uint256 xsolaceOut = amountIn * 1 ether / pricePerXSolace;
// verify xsolace rewards
uint256 vestedXSolace_ = purchaseableVestedXSolace(depositor);
if(xsolaceOut > vestedXSolace_) {
xsolaceOut = vestedXSolace_;
// calculate amount in for max solace
actualAmountIn = xsolaceOut * pricePerXSolace / 1 ether;
} else {
actualAmountIn = amountIn;
}
// reward
SafeERC20.safeTransfer(IERC20(xsolace), depositor, xsolaceOut);
// record
redeemedRewards[depositor] += xsolaceOut;
return actualAmountIn;
}
/***************************************
GOVERNANCE FUNCTIONS
***************************************/
/**
* @notice Adds support for tokens. Should be stablecoins.
* Can only be called by the current [**governor**](/docs/protocol/governance).
* @param tokens The tokens to add support for.
*/
function supportTokens(address[] calldata tokens) external override onlyGovernance {
for(uint256 i = 0; i < tokens.length; ++i) {
address token = tokens[i];
require(token != address(0x0), "zero address token");
tokenInSupported[token] = true;
}
}
/**
* @notice Sets the recipient for proceeds.
* Can only be called by the current [**governor**](/docs/protocol/governance).
* @param receiver_ The new recipient.
*/
function setReceiver(address payable receiver_) external override onlyGovernance {
require(receiver_ != address(0x0), "zero address receiver");
receiver = receiver_;
emit ReceiverSet(receiver_);
}
/**
* @notice Returns excess [**xSOLACE**](./xSOLACE).
* Can only be called by the current [**governor**](/docs/protocol/governance).
* @param amount Amount to send. Will be sent from this contract to `receiver`.
*/
function returnXSolace(uint256 amount) external override onlyGovernance {
SafeERC20.safeTransfer(IERC20(xsolace), receiver, amount);
}
/**
* @notice Sets the rewards that farmers have earned.
* Can only be called by the current [**governor**](/docs/protocol/governance).
* @param farmers Array of farmers to set.
* @param rewards Array of rewards to set.
*/
function setFarmedRewards(address[] calldata farmers, uint256[] calldata rewards) external override onlyGovernance {
require(farmers.length == rewards.length, "length mismatch");
for(uint256 i = 0; i < farmers.length; i++) {
farmedRewards[farmers[i]] = rewards[i];
}
}
}
| 37,248 |
27 | // this is a boring normal card | if (s.darkBG == 1) {
color = _colorsLight[s.color];
gradient = _gradientsDark[s.gradient];
gradientDesc = _gradientsDarkDesc[s.gradient];
} else {
| if (s.darkBG == 1) {
color = _colorsLight[s.color];
gradient = _gradientsDark[s.gradient];
gradientDesc = _gradientsDarkDesc[s.gradient];
} else {
| 42,731 |
13 | // EFFECTS (checks already handled by modifiers) | selector = selector_;
| selector = selector_;
| 38,485 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.