Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ethx rewards #8

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,15 @@ update:; forge update
# Build & test
build :; forge build --sizes --via-ir
test :; forge test -vvv

test-contract :; forge test --match-contract ${filter} -vv

test-sd-rewards :; forge test -vvv --match-contract EmissionTestSDPolygon
test-stmatic-rewards :; forge test -vvv --match-contract EmissionTestSTMATICPolygon
test-Ethx-rewards :; FOUNDRY_PROFILE=mainnet forge test -vvv --match-contract EmissionTestEthXMainnet
test-maticx-rewards :; forge test -vvv --match-contract EmissionTestMATICXPolygon

# scripts
deploy-sd-transfer-strategy :; forge script scripts/RewardsConfigHelpers.s.sol:SDDeployTransferStrategy --rpc-url polygon --broadcast --legacy --ledger --mnemonic-indexes ${MNEMONIC_INDEX} --sender ${LEDGER_SENDER} --verify -vvvv
deploy-stmatic-transfer-strategy :; forge script scripts/RewardsConfigHelpers.s.sol:STMATICDeployTransferStrategy --rpc-url polygon --broadcast --legacy --ledger --mnemonic-indexes ${MNEMONIC_INDEX} --sender ${LEDGER_SENDER} --verify -vvvv
deploy-mainnet-sd-transfer-strategy :; forge script scripts/RewardsConfigHelpers.s.sol:SDMainnetDeployTransferStrategy --rpc-url mainnet -- sender ${SENDER} --private-key ${PRIVATE_KEY} --verify -vvvv --slow --broadcast
27 changes: 13 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ This repository contains:

