-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathOffsetHelper.sol
More file actions
559 lines (498 loc) · 19.9 KB
/
OffsetHelper.sol
File metadata and controls
559 lines (498 loc) · 19.9 KB
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "./OffsetHelperStorage.sol";
import "./interfaces/IToucanPoolToken.sol";
import "./interfaces/IToucanCarbonOffsets.sol";
import "./interfaces/IToucanContractRegistry.sol";
import "hardhat/console.sol";
/**
* @title Toucan Protocol Offset Helpers
* @notice Helper functions that simplify the carbon offsetting (retirement)
* process.
*
* Retiring carbon tokens requires multiple steps and interactions with
* Toucan Protocol's main contracts:
* 1. Obtain a Toucan pool token such as BCT or NCT (by performing a token
* swap).
* 2. Redeem the pool token for a TCO2 token.
* 3. Retire the TCO2 token.
*
* These steps are combined in each of the following "auto offset" methods
* implemented in `OffsetHelper` to allow a retirement within one transaction:
* - `autoOffsetUsingPoolToken()` if the user already owns a Toucan pool
* token such as BCT or NCT,
* - `autoOffsetUsingETH()` if the user would like to perform a retirement
* using MATIC,
* - `autoOffsetUsingToken()` if the user would like to perform a retirement
* using an ERC20 token: USDC, WETH or WMATIC.
*
* In these methods, "auto" refers to the fact that these methods use
* `autoRedeem()` in order to automatically choose a TCO2 token corresponding
* to the oldest tokenized carbon project in the specfified token pool.
* There are no fees incurred by the user when using `autoRedeem()`, i.e., the
* user receives 1 TCO2 token for each pool token (BCT/NCT) redeemed.
*
* There are two `view` helper functions `calculateNeededETHAmount()` and
* `calculateNeededTokenAmount()` that should be called before using
* `autoOffsetUsingETH()` and `autoOffsetUsingToken()`, to determine how much
* MATIC, respectively how much of the ERC20 token must be sent to the
* `OffsetHelper` contract in order to retire the specified amount of carbon.
*/
contract OffsetHelper is OffsetHelperStorage {
using SafeERC20 for IERC20;
/**
* @notice Contract constructor. Should specify arrays of ERC20 symbols and
* addresses that can used by the contract.
*
* @dev See `isEligible()` for a list of tokens that can be used in the
* contract. These can be modified after deployment by the contract owner
* using `setEligibleTokenAddress()` and `deleteEligibleTokenAddress()`.
*
* @param _eligibleTokenSymbols A list of token symbols.
* @param _eligibleTokenAddresses A list of token addresses corresponding
* to the provided token symbols.
*/
constructor(
string[] memory _eligibleTokenSymbols,
address[] memory _eligibleTokenAddresses
) {
uint256 i = 0;
uint256 eligibleTokenSymbolsLen = _eligibleTokenSymbols.length;
while (i < eligibleTokenSymbolsLen) {
eligibleTokenAddresses[
_eligibleTokenSymbols[i]
] = _eligibleTokenAddresses[i];
i += 1;
}
}
/**
* @notice Emitted upon successful redemption of TCO2 tokens from a Toucan
* pool token such as BCT or NCT.
*
* @param who The sender of the transaction
* @param poolToken The address of the Toucan pool token used in the
* redemption, for example, NCT or BCT
* @param tco2s An array of the TCO2 addresses that were redeemed
* @param amounts An array of the amounts of each TCO2 that were redeemed
*/
event Redeemed(
address who,
address poolToken,
address[] tco2s,
uint256[] amounts
);
/**
* @notice Retire carbon credits using the lowest quality (oldest) TCO2
* tokens available from the specified Toucan token pool by sending ERC20
* tokens (USDC, WETH, WMATIC). Use `calculateNeededTokenAmount` first in
* order to find out how much of the ERC20 token is required to retire the
* specified quantity of TCO2.
*
* This function:
* 1. Swaps the ERC20 token sent to the contract for the specified pool token.
* 2. Redeems the pool token for the poorest quality TCO2 tokens available.
* 3. Retires the TCO2 tokens.
*
* Note: The client must approve the ERC20 token that is sent to the contract.
*
* @dev When automatically redeeming pool tokens for the lowest quality
* TCO2s there are no fees and you receive exactly 1 TCO2 token for 1 pool
* token.
*
* @param _depositedToken The address of the ERC20 token that the user sends
* (must be one of USDC, WETH, WMATIC)
* @param _poolToken The address of the Toucan pool token that the
* user wants to use, for example, NCT or BCT
* @param _amountToOffset The amount of TCO2 to offset
*
* @return tco2s An array of the TCO2 addresses that were redeemed
* @return amounts An array of the amounts of each TCO2 that were redeemed
*/
function autoOffsetUsingToken(
address _depositedToken,
address _poolToken,
uint256 _amountToOffset
) public returns (address[] memory tco2s, uint256[] memory amounts) {
// swap input token for BCT / NCT
swap(_depositedToken, _poolToken, _amountToOffset);
// redeem BCT / NCT for TCO2s
(tco2s, amounts) = autoRedeem(_poolToken, _amountToOffset);
// retire the TCO2s to achieve offset
autoRetire(tco2s, amounts);
}
/**
* @notice Retire carbon credits using the lowest quality (oldest) TCO2
* tokens available from the specified Toucan token pool by sending MATIC.
* Use `calculateNeededETHAmount()` first in order to find out how much
* MATIC is required to retire the specified quantity of TCO2.
*
* This function:
* 1. Swaps the Matic sent to the contract for the specified pool token.
* 2. Redeems the pool token for the poorest quality TCO2 tokens available.
* 3. Retires the TCO2 tokens.
*
* @dev If the user sends much MATIC, the leftover amount will be sent back
* to the user.
*
* @param _poolToken The address of the Toucan pool token that the
* user wants to use, for example, NCT or BCT.
* @param _amountToOffset The amount of TCO2 to offset.
*
* @return tco2s An array of the TCO2 addresses that were redeemed
* @return amounts An array of the amounts of each TCO2 that were redeemed
*/
function autoOffsetUsingETH(address _poolToken, uint256 _amountToOffset)
public
payable
returns (address[] memory tco2s, uint256[] memory amounts)
{
// swap MATIC for BCT / NCT
swap(_poolToken, _amountToOffset);
// redeem BCT / NCT for TCO2s
(tco2s, amounts) = autoRedeem(_poolToken, _amountToOffset);
// retire the TCO2s to achieve offset
autoRetire(tco2s, amounts);
}
/**
* @notice Retire carbon credits using the lowest quality (oldest) TCO2
* tokens available by sending Toucan pool tokens, for example, BCT or NCT.
*
* This function:
* 1. Redeems the pool token for the poorest quality TCO2 tokens available.
* 2. Retires the TCO2 tokens.
*
* Note: The client must approve the pool token that is sent.
*
* @param _poolToken The address of the Toucan pool token that the
* user wants to use, for example, NCT or BCT.
* @param _amountToOffset The amount of TCO2 to offset.
*
* @return tco2s An array of the TCO2 addresses that were redeemed
* @return amounts An array of the amounts of each TCO2 that were redeemed
*/
function autoOffsetUsingPoolToken(
address _poolToken,
uint256 _amountToOffset
) public returns (address[] memory tco2s, uint256[] memory amounts) {
// deposit pool token from user to this contract
deposit(_poolToken, _amountToOffset);
// redeem BCT / NCT for TCO2s
(tco2s, amounts) = autoRedeem(_poolToken, _amountToOffset);
// retire the TCO2s to achieve offset
autoRetire(tco2s, amounts);
}
/**
* @notice Checks whether an address can be used by the contract.
* @param _erc20Address address of the ERC20 token to be checked
* @return True if the address can be used by the contract
*/
function isEligible(address _erc20Address) private view returns (bool) {
bool isToucanContract = IToucanContractRegistry(contractRegistryAddress)
.checkERC20(_erc20Address);
if (isToucanContract) return true;
if (_erc20Address == eligibleTokenAddresses["BCT"]) return true;
if (_erc20Address == eligibleTokenAddresses["NCT"]) return true;
if (_erc20Address == eligibleTokenAddresses["USDC"]) return true;
if (_erc20Address == eligibleTokenAddresses["WETH"]) return true;
if (_erc20Address == eligibleTokenAddresses["WMATIC"]) return true;
return false;
}
/**
* @notice Checks whether an address can be used in a token swap
* @param _erc20Address address of token to be checked
* @return True if the specified address can be used in a swap
*/
function isSwapable(address _erc20Address) private view returns (bool) {
if (_erc20Address == eligibleTokenAddresses["USDC"]) return true;
if (_erc20Address == eligibleTokenAddresses["WETH"]) return true;
if (_erc20Address == eligibleTokenAddresses["WMATIC"]) return true;
return false;
}
/**
* @notice Checks whether an address is a Toucan pool token address
* @param _erc20Address address of token to be checked
* @return True if the address is a Toucan pool token address
*/
function isRedeemable(address _erc20Address) private view returns (bool) {
if (_erc20Address == eligibleTokenAddresses["BCT"]) return true;
if (_erc20Address == eligibleTokenAddresses["NCT"]) return true;
return false;
}
/**
* @notice Return how much of the specified ERC20 token is required in
* order to swap for the desired amount of a Toucan pool token, for
* example, BCT or NCT.
*
* @param _fromToken The address of the ERC20 token used for the swap
* @param _toToken The address of the pool token to swap for,
* for example, NCT or BCT
* @param _amount The desired amount of pool token to receive
* @return amountsIn The amount of the ERC20 token required in order to
* swap for the specified amount of the pool token
*/
function calculateNeededTokenAmount(
address _fromToken,
address _toToken,
uint256 _amount
) public view returns (uint256) {
// check tokens
require(
isSwapable(_fromToken) && isRedeemable(_toToken),
"Token not eligible"
);
// instantiate router
IUniswapV2Router02 routerSushi = IUniswapV2Router02(sushiRouterAddress);
// generate path
address[] memory path = generatePath(_fromToken, _toToken);
// get expected amountsIn
uint256[] memory amountsIn = routerSushi.getAmountsIn(_amount, path);
return amountsIn[0];
}
/**
* @notice Swap eligible ERC20 tokens for Toucan pool tokens (BCT/NCT) on SushiSwap
* @dev Needs to be approved on the client side
* @param _fromToken The ERC20 oken to deposit and swap
* @param _toToken The token to swap for (will be held within contract)
* @param _amount The required amount of the Toucan pool token (NCT/BCT)
*/
function swap(
address _fromToken,
address _toToken,
uint256 _amount
) public {
// check tokens
require(
isSwapable(_fromToken) && isRedeemable(_toToken),
"Token not eligible"
);
// instantiate router
IUniswapV2Router02 routerSushi = IUniswapV2Router02(sushiRouterAddress);
// generate path
address[] memory path = generatePath(_fromToken, _toToken);
// estimate amountsIn
uint256[] memory expectedAmountsIn = routerSushi.getAmountsIn(
_amount,
path
);
// transfer tokens
IERC20(_fromToken).safeTransferFrom(
msg.sender,
address(this),
expectedAmountsIn[0]
);
// approve router
IERC20(_fromToken).approve(sushiRouterAddress, expectedAmountsIn[0]);
// swap
routerSushi.swapTokensForExactTokens(
_amount,
expectedAmountsIn[0],
path,
address(this),
block.timestamp
);
// update balances
balances[msg.sender][_toToken] += _amount;
}
// apparently I need a fallback and a receive method to fix the situation where transfering dust MATIC
// in the MATIC to token swap fails
fallback() external payable {}
receive() external payable {}
/**
* @notice Return how much MATIC is required in order to swap for the
* desired amount of a Toucan pool token, for example, BCT or NCT.
*
* @param _toToken The address of the pool token to swap for, for
* example, NCT or BCT
* @param _amount The desired amount of pool token to receive
* @return amounts The amount of MATIC required in order to swap for
* the specified amount of the pool token
*/
function calculateNeededETHAmount(address _toToken, uint256 _amount)
public
view
returns (uint256)
{
// check token
require(isRedeemable(_toToken), "Token not eligible");
// instantiate router
IUniswapV2Router02 routerSushi = IUniswapV2Router02(sushiRouterAddress);
// generate path
address[] memory path = generatePath(
eligibleTokenAddresses["WMATIC"],
_toToken
);
// get expectedAmountsIn
uint256[] memory amounts = routerSushi.getAmountsIn(_amount, path);
return amounts[0];
}
/**
* @notice Swap MATIC for Toucan pool tokens (BCT/NCT) on SushiSwap
* @param _toToken Token to swap for (will be held within contract)
* @param _amount Amount of NCT / BCT wanted
*/
function swap(address _toToken, uint256 _amount) public payable {
// check tokens
require(isRedeemable(_toToken), "Token not eligible");
// instantiate router
IUniswapV2Router02 routerSushi = IUniswapV2Router02(sushiRouterAddress);
// generate path
address[] memory path = generatePath(
eligibleTokenAddresses["WMATIC"],
_toToken
);
// estimate amountsIn
uint256[] memory expectedAmountsIn = routerSushi.getAmountsIn(
_amount,
path
);
// check user sent enough ETH/MATIC
require(msg.value >= expectedAmountsIn[0], "Didn't send enough MATIC");
// swap
uint256[] memory amountsIn = routerSushi.swapETHForExactTokens{
value: msg.value
}(_amount, path, address(this), block.timestamp);
// send surplus back
if (msg.value > amountsIn[0]) {
uint256 leftoverETH = msg.value - amountsIn[0];
(bool success, ) = msg.sender.call{value: leftoverETH}(
new bytes(0)
);
require(success, "Failed to send surplus back");
}
// update balances
balances[msg.sender][_toToken] += _amount;
}
/**
* @notice Allow users to withdraw tokens they have deposited.
*/
function withdraw(address _erc20Addr, uint256 _amount) public {
require(
balances[msg.sender][_erc20Addr] >= _amount,
"Insufficient balance"
);
IERC20(_erc20Addr).safeTransfer(msg.sender, _amount);
balances[msg.sender][_erc20Addr] -= _amount;
}
/**
* @notice Allow users to deposit BCT / NCT.
* @dev Needs to be approved
*/
function deposit(address _erc20Addr, uint256 _amount) public {
require(isRedeemable(_erc20Addr), "Token not eligible");
IERC20(_erc20Addr).safeTransferFrom(msg.sender, address(this), _amount);
balances[msg.sender][_erc20Addr] += _amount;
}
/**
* @notice Redeems the specified amount of NCT / BCT for TCO2.
* @dev Needs to be approved on the client side
* @param _fromToken Could be the address of NCT or BCT
* @param _amount Amount to redeem
* @return tco2s An array of the TCO2 addresses that were redeemed
* @return amounts An array of the amounts of each TCO2 that were redeemed
*/
function autoRedeem(address _fromToken, uint256 _amount)
public
returns (address[] memory tco2s, uint256[] memory amounts)
{
require(isRedeemable(_fromToken), "Token not eligible");
require(
balances[msg.sender][_fromToken] >= _amount,
"Insufficient NCT/BCT balance"
);
// instantiate pool token (NCT or BCT)
IToucanPoolToken PoolTokenImplementation = IToucanPoolToken(_fromToken);
// auto redeem pool token for TCO2; will transfer automatically picked TCO2 to this contract
(tco2s, amounts) = PoolTokenImplementation.redeemAuto2(_amount);
// update balances
balances[msg.sender][_fromToken] -= _amount;
uint256 tco2sLen = tco2s.length;
for (uint256 index = 0; index < tco2sLen; index++) {
balances[msg.sender][tco2s[index]] += amounts[index];
}
emit Redeemed(msg.sender, _fromToken, tco2s, amounts);
}
/**
* @notice Retire the specified TCO2 tokens.
* @param _tco2s The addresses of the TCO2s to retire
* @param _amounts The amounts to retire from each of the corresponding
* TCO2 addresses
*/
function autoRetire(address[] memory _tco2s, uint256[] memory _amounts)
public
{
uint256 tco2sLen = _tco2s.length;
require(tco2sLen != 0, "Array empty");
require(tco2sLen == _amounts.length, "Arrays unequal");
uint256 i = 0;
while (i < tco2sLen) {
require(
balances[msg.sender][_tco2s[i]] >= _amounts[i],
"Insufficient TCO2 balance"
);
if (_amounts[i] > 0) {
balances[msg.sender][_tco2s[i]] -= _amounts[i];
IToucanCarbonOffsets(_tco2s[i]).retire(_amounts[i]);
}
unchecked {
++i;
}
}
}
function generatePath(address _fromToken, address _toToken)
internal
view
returns (address[] memory)
{
if (_fromToken == eligibleTokenAddresses["USDC"]) {
address[] memory path = new address[](2);
path[0] = _fromToken;
path[1] = _toToken;
return path;
} else {
address[] memory path = new address[](3);
path[0] = _fromToken;
path[1] = eligibleTokenAddresses["USDC"];
path[2] = _toToken;
return path;
}
}
// ----------------------------------------
// Admin methods
// ----------------------------------------
/**
* @notice Change or add eligible tokens and their addresses.
* @param _tokenSymbol The symbol of the token to add
* @param _address The address of the token to add
*/
function setEligibleTokenAddress(
string memory _tokenSymbol,
address _address
) public virtual onlyOwner {
eligibleTokenAddresses[_tokenSymbol] = _address;
}
/**
* @notice Delete eligible tokens stored in the contract.
* @param _tokenSymbol The symbol of the token to remove
*/
function deleteEligibleTokenAddress(string memory _tokenSymbol)
public
virtual
onlyOwner
{
delete eligibleTokenAddresses[_tokenSymbol];
}
/**
* @notice Change the TCO2 contracts registry.
* @param _address The address of the Toucan contract registry to use
*/
function setToucanContractRegistry(address _address)
public
virtual
onlyOwner
{
contractRegistryAddress = _address;
}
}