Verified contractExactMIT
LockingPositionServiceV3
Address0xc809e0729d7ea45b1ce6149baab79991e2cb1262
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 250 runs
- EVM version
- cancun
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 20,435,758
- Creation transaction
- 0xc6ccdee459…b60b30c833
43 files
- contracts/Locking/LockingPositionServiceV3.solmain43.46 KB
- @chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol592 B
- @openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol2.54 KB
- @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol3.17 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol6.64 KB
- @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol9.38 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.48 KB
- @openzeppelin/contracts/interfaces/IERC20Metadata.sol178 B
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.74 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- @openzeppelin/contracts/token/ERC721/IERC721.sol4.88 KB
- @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol1.02 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol853 B
- contracts/interfaces/IBondCalculator.sol480 B
- contracts/interfaces/IBondDepository.sol820 B
- contracts/interfaces/IBondLogo.sol805 B
- contracts/interfaces/IBondPositionManager.sol940 B
- contracts/interfaces/IBondStruct.sol4.58 KB
- contracts/interfaces/ICommonStruct.sol340 B
- contracts/interfaces/ICvg.sol1.66 KB
- contracts/interfaces/ICvgControlTower.sol3.91 KB
- contracts/interfaces/ICvgOracle.sol1.67 KB
- contracts/interfaces/ICvgRewards.sol853 B
- contracts/interfaces/IERC20Mintable.sol422 B
- contracts/interfaces/IGaugeController.sol1.46 KB
- contracts/interfaces/ILockingLogo.sol1.09 KB
- contracts/interfaces/ILockingPositionDelegate.sol1.71 KB
- contracts/interfaces/ILockingPositionManager.sol958 B
- contracts/interfaces/ILockingPositionService.sol4.25 KB
- contracts/interfaces/IOracleStruct.sol1.96 KB
- contracts/interfaces/IPresaleCvgSeed.sol2.22 KB
- contracts/interfaces/ISdAssets.sol2.25 KB
- contracts/interfaces/ISdtBlackHole.sol605 B
- contracts/interfaces/ISdtBuffer.sol544 B
- contracts/interfaces/ISdtFeeCollector.sol479 B
- contracts/interfaces/ISdtRewardDistributor.sol409 B
- contracts/interfaces/ISdtStakingLogo.sol966 B
- contracts/interfaces/ISdtStakingPositionManager.sol1.21 KB
- contracts/interfaces/ISdtStakingPositionService.sol2.09 KB
- contracts/interfaces/IVestingCvg.sol1.14 KB
- contracts/interfaces/IVotingPowerEscrow.sol639 B
- contracts/interfaces/IYsDistributor.sol719 B
- contracts/interfaces/IYsStreamer.sol1.57 KB
contracts/Locking/LockingPositionServiceV3.sol
// SPDX-License-Identifier: MIT
/**
_____
/ __ \
| / \/ ___ _ ____ _____ _ __ __ _ ___ _ __ ___ ___
| | / _ \| '_ \ \ / / _ \ '__/ _` |/ _ \ '_ \ / __/ _ \
| \__/\ (_) | | | \ V / __/ | | (_| | __/ | | | (_| __/
\____/\___/|_| |_|\_/ \___|_| \__, |\___|_| |_|\___\___|
__/ |
|___/
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/ICvgControlTower.sol";
import "../interfaces/ILockingPositionService.sol";
import "../interfaces/IYsStreamer.sol";
/**
* @title Cvg-Finance - LockingPositionService
* @notice Allows to lock CVG, gives yield and governance power.
* @dev When a position is minted, the amount can be split between 2 different type of CVG :
* veCVG : used for voting power ( associated with MgCVG meta-governance voting power )
* | ysCVG : used for treasury shares( allow the user to claim a part of the treasury at each TDE ( treasury distribution event ) )
* | the amount of ys/Ve the user will receive for each CVG locked is proportional with the duration of the lock.
*/
contract LockingPositionServiceV3 is Ownable2StepUpgradeable {
event MintLockingPosition(uint256 tokenId, ILockingPositionService.LockingPosition lockingPosition);
event IncreaseLockAmount(uint256 tokenId, ILockingPositionService.LockingPosition lockingPosition);
event IncreaseLockTime(
uint256 tokenId,
ILockingPositionService.LockingPosition lockingPosition,
uint256 oldEndCycle
);
event IncreaseLockTimeAndAmount(
uint256 tokenId,
ILockingPositionService.LockingPosition lockingPosition,
uint256 oldEndCycle
);
event UpdateTotalSupplies(uint256 newYsSupply, uint256 veCvgSupply, uint256 cycle);
event LockingPositionBurn(uint256 tokenId);
/// @dev Maximum locking time in cycle(weeks)
uint256 internal constant MAX_LOCK = 96;
uint256 internal constant MAX_PERCENTAGE = 100;
uint256 internal constant MAX_LOCK_MUL_MAX_PERCENTAGE = 9_600;
/// @dev TDE duration in weeks
uint256 internal constant TDE_DURATION = 12;
/// @dev percentage can only be set as multiple of this value
uint256 internal constant RANGE_PERCENTAGE = 10;
/// @dev Convergence ControlTower.
ICvgControlTower public cvgControlTower;
/// @dev Convergence CVG.
ICvg public cvg;
/// @dev Voting Power Escrow.
IVotingPowerEscrow public veCvg;
/// @dev Locking Position Manager
ILockingPositionManager public lockingPositionManager;
/// @dev Locking Position Delegate
ILockingPositionDelegate public lockingPositionDelegate;
/// @dev Cvg Rewards
ICvgRewards public cvgRewards;
/// @dev Keeps global data of a LockingPosition.
mapping(uint256 => ILockingPositionService.LockingPosition) public lockingPositions; // tokenId => LockingPosition
mapping(uint256 => ILockingPositionService.Checkpoints[]) public checkpoints; // tokenId => ysCheckpoints
/// @dev Keep track of the ySCvg supply changes for each cycle, so we can compute the totalSupply of ysCvg at each cycle.
mapping(uint256 => ILockingPositionService.TrackingBalance) public totalSuppliesTracking;
/// @dev Keep track of the ysCvg supply at each cycle.
mapping(uint256 => uint256) public totalSupplyYsCvgHistories;
/// @dev Multisig or contracts able to lock CVG
mapping(address => bool) public isContractLocker; // Address => bool
/// @dev Special contracts able to ( bonds for instance ) chaining locking.
mapping(address => bool) public isSpecialLocker; // Address => bool
///@dev STORAGE V2 STARTS HERE
/// @dev YsStreamer contract
IYsStreamer constant ysStreamer = IYsStreamer(0x660A45986E9b8F60C41AadeBD2941724200FBCF8);
bool public isLockActive;
/**
* @dev Some methods that are called by wallet ,
* can also be called by cvgUtilities meta functionalities
* this modifier allow to check both case.
*/
modifier onlyWalletOrWhiteListedContract() {
_onlyWalletOrWhiteListedContract();
_;
}
/**
* @notice Check if the caller is a wallet or a whitelisted contract.
*/
function _onlyWalletOrWhiteListedContract() internal view {
require(
// solhint-disable-next-line avoid-tx-origin
msg.sender == tx.origin || isContractLocker[msg.sender],
"NOT_CONTRACT_OR_WL"
);
}
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
INFO
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-= */
struct LockingInfo {
uint256 tokenId;
uint256 cvgLocked;
uint256 lockEnd;
uint256 ysPercentage;
uint256 mgCvg;
}
/**
* @notice Get position information for a given tokenId, used by the CVG display of the token.
* @param tokenId is the token ID of the position.
*/
function lockingInfo(uint256 tokenId) external view returns (LockingInfo memory) {
uint256 _cvgCycle = cvgControlTower.cvgCycle();
ILockingPositionService.LockingPosition memory _lockingPosition = lockingPositions[tokenId];
uint256 tokenLastEndCycle = _lockingPosition.lastEndCycle;
return
LockingInfo({
tokenId: tokenId,
cvgLocked: _lockingPosition.totalCvgLocked,
lockEnd: tokenLastEndCycle,
ysPercentage: _lockingPosition.ysPercentage,
mgCvg: _cvgCycle > tokenLastEndCycle ? 0 : _lockingPosition.mgCvgAmount
});
}
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
PUBLIC FUNCTIONS
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-= */
/**
* @notice Mint a locking position (ERC721) for the user.
* @dev Lock can't be greater than the Maximum locking time / The end of the lock must finish on a TDE event cycle | The percentage of ys determines the repartition in veCVG,mgCVG/YsCVG.
* @param lockDuration is the duration in cycle(week) of the lock.
* @param amount is the amount of cvg to lock in the position.
* @param ysPercentage percentage of lock dedicated to treasury shares (ysCVG).
* @param receiver address of the receiver of the locking position.
* @param isAddToManagedTokens add the created token in managed tokens(voting power) directly.
*/
function mintPosition(
uint24 lockDuration,
uint128 amount,
uint8 ysPercentage,
address receiver,
bool isAddToManagedTokens
) external onlyWalletOrWhiteListedContract {
require(isLockActive, "LOCKS_ARE_PAUSED");
require(amount > 0, "LTE");
/** @dev Percentage cannot be over 100%. */
require(ysPercentage <= MAX_PERCENTAGE, "YS_%_OVER_100");
/** @dev Only percentage with multiple of 10 are possible to use. */
require(ysPercentage % RANGE_PERCENTAGE == 0, "YS_%_10_MULTIPLE");
/** @dev Lock cannot be longer than MAX_LOCK. */
require(lockDuration <= MAX_LOCK, "MAX_LOCK_96_CYCLES");
/// @dev Lock duration cannot be zero
require(lockDuration != 0, "LOCK_DURATION_ZERO");
/** @dev Retrieve actual staking cycle. */
uint24 actualCycle = uint24(cvgRewards.getCycleLocking(block.timestamp));
uint24 endLockCycle = actualCycle + lockDuration;
/** @dev End of lock must finish on TDE. */
require(endLockCycle % TDE_DURATION == 0, "END_MUST_BE_TDE_MULTIPLE");
/// @dev get the nextId on the LockingPosition manager
uint256 tokenId = lockingPositionManager.mint(receiver);
uint96 _mgCvgCreated;
/// @dev Update checkpoints for YsCvg TotalSupply and Supply by NFT.
if (ysPercentage != 0) {
_ysCvgCheckpointMint(tokenId, lockDuration, amount * ysPercentage, actualCycle, endLockCycle);
}
/// @dev Create voting power through Curve contract, link voting power to the token (NFT).
if (ysPercentage != MAX_PERCENTAGE) {
uint256 amountVote = amount * (MAX_PERCENTAGE - ysPercentage);
/// @dev Creates the lock until the end of the ending cycle.
/// @dev Unlocking is available at the beginning of endCycle+1
veCvg.create_lock(
tokenId,
amountVote / MAX_PERCENTAGE,
block.timestamp + (uint256(lockDuration) + 1) * 7 days
);
/// @dev compute the amount of mgCvg
_mgCvgCreated = uint96((amountVote * lockDuration) / MAX_LOCK_MUL_MAX_PERCENTAGE);
/// @dev Automatically add the veCVG and mgCVG in the balance taken from Snapshot.
if (isAddToManagedTokens) {
lockingPositionDelegate.addTokenAtMint(tokenId, receiver);
}
}
ILockingPositionService.LockingPosition memory lockingPosition = ILockingPositionService.LockingPosition({
startCycle: actualCycle,
lastEndCycle: endLockCycle,
totalCvgLocked: uint104(amount),
mgCvgAmount: _mgCvgCreated,
ysPercentage: ysPercentage
});
/// @dev Associate this Locking position on the tokenId.
lockingPositions[tokenId] = lockingPosition;
/// @dev Transfer CVG from user wallet to here.
cvg.transferFrom(msg.sender, address(this), amount);
if (ysPercentage != 0) {
ysStreamer.checkInFromLocking(tokenId, actualCycle);
}
emit MintLockingPosition(tokenId, lockingPosition);
}
/**
* @notice Increase the amount of CVG token in the locking position proportionally from the actual cycle to the end of lock.
* @dev We don't check the timelocking on the TokenId on this function, as an amount increase cannot be detrimental to a potential buyer.
* @param tokenId is the token ID of the position to extend
* @param amount of cvg to add to the position
* @param operator address of token owner (used when call from a special Locker contract)
*/
function increaseLockAmount(
uint256 tokenId,
uint128 amount,
address operator
) external onlyWalletOrWhiteListedContract {
require(isLockActive, "LOCKS_ARE_PAUSED");
operator = isSpecialLocker[msg.sender] ? operator : msg.sender;
lockingPositionManager.checkOwnership(tokenId, operator);
require(amount > 0, "LTE");
ILockingPositionService.LockingPosition memory lockingPosition = lockingPositions[tokenId];
/// @dev Retrieve actual staking cycle. */
uint24 actualCycle = uint24(cvgRewards.getCycleLocking(block.timestamp));
/// @dev Impossible to increase the lock in amount after the end of the lock. */
require(lockingPosition.lastEndCycle > actualCycle, "LOCK_OVER");
/// @dev YsCvg TotalSupply Part, access only if some % has been given to ys on the NFT.
if (lockingPosition.ysPercentage != 0) {
_ysCvgCheckpointIncrease(
tokenId,
lockingPosition.lastEndCycle - actualCycle,
amount * lockingPosition.ysPercentage,
actualCycle,
lockingPosition.lastEndCycle
);
}
/** @dev Update voting power through Curve contract, link voting power to the nft tokenId. */
if (lockingPosition.ysPercentage != MAX_PERCENTAGE) {
uint256 amountVote = amount * (MAX_PERCENTAGE - lockingPosition.ysPercentage);
veCvg.increase_amount(tokenId, amountVote / MAX_PERCENTAGE);
lockingPosition.mgCvgAmount += uint96(
(amountVote * (lockingPosition.lastEndCycle - actualCycle)) / MAX_LOCK_MUL_MAX_PERCENTAGE
);
}
/** @dev Update cvgLocked balance. */
lockingPosition.totalCvgLocked += uint104(amount);
lockingPositions[tokenId] = lockingPosition;
/** @dev Transfer CVG from user wallet to here. */
cvg.transferFrom(msg.sender, address(this), amount);
if (lockingPosition.ysPercentage != 0) {
ysStreamer.checkInFromLocking(tokenId, actualCycle);
}
emit IncreaseLockAmount(tokenId, lockingPosition);
}
/**
* @notice Increase the time of the lock
* Increasing the locking time will not increase the amount of ysCvg & mgCvg
* The amounts will be just extended on the new duration.
* @dev The token must not be time locked , as an increase in time can be detrimental to a potential buyer.
* @param tokenId is the token ID of the position
* @param durationAdd is the number of cycle to add to the position lockingTime
*/
function increaseLockTime(uint256 tokenId, uint256 durationAdd) external onlyWalletOrWhiteListedContract {
require(isLockActive, "LOCKS_ARE_PAUSED");
lockingPositionManager.checkFullCompliance(tokenId, msg.sender);
/// @dev Retrieve actual staking cycle.
uint24 actualCycle = uint24(cvgRewards.getCycleLocking(block.timestamp));
ILockingPositionService.LockingPosition memory lockingPosition = lockingPositions[tokenId];
uint256 oldEndCycle = lockingPosition.lastEndCycle + 1;
uint256 newEndCycle = oldEndCycle + durationAdd;
/// @dev Not possible extend a lock in duration after it's expiration.
require(oldEndCycle > actualCycle, "LOCK_TIME_OVER");
/// @dev Not possible to have an active lock longer than the MAX_LOCK.
require(newEndCycle - actualCycle - 1 <= MAX_LOCK, "MAX_LOCK_96_CYCLES");
/// @dev As the oldEnd cycle is a xTDE_DURATION. */
/// @dev We just need to verify that the time we add is a xTDE_DURATION to ensure new lock is ending on a xTDE_DURATION.
require(durationAdd % TDE_DURATION == 0, "NEW_END_MUST_BE_TDE_MULTIPLE");
/// @dev Addition of duration cannot be zero
require(durationAdd != 0, "LOCK_DURATION_ZERO");
/// @dev YsCvg TotalSupply Part, access only if some % has been given to ys on the NFT.
if (lockingPosition.ysPercentage != 0) {
/// @dev Retrieve the balance registered at the cycle where the ysBalance is supposed to drop.
uint128 _ysToReport = uint128(balanceOfYsCvgAt(tokenId, oldEndCycle - 1));
/** @dev Add this value to the tracking on the oldEndCycle. */
totalSuppliesTracking[oldEndCycle].ysToAdd += _ysToReport;
/** @dev Report this value in the newEndCycle in the Sub part. */
totalSuppliesTracking[newEndCycle].ysToSub += _ysToReport;
}
/** @dev Vote part, access here only if some % has been given to ve/mg on the NFT. */
if (lockingPosition.ysPercentage != MAX_PERCENTAGE) {
/** @dev Increase Locking time to a new timestamp, computed with the cycle. */
veCvg.increase_unlock_time(tokenId, block.timestamp + (uint256(newEndCycle - actualCycle) * 7 days));
}
/** @dev Update the new end cycle on the locking position. */
lockingPositions[tokenId].lastEndCycle = uint24(newEndCycle - 1);
lockingPosition.lastEndCycle = uint24(newEndCycle - 1);
emit IncreaseLockTime(tokenId, lockingPosition, oldEndCycle - 1);
}
/**
* @notice Increase first the time THEN the amount in the position proportionally from the actual cycle to the end of lock.
* @dev The token must not be time locked, as an increase in the time can be detrimental to a potential buyer.
* @param tokenId is the token ID of the position
* @param durationAdd is the number of cycle to add to the position lockingTime
* @param amount of cvg to add to the position
* @param operator address of token owner (used when call from a special contract)
*/
function increaseLockTimeAndAmount(
uint256 tokenId,
uint24 durationAdd,
uint128 amount,
address operator
) external onlyWalletOrWhiteListedContract {
require(isLockActive, "LOCKS_ARE_PAUSED");
operator = isSpecialLocker[msg.sender] ? operator : msg.sender;
lockingPositionManager.checkFullCompliance(tokenId, operator);
require(amount > 0, "LTE");
/** @dev Retrieve actual staking cycle. */
uint24 actualCycle = uint24(cvgRewards.getCycleLocking(block.timestamp));
ILockingPositionService.LockingPosition memory lockingPosition = lockingPositions[tokenId];
uint24 oldEndCycle = lockingPosition.lastEndCycle + 1;
/** @dev Calculating the new end cycle. */
uint24 newEndCycle = oldEndCycle + durationAdd;
/** @dev Check the new end cycle. */
require(oldEndCycle > actualCycle, "LOCK_OVER");
require(newEndCycle - actualCycle - 1 <= MAX_LOCK, "MAX_LOCK_96_CYCLES");
require(durationAdd % TDE_DURATION == 0, "END_MUST_BE_TDE_MULTIPLE");
/// @dev Addition of duration cannot be zero
require(durationAdd != 0, "LOCK_DURATION_ZERO");
if (lockingPosition.ysPercentage != 0) {
/** @dev Taking in account the change of YsCvg TotalSupply update. */
uint128 _ysToReport = uint128(balanceOfYsCvgAt(tokenId, oldEndCycle - 1));
totalSuppliesTracking[oldEndCycle].ysToAdd += _ysToReport;
totalSuppliesTracking[newEndCycle].ysToSub += _ysToReport;
_ysCvgCheckpointIncrease(
tokenId,
newEndCycle - actualCycle - 1,
amount * lockingPosition.ysPercentage,
actualCycle,
newEndCycle - 1
);
}
if (lockingPosition.ysPercentage != MAX_PERCENTAGE) {
/** @dev Update voting power through veCVG contract, link voting power to the nft tokenId. */
uint256 amountVote = amount * (MAX_PERCENTAGE - lockingPosition.ysPercentage);
lockingPosition.mgCvgAmount += uint96(
(amountVote * (newEndCycle - actualCycle - 1)) / MAX_LOCK_MUL_MAX_PERCENTAGE
);
veCvg.increase_unlock_time_and_amount(
tokenId,
block.timestamp + (uint256(newEndCycle - actualCycle) * 7 days),
amountVote / MAX_PERCENTAGE
);
}
/** @dev Update the new end cycle on the locking position. */
lockingPosition.lastEndCycle = newEndCycle - 1;
lockingPosition.totalCvgLocked += uint104(amount);
lockingPositions[tokenId] = lockingPosition;
/** @dev Transfer CVG */
cvg.transferFrom(msg.sender, address(this), amount);
if (lockingPosition.ysPercentage != 0) {
ysStreamer.checkInFromLocking(tokenId, actualCycle);
}
emit IncreaseLockTimeAndAmount(tokenId, lockingPosition, oldEndCycle - 1);
}
/**
* @notice Unlock CVG tokens under the NFT Locking Position : Burn the NFT, Transfer back the CVG to the user. Rewards from YsDistributor must be claimed before or they will be lost. * @dev The locking time must be over
* @param tokenId to burn
*/
function burnPosition(uint256 tokenId) external {
ILockingPositionService.LockingPosition memory lockingPosition = lockingPositions[tokenId];
require(cvgControlTower.cvgCycle() > lockingPosition.lastEndCycle, "LOCKED");
/** @dev if the position contains veCvg , we must remove it from the voting escrow */
if (lockingPosition.ysPercentage != MAX_PERCENTAGE) {
veCvg.withdraw(tokenId);
}
/** @dev Burn the NFT representing the position. */
lockingPositionManager.burn(tokenId, msg.sender);
/** @dev Transfer CVG back to the user. */
cvg.transfer(msg.sender, lockingPosition.totalCvgLocked);
emit LockingPositionBurn(tokenId);
}
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
ONLY CONTROL TOWER
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-= */
/**
* @notice Compute the new Ys total supply by adding and subtracting checkpoints formerly created on mint & increaseLock by the _YsCvgCheckpoint().
* @dev Only callable by ControlTower ( DAO ).
*/
function updateYsTotalSupply() external {
require(msg.sender == address(cvgRewards), "NOT_CVG_REWARDS");
uint256 actualCycle = cvgControlTower.cvgCycle();
uint256 totalSupplyYsBeforeUpdate = totalSupplyYsCvgHistories[actualCycle - 1];
/** @dev Update ysCVG total supply with checkpoints for the actual cycle */
totalSupplyYsCvgHistories[actualCycle] =
totalSupplyYsBeforeUpdate +
totalSuppliesTracking[actualCycle].ysToAdd -
totalSuppliesTracking[actualCycle].ysToSub;
emit UpdateTotalSupplies(totalSupplyYsBeforeUpdate, veCvg.total_supply(), actualCycle - 1);
}
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
INTERNAL FUNCTIONS
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-= */
function _ysCvgCheckpointMint(
uint256 tokenId,
uint24 lockDuration,
uint128 cvgLockAmount,
uint24 actualCycle,
uint24 endLockCycle
) internal {
/** @dev Compute the amount of ysCVG on this Locking Position proportionally with the ratio of lockDuration and MAX LOCK duration. */
uint128 commonNum = lockDuration * cvgLockAmount;
uint128 ysTotalAmount = uint128(commonNum / MAX_LOCK_MUL_MAX_PERCENTAGE);
/// @dev realEndCycle is the cycle where we remove the ysAmount from the totalSupply.
uint24 realEndCycle = endLockCycle + 1;
uint24 nextTdeCycle = uint24((actualCycle / TDE_DURATION + 1) * TDE_DURATION);
/// @dev If the lock is not made on a TDE cycle, we need to compute the partial amount of ysCVG for the next TDE.
if (actualCycle % TDE_DURATION != 0) {
/// @dev Represent the amount of ysCvg to be taken into account on the next TDE of this LockingPosition.
uint128 ysPartialAmount = uint128(
((nextTdeCycle - actualCycle) * commonNum) / (TDE_DURATION * MAX_LOCK_MUL_MAX_PERCENTAGE)
);
totalSuppliesTracking[nextTdeCycle].ysToAdd += ysPartialAmount;
/// @dev We always push a checkpoint on the nextTDE with the partialAmount.
checkpoints[tokenId].push(
ILockingPositionService.Checkpoints({cycleId: nextTdeCycle, ysBalance: ysPartialAmount})
);
/// @dev When a lock is greater than a TDE_DURATION
if (lockDuration > TDE_DURATION) {
/// @dev We add in the tracking add, on next TDE + 1 TDE, the delta between full and partial, in order to get fullAmount on the TDE.
totalSuppliesTracking[nextTdeCycle + TDE_DURATION].ysToAdd += ysTotalAmount - ysPartialAmount;
/// @dev We add in the tracking sub on the end of the lock, the ysTotalAmount
totalSuppliesTracking[realEndCycle].ysToSub += ysTotalAmount;
checkpoints[tokenId].push(
ILockingPositionService.Checkpoints({
cycleId: uint24(nextTdeCycle + TDE_DURATION),
ysBalance: ysTotalAmount
})
);
}
/// @dev If the lock less than TDE_DURATION.
else {
/// @dev We remove the amount from the supply calculation at the end of the TDE
totalSuppliesTracking[realEndCycle].ysToSub += ysPartialAmount;
}
}
/// @dev If the lock is performed on a TDE cycle, no need to compute partialAmount.
else {
totalSuppliesTracking[nextTdeCycle].ysToAdd += ysTotalAmount;
totalSuppliesTracking[realEndCycle].ysToSub += ysTotalAmount;
/// @dev We push a checkpoint on the nextTDE with the ysTotalAmount
checkpoints[tokenId].push(
ILockingPositionService.Checkpoints({cycleId: nextTdeCycle, ysBalance: ysTotalAmount})
);
}
}
/**
* @notice Compute the new Ys by adding and subtracting
* checkpoints formerly created on mint & increaseLock by the _YsCvgCheckpoint().
* @dev Only callable by ControlTower ( DAO ).
* @param lockDuration is the duration in cycle(week) of the lock
* @param cvgLockAmount is the amount of cvg to lock in the position
* @param actualCycle is the actual cycle of the cvg
* @param endLockCycle is the end cycle of the lock
*/
function _ysCvgCheckpointIncrease(
uint256 tokenId,
uint24 lockDuration,
uint128 cvgLockAmount,
uint24 actualCycle,
uint24 endLockCycle
) internal {
/** @dev Compute the amount of ysCVG on this Locking Position proportionally with the ratio of lockDuration and MAX LOCK duration. */
uint128 commonNum = lockDuration * cvgLockAmount;
uint128 ysTotalAmount = uint128(commonNum / MAX_LOCK_MUL_MAX_PERCENTAGE);
uint24 realEndCycle = endLockCycle + 1;
uint24 nextTdeCycle = uint24((actualCycle / TDE_DURATION + 1) * TDE_DURATION);
uint256 checkpointsLength = checkpoints[tokenId].length;
ILockingPositionService.Checkpoints memory lastCheckpoint = checkpoints[tokenId][checkpointsLength - 1];
// @dev If the lock is not made on a TDE cycle, we need to compute the partial amount of ys for the next TDE.
if (actualCycle % TDE_DURATION != 0) {
/** @dev Represent the amount of ysCvg to be taken into account on the next TDE of this LockingPosition. */
uint128 ysPartialAmount = uint128(
((nextTdeCycle - actualCycle) * commonNum) / (TDE_DURATION * MAX_LOCK_MUL_MAX_PERCENTAGE)
);
totalSuppliesTracking[nextTdeCycle].ysToAdd += ysPartialAmount;
/** @dev When a lock is greater than a TDE_DURATION */
if (lockDuration >= TDE_DURATION) {
/** @dev we add the calculations for the next full TDE */
totalSuppliesTracking[nextTdeCycle + TDE_DURATION].ysToAdd += ysTotalAmount - ysPartialAmount;
totalSuppliesTracking[realEndCycle].ysToSub += ysTotalAmount;
/// @dev If there is only one checkpoint
if (checkpointsLength == 1) {
if (lastCheckpoint.cycleId == nextTdeCycle) {
/// @dev update last checkpoint with partial
checkpoints[tokenId][checkpointsLength - 1].ysBalance =
lastCheckpoint.ysBalance +
ysPartialAmount;
} else {
checkpoints[tokenId].push(
ILockingPositionService.Checkpoints({
cycleId: nextTdeCycle,
ysBalance: lastCheckpoint.ysBalance + ysPartialAmount
})
);
}
checkpoints[tokenId].push(
ILockingPositionService.Checkpoints({
cycleId: uint24(nextTdeCycle + TDE_DURATION),
ysBalance: lastCheckpoint.ysBalance + ysTotalAmount
})
);
}
/// @dev Else there are more than 1 checkpoint
else {
uint256 _tokenId = tokenId;
/// @dev Both cycle in common
if (
checkpoints[_tokenId][checkpointsLength - 2].cycleId == nextTdeCycle &&
lastCheckpoint.cycleId == nextTdeCycle + TDE_DURATION
) {
checkpoints[_tokenId][checkpointsLength - 2].ysBalance += ysPartialAmount;
checkpoints[_tokenId][checkpointsLength - 1].ysBalance += ysTotalAmount;
}
/// @dev If the last checkpoint is the nextTdeCycle but the second to last checkpoint is not the
else if (lastCheckpoint.cycleId == nextTdeCycle) {
checkpoints[_tokenId][checkpointsLength - 1].ysBalance += ysPartialAmount;
checkpoints[_tokenId].push(
ILockingPositionService.Checkpoints({
cycleId: uint24(nextTdeCycle + TDE_DURATION),
ysBalance: lastCheckpoint.ysBalance + ysTotalAmount
})
);
}
/// @dev Else no cycles in common
else {
checkpoints[_tokenId].push(
ILockingPositionService.Checkpoints({
cycleId: nextTdeCycle,
ysBalance: lastCheckpoint.ysBalance + ysPartialAmount
})
);
checkpoints[_tokenId].push(
ILockingPositionService.Checkpoints({
cycleId: uint24(nextTdeCycle + TDE_DURATION),
ysBalance: lastCheckpoint.ysBalance + ysTotalAmount
})
);
}
}
}
/// @dev Else the lock remaining is smaller than a TDE
else {
/// @dev We need to remove the ysPartial after the nextTDE
totalSuppliesTracking[realEndCycle].ysToSub += ysPartialAmount;
/// @dev If the last checkpoint is not already pushed
if (lastCheckpoint.cycleId != nextTdeCycle) {
checkpoints[tokenId].push(
ILockingPositionService.Checkpoints({
cycleId: nextTdeCycle,
ysBalance: lastCheckpoint.ysBalance + ysPartialAmount
})
);
}
/// @dev Else we just increment the ysBalance in the checkpoint.
else {
checkpoints[tokenId][checkpointsLength - 1].ysBalance += ysPartialAmount;
}
}
}
/// @dev If the remaining or new time of locking is a TDE_DURATION multiple
else {
/// @dev Add amount for the ysTotal on the next cycle, no partial are needed.
totalSuppliesTracking[nextTdeCycle].ysToAdd += ysTotalAmount;
totalSuppliesTracking[realEndCycle].ysToSub += ysTotalAmount;
/// @dev If nextTde older than last checkpoint.
if (lastCheckpoint.cycleId != nextTdeCycle) {
checkpoints[tokenId].push(
ILockingPositionService.Checkpoints({
cycleId: nextTdeCycle,
ysBalance: lastCheckpoint.ysBalance + ysTotalAmount
})
);
}
/// @dev If the last checkpoint is already the nextTde, we just update it's ysAmount
else {
checkpoints[tokenId][checkpointsLength - 1].ysBalance += ysTotalAmount;
}
}
}
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
VIEW FUNCTIONS
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-= */
/**
* @notice Returns the information needed to display the lock position display svg.
* @param _tokenId id of the token
*/
function tokenInfos(uint256 _tokenId) external view returns (ILockingPositionService.TokenView memory) {
ILockingPositionService.LockingPosition memory _lockingPosition = lockingPositions[_tokenId];
uint256 _cvgCycle = cvgControlTower.cvgCycle();
return
ILockingPositionService.TokenView({
tokenId: _tokenId,
cvgLocked: _lockingPosition.totalCvgLocked,
startCycle: _lockingPosition.startCycle,
endCycle: _lockingPosition.lastEndCycle,
veCvgActual: veCvg.balanceOf(_tokenId),
ysTotal: balanceOfYsCvgAt(_tokenId, _lockingPosition.lastEndCycle),
ysActual: balanceOfYsCvgAt(_tokenId, _cvgCycle),
mgCvg: _cvgCycle > _lockingPosition.lastEndCycle ? 0 : _lockingPosition.mgCvgAmount,
ysPercentage: _lockingPosition.ysPercentage
});
}
/**
* @notice Fetch the balance of veCVG (gauge voting power) for a specified tokenId.
* @param _tokenId id of the token
*/
function balanceOfVeCvg(uint256 _tokenId) public view returns (uint256) {
return veCvg.balanceOf(_tokenId);
}
/**
* @notice Fetch the balance of ysCVG (treasury share) for a specified tokenId and at a specified cycle, can be in the future.
* @param _tokenId id of the token
* @param _cycleId id of the cycle
*/
function balanceOfYsCvgAt(uint256 _tokenId, uint256 _cycleId) public view returns (uint256) {
require(_cycleId != 0, "NOT_EXISTING_CYCLE");
ILockingPositionService.LockingPosition memory _lockingPosition = lockingPositions[_tokenId];
uint256 checkpointsLength = checkpoints[_tokenId].length;
uint256 ysBalance;
/// @dev If the requested cycle is before the beginning of the lock or after the end of the lock. The balance in ysCVG is so 0.
if (_lockingPosition.startCycle >= _cycleId || _lockingPosition.lastEndCycle < _cycleId) {
return 0;
}
/// @dev We iterate from the last index of the checkpoints
for (uint256 i = checkpointsLength; i != 0; ) {
ILockingPositionService.Checkpoints memory cycleCheckpoint = checkpoints[_tokenId][i - 1];
if (cycleCheckpoint.cycleId <= _cycleId) {
ysBalance = cycleCheckpoint.ysBalance;
break;
}
unchecked {
--i;
}
}
return ysBalance;
}
/**
* @notice Fetch the balance of mgCVG (meta-governance voting power ) for a specified tokenId.
* @param _tokenId id of the token
*/
function balanceOfMgCvg(uint256 _tokenId) public view returns (uint256) {
uint256 cycleId = cvgControlTower.cvgCycle();
ILockingPositionService.LockingPosition memory _lockingPosition = lockingPositions[_tokenId];
/** @dev If the requested cycle is before or after the lock , there is no balance. */
if (_lockingPosition.startCycle > cycleId || cycleId > _lockingPosition.lastEndCycle) {
return 0;
}
return _lockingPosition.mgCvgAmount;
}
/**
* @notice Fetch the voting power (in veCvg) for a specified address, used in the Cvg Governance proposal strategy.
* @param _user is the address that we want to fetch voting power from
*/
function veCvgVotingPowerPerAddress(address _user) external view returns (uint256) {
uint256 _totalVotingPower;
ILockingPositionDelegate _lockingPositionDelegate = lockingPositionDelegate;
ILockingPositionManager _lockingPositionManager = lockingPositionManager;
(uint256[] memory tokenIdsOwneds, uint256[] memory tokenIdsDelegateds) = _lockingPositionDelegate
.getTokenVeOwnedAndDelegated(_user);
/** @dev Sum voting power from delegated tokenIds to _user. */
for (uint256 i; i < tokenIdsDelegateds.length; ) {
uint256 _tokenId = tokenIdsDelegateds[i];
/** @dev Check if is really delegated, if not ve voting power for this tokenId is 0. */
if (_user == _lockingPositionDelegate.delegatedVeCvg(_tokenId)) {
_totalVotingPower += balanceOfVeCvg(_tokenId);
}
unchecked {
++i;
}
}
/** @dev Sum voting power from _user owned tokenIds. */
for (uint256 i; i < tokenIdsOwneds.length; ) {
uint256 _tokenId = tokenIdsOwneds[i];
/** @dev Check if is really owned AND not delegated to another user,if not ve voting power for this tokenId is 0. */
if (
_lockingPositionDelegate.delegatedVeCvg(_tokenId) == address(0) &&
_user == _lockingPositionManager.ownerOf(_tokenId)
) {
_totalVotingPower += balanceOfVeCvg(_tokenId);
}
unchecked {
++i;
}
}
return _totalVotingPower;
}
/**
* @notice Fetch the voting power (in mgCVG) for a specified address, used in Meta-governance strategy
* @param _user is the address that we want to fetch voting power from
*/
function mgCvgVotingPowerPerAddress(address _user) public view returns (uint256) {
uint256 _totalMetaGovernance;
ILockingPositionDelegate _lockingPositionDelegate = lockingPositionDelegate;
ILockingPositionManager _lockingPositionManager = lockingPositionManager;
(uint256[] memory tokenIdsOwneds, uint256[] memory tokenIdsDelegateds) = _lockingPositionDelegate
.getTokenMgOwnedAndDelegated(_user);
/** @dev Sum voting power from delegated (allowed) tokenIds to _user. */
for (uint256 i; i < tokenIdsDelegateds.length; ) {
uint256 _tokenId = tokenIdsDelegateds[i];
(uint256 _toPercentage, , uint256 _toIndex) = _lockingPositionDelegate.getMgDelegateeInfoPerTokenAndAddress(
_tokenId,
_user
);
/** @dev Check if is really delegated, if not mg voting power for this tokenId is 0. */
if (_toIndex < 999) {
uint256 _tokenBalance = balanceOfMgCvg(_tokenId);
_totalMetaGovernance += (_tokenBalance * _toPercentage) / MAX_PERCENTAGE;
}
unchecked {
++i;
}
}
/** @dev Sum voting power from _user owned (allowed) tokenIds. */
for (uint256 i; i < tokenIdsOwneds.length; ) {
uint256 _tokenId = tokenIdsOwneds[i];
/** @dev Check if is really owned,if not mg voting power for this tokenId is 0. */
if (_user == _lockingPositionManager.ownerOf(_tokenId)) {
(, uint256 _totalPercentageDelegated, ) = _lockingPositionDelegate.getMgDelegateeInfoPerTokenAndAddress(
_tokenId,
_user
);
uint256 _tokenBalance = balanceOfMgCvg(_tokenId);
_totalMetaGovernance += (_tokenBalance * (MAX_PERCENTAGE - _totalPercentageDelegated)) / MAX_PERCENTAGE;
}
unchecked {
++i;
}
}
return _totalMetaGovernance;
}
/**
* @notice Get the supply of YsCvg at a given cycle, can be in the future.
* @param _at cycle requested
*/
function totalSupplyOfYsCvgAt(uint256 _at) public view returns (uint256) {
require(_at != 0, "NOT_EXISTING_CYCLE");
uint256 actualCycle = cvgControlTower.cvgCycle();
uint256 _ysCvgAt;
if (actualCycle <= _at) {
/** @dev If the requested cycle is in the future/actual cycle, we compute the future balance with the tracking. */
/** @dev Start from the last known totalSupply . */
_ysCvgAt = totalSupplyYsCvgHistories[actualCycle - 1];
for (uint256 i = actualCycle; i <= _at; ) {
_ysCvgAt += totalSuppliesTracking[i].ysToAdd;
_ysCvgAt -= totalSuppliesTracking[i].ysToSub;
++i;
}
} else {
/** @dev If the requested cycle is in the past, we can directly return the balance. */
_ysCvgAt = totalSupplyYsCvgHistories[_at];
}
return _ysCvgAt;
}
/**
* @notice Get the total supply of ysCVG AND the ysCVG balance of a position, for a given cycle.
* @dev The totalSupply cannot be fetched in the future here.
* @param tokenId Token Id of the position to fetch the ysBalance on.
* @param cycleId Cycle Id to fetch the ysBalance and totalSupply.
*/
function getTotalSupplyHistoryAndBalanceOfYs(
uint256 tokenId,
uint256 cycleId
) external view returns (uint256, uint256) {
return (totalSupplyYsCvgHistories[cycleId], balanceOfYsCvgAt(tokenId, cycleId));
}
/**
* @notice Get the total supply of ysCVG AND the ysCVG balance of a position, for a given cycle.
* @dev The totalSupply can be fetched in the future here.
* @param tokenId Token Id of the position to fetch the ysBalance on.
* @param cycleId Cycle Id to fetch the ysBalance and totalSupply.
*/
function getTotalSupplyAtAndBalanceOfYs(uint256 tokenId, uint256 cycleId) external view returns (uint256, uint256) {
return (totalSupplyOfYsCvgAt(cycleId), balanceOfYsCvgAt(tokenId, cycleId));
}
/**
* @notice Add/remove a contract address to the whitelist. This contract will be able to perform locks on the LockingPositionService.
* @param contractWL Address of the contract of multisig to WL.
*/
function toggleContractLocker(address contractWL) external onlyOwner {
isContractLocker[contractWL] = !isContractLocker[contractWL];
}
/**
* @notice Add/remove a special locker
* @dev Special lockers are contracts from Convergence calling locking functions here and changing the nominal behavior of the functions.
* @param specialLocker Address of the special locker to activate/deactivate
*/
function toggleSpecialLocker(address specialLocker) external onlyOwner {
isSpecialLocker[specialLocker] = !isSpecialLocker[specialLocker];
isContractLocker[specialLocker] = !isContractLocker[specialLocker];
}
function setCvgRewards(ICvgRewards _cvgRewards) external onlyOwner {
cvgRewards = _cvgRewards;
}
function setVotingPowerEscrow(IVotingPowerEscrow _veCvg) external onlyOwner {
veCvg = _veCvg;
}
}
@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(
uint80 _roundId
) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.0;
import "./OwnableUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
function __Ownable2Step_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable2Step_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
_transferOwnership(sender);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts/interfaces/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/extensions/IERC20Metadata.sol";
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
contracts/interfaces/IBondCalculator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IBondStruct.sol";
interface IBondCalculator {
function computeRoi(
uint256 durationFromStart,
uint256 totalDuration,
IBondStruct.BondFunction composedFunction,
uint256 totalTokenOut,
uint256 amountTokenSold,
uint256 gamma,
uint256 scale,
uint256 minRoi,
uint256 maxRoi
) external pure returns (uint256 bondRoi);
}
contracts/interfaces/IBondDepository.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ICvgControlTower.sol";
import "./IBondStruct.sol";
import "./ICvgOracle.sol";
interface IBondDepository {
// Deposit Principle token in Treasury through Bond contract
function deposit(uint256 tokenId, uint256 amount, address receiver) external;
function depositToLock(uint256 amount, address receiver) external returns (uint256 cvgToMint);
function positionInfos(uint256 tokenId) external view returns (IBondStruct.BondPending memory);
function getTokenVestingInfo(uint256 tokenId) external view returns (IBondStruct.TokenVestingInfo memory);
function bondParams() external view returns (IBondStruct.BondParams memory);
function pendingPayoutFor(uint256 tokenId) external view returns (uint256);
}
contracts/interfaces/IBondLogo.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IBondLogo {
struct LogoInfos {
uint256 tokenId;
uint256 termTimestamp;
uint256 pending;
uint256 cvgClaimable;
uint256 unlockingTimestamp;
}
struct LogoInfosFull {
uint256 tokenId;
uint256 termTimestamp;
uint256 pending;
uint256 cvgClaimable;
uint256 unlockingTimestamp;
uint256 year;
uint256 month;
uint256 day;
bool isLocked;
uint256 hoursLock;
uint256 cvgPrice;
}
function _tokenURI(LogoInfos memory logoInfos) external pure returns (string memory output);
function getLogoInfo(uint256 tokenId) external view returns (IBondLogo.LogoInfosFull memory);
}
contracts/interfaces/IBondPositionManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IBondStruct.sol";
import "./IBondLogo.sol";
import "./IBondDepository.sol";
interface IBondPositionManager {
function bondDepository() external view returns (IBondDepository);
function getTokenIdsForWallet(address _wallet) external view returns (uint256[] memory);
function bondPerTokenId(uint256 tokenId) external view returns (uint256);
// Deposit Principle token in Treasury through Bond contract
function mintOrCheck(uint256 bondId, uint256 tokenId, address receiver) external returns (uint256);
function burn(uint256 tokenId) external;
function unlockingTimestampPerToken(uint256 tokenId) external view returns (uint256);
function logoInfo(uint256 tokenId) external view returns (IBondLogo.LogoInfos memory);
function checkTokenRedeem(uint256[] calldata tokenIds, address receiver) external view;
}
contracts/interfaces/IBondStruct.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IBondStruct {
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
STORED STRUCTS
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-= */
struct BondParams {
/**
* @dev Type of function used to compute the actual ROI of a bond.
* - 0 is SquareRoot
* - 1 is Ln
* - 2 is Square
* - 3 is Linear
*/
BondFunction composedFunction;
/// @dev Address of the underlaying token of the bond.
address token;
/**
* @dev Gamma is used in the BondCalculator.It's the value dividing the ratio between the amount already sold and the theorical amount sold.
* 250_000 correspond to 0.25 (25%).
*/
uint40 gamma;
/// @dev Total duration of the bond, uint40 is enough for a timestamp.
uint40 bondDuration;
/// @dev Determine if a Bond is paused. Can't deposit on a bond paused.
bool isPaused;
/**
* @dev Scale is used in the BondCalculator. When a scale is A, the ROI vary by incremental of A.
* If scale is 5_000 correspond to 0.5%, the ROI will vary from the maxROI to minROI by increment of 0.5%.
*/
uint32 scale;
/**
* @dev Minimum ROI of the bond. Discount cannot be less than the minROI.
* If minRoi is 100_000, it represents 10%.
*/
uint24 minRoi;
/**
* @dev Maximum ROI of the bond. Discount cannot be more than the maxROI.
* If maxRoi is 150_000, it represents 15%.
*/
uint24 maxRoi;
/**
* @dev Percentage maximum of the cvgToSell that an user can buy in one deposit
* If percentageOneTx is 200, it represents 20% of cvgToSell.
*/
uint24 percentageOneTx;
/// @dev Duration of the vesting in second.
uint32 vestingTerm;
/**
* @dev Maximum amount that can be bought through this bond.
* uint80 represents 1.2M tokens in ethers. It means that we are never going to open a bond with more than 1.2M tokens.
*/
uint80 cvgToSell; // Limit of Max CVG to sell => 1.2M CVG max approx
/// @dev Timestamp in second of the beginning of the bond. Has to be in the future.
uint40 startBondTimestamp;
}
struct BondPending {
/// @dev Timestamp in second of the last interaction with this position.
uint64 lastTimestamp;
/// @dev Time in seconds lefting before the position is fully unvested
uint64 vestingTimeLeft;
/**
* @dev Total amount of CVG still vested in the position.
* uint128 is way enough because it's an amount in CVG that have a max supply of 150M tokens.
*/
uint128 leftClaimable;
}
struct BondCreateStruct {
/// @dev Timestamp in second of the last interaction with this position.
BondParams bondParams;
/// @dev Time in seconds lefting before the position is fully unvested
bool isLockMandatory;
}
enum BondFunction {
SQRT,
LN,
POWER_2,
LINEAR
}
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
VIEW STRUCTS
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-= */
struct BondTokenView {
uint128 lastTimestamp;
uint128 vestingEnd;
uint256 claimableCvg;
uint256 leftClaimable;
}
struct BondView {
uint256 actualRoi;
uint256 cvgAlreadySold;
uint256 usdExecutionPrice;
uint256 usdLimitPrice;
uint256 assetBondPrice;
uint256 usdBondPrice;
bool isOracleValid;
BondParams bondParameters;
ERC20View token;
}
struct BondViewV2 {
uint256 actualRoi;
uint256 cvgAlreadySold;
uint256 usdExecutionPrice;
uint256 usdLimitPrice;
uint256 assetBondPrice;
uint256 usdBondPrice;
bool isOracleValid;
BondParams bondParameters;
ERC20View token;
bool isLockingMandatory;
}
struct ERC20View {
string token;
address tokenAddress;
uint256 decimals;
}
struct TokenVestingInfo {
uint256 term;
uint256 claimable;
uint256 pending;
}
}
contracts/interfaces/ICommonStruct.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ICommonStruct {
struct TokenAmount {
IERC20 token;
uint256 amount;
}
struct ApproveStruct {
IERC20 token;
address spender;
uint256 amount;
}
}
contracts/interfaces/ICvg.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/interfaces/IERC20Metadata.sol";
interface ICvg is IERC20Metadata {
function MAX_AIRDROP() external view returns (uint256);
function MAX_BOND() external view returns (uint256);
function MAX_STAKING() external view returns (uint256);
function MAX_VESTING() external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
function burn(uint256 amount) external;
function cvgControlTower() external view returns (address);
function decimals() external view returns (uint8);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function mintBond(address account, uint256 amount) external;
function mintStaking(address account, uint256 amount) external;
function mintedBond() external view returns (uint256);
function mintedStaking() external view returns (uint256);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function totalSupply() external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
contracts/interfaces/ICvgControlTower.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./IERC20Mintable.sol";
import "./ICvg.sol";
import "./IBondDepository.sol";
import "./IBondCalculator.sol";
import "./IBondStruct.sol";
import "./ICvgOracle.sol";
import "./IVotingPowerEscrow.sol";
import "./ICvgRewards.sol";
import "./ILockingPositionManager.sol";
import "./ILockingPositionDelegate.sol";
import "./IGaugeController.sol";
import "./IYsDistributor.sol";
import "./IBondPositionManager.sol";
import "./ISdtStakingPositionManager.sol";
import "./IBondLogo.sol";
import "./ILockingLogo.sol";
import "./ILockingPositionService.sol";
import "./IVestingCvg.sol";
import "./ISdtBuffer.sol";
import "./ISdtBlackHole.sol";
import "./ISdtStakingPositionService.sol";
import "./ISdtFeeCollector.sol";
import "./ISdtBuffer.sol";
import "./ISdtRewardDistributor.sol";
interface ICvgControlTower {
function cvgToken() external view returns (ICvg);
function cvgOracle() external view returns (ICvgOracle);
function bondCalculator() external view returns (IBondCalculator);
function gaugeController() external view returns (IGaugeController);
function cvgCycle() external view returns (uint128);
function votingPowerEscrow() external view returns (IVotingPowerEscrow);
function treasuryDao() external view returns (address);
function treasuryPod() external view returns (address);
function treasuryPdd() external view returns (address);
function treasuryAirdrop() external view returns (address);
function treasuryTeam() external view returns (address);
function cvgRewards() external view returns (ICvgRewards);
function lockingPositionManager() external view returns (ILockingPositionManager);
function lockingPositionService() external view returns (ILockingPositionService);
function lockingPositionDelegate() external view returns (ILockingPositionDelegate);
function isStakingContract(address contractAddress) external view returns (bool);
function ysDistributor() external view returns (IYsDistributor);
function isBond(address account) external view returns (bool);
function bondPositionManager() external view returns (IBondPositionManager);
function sdtStakingPositionManager() external view returns (ISdtStakingPositionManager);
function sdtStakingLogo() external view returns (ISdtStakingLogo);
function bondLogo() external view returns (IBondLogo);
function lockingLogo() external view returns (ILockingLogo);
function isSdtStaking(address contractAddress) external view returns (bool);
function vestingCvg() external view returns (IVestingCvg);
function sdt() external view returns (IERC20);
function cvgSDT() external view returns (IERC20Mintable);
function cvgSdtStaking() external view returns (ISdtStakingPositionService);
function cvgSdtBuffer() external view returns (ISdtBuffer);
function veSdtMultisig() external view returns (address);
function cloneFactory() external view returns (address);
function sdtUtilities() external view returns (address);
function insertNewSdtStaking(address _sdtStakingClone) external;
function allBaseSdAssetStaking(uint256 _index) external view returns (address);
function allBaseSdAssetBuffer(uint256 _index) external view returns (address);
function sdtFeeCollector() external view returns (ISdtFeeCollector);
function updateCvgCycle() external;
function sdtBlackHole() external view returns (ISdtBlackHole);
function sdtRewardDistributor() external view returns (address);
function poolCvgSdt() external view returns (address);
function bondDepository() external view returns (address);
}
contracts/interfaces/ICvgOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./IOracleStruct.sol";
interface ICvgOracle {
function getPriceVerified(address erc20) external view returns (uint256);
function getPriceUnverified(address erc20) external view returns (uint256);
function getAndVerifyTwoPrices(address tokenIn, address tokenOut) external view returns (uint256, uint256);
function getTwoPricesAndIsValid(
address tokenIn,
address tokenOut
) external view returns (uint256, uint256, bool, uint256, uint256, bool);
function getPriceAndValidationData(
address erc20Address
) external view returns (uint256, uint256, bool, bool, bool, bool);
function getPoolAddressByToken(address erc20) external view returns (address);
function poolTypePerErc20(address) external view returns (IOracleStruct.PoolType);
//OWNER
function setPoolTypeForToken(address _erc20Address, IOracleStruct.PoolType _poolType) external;
function setStableParams(address _erc20Address, IOracleStruct.StableParams calldata _stableParams) external;
function setCurveDuoParams(address _erc20Address, IOracleStruct.CurveDuoParams calldata _curveDuoParams) external;
function setCurveTriParams(address _erc20Address, IOracleStruct.CurveTriParams calldata _curveTriParams) external;
function setUniV3Params(address _erc20Address, IOracleStruct.UniV3Params calldata _uniV3Params) external;
function setUniV2Params(address _erc20Address, IOracleStruct.UniV2Params calldata _uniV2Params) external;
}
contracts/interfaces/ICvgRewards.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ICvgRewards {
struct CvgAprStruct {
GaugeView[] gaugeData;
uint256 totalWeight;
}
struct GaugeView {
string symbol;
address stakingAddress;
uint256 weight;
uint256 typeWeight;
int128 gaugeType;
}
function cvgCycleRewards() external view returns (uint256);
function addGauge(address gaugeAddress) external;
function removeGauge(address gaugeAddress) external;
function getCycleLocking(uint256 timestamp) external view returns (uint256);
function writeStakingRewards(uint256 stepAmount) external;
function getGaugeChunk(uint256 from, uint256 to) external view returns (GaugeView[] memory);
function gaugesLength() external view returns (uint256);
}
contracts/interfaces/IERC20Mintable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/interfaces/IERC20Metadata.sol";
/**
* @dev Interface for the optional mint function from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Mintable is IERC20Metadata {
/**
* @dev Mint `amount` of token to `account`
*/
function mint(address account, uint256 amount) external;
}
contracts/interfaces/IGaugeController.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IGaugeController {
struct WeightType {
uint256 weight;
uint256 type_weight;
int128 gauge_type;
}
function add_type(string memory typeName, uint256 weight) external;
function add_gauge(address addr, int128 gaugeType, uint256 weight) external;
function get_gauge_weight(address gaugeAddress) external view returns (uint256);
function get_gauge_weights(address[] memory gaugeAddresses) external view returns (uint256[] memory, uint256);
function get_gauge_weights_and_types(address[] memory gaugeAddresses) external view returns (WeightType[] memory);
function get_total_weight() external view returns (uint256);
function n_gauges() external view returns (uint128);
function gauges(uint256 index) external view returns (address);
function gauge_types(address gaugeAddress) external view returns (int128);
function get_type_weight(int128 typeId) external view returns (uint256);
function gauge_relative_weight(address addr, uint256 time) external view returns (uint256);
function set_lock(bool isLock) external;
function gauge_relative_weight_write(address gaugeAddress) external;
function gauge_relative_weight_writes(uint256 from, uint256 length) external;
function simple_vote(uint256 tokenId, address gaugeAddress, uint256 tokenWeight) external;
}
contracts/interfaces/ILockingLogo.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ILockingLogo {
struct LogoInfos {
uint256 tokenId;
uint256 cvgLocked;
uint256 lockEnd;
uint256 ysPercentage;
uint256 mgCvg;
uint256 unlockingTimestamp;
}
struct GaugePosition {
uint256 ysWidth; // width of the YS gauge part
uint256 veWidth; // width of the VE gauge part
}
struct LogoInfosFull {
uint256 tokenId;
uint256 cvgLocked;
uint256 lockEnd;
uint256 ysPercentage;
uint256 mgCvg;
uint256 unlockingTimestamp;
uint256 cvgLockedInUsd;
uint256 ysCvgActual;
uint256 ysCvgNext;
uint256 veCvg;
GaugePosition gaugePosition;
uint256 claimableInUsd;
bool isLocked;
uint256 hoursLock;
}
function _tokenURI(LogoInfos memory logoInfos) external pure returns (string memory output);
function getLogoInfo(uint256 tokenId) external view returns (ILockingLogo.LogoInfosFull memory);
}
contracts/interfaces/ILockingPositionDelegate.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ILockingPositionDelegate {
struct OwnedAndDelegated {
uint256[] owneds;
uint256[] mgDelegateds;
uint256[] veDelegateds;
}
function delegatedYsCvg(uint256 tokenId) external view returns (address);
function getMgDelegateeInfoPerTokenAndAddress(
uint256 _tokenId,
address _to
) external view returns (uint256, uint256, uint256);
function getIndexForVeDelegatee(address _delegatee, uint256 _tokenId) external view returns (uint256);
function getIndexForMgCvgDelegatee(address _delegatee, uint256 _tokenId) external view returns (uint256);
function delegateVeCvg(uint256 _tokenId, address _to) external;
function delegateYsCvg(uint256 _tokenId, address _to, bool _status) external;
function delegateMgCvg(uint256 _tokenId, address _to, uint256 _percentage) external;
function delegatedVeCvg(uint256 tokenId) external view returns (address);
function getVeCvgDelegatees(address account) external view returns (uint256[] memory);
function getMgCvgDelegatees(address account) external view returns (uint256[] memory);
function getTokenOwnedAndDelegated(address _addr) external view returns (OwnedAndDelegated[] memory);
function getTokenMgOwnedAndDelegated(address _addr) external view returns (uint256[] memory, uint256[] memory);
function getTokenVeOwnedAndDelegated(address _addr) external view returns (uint256[] memory, uint256[] memory);
function addTokenAtMint(uint256 _tokenId, address minter) external;
function cleanDelegateesOnTransfer(uint256 _tokenId) external;
}
contracts/interfaces/ILockingPositionManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ILockingLogo.sol";
interface ILockingPositionManager {
function ownerOf(uint256 tokenId) external view returns (address);
function mint(address account) external returns (uint256);
function burn(uint256 tokenId, address caller) external;
function logoInfo(uint256 tokenId) external view returns (ILockingLogo.LogoInfos memory);
function checkYsClaim(uint256 tokenId, address caller) external view;
function checkOwnership(uint256 _tokenId, address operator) external view;
function checkOwnerships(uint256[] memory _tokenIds, address operator) external view;
function checkFullCompliance(uint256 tokenId, address operator) external view;
function getTokenIdsForWallet(address _wallet) external view returns (uint256[] memory);
function unlockingTimestampPerToken(uint256 tokenId) external view returns (uint256);
}
contracts/interfaces/ILockingPositionService.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ILockingPositionService {
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
STORED STRUCTS
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-= */
struct LockingPosition {
/// @dev Starting cycle of a LockingPosition. Maximum value of uint24 is 16M, so 16M weeks is way enough.
uint24 startCycle;
/// @dev End cycle of a LockingPosition. Maximum value of uint24 is 16M, so 16M weeks is way enough.
uint24 lastEndCycle;
/** @dev Percentage of the token allocated to ysCvg. Amount dedicated to vote is so equal to 100 - ysPercentage.
* A position with ysPercentage as 60 will allocate 60% of his locking to YsCvg and 40% to veCvg and mgCvg.
*/
uint8 ysPercentage;
/** @dev Total Cvg amount locked in the position.
* Max supply of CVG is 150M, it so fits into an uint104 (20 000 billions approx).
*/
uint104 totalCvgLocked;
/** @dev MgCvgAmount held by the position.
* Max supply of mgCVG is 150M, it so fits into an uint96 (20 billions approx).
*/
uint96 mgCvgAmount;
}
struct TrackingBalance {
/** @dev Amount of ysCvg to add to the total supply when the corresponding cvgCycle is triggered.
* Max supply of ysCVG is 150M, it so fits into an uint128.
*/
uint128 ysToAdd;
/** @dev Amount of ysCvg to remove from the total supply when the corresponding cvgCycle is triggered.
* Max supply of ysCVG is 150M, it so fits into an uint128.
*/
uint128 ysToSub;
}
struct Checkpoints {
uint24 cycleId;
uint232 ysBalance;
}
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
VIEW STRUCTS
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-= */
struct TokenView {
uint256 tokenId;
uint128 startCycle;
uint128 endCycle;
uint256 cvgLocked;
uint256 ysActual;
uint256 ysTotal;
uint256 veCvgActual;
uint256 mgCvg;
uint256 ysPercentage;
}
struct LockingInfo {
uint256 tokenId;
uint256 cvgLocked;
uint256 lockEnd;
uint256 ysPercentage;
uint256 mgCvg;
}
function TDE_DURATION() external view returns (uint256);
function MAX_LOCK() external view returns (uint24);
function updateYsTotalSupply() external;
function ysTotalSupplyHistory(uint256) external view returns (uint256);
function ysShareOnTokenAtTde(uint256, uint256) external view returns (uint256);
function veCvgVotingPowerPerAddress(address _user) external view returns (uint256);
function mintPosition(
uint24 lockDuration,
uint128 amount,
uint8 ysPercentage,
address receiver,
bool isAddToManagedTokens
) external;
function increaseLockAmount(uint256 tokenId, uint128 amount, address operator) external;
function increaseLockTime(uint256 tokenId, uint256 durationAdd) external;
function increaseLockTimeAndAmount(uint256 tokenId, uint24 durationAdd, uint128 amount, address operator) external;
function totalSupplyYsCvgHistories(uint256 cycleClaimed) external view returns (uint256);
function balanceOfYsCvgAt(uint256 tokenId, uint256 cycle) external view returns (uint256);
function lockingPositions(uint256 tokenId) external view returns (LockingPosition memory);
function unlockingTimestampPerToken(uint256 tokenId) external view returns (uint256);
function lockingInfo(uint256 tokenId) external view returns (LockingInfo memory);
function isContractLocker(address contractAddress) external view returns (bool);
function getTotalSupplyAtAndBalanceOfYs(uint256 tokenId, uint256 cycleId) external view returns (uint256, uint256);
function getTotalSupplyHistoryAndBalanceOfYs(
uint256 tokenId,
uint256 cycleId
) external view returns (uint256, uint256);
}
contracts/interfaces/IOracleStruct.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
interface IOracleStruct {
enum PoolType {
NOT_INIT,
STABLE,
CURVE_DUO,
CURVE_TRI,
UNI_V3,
UNI_V2
}
struct StableParams {
AggregatorV3Interface aggregatorOracle;
uint40 deltaLimitOracle; // 5 % => 500 & 100 % => 10 000
uint56 maxLastUpdate; // Buffer time before a not updated price is considered as stale
uint128 minPrice;
uint128 maxPrice;
}
struct CurveDuoParams {
bool isReversed;
bool isEthPriceRelated;
address poolAddress;
uint40 deltaLimitOracle; // 5 % => 500 & 100 % => 10 000
uint40 maxLastUpdate; // Buffer time before a not updated price is considered as stale
uint128 minPrice;
uint128 maxPrice;
address[] stablesToCheck;
}
struct CurveTriParams {
bool isReversed;
bool isEthPriceRelated;
address poolAddress;
uint40 deltaLimitOracle;
uint40 maxLastUpdate;
uint8 k;
uint120 minPrice;
uint128 maxPrice;
address[] stablesToCheck;
}
struct UniV2Params {
bool isReversed;
bool isEthPriceRelated;
address poolAddress;
uint80 deltaLimitOracle;
uint96 maxLastUpdate;
AggregatorV3Interface aggregatorOracle;
uint128 minPrice;
uint128 maxPrice;
address[] stablesToCheck;
}
struct UniV3Params {
bool isReversed;
bool isEthPriceRelated;
address poolAddress;
uint80 deltaLimitOracle;
uint80 maxLastUpdate;
uint16 twap;
AggregatorV3Interface aggregatorOracle;
uint128 minPrice;
uint128 maxPrice;
address[] stablesToCheck;
}
}
contracts/interfaces/IPresaleCvgSeed.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface IPresaleCvgSeed is IERC721Enumerable {
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
ENUMS & STRUCTS
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-= */
enum SaleState {
NOT_ACTIVE,
PRESEED,
SEED,
OVER
}
struct PresaleInfo {
uint256 vestingType; // Define the presaler type
uint256 cvgAmount; // Total CVG amount claimable for the nft owner
}
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
SETTERS
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-= */
function setSaleState(SaleState _saleState) external;
function grantPreseed(address _wallet, uint256 _amount) external;
function grantSeed(address _wallet, uint256 _amount) external;
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
EXTERNALS
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-= */
function investMint(bool _isDai) external;
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
GETTERS
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-= */
function presaleInfoTokenId(uint256 _tokenId) external view returns (PresaleInfo memory);
function saleState() external view returns (SaleState);
function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256);
function getTokenIdAndType(
address _wallet,
uint256 _index
) external view returns (uint256 tokenId, uint256 typeVesting);
function getTokenIdsForWallet(address _wallet) external view returns (uint256[] memory);
function getTotalCvg() external view returns (uint256);
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=
WITHDRAW OWNER
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-= */
function withdrawFunds() external;
function withdrawToken(address _token) external;
}
contracts/interfaces/ISdAssets.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "./ICvgControlTower.sol";
import "./ISdtBuffer.sol";
struct SdGaugeReward {
address token;
address distributor;
uint256 period_finish;
uint256 rate;
uint256 last_update;
uint256 integral;
}
interface IOperator {
function token() external view returns (IERC20Metadata);
function deposit(uint256 amount, bool isLock, bool isStake, address receiver) external;
}
interface ISdAsset is IERC20Metadata {
function sdAssetGauge() external view returns (IERC20);
function initialize(
ICvgControlTower _cvgControlTower,
IERC20 _sdAssetGauge,
string memory setName,
string memory setSymbol
) external;
function setSdAssetBuffer(address _sdAssetBuffer) external;
function mint(address to, uint256 amount) external;
function operator() external view returns (IOperator);
}
interface ISdAssetGauge is IERC20Metadata {
function deposit(uint256 value, address addr) external;
function deposit(uint256 value, address addr, bool claimRewards) external;
function staking_token() external view returns (IERC20);
function reward_count() external view returns (uint256);
function reward_tokens(uint256 i) external view returns (IERC20);
function claim_rewards(address account) external;
function set_rewards_receiver(address account) external;
function claimable_reward(address account, address token) external view returns (uint256);
function set_reward_distributor(address rewardToken, address distributor) external;
function deposit_reward_token(address rewardToken, uint256 amount) external;
function admin() external view returns (address);
function working_balances(address) external view returns (uint256);
function working_supply() external view returns (uint256);
function reward_data(address rewardToken) external view returns (SdGaugeReward memory);
}
contracts/interfaces/ISdtBlackHole.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./ICommonStruct.sol";
interface ISdtBlackHole {
function withdraw(uint256 amount, address receiver) external;
function setGaugeReceiver(address gaugeAddress, address bufferReceiver) external;
function getBribeTokensForBuffer(address buffer) external view returns (IERC20[] memory);
function pullSdStakingBribes(
address _processor,
uint256 _processorRewardsPercentage
) external returns (ICommonStruct.TokenAmount[] memory);
}
contracts/interfaces/ISdtBuffer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ICvgControlTower.sol";
import "./ISdAssets.sol";
import "./ICommonStruct.sol";
interface ISdtBuffer {
function initialize(
ICvgControlTower _cvgControlTower,
address _sdAssetStaking,
ISdAssetGauge _sdGaugeAsset,
IERC20 _sdt
) external;
function pullRewards(address _processor) external returns (ICommonStruct.TokenAmount[] memory);
function processorRewardsPercentage() external view returns (uint256);
}
contracts/interfaces/ISdtFeeCollector.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ISdtFeeCollector {
function rootFees() external returns (uint256);
function withdrawToken(IERC20[] calldata _tokens) external;
function withdrawSdt() external;
struct Fees {
address receiver;
uint96 feePercentage;
}
function feesRepartition(uint256 index) external view returns (Fees memory);
}
contracts/interfaces/ISdtRewardDistributor.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./ICommonStruct.sol";
interface ISdtRewardDistributor {
function claimCvgSdtSimple(
address receiver,
uint256 cvgAmount,
ICommonStruct.TokenAmount[] memory sdtRewards,
uint256 minCvgSdtAmountOut,
bool isConvert
) external;
}
contracts/interfaces/ISdtStakingLogo.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ICommonStruct.sol";
interface ISdtStakingLogo {
struct LogoInfos {
uint256 tokenId;
string symbol;
uint256 pending;
uint256 totalStaked;
uint256 cvgClaimable;
ICommonStruct.TokenAmount[] sdtClaimable;
uint256 unlockingTimestamp;
}
struct LogoInfosFull {
uint256 tokenId;
string symbol;
uint256 pending;
uint256 totalStaked;
uint256 cvgClaimable;
ICommonStruct.TokenAmount[] sdtClaimable;
uint256 unlockingTimestamp;
uint256 claimableInUsd;
bool erroneousAmount;
bool isLocked;
uint256 hoursLock;
}
function _tokenURI(LogoInfos memory logoInfos) external pure returns (string memory output);
function getLogoInfo(uint256 tokenId) external view returns (ISdtStakingLogo.LogoInfosFull memory);
}
contracts/interfaces/ISdtStakingPositionManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ISdtStakingLogo.sol";
import "./ISdtStakingPositionService.sol";
interface ISdtStakingPositionManager {
struct ClaimSdtStakingContract {
ISdtStakingPositionService stakingContract;
uint256[] tokenIds;
}
function mint(address account) external;
function burn(uint256 tokenId) external;
function nextId() external view returns (uint256);
function ownerOf(uint256 tokenId) external view returns (address);
function checkMultipleClaimCompliance(ClaimSdtStakingContract[] calldata, address account) external view;
function checkTokenFullCompliance(uint256 tokenId, address account) external view;
function checkIncreaseDepositCompliance(uint256 tokenId, address account) external view;
function stakingPerTokenId(uint256 tokenId) external view returns (address);
function unlockingTimestampPerToken(uint256 tokenId) external view returns (uint256);
function logoInfo(uint256 tokenId) external view returns (ISdtStakingLogo.LogoInfos memory);
function getTokenIdsForWallet(address _wallet) external view returns (uint256[] memory);
}
contracts/interfaces/ISdtStakingPositionService.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./ICommonStruct.sol";
import "./ISdtBuffer.sol";
import "./ISdAssets.sol";
interface ISdtStakingPositionService {
struct CycleInfo {
uint256 cvgRewardsAmount;
uint256 totalStaked;
bool isSdtProcessed;
}
struct TokenInfo {
uint256 amountStaked;
uint256 pendingStaked;
}
struct CycleInfoMultiple {
uint256 totalStaked;
ICommonStruct.TokenAmount[] sdtClaimable;
}
struct StakingInfo {
uint256 tokenId;
string symbol;
uint256 pending;
uint256 totalStaked;
uint256 cvgClaimable;
ICommonStruct.TokenAmount[] sdtClaimable;
}
function setBuffer(address _buffer) external;
function symbol() external view returns (string memory);
function stakingCycle() external view returns (uint256);
function cycleInfo(uint256 cycleId) external view returns (CycleInfo memory);
function stakingAsset() external view returns (ISdAssetGauge);
function buffer() external view returns (ISdtBuffer);
function tokenTotalStaked(uint256 _tokenId) external view returns (uint256 amount);
function stakedAmountEligibleAtCycle(
uint256 cvgCycle,
uint256 tokenId,
uint256 actualCycle
) external view returns (uint256);
function tokenInfoByCycle(uint256 cycleId, uint256 tokenId) external view returns (TokenInfo memory);
function stakingInfo(uint256 tokenId) external view returns (StakingInfo memory);
function getProcessedSdtRewards(uint256 _cycleId) external view returns (ICommonStruct.TokenAmount[] memory);
function deposit(uint256 tokenId, uint256 amount, address operator) external;
function claimCvgSdtMultiple(
uint256 _tokenId,
address operator
) external returns (uint256, ICommonStruct.TokenAmount[] memory);
function processSdtRewards() external;
}
contracts/interfaces/IVestingCvg.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IPresaleCvgSeed.sol";
interface IVestingCvg {
/// @dev Struct Info about VestingSchedules
struct VestingSchedule {
uint16 daysBeforeCliff;
uint16 daysAfterCliff;
uint24 dropCliff;
uint256 totalAmount;
uint256 totalReleased;
}
struct InfoVestingTokenId {
uint256 amountReleasable;
uint256 totalCvg;
uint256 amountRedeemed;
}
enum VestingType {
SEED,
WL,
IBO,
TEAM,
DAO
}
function vestingSchedules(VestingType vestingType) external view returns (VestingSchedule memory);
function getInfoVestingTokenId(
uint256 _tokenId,
VestingType vestingType
) external view returns (InfoVestingTokenId memory);
function whitelistedTeam() external view returns (address);
function presaleSeed() external view returns (IPresaleCvgSeed);
function MAX_SUPPLY_TEAM() external view returns (uint256);
function startTimestamp() external view returns (uint256);
}
contracts/interfaces/IVotingPowerEscrow.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IVotingPowerEscrow {
function create_lock(uint256 tokenId, uint256 value, uint256 unlockTime) external;
function increase_amount(uint256 tokenId, uint256 value) external;
function increase_unlock_time(uint256 tokenId, uint256 unlockTime) external;
function increase_unlock_time_and_amount(uint256 tokenId, uint256 unlockTime, uint256 amount) external;
function withdraw(uint256 tokenId) external;
function total_supply() external returns (uint256);
function balanceOf(uint256 tokenId) external view returns (uint256);
}
contracts/interfaces/IYsDistributor.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ICommonStruct.sol";
interface IYsDistributor {
struct TokenAmount {
IERC20 token;
uint96 amount;
}
struct Claim {
uint256 tdeCycle;
bool isClaimed;
TokenAmount[] tokenAmounts;
}
function getRewardsForPosition(uint256 _tokenId) external view returns (ICommonStruct.TokenAmount[] memory);
function getPositionRewardsForTdes(
uint256[] calldata _tdeIds,
uint256 actualCycle,
uint256 _tokenId
) external view returns (Claim[] memory);
function getAllRewardsForTde() external view returns (ICommonStruct.TokenAmount[] memory);
}
contracts/interfaces/IYsStreamer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./ICommonStruct.sol";
interface IYsStreamer is IERC20Metadata {
struct Reward {
uint128 lastUpdateTime;
uint128 periodFinish;
uint256 rewardRate;
uint256 rewardPerTokenStored;
}
struct AddTokenRewardInput {
IERC20 token;
address distributor;
}
struct GetRewardInput {
uint256 tdeId;
uint256[] tokenIds;
}
struct EarnedData {
IERC20 token;
uint256 amount;
}
struct ClaimableData {
IERC20 token;
uint256 claimable;
uint256 rewardsForPeriod;
}
function rewardTokens(uint256 index) external view returns (IERC20);
function userRewardPerTokenPaid(address account, IERC20 reward) external view returns (uint256);
function claimableRewards(
uint256 tdeId,
uint256 tokenId
) external view returns (ICommonStruct.TokenAmount[] memory userRewards);
function getRewardsForDuration(
uint256 tdeId
) external view returns (ICommonStruct.TokenAmount[] memory totalRewards);
function balanceCheckedIn(uint256 tdeId, uint256 tokenId) external view returns (uint256);
function totalSupplyCheckedIn(uint256 tdeId) external view returns (uint256);
function checkIn(uint256 tokenId) external;
function checkInFromLocking(uint256 tokenId, uint256 actualCycle) external;
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 250,
"enabled": true
},
"evmVersion": "cancun",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.