generated from AngleProtocol/boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Distributor.sol
347 lines (288 loc) · 16.4 KB
/
Distributor.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// SPDX-License-Identifier: BUSL-1.1
/*
* █
***** ▓▓▓
* ▓▓▓▓▓▓▓
* ///. ▓▓▓▓▓▓▓▓▓▓▓▓▓
***** //////// ▓▓▓▓▓▓▓
* ///////////// ▓▓▓
▓▓ ////////////////// █ ▓▓
▓▓ ▓▓ /////////////////////// ▓▓ ▓▓
▓▓ ▓▓ //////////////////////////// ▓▓ ▓▓
▓▓ ▓▓ /////////▓▓▓///////▓▓▓///////// ▓▓ ▓▓
▓▓ ,////////////////////////////////////// ▓▓ ▓▓
▓▓ ////////////////////////////////////////// ▓▓
▓▓ //////////////////////▓▓▓▓/////////////////////
,////////////////////////////////////////////////////
.//////////////////////////////////////////////////////////
.//////////////////////////██.,//////////////////////////█
.//////////////////////████..,./////////////////////██
...////////////////███████.....,.////////////////███
,.,////////////████████ ........,///////////████
.,.,//////█████████ ,.......///////████
,..//████████ ........./████
..,██████ .....,███
.██ ,.,█
▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓ ▓▓▓ ▓▓▓ ▓▓ ▓▓ ▓▓▓▓
▓▓▓ ▓▓▓ ▓▓▓ ▓▓▓ ▓▓▓ ▓▓▓ ▓▓ ▓▓▓▓▓
▓▓▓ ▓▓ ▓▓▓ ▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
*/
pragma solidity ^0.8.17;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./utils/UUPSHelper.sol";
struct MerkleTree {
// Root of a Merkle tree which leaves are `(address user, address token, uint amount)`
// representing an amount of tokens accumulated by `user`.
// The Merkle tree is assumed to have only increasing amounts: that is to say if a user can claim 1,
// then after the amount associated in the Merkle tree for this token should be x > 1
bytes32 merkleRoot;
// Ipfs hash of the tree data
bytes32 ipfsHash;
}
struct Claim {
uint208 amount;
uint48 timestamp;
}
/// @title Distributor
/// @notice Allows LPs on AMMs with concentrated liquidity to claim the rewards that were distributed to them
/// @author Angle Labs. Inc
contract Distributor is UUPSHelper {
using SafeERC20 for IERC20;
/// @notice Epoch duration
uint32 internal constant _EPOCH_DURATION = 3600;
// ================================= VARIABLES =================================
/// @notice Tree of claimable tokens through this contract
MerkleTree public tree;
/// @notice Tree that was in place in the contract before the last `tree` update
MerkleTree public lastTree;
/// @notice Token to deposit to freeze the roots update
IERC20 public disputeToken;
/// @notice `Core` contract handling access control
ICore public core;
/// @notice Address which created the dispute
/// @dev Used to store if there is an ongoing dispute
address public disputer;
/// @notice When the current tree will become valid
uint48 public endOfDisputePeriod;
/// @notice Time before which a change in a tree becomes effective, in EPOCH_DURATION
uint48 public disputePeriod;
/// @notice Amount to deposit to freeze the roots update
uint256 public disputeAmount;
/// @notice Mapping user -> token -> amount to track claimed amounts
mapping(address => mapping(address => Claim)) public claimed;
/// @notice Trusted EOAs to update the Merkle root
mapping(address => uint256) public canUpdateMerkleRoot;
/// @notice Whether or not to disable permissionless claiming
mapping(address => uint256) public onlyOperatorCanClaim;
/// @notice user -> operator -> authorisation to claim
mapping(address => mapping(address => uint256)) public operators;
uint256[38] private __gap;
// =================================== EVENTS ==================================
event Claimed(address user, address token, uint256 amount);
event DisputeAmountUpdated(uint256 _disputeAmount);
event Disputed(string reason);
event DisputePeriodUpdated(uint48 _disputePeriod);
event DisputeResolved(bool valid);
event DisputeTokenUpdated(address indexed _disputeToken);
event OperatorClaimingToggled(address user, bool isEnabled);
event OperatorToggled(address user, address operator, bool isWhitelisted);
event Recovered(address indexed token, address indexed to, uint256 amount);
event Revoked(); // With this event an indexer could maintain a table (timestamp, merkleRootUpdate)
event TreeUpdated(bytes32 merkleRoot, bytes32 ipfsHash, uint48 endOfDisputePeriod);
event TrustedToggled(address indexed eoa, bool trust);
// ================================= MODIFIERS =================================
/// @notice Checks whether the `msg.sender` has the governor role or the guardian role
modifier onlyGovernorOrGuardian() {
if (!core.isGovernorOrGuardian(msg.sender)) revert NotGovernorOrGuardian();
_;
}
/// @notice Checks whether the `msg.sender` is the `user` address or is a trusted address
modifier onlyTrustedOrUser(address user) {
if (user != msg.sender && canUpdateMerkleRoot[msg.sender] != 1 && !core.isGovernorOrGuardian(msg.sender))
revert NotTrusted();
_;
}
// ================================ CONSTRUCTOR ================================
constructor() initializer {}
function initialize(ICore _core) external initializer {
if (address(_core) == address(0)) revert ZeroAddress();
core = _core;
}
/// @inheritdoc UUPSUpgradeable
function _authorizeUpgrade(address) internal view override onlyGuardianUpgrader(core) {}
// =============================== MAIN FUNCTION ===============================
/// @notice Claims rewards for a given set of users
/// @dev Anyone may call this function for anyone else, funds go to destination regardless, it's just a question of
/// who provides the proof and pays the gas: `msg.sender` is used only for addresses that require a trusted operator
/// @param users Recipient of tokens
/// @param tokens ERC20 claimed
/// @param amounts Amount of tokens that will be sent to the corresponding users
/// @param proofs Array of hashes bridging from a leaf `(hash of user | token | amount)` to the Merkle root
function claim(
address[] calldata users,
address[] calldata tokens,
uint256[] calldata amounts,
bytes32[][] calldata proofs
) external {
uint256 usersLength = users.length;
if (
usersLength == 0 ||
usersLength != tokens.length ||
usersLength != amounts.length ||
usersLength != proofs.length
) revert InvalidLengths();
for (uint256 i; i < usersLength; ) {
address user = users[i];
address token = tokens[i];
uint256 amount = amounts[i];
// Checking if only an approved operator can claim for `user`
if (onlyOperatorCanClaim[user] == 1 && operators[user][msg.sender] == 0) revert NotWhitelisted();
// Verifying proof
bytes32 leaf = keccak256(abi.encode(user, token, amount));
if (!_verifyProof(leaf, proofs[i])) revert InvalidProof();
// Closing reentrancy gate here
uint256 toSend = amount - claimed[user][token].amount;
claimed[user][token] = Claim(SafeCast.toUint208(amount), uint48(block.timestamp));
IERC20(token).safeTransfer(user, toSend);
emit Claimed(user, token, toSend);
unchecked {
++i;
}
}
}
/// @notice Returns the MerkleRoot that is currently live for the contract
function getMerkleRoot() public view returns (bytes32) {
if (block.timestamp >= endOfDisputePeriod && disputer == address(0)) return tree.merkleRoot;
else return lastTree.merkleRoot;
}
// ============================ GOVERNANCE FUNCTIONS ===========================
/// @notice Adds or removes EOAs which are trusted to update the Merkle root
function toggleTrusted(address eoa) external onlyGovernorOrGuardian {
uint256 trustedStatus = 1 - canUpdateMerkleRoot[eoa];
canUpdateMerkleRoot[eoa] = trustedStatus;
emit TrustedToggled(eoa, trustedStatus == 1);
}
/// @notice Updates Merkle Tree
function updateTree(MerkleTree calldata _tree) external {
if (
disputer != address(0) ||
// A trusted address cannot update a tree right after a precedent tree update otherwise it can de facto
// validate a tree which has not passed the dispute period
((canUpdateMerkleRoot[msg.sender] != 1 || block.timestamp < endOfDisputePeriod) &&
!core.isGovernorOrGuardian(msg.sender))
) revert NotTrusted();
MerkleTree memory _lastTree = tree;
tree = _tree;
lastTree = _lastTree;
uint48 _endOfPeriod = _endOfDisputePeriod(uint48(block.timestamp));
endOfDisputePeriod = _endOfPeriod;
emit TreeUpdated(_tree.merkleRoot, _tree.ipfsHash, _endOfPeriod);
}
/// @notice Freezes the Merkle tree update until the dispute is resolved
/// @dev Requires a deposit of `disputeToken` that'll be slashed if the dispute is not accepted
/// @dev It is only possible to create a dispute within `disputePeriod` after each tree update
function disputeTree(string memory reason) external {
if (disputer != address(0)) revert UnresolvedDispute();
if (block.timestamp >= endOfDisputePeriod) revert InvalidDispute();
IERC20(disputeToken).safeTransferFrom(msg.sender, address(this), disputeAmount);
disputer = msg.sender;
emit Disputed(reason);
}
/// @notice Resolve the ongoing dispute, if any
/// @param valid Whether the dispute was valid
function resolveDispute(bool valid) external onlyGovernorOrGuardian {
if (disputer == address(0)) revert NoDispute();
if (valid) {
IERC20(disputeToken).safeTransfer(disputer, disputeAmount);
// If a dispute is valid, the contract falls back to the last tree that was updated
_revokeTree();
} else {
IERC20(disputeToken).safeTransfer(msg.sender, disputeAmount);
endOfDisputePeriod = _endOfDisputePeriod(uint48(block.timestamp));
}
disputer = address(0);
emit DisputeResolved(valid);
}
/// @notice Allows the governor or the guardian of this contract to fallback to the last version of the tree
/// immediately
function revokeTree() external onlyGovernorOrGuardian {
if (disputer != address(0)) revert UnresolvedDispute();
_revokeTree();
}
/// @notice Toggles permissioned claiming for a given user
function toggleOnlyOperatorCanClaim(address user) external onlyTrustedOrUser(user) {
uint256 oldValue = onlyOperatorCanClaim[user];
onlyOperatorCanClaim[user] = 1 - oldValue;
emit OperatorClaimingToggled(user, oldValue == 0);
}
/// @notice Toggles whitelisting for a given user and a given operator
function toggleOperator(address user, address operator) external onlyTrustedOrUser(user) {
uint256 oldValue = operators[user][operator];
operators[user][operator] = 1 - oldValue;
emit OperatorToggled(user, operator, oldValue == 0);
}
/// @notice Recovers any ERC20 token
function recoverERC20(address tokenAddress, address to, uint256 amountToRecover) external onlyGovernorOrGuardian {
IERC20(tokenAddress).safeTransfer(to, amountToRecover);
emit Recovered(tokenAddress, to, amountToRecover);
}
/// @notice Sets the dispute period before which a tree update becomes effective
function setDisputePeriod(uint48 _disputePeriod) external onlyGovernorOrGuardian {
disputePeriod = uint48(_disputePeriod);
emit DisputePeriodUpdated(_disputePeriod);
}
/// @notice Sets the token used as a caution during disputes
function setDisputeToken(IERC20 _disputeToken) external onlyGovernorOrGuardian {
if (disputer != address(0)) revert UnresolvedDispute();
disputeToken = _disputeToken;
emit DisputeTokenUpdated(address(_disputeToken));
}
/// @notice Sets the amount of `disputeToken` used as a caution during disputes
function setDisputeAmount(uint256 _disputeAmount) external onlyGovernorOrGuardian {
if (disputer != address(0)) revert UnresolvedDispute();
disputeAmount = _disputeAmount;
emit DisputeAmountUpdated(_disputeAmount);
}
// ============================= INTERNAL FUNCTIONS ============================
/// @notice Fallback to the last version of the tree
function _revokeTree() internal {
MerkleTree memory _tree = lastTree;
endOfDisputePeriod = 0;
tree = _tree;
emit Revoked();
emit TreeUpdated(
_tree.merkleRoot,
_tree.ipfsHash,
(uint48(block.timestamp) / _EPOCH_DURATION) * (_EPOCH_DURATION) // Last hour
);
}
/// @notice Returns the end of the dispute period
/// @dev treeUpdate is rounded up to next hour and then `disputePeriod` hours are added
function _endOfDisputePeriod(uint48 treeUpdate) internal view returns (uint48) {
return ((treeUpdate - 1) / _EPOCH_DURATION + 1 + disputePeriod) * (_EPOCH_DURATION);
}
/// @notice Checks the validity of a proof
/// @param leaf Hashed leaf data, the starting point of the proof
/// @param proof Array of hashes forming a hash chain from leaf to root
/// @return true If proof is correct, else false
function _verifyProof(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) {
bytes32 currentHash = leaf;
uint256 proofLength = proof.length;
for (uint256 i; i < proofLength; ) {
if (currentHash < proof[i]) {
currentHash = keccak256(abi.encode(currentHash, proof[i]));
} else {
currentHash = keccak256(abi.encode(proof[i], currentHash));
}
unchecked {
++i;
}
}
bytes32 root = getMerkleRoot();
if (root == bytes32(0)) revert InvalidUninitializedRoot();
return currentHash == root;
}
}