/
LUSDToken.sol
418 lines (340 loc) · 16 KB
/
LUSDToken.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
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
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.6.11;
import "./Interfaces/ILUSDToken.sol";
import "./Interfaces/ITroveManager.sol";
import "./Dependencies/SafeMath.sol";
import "./Dependencies/CheckContract.sol";
import "./Dependencies/console.sol";
/*
*
* Based upon OpenZeppelin's ERC20 contract:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol
*
* and their EIP2612 (ERC20Permit / ERC712) functionality:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/53516bc555a454862470e7860a9b5254db4d00f5/contracts/token/ERC20/ERC20Permit.sol
*
*
* --- Functionality added specific to the LUSDToken ---
*
* 1) Transfer protection: blacklist of addresses that are invalid recipients (i.e. core Liquity contracts) in external
* transfer() and transferFrom() calls. The purpose is to protect users from losing tokens by mistakenly sending LUSD directly to a Liquity
* core contract, when they should rather call the right function.
*
* 2) sendToPool() and returnFromPool(): functions callable only Liquity core contracts, which move LUSD tokens between Liquity <-> user.
*/
contract LUSDToken is CheckContract, ILUSDToken {
using SafeMath for uint256;
uint256 private _totalSupply;
string constant internal _NAME = "LUSD Stablecoin";
string constant internal _SYMBOL = "LUSD";
string constant internal _VERSION = "1";
uint8 constant internal _DECIMALS = 18;
bool public mintingPaused = false;
// --- Data for EIP2612 ---
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant _PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
// keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 private constant _TYPE_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
mapping (address => uint256) private _nonces;
// User data for LUSD token
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
// --- Addresses ---
// mappings store addresses of old versions so they can still burn (close troves)
mapping (address => bool) public troveManagers;
mapping (address => bool) public stabilityPools;
mapping (address => bool) public borrowerOperations;
// simple address variables track current version that can mint (in addition to burning)
// this design makes it so that only the latest version can open troves
address public troveManagerAddress;
address public stabilityPoolAddress;
address public borrowerOperationsAddress;
address public governanceAddress; // can pause/unpause minting and upgrade addresses
address public guardianAddress; // can pause minting during emergency
// Copied from LQTYToken.sol; since we deleted that file, we use LUSDToken's initialization
// to mark system deployment start time
uint internal immutable deploymentStartTime;
// --- Events ---
event TroveManagerAddressChanged(address _troveManagerAddress);
event StabilityPoolAddressChanged(address _newStabilityPoolAddress);
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event GovernanceAddressChanged(address _governanceAddress);
event GuardianAddressChanged(address _guardianAddress);
constructor
(
address _troveManagerAddress,
address _stabilityPoolAddress,
address _borrowerOperationsAddress,
address _governanceAddress,
address _guardianAddress
)
public
{
checkContract(_troveManagerAddress);
checkContract(_stabilityPoolAddress);
checkContract(_borrowerOperationsAddress);
// must be a smart contract (multi-sig, timelock, etc.)
checkContract(_governanceAddress);
checkContract(_guardianAddress);
troveManagerAddress = _troveManagerAddress;
troveManagers[_troveManagerAddress] = true;
emit TroveManagerAddressChanged(_troveManagerAddress);
stabilityPoolAddress = _stabilityPoolAddress;
stabilityPools[_stabilityPoolAddress] = true;
emit StabilityPoolAddressChanged(_stabilityPoolAddress);
borrowerOperationsAddress = _borrowerOperationsAddress;
borrowerOperations[_borrowerOperationsAddress] = true;
emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress);
governanceAddress = _governanceAddress;
emit GovernanceAddressChanged(_governanceAddress);
guardianAddress = _guardianAddress;
emit GuardianAddressChanged(_guardianAddress);
bytes32 hashedName = keccak256(bytes(_NAME));
bytes32 hashedVersion = keccak256(bytes(_VERSION));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = _chainID();
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(_TYPE_HASH, hashedName, hashedVersion);
deploymentStartTime = block.timestamp;
}
// --- Governance operations ---
function pauseMinting() external {
require(
msg.sender == guardianAddress || msg.sender == governanceAddress,
"LUSD: Caller is not guardian or governance"
);
mintingPaused = true;
}
function unpauseMinting() external {
_requireCallerIsGovernance();
mintingPaused = false;
}
function updateGovernance(address _newGovernanceAddress) external {
_requireCallerIsGovernance();
checkContract(_newGovernanceAddress); // must be a smart contract (multi-sig, timelock, etc.)
governanceAddress = _newGovernanceAddress;
emit GovernanceAddressChanged(_newGovernanceAddress);
}
function updateGuardian(address _newGuardianAddress) external {
_requireCallerIsGovernance();
checkContract(_newGuardianAddress); // must be a smart contract (multi-sig, timelock, etc.)
guardianAddress = _newGuardianAddress;
emit GuardianAddressChanged(_newGuardianAddress);
}
function upgradeProtocol(
address _newTroveManagerAddress,
address _newStabilityPoolAddress,
address _newBorrowerOperationsAddress
) external {
_requireCallerIsGovernance();
checkContract(_newTroveManagerAddress);
checkContract(_newStabilityPoolAddress);
checkContract(_newBorrowerOperationsAddress);
troveManagerAddress = _newTroveManagerAddress;
troveManagers[_newTroveManagerAddress] = true;
emit TroveManagerAddressChanged(_newTroveManagerAddress);
stabilityPoolAddress = _newStabilityPoolAddress;
stabilityPools[_newStabilityPoolAddress] = true;
emit StabilityPoolAddressChanged(_newStabilityPoolAddress);
borrowerOperationsAddress = _newBorrowerOperationsAddress;
borrowerOperations[_newBorrowerOperationsAddress] = true;
emit BorrowerOperationsAddressChanged(_newBorrowerOperationsAddress);
}
// --- Functions for intra-Liquity calls ---
function mint(address _account, uint256 _amount) external override {
_requireMintingNotPaused();
_requireCallerIsBorrowerOperations();
_mint(_account, _amount);
}
function burn(address _account, uint256 _amount) external override {
_requireCallerIsBOorTroveMorSP();
_burn(_account, _amount);
}
function sendToPool(address _sender, address _poolAddress, uint256 _amount) external override {
_requireCallerIsStabilityPool();
_transfer(_sender, _poolAddress, _amount);
}
function returnFromPool(address _poolAddress, address _receiver, uint256 _amount) external override {
_requireCallerIsTroveMorSP();
_transfer(_poolAddress, _receiver, _amount);
}
function getDeploymentStartTime() external view override returns (uint256) {
return deploymentStartTime;
}
// --- External functions ---
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_requireValidRecipient(recipient);
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_requireValidRecipient(recipient);
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) external override returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external override returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
// --- EIP 2612 Functionality ---
function domainSeparator() public view override returns (bytes32) {
if (_chainID() == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function permit
(
address owner,
address spender,
uint amount,
uint deadline,
uint8 v,
bytes32 r,
bytes32 s
)
external
override
{
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert('LUSD: Invalid s value');
}
require(deadline >= now, 'LUSD: expired deadline');
bytes32 digest = keccak256(abi.encodePacked('\x19\x01',
domainSeparator(), keccak256(abi.encode(
_PERMIT_TYPEHASH, owner, spender, amount,
_nonces[owner]++, deadline))));
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress == owner, 'LUSD: invalid signature');
_approve(owner, spender, amount);
}
function nonces(address owner) external view override returns (uint256) { // FOR EIP 2612
return _nonces[owner];
}
// --- Internal operations ---
function _chainID() private pure returns (uint256 chainID) {
assembly {
chainID := chainid()
}
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, name, version, _chainID(), address(this)));
}
// --- Internal operations ---
// Warning: sanity checks (for sender and recipient) should have been done before calling these internal functions
function _transfer(address sender, address recipient, uint256 amount) internal {
assert(sender != address(0));
assert(recipient != address(0));
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal {
assert(account != address(0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal {
assert(account != address(0));
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal {
assert(owner != address(0));
assert(spender != address(0));
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// --- 'require' functions ---
function _requireValidRecipient(address _recipient) internal view {
require(
_recipient != address(0) &&
_recipient != address(this),
"LUSD: Cannot transfer tokens directly to the LUSD token contract or the zero address"
);
require(
!stabilityPools[_recipient] &&
!troveManagers[_recipient] &&
!borrowerOperations[_recipient],
"LUSD: Cannot transfer tokens directly to the StabilityPool, TroveManager or BorrowerOps"
);
}
function _requireCallerIsBorrowerOperations() internal view {
// only latest borrowerOps version can mint
require(msg.sender == borrowerOperationsAddress, "LUSDToken: Caller is not BorrowerOperations");
}
function _requireCallerIsBOorTroveMorSP() internal view {
// old versions of the protocol may still burn
require(
troveManagers[msg.sender] ||
stabilityPools[msg.sender] ||
borrowerOperations[msg.sender],
"LUSD: Caller is neither BorrowerOperations nor TroveManager nor StabilityPool"
);
}
function _requireCallerIsStabilityPool() internal view {
// only latest stabilityPool can accept new deposits
require(msg.sender == stabilityPoolAddress, "LUSD: Caller is not the StabilityPool");
}
function _requireCallerIsTroveMorSP() internal view {
// old versions of the protocol may still:
// 1. send lusd gas reserve to liquidator
// 2. be able to return users their lusd from the stability pool
require(
troveManagers[msg.sender] || stabilityPools[msg.sender],
"LUSD: Caller is neither TroveManager nor StabilityPool");
}
function _requireCallerIsGovernance() internal view {
require(msg.sender == governanceAddress, "LUSDToken: Caller is not Governance");
}
function _requireMintingNotPaused() internal view {
require(!mintingPaused, "LUSDToken: Minting is currently paused");
}
// --- Optional functions ---
function name() external view override returns (string memory) {
return _NAME;
}
function symbol() external view override returns (string memory) {
return _SYMBOL;
}
function decimals() external view override returns (uint8) {
return _DECIMALS;
}
function version() external view override returns (string memory) {
return _VERSION;
}
function permitTypeHash() external view override returns (bytes32) {
return _PERMIT_TYPEHASH;
}
}