-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathFloki.sol
466 lines (392 loc) · 17.4 KB
/
Floki.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
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
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./governance/IGovernanceToken.sol";
import "./tax/ITaxHandler.sol";
import "./treasury/ITreasuryHandler.sol";
/**
* @title Floki token contract
* @dev The Floki token has modular systems for tax and treasury handler as well as governance capabilities.
*/
contract FLOKI is IERC20, IGovernanceToken, Ownable {
/// @dev Registry of user token balances.
mapping(address => uint256) private _balances;
/// @dev Registry of addresses users have given allowances to.
mapping(address => mapping(address => uint256)) private _allowances;
/// @notice Registry of user delegates for governance.
mapping(address => address) public delegates;
/// @notice Registry of nonces for vote delegation.
mapping(address => uint256) public nonces;
/// @notice Registry of the number of balance checkpoints an account has.
mapping(address => uint32) public numCheckpoints;
/// @notice Registry of balance checkpoints per account.
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The EIP-712 typehash for the contract's domain.
bytes32 public constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract.
bytes32 public constant DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The contract implementing tax calculations.
ITaxHandler public taxHandler;
/// @notice The contract that performs treasury-related operations.
ITreasuryHandler public treasuryHandler;
/// @notice Emitted when the tax handler contract is changed.
event TaxHandlerChanged(address oldAddress, address newAddress);
/// @notice Emitted when the treasury handler contract is changed.
event TreasuryHandlerChanged(address oldAddress, address newAddress);
/// @dev Name of the token.
string private _name;
/// @dev Symbol of the token.
string private _symbol;
/**
* @param name_ Name of the token.
* @param symbol_ Symbol of the token.
* @param taxHandlerAddress Initial tax handler contract.
* @param treasuryHandlerAddress Initial treasury handler contract.
*/
constructor(
string memory name_,
string memory symbol_,
address taxHandlerAddress,
address treasuryHandlerAddress
) {
_name = name_;
_symbol = symbol_;
taxHandler = ITaxHandler(taxHandlerAddress);
treasuryHandler = ITreasuryHandler(treasuryHandlerAddress);
_balances[_msgSender()] = totalSupply();
emit Transfer(address(0), _msgSender(), totalSupply());
}
/**
* @notice Get token name.
* @return Name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @notice Get token symbol.
* @return Symbol of the token.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @notice Get number of decimals used by the token.
* @return Number of decimals used by the token.
*/
function decimals() external pure returns (uint8) {
return 9;
}
/**
* @notice Get the maximum number of tokens.
* @return The maximum number of tokens that will ever be in existence.
*/
function totalSupply() public pure override returns (uint256) {
// Ten trillion, i.e., 10,000,000,000,000 tokens.
return 1e13 * 1e9;
}
/**
* @notice Get token balance of given account.
* @param account Address to retrieve balance for.
* @return The number of tokens owned by `account`.
*/
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
/**
* @notice Transfer tokens from caller's address to another.
* @param recipient Address to send the caller's tokens to.
* @param amount The number of tokens to transfer to recipient.
* @return True if transfer succeeds, else an error is raised.
*/
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @notice Get the allowance `owner` has given `spender`.
* @param owner The address on behalf of whom tokens can be spent by `spender`.
* @param spender The address authorized to spend tokens on behalf of `owner`.
* @return The allowance `owner` has given `spender`.
*/
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @notice Approve address to spend caller's tokens.
* @dev This method can be exploited by malicious spenders if their allowance is already non-zero. See the following
* document for details: https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/edit.
* Ensure the spender can be trusted before calling this method if they've already been approved before. Otherwise
* use either the `increaseAllowance`/`decreaseAllowance` functions, or first set their allowance to zero, before
* setting a new allowance.
* @param spender Address to authorize for token expenditure.
* @param amount The number of tokens `spender` is allowed to spend.
* @return True if the approval succeeds, else an error is raised.
*/
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @notice Transfer tokens from one address to another.
* @param sender Address to move tokens from.
* @param recipient Address to send the caller's tokens to.
* @param amount The number of tokens to transfer to recipient.
* @return True if the transfer succeeds, else an error is raised.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(
currentAllowance >= amount,
"FLOKI:transferFrom:ALLOWANCE_EXCEEDED: Transfer amount exceeds allowance."
);
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @notice Increase spender's allowance.
* @param spender Address of user authorized to spend caller's tokens.
* @param addedValue The number of tokens to add to `spender`'s allowance.
* @return True if the allowance is successfully increased, else an error is raised.
*/
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @notice Decrease spender's allowance.
* @param spender Address of user authorized to spend caller's tokens.
* @param subtractedValue The number of tokens to remove from `spender`'s allowance.
* @return True if the allowance is successfully decreased, else an error is raised.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(
currentAllowance >= subtractedValue,
"FLOKI:decreaseAllowance:ALLOWANCE_UNDERFLOW: Subtraction results in sub-zero allowance."
);
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @notice Delegate votes to given address.
* @dev It should be noted that users that want to vote themselves, also need to call this method, albeit with their
* own address.
* @param delegatee Address to delegate votes to.
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegate votes from signatory to `delegatee`.
* @param delegatee The address to delegate votes to.
* @param nonce The contract state required to match the signature.
* @param expiry The time at which to expire the signature.
* @param v The recovery byte of the signature.
* @param r Half of the ECDSA signature pair.
* @param s Half of the ECDSA signature pair.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 domainSeparator = keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), block.chainid, address(this))
);
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "FLOKI:delegateBySig:INVALID_SIGNATURE: Received signature was invalid.");
require(block.timestamp <= expiry, "FLOKI:delegateBySig:EXPIRED_SIGNATURE: Received signature has expired.");
require(nonce == nonces[signatory]++, "FLOKI:delegateBySig:INVALID_NONCE: Received nonce was invalid.");
return _delegate(signatory, delegatee);
}
/**
* @notice Determine the number of votes for an account as of a block number.
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check.
* @param blockNumber The block number to get the vote balance at.
* @return The number of votes the account had as of the given block.
*/
function getVotesAtBlock(address account, uint32 blockNumber) public view returns (uint224) {
require(
blockNumber < block.number,
"FLOKI:getVotesAtBlock:FUTURE_BLOCK: Cannot get votes at a block in the future."
);
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance.
if (checkpoints[account][nCheckpoints - 1].blockNumber <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance.
if (checkpoints[account][0].blockNumber > blockNumber) {
return 0;
}
// Perform binary search.
uint32 lowerBound = 0;
uint32 upperBound = nCheckpoints - 1;
while (upperBound > lowerBound) {
uint32 center = upperBound - (upperBound - lowerBound) / 2;
Checkpoint memory checkpoint = checkpoints[account][center];
if (checkpoint.blockNumber == blockNumber) {
return checkpoint.votes;
} else if (checkpoint.blockNumber < blockNumber) {
lowerBound = center;
} else {
upperBound = center - 1;
}
}
// No exact block found. Use last known balance before that block number.
return checkpoints[account][lowerBound].votes;
}
/**
* @notice Set new tax handler contract.
* @param taxHandlerAddress Address of new tax handler contract.
*/
function setTaxHandler(address taxHandlerAddress) external onlyOwner {
address oldTaxHandlerAddress = address(taxHandler);
taxHandler = ITaxHandler(taxHandlerAddress);
emit TaxHandlerChanged(oldTaxHandlerAddress, taxHandlerAddress);
}
/**
* @notice Set new treasury handler contract.
* @param treasuryHandlerAddress Address of new treasury handler contract.
*/
function setTreasuryHandler(address treasuryHandlerAddress) external onlyOwner {
address oldTreasuryHandlerAddress = address(treasuryHandler);
treasuryHandler = ITreasuryHandler(treasuryHandlerAddress);
emit TreasuryHandlerChanged(oldTreasuryHandlerAddress, treasuryHandlerAddress);
}
/**
* @notice Delegate votes from one address to another.
* @param delegator Address from which to delegate votes for.
* @param delegatee Address to delegate votes to.
*/
function _delegate(address delegator, address delegatee) private {
address currentDelegate = delegates[delegator];
uint256 delegatorBalance = _balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, uint224(delegatorBalance));
}
/**
* @notice Move delegates from one address to another.
* @param from Representative to move delegates from.
* @param to Representative to move delegates to.
* @param amount Number of delegates to move.
*/
function _moveDelegates(
address from,
address to,
uint224 amount
) private {
// No need to update checkpoints if the votes don't actually move between different delegates. This can be the
// case where tokens are transferred between two parties that have delegated their votes to the same address.
if (from == to) {
return;
}
// Some users preemptively delegate their votes (i.e. before they have any tokens). No need to perform an update
// to the checkpoints in that case.
if (amount == 0) {
return;
}
if (from != address(0)) {
uint32 fromRepNum = numCheckpoints[from];
uint224 fromRepOld = fromRepNum > 0 ? checkpoints[from][fromRepNum - 1].votes : 0;
uint224 fromRepNew = fromRepOld - amount;
_writeCheckpoint(from, fromRepNum, fromRepOld, fromRepNew);
}
if (to != address(0)) {
uint32 toRepNum = numCheckpoints[to];
uint224 toRepOld = toRepNum > 0 ? checkpoints[to][toRepNum - 1].votes : 0;
uint224 toRepNew = toRepOld + amount;
_writeCheckpoint(to, toRepNum, toRepOld, toRepNew);
}
}
/**
* @notice Write balance checkpoint to chain.
* @param delegatee The address to write the checkpoint for.
* @param nCheckpoints The number of checkpoints `delegatee` already has.
* @param oldVotes Number of votes prior to this checkpoint.
* @param newVotes Number of votes `delegatee` now has.
*/
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint224 oldVotes,
uint224 newVotes
) private {
uint32 blockNumber = uint32(block.number);
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].blockNumber == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
/**
* @notice Approve spender on behalf of owner.
* @param owner Address on behalf of whom tokens can be spent by `spender`.
* @param spender Address to authorize for token expenditure.
* @param amount The number of tokens `spender` is allowed to spend.
*/
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "FLOKI:_approve:OWNER_ZERO: Cannot approve for the zero address.");
require(spender != address(0), "FLOKI:_approve:SPENDER_ZERO: Cannot approve to the zero address.");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Transfer `amount` tokens from account `from` to account `to`.
* @param from Address the tokens are moved out of.
* @param to Address the tokens are moved to.
* @param amount The number of tokens to transfer.
*/
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "FLOKI:_transfer:FROM_ZERO: Cannot transfer from the zero address.");
require(to != address(0), "FLOKI:_transfer:TO_ZERO: Cannot transfer to the zero address.");
require(amount > 0, "FLOKI:_transfer:ZERO_AMOUNT: Transfer amount must be greater than zero.");
require(amount <= _balances[from], "FLOKI:_transfer:INSUFFICIENT_BALANCE: Transfer amount exceeds balance.");
treasuryHandler.beforeTransferHandler(from, to, amount);
uint256 tax = taxHandler.getTax(from, to, amount);
uint256 taxedAmount = amount - tax;
_balances[from] -= amount;
_balances[to] += taxedAmount;
_moveDelegates(delegates[from], delegates[to], uint224(taxedAmount));
if (tax > 0) {
_balances[address(treasuryHandler)] += tax;
_moveDelegates(delegates[from], delegates[address(treasuryHandler)], uint224(tax));
emit Transfer(from, address(treasuryHandler), tax);
}
treasuryHandler.afterTransferHandler(from, to, amount);
emit Transfer(from, to, taxedAmount);
}
}