2. Do an ERC-20 approve of the total rewards to be distributed to the Transfer Strategy contract, this is contract by Aave which helps to pull the Liquidity Mining rewards from the Rewards Vault address to distribute to the user. To know more about how Transfer Strategy contract works you can check [here](https://github.com/aave/aave-v3-periphery/blob/master/docs/rewards/rewards-transfer-strategies.md).

_Note: The Emission Admin is an address which has access to manage and configure the reward emissions by calling the Emission Manager contract and the general type of Transfer Strategy contract used for Liquidity Mining is of type PullRewardsStrategy._
_Note: The Emission Admin is an address which has access to manage and configure the reward emissions by calling the Emission Manager contract and the general type of Transfer Strategy contract used for Liquidity Mining is of type PullRewardsStrategy._

3. Finally we need to configure the Liquidity Mining emissions on the Emission Manager contract from the Emission Admin by calling the `configureAssets()` function which will take the array of the following struct to configure liquidity mining for mulitple assets for the same reward or multiple assets for mutiple rewards.

Expand Down Expand Up @@ -108,23 +108,22 @@ Similarly you can also run the test via `forge test -vv` which will emit the sel
- Why do we need to approve funds from the Rewards Vault to the Aave Transfer Strategy contract?

This is needed so the Transfer Strategy contract can pull the rewards from the Rewards Vault to distribute it to the user when the user claims them.

- Can I reuse an already deployed transfer strategy?

Yes, a transfer strategy could be reused if it has already been deployed for the given network (given that you want the rewards vault, rewards admin and the incentives controller to be the same).

Yes, a transfer strategy could be reused if it has already been deployed for the given network (given that you want the rewards vault, rewards admin and the incentives controller to be the same).
- If a transfer strategy does not exist, how do I create one?

The transfer strategy is an immutable contract which determines the logic of the rewards transfer. To create a new pull reward transfer strategy (most common transfer strategy for liquidity mining) you could use the
[PullRewardsTransferStrategy.sol](https://github.com/aave/aave-v3-periphery/blob/master/contracts/rewards/transfer-strategies/PullRewardsTransferStrategy.sol) contract with the following constructor params:
The transfer strategy is an immutable contract which determines the logic of the rewards transfer. To create a new pull reward transfer strategy (most common transfer strategy for liquidity mining) you could use the

[PullRewardsTransferStrategy.sol](https://github.com/aave/aave-v3-periphery/blob/master/contracts/rewards/transfer-strategies/PullRewardsTransferStrategy.sol) contract with the following constructor params:

- `incentivesController`: address of the incentives controller
- `rewardsAdmin`: address of the incentives controller for access control
- `rewardsVault`: address of the rewards vault containing the funds for the Liquidity Mining program.

- `incentivesController`: address of the incentives controller
- `rewardsAdmin`: address of the incentives controller for access control
- `rewardsVault`: address of the rewards vault containing the funds for the Liquidity Mining program.
Example to deploy a transfer strategy can be found [here](./scripts/RewardsConfigHelpers.s.sol).

Example to deploy a transfer strategy can be found [here](./scripts/RewardsConfigHelpers.s.sol).

_Note: All transfer strategy should inherit from the base contract [TransferStrategyBase.sol](https://github.com/aave/aave-v3-periphery/blob/master/contracts/rewards/transfer-strategies/TransferStrategyBase.sol) and you could also define your own custom transfer strategy even with NFT’s as rewards, given that you inherit from the base contract._
_Note: All transfer strategy should inherit from the base contract [TransferStrategyBase.sol](https://github.com/aave/aave-v3-periphery/blob/master/contracts/rewards/transfer-strategies/TransferStrategyBase.sol) and you could also define your own custom transfer strategy even with NFT’s as rewards, given that you inherit from the base contract._

- Can we stop the liquidity mining program at any time?

Expand All @@ -135,7 +134,7 @@ Similarly you can also run the test via `forge test -vv` which will emit the sel
- Can we change the amount of liquidty mining rewards?

Yes, the liquidity mining rewards could be increased or decreased by the Emission Admin. To do so, please refer
[here](https://github.com/bgd-labs/example-liquidity-mining-aave-v3/tree/feat/configure-emissions#how-to-configure-emissions-after-the-lm-program-has-been-created)
[here](https://github.com/bgd-labs/example-liquidity-mining-aave-v3/tree/feat/configure-emissions#how-to-configure-emissions-after-the-lm-program-has-been-created)

### Setup

Expand Down
1 change: 1 addition & 0 deletions foundry.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ src = 'src'
test = 'tests'
script = 'scripts'
out = 'out'
evm_version = 'shanghai'
libs = ['lib']
remappings = [
"@aave/core-v3/=lib/aave-v3-core/",
Expand Down
18 changes: 17 additions & 1 deletion scripts/RewardsConfigHelpers.s.sol
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ pragma solidity ^0.8.0;
import {Script} from 'forge-std/Script.sol';
import {PullRewardsTransferStrategy} from 'aave-v3-periphery/contracts/rewards/transfer-strategies/PullRewardsTransferStrategy.sol';
import {AaveV3Polygon} from 'aave-address-book/AaveV3Polygon.sol';
import {AaveV3Ethereum} from 'aave-address-book/AaveV3Ethereum.sol';

contract SDDeployTransferStrategy is Script {
address internal constant EMISSION_ADMIN = 0x51358004cFe135E64453d7F6a0dC433CAba09A2a;
address internal constant EMISSION_ADMIN = 0xac140648435d03f784879cd789130F22Ef588Fcd;
address internal constant REWARDS_VAULT = EMISSION_ADMIN;

function run() external {
Expand Down Expand Up @@ -35,3 +36,18 @@ contract STMATICDeployTransferStrategy is Script {
vm.stopBroadcast();
}
}

contract SDMainnetDeployTransferStrategy is Script {
address internal constant REWARDS_VAULT = EMISSION_ADMIN;
address internal constant EMISSION_ADMIN = 0xac140648435d03f784879cd789130F22Ef588Fcd;

function run() external {
vm.startBroadcast();
new PullRewardsTransferStrategy(
AaveV3Ethereum.DEFAULT_INCENTIVES_CONTROLLER,
EMISSION_ADMIN,
REWARDS_VAULT
);
vm.stopBroadcast();
}
}
6 changes: 1 addition & 5 deletions src/contracts/AddEmissionAdminPayload.sol
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,7 @@ contract AddEmissionAdminPayload is IProposalGenericExecutor {

address public immutable EMISSION_ADMIN;

constructor(
IEmissionManager emissionManager,
address reward,
address emissionAdmin
) {
constructor(IEmissionManager emissionManager, address reward, address emissionAdmin) {
EMISSION_MANAGER = emissionManager;
REWARD = reward;
EMISSION_ADMIN = emissionAdmin;
Expand Down
64 changes: 20 additions & 44 deletions src/interfaces/IEmissionManager.sol
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,7 @@ interface ITransferStrategyBase {
* @param amount Amount to transfer to the "to" address parameter
* @return Returns true bool if transfer logic succeeds
*/
function performTransfer(
address to,
address reward,
uint256 amount
) external returns (bool);
function performTransfer(address to, address reward, uint256 amount) external returns (bool);

/**
* @return Returns the address of the Incentives Controller
Expand All @@ -55,11 +51,7 @@ interface ITransferStrategyBase {
* @param to Address of the recipient of the withdrawal
* @param amount Amount of the withdrawal
*/
function emergencyWithdrawal(
address token,
address to,
uint256 amount
) external;
function emergencyWithdrawal(address token, address to, uint256 amount) external;
}

library RewardsDataTypes {
Expand Down Expand Up @@ -160,11 +152,7 @@ interface IRewardsDistributor {
* @param reward The reward token that incentives the asset
* @param newDistributionEnd The end date of the incentivization, in unix time format
**/
function setDistributionEnd(
address asset,
address reward,
uint32 newDistributionEnd
) external;
function setDistributionEnd(address asset, address reward, uint32 newDistributionEnd) external;

/**
* @dev Sets the emission per second of a set of reward distributions
Expand Down Expand Up @@ -208,15 +196,10 @@ interface IRewardsDistributor {
* @return The timestamp of the last update of the index
* @return The timestamp of the distribution end
**/
function getRewardsData(address asset, address reward)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function getRewardsData(
address asset,
address reward
) external view returns (uint256, uint256, uint256, uint256);

/**
* @dev Returns the list of available reward token addresses of an incentivized asset
Expand Down Expand Up @@ -259,10 +242,10 @@ interface IRewardsDistributor {
* @return The list of reward addresses
* @return The list of unclaimed amount of rewards
**/
function getAllUserRewards(address[] calldata assets, address user)
external
view
returns (address[] memory, uint256[] memory);
function getAllUserRewards(
address[] calldata assets,
address user
) external view returns (address[] memory, uint256[] memory);

/**
* @dev Returns the decimals of an asset to calculate the distribution delta
Expand Down Expand Up @@ -393,11 +376,7 @@ interface IRewardsController is IRewardsDistributor {
* @param userBalance The user balance of the asset
* @param totalSupply The total supply of the asset
**/
function handleAction(
address user,
uint256 userBalance,
uint256 totalSupply
) external;
function handleAction(address user, uint256 userBalance, uint256 totalSupply) external;

/**
* @dev Claims reward for a user to the desired address, on all the assets of the pool, accumulating the pending rewards
Expand Down Expand Up @@ -452,9 +431,10 @@ interface IRewardsController is IRewardsDistributor {
* @return rewardsList List of addresses of the reward tokens
* @return claimedAmounts List that contains the claimed amount per reward, following same order as "rewardList"
**/
function claimAllRewards(address[] calldata assets, address to)
external
returns (address[] memory rewardsList, uint256[] memory claimedAmounts);
function claimAllRewards(
address[] calldata assets,
address to
) external returns (address[] memory rewardsList, uint256[] memory claimedAmounts);

/**
* @dev Claims all rewards for a user on behalf, on all the assets of the pool, accumulating the pending rewards. The caller must
Expand All @@ -477,9 +457,9 @@ interface IRewardsController is IRewardsDistributor {
* @return rewardsList List of addresses of the reward tokens
* @return claimedAmounts List that contains the claimed amount per reward, following same order as "rewardsList"
**/
function claimAllRewardsToSelf(address[] calldata assets)
external
returns (address[] memory rewardsList, uint256[] memory claimedAmounts);
function claimAllRewardsToSelf(
address[] calldata assets
) external returns (address[] memory rewardsList, uint256[] memory claimedAmounts);
}

/**
Expand Down Expand Up @@ -542,11 +522,7 @@ interface IEmissionManager {
* @param reward The reward token that incentives the asset
* @param newDistributionEnd The end date of the incentivization, in unix time format
**/
function setDistributionEnd(
address asset,
address reward,
uint32 newDistributionEnd
) external;
function setDistributionEnd(address asset, address reward, uint32 newDistributionEnd) external;

/**
* @dev Sets the emission per second of a set of reward distributions
Expand Down
145 changes: 145 additions & 0 deletions tests/EmissionTestEthxEthereum.t.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import {Test} from 'forge-std/Test.sol';
import {IERC20} from 'forge-std/interfaces/IERC20.sol';
import {AaveV3Ethereum, AaveV3EthereumAssets} from 'aave-address-book/AaveV3Ethereum.sol';
import {IAaveIncentivesController} from '../src/interfaces/IAaveIncentivesController.sol';
import {IEmissionManager, ITransferStrategyBase, RewardsDataTypes, IEACAggregatorProxy} from '../src/interfaces/IEmissionManager.sol';
import {BaseTest} from './utils/BaseTest.sol';
import 'forge-std/console.sol';

contract EmissionTestEthXMainnet is BaseTest {
// @dev Used to simplify the definition of a program of emissions
// asset The asset on which to put reward on, usually Aave aTokens or vTokens (variable debt tokens)
// emission Total emission of a `reward` token during the whole distribution duration defined
// E.g. With an emission of 10_000 MATICX tokens during 1 month, an emission of 50% for variableDebtPolWMATIC would be
// 10_000 * 1e18 * 50% / 30 days in seconds = 1_000 * 1e18 / 2_592_000 = ~ 0.0003858 * 1e18 MATICX per second

// SD is not part of the onboarded assets on Aave, we can't call lib so we import it here

address constant SD = 0x30D20208d987713f46DFD34EF128Bb16C404D10f;
address constant SD_ORACLE = 0x92F786E1Cb028FF9D12c7597fBD8ecc266E9e8fb;
address constant a_ETHx = 0x1c0E06a0b1A4c160c17545FF2A951bfcA57C0002;

struct EmissionPerAsset {
address asset;
uint256 emission;
}

address constant EMISSION_ADMIN = 0xac140648435d03f784879cd789130F22Ef588Fcd; // ACI
address constant REWARD_ASSET = SD;

IEACAggregatorProxy constant REWARD_ORACLE = IEACAggregatorProxy(SD_ORACLE);

ITransferStrategyBase constant TRANSFER_STRATEGY =
ITransferStrategyBase(0x4fDB95C607EDe09A548F60685b56C034992B194a); // new deployed strategy

uint256 constant TOTAL_DISTRIBUTION = 25_000 ether; // 25'000 SD/month, 1 month
uint88 constant DURATION_DISTRIBUTION = 30 days;

address SD_WHALE = 0xae7104B8eFeD6Cf969369a1972e97f1891D9BECE;
address a_ETHx_WHALE = 0x5A14BD3f2bf84c3690d653F1d40cfb7a8a9B3c26;

function setUp() public {
vm.createSelectFork(vm.rpcUrl('mainnet'), 20320183);
}

function test_activation() public {
vm.startPrank(EMISSION_ADMIN);
/// @dev IMPORTANT!!
/// The emissions admin should have REWARD_ASSET funds, and have approved the TOTAL_DISTRIBUTION
/// amount to the transfer strategy. If not, REWARDS WILL ACCRUE FINE AFTER `configureAssets()`, BUT THEY
/// WILL NOT BE CLAIMABLE UNTIL THERE IS FUNDS AND ALLOWANCE.
/// It is possible to approve less than TOTAL_DISTRIBUTION and doing it progressively over time as users
/// accrue more, but that is a decision of the emission's admin
IERC20(REWARD_ASSET).approve(address(TRANSFER_STRATEGY), TOTAL_DISTRIBUTION);

IEmissionManager(AaveV3Ethereum.EMISSION_MANAGER).configureAssets(_getAssetConfigs());

emit log_named_bytes(
'calldata to submit from Gnosis Safe',
abi.encodeWithSelector(
IEmissionManager(AaveV3Ethereum.EMISSION_MANAGER).configureAssets.selector,
_getAssetConfigs()
)
);

vm.stopPrank();

vm.startPrank(SD_WHALE);
IERC20(REWARD_ASSET).transfer(EMISSION_ADMIN, TOTAL_DISTRIBUTION);
vm.stopPrank();

vm.startPrank(a_ETHx_WHALE);

vm.warp(block.timestamp + 30 days);

address[] memory assets = new address[](1);
assets[0] = a_ETHx;

uint256 balanceBefore = IERC20(REWARD_ASSET).balanceOf(a_ETHx_WHALE);

IAaveIncentivesController(AaveV3Ethereum.DEFAULT_INCENTIVES_CONTROLLER).claimRewards(
assets,
type(uint256).max,
a_ETHx_WHALE,
REWARD_ASSET
);

uint256 balanceAfter = IERC20(REWARD_ASSET).balanceOf(a_ETHx_WHALE);

uint256 deviationAccepted = 25000 ether; // Approx estimated rewards with current emission in 1 month
assertApproxEqAbs(
balanceBefore,
balanceAfter,
deviationAccepted,
'Invalid delta on claimed rewards'
);

vm.stopPrank();
}

function _getAssetConfigs() internal view returns (RewardsDataTypes.RewardsConfigInput[] memory) {
uint32 distributionEnd = uint32(block.timestamp + DURATION_DISTRIBUTION);

EmissionPerAsset[] memory emissionsPerAsset = _getEmissionsPerAsset();

RewardsDataTypes.RewardsConfigInput[]
memory configs = new RewardsDataTypes.RewardsConfigInput[](emissionsPerAsset.length);
for (uint256 i = 0; i < emissionsPerAsset.length; i++) {
configs[i] = RewardsDataTypes.RewardsConfigInput({
emissionPerSecond: _toUint88(emissionsPerAsset[i].emission / DURATION_DISTRIBUTION),
totalSupply: 0, // IMPORTANT this will not be taken into account by the contracts, so 0 is fine
distributionEnd: distributionEnd,
asset: emissionsPerAsset[i].asset,
reward: REWARD_ASSET,
transferStrategy: TRANSFER_STRATEGY,
rewardOracle: REWARD_ORACLE
});
}

return configs;
}

function _getEmissionsPerAsset() internal pure returns (EmissionPerAsset[] memory) {
EmissionPerAsset[] memory emissionsPerAsset = new EmissionPerAsset[](1);
emissionsPerAsset[0] = EmissionPerAsset({
asset: a_ETHx,
emission: TOTAL_DISTRIBUTION // 100% of the distribution
});

uint256 totalDistribution;
for (uint256 i = 0; i < emissionsPerAsset.length; i++) {
totalDistribution += emissionsPerAsset[i].emission;
}
require(totalDistribution == TOTAL_DISTRIBUTION, 'INVALID_SUM_OF_EMISSIONS');

return emissionsPerAsset;
}

function _toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(value);
}
}