-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdvancedERC20.sol
2051 lines (1823 loc) · 82.2 KB
/
AdvancedERC20.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
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../interfaces/ERC1363Spec.sol";
import "../interfaces/EIP2612.sol";
import "../interfaces/EIP3009.sol";
import "../lib/AddressUtils.sol";
import "../lib/ECDSA.sol";
import "@ai-protocol/access-control-upgradeable/contracts/InitializableAccessControl.sol";
/**
* @title Advanced ERC20
*
* @notice Feature rich lightweight ERC20 implementation which is not built on top of OpenZeppelin ERC20 implementation.
* It uses some other OpenZeppelin code:
* - low level functions to work with ECDSA signatures (recover)
* - low level functions to work contract addresses (isContract)
* - OZ UUPS proxy and smart contracts upgradeability code
*
* @notice Token Summary:
* - Symbol: configurable (set on deployment)
* - Name: configurable (set on deployment)
* - Decimals: 18
* - Initial/maximum total supply: configurable (set on deployment)
* - Initial supply holder (initial holder) address: configurable (set on deployment)
* - Mintability: configurable (initially enabled, but possible to revoke forever)
* - Burnability: configurable (initially enabled, but possible to revoke forever)
* - DAO Support: supports voting delegation
*
* @notice Features Summary:
* - Supports atomic allowance modification, resolves well-known ERC20 issue with approve (arXiv:1907.00903)
* - Voting delegation and delegation on behalf via EIP-712 (like in Compound CMP token) - gives the token
* powerful governance capabilities by allowing holders to form voting groups by electing delegates
* - Unlimited approval feature (like in 0x ZRX token) - saves gas for transfers on behalf
* by eliminating the need to update “unlimited” allowance value
* - ERC-1363 Payable Token - ERC721-like callback execution mechanism for transfers,
* transfers on behalf and approvals; allows creation of smart contracts capable of executing callbacks
* in response to transfer or approval in a single transaction
* - EIP-2612: permit - 712-signed approvals - improves user experience by allowing to use a token
* without having an ETH to pay gas fees
* - EIP-3009: Transfer With Authorization - improves user experience by allowing to use a token
* without having an ETH to pay gas fees
*
* @dev Even though smart contract has mint() function which is used to mint initial token supply,
* the function is disabled forever after smart contract deployment by revoking `TOKEN_CREATOR`
* permission from the deployer account
*
* @dev Token balances and total supply are effectively 192 bits long, meaning that maximum
* possible total supply smart contract is able to track is 2^192 (close to 10^40 tokens)
*
* @dev Smart contract doesn't use safe math. All arithmetic operations are overflow/underflow safe.
* Additionally, Solidity 0.8.7 enforces overflow/underflow safety.
*
* @dev Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) - resolved
* Related events and functions are marked with "arXiv:1907.00903" tag:
* - event Transfer(address indexed _by, address indexed _from, address indexed _to, uint256 _value)
* - event Approve(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value)
* - function increaseAllowance(address _spender, uint256 _value) public returns (bool)
* - function decreaseAllowance(address _spender, uint256 _value) public returns (bool)
* See: https://arxiv.org/abs/1907.00903v1
* https://ieeexplore.ieee.org/document/8802438
* See: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* @dev Reviewed
* ERC-20 - according to https://eips.ethereum.org/EIPS/eip-20
* ERC-1363 - according to https://eips.ethereum.org/EIPS/eip-1363
* EIP-2612 - according to https://eips.ethereum.org/EIPS/eip-2612
* EIP-3009 - according to https://eips.ethereum.org/EIPS/eip-3009
*
* @dev ERC20: contract has passed
* - OpenZeppelin ERC20 tests
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.behavior.js
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.test.js
* - Ref ERC1363 tests
* https://github.com/vittominacori/erc1363-payable-token/blob/master/test/token/ERC1363/ERC1363.behaviour.js
* - OpenZeppelin EIP2612 tests
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/extensions/draft-ERC20Permit.test.js
* - Coinbase EIP3009 tests
* https://github.com/CoinbaseStablecoin/eip-3009/blob/master/test/EIP3009.test.ts
* - Compound voting delegation tests
* https://github.com/compound-finance/compound-protocol/blob/master/tests/Governance/CompTest.js
* https://github.com/compound-finance/compound-protocol/blob/master/tests/Utils/EIP712.js
* - OpenZeppelin voting delegation tests
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/extensions/ERC20Votes.test.js
* See adopted copies of all the tests in the project test folder
*
* @dev Compound-like voting delegation functions', public getters', and events' names
* were changed for better code readability (Advanced ERC20 Name <- Comp/Zeppelin name):
* - votingDelegates <- delegates
* - votingPowerHistory <- checkpoints
* - votingPowerHistoryLength <- numCheckpoints
* - totalSupplyHistory <- _totalSupplyCheckpoints (private)
* - usedNonces <- nonces (note: nonces are random instead of sequential)
* - DelegateChanged (unchanged)
* - VotingPowerChanged <- DelegateVotesChanged
* - votingPowerOf <- getCurrentVotes
* - votingPowerAt <- getPriorVotes
* - totalSupplyAt <- getPriorTotalSupply
* - delegate (unchanged)
* - delegateWithAuthorization <- delegateBySig
* @dev Compound-like voting delegation improved to allow the use of random nonces like in EIP-3009,
* instead of sequential; same `usedNonces` EIP-3009 mapping is used to track nonces
*
* @dev Reference implementations "used":
* - Atomic allowance: https://github.com/OpenZeppelin/openzeppelin-contracts
* - Unlimited allowance: https://github.com/0xProject/protocol
* - Voting delegation: https://github.com/compound-finance/compound-protocol
* https://github.com/OpenZeppelin/openzeppelin-contracts
* - ERC-1363: https://github.com/vittominacori/erc1363-payable-token
* - EIP-2612: https://github.com/Uniswap/uniswap-v2-core
* - EIP-3009: https://github.com/centrehq/centre-tokens
* https://github.com/CoinbaseStablecoin/eip-3009
* - Meta transactions: https://github.com/0xProject/protocol
*
* @dev The code is based on Artificial Liquid Intelligence Token (ALI) developed by Alethea team
* @dev Includes resolutions for ALI ERC20 Audit by Miguel Palhas, https://hackmd.io/@naps62/alierc20-audit
*/
contract AdvancedERC20 is ERC1363, MintableBurnableERC20, EIP2612, EIP3009, InitializableAccessControl {
/**
* @dev Smart contract unique identifier, a random number
*
* @dev Should be regenerated each time smart contact source code is changed
* and changed smart contract itself is to be redeployed
*
* @dev Generated using https://www.random.org/bytes/
*/
uint256 public constant TOKEN_UID = 0x85852ae5a7cdee80493c98daa64f98f0cb54ed1def5bdc3f1c4a1feff79713d2;
/**
* @notice Name of the token
*
* @notice ERC20 name of the token (long name)
*
* @dev ERC20 `function name() public view returns (string)`
*
* @dev Field is declared public: getter name() is created when compiled,
* it returns the name of the token.
*/
string public name;
/**
* @notice Symbol of the token
*
* @notice ERC20 symbol of that token (short name)
*
* @dev ERC20 `function symbol() public view returns (string)`
*
* @dev Field is declared public: getter symbol() is created when compiled,
* it returns the symbol of the token
*/
string public symbol;
/**
* @notice Decimals of the token: 18
*
* @dev ERC20 `function decimals() public view returns (uint8)`
*
* @dev Field is declared public: getter decimals() is created when compiled,
* it returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should
* be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`).
*
* @dev NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including balanceOf() and transfer().
*/
uint8 public constant decimals = 18;
/**
* @notice Total supply of the token: initially 10,000,000,000,
* with the potential to decline over time as some tokens may get burnt but not minted
*
* @dev ERC20 `function totalSupply() public view returns (uint256)`
*
* @dev Field is declared public: getter totalSupply() is created when compiled,
* it returns the amount of tokens in existence.
*/
uint256 public override totalSupply; // is set to 10 billion * 10^18 in the constructor
/**
* @dev A record of all the token balances
* @dev This mapping keeps record of all token owners:
* owner => balance
*/
mapping(address => uint256) private tokenBalances;
/**
* @notice A record of each account's voting delegate
*
* @dev Auxiliary data structure used to sum up an account's voting power
*
* @dev This mapping keeps record of all voting power delegations:
* voting delegator (token owner) => voting delegate
*/
mapping(address => address) public votingDelegates;
/**
* @notice Auxiliary structure to store key-value pair, used to store:
* - voting power record (key: block.timestamp, value: voting power)
* - total supply record (key: block.timestamp, value: total supply)
* @notice A voting power record binds voting power of a delegate to a particular
* block when the voting power delegation change happened
* k: block.number when delegation has changed; starting from
* that block voting power value is in effect
* v: cumulative voting power a delegate has obtained starting
* from the block stored in blockNumber
* @notice Total supply record binds total token supply to a particular
* block when total supply change happened (due to mint/burn operations)
*/
struct KV {
/*
* @dev key, a block number
*/
uint64 k;
/*
* @dev value, token balance or voting power
*/
uint192 v;
}
/**
* @notice A record of each account's voting power historical data
*
* @dev Primarily data structure to store voting power for each account.
* Voting power sums up from the account's token balance and delegated
* balances.
*
* @dev Stores current value and entire history of its changes.
* The changes are stored as an array of checkpoints (key-value pairs).
* Checkpoint is an auxiliary data structure containing voting
* power (number of votes) and block number when the checkpoint is saved
*
* @dev Maps voting delegate => voting power record
*/
mapping(address => KV[]) public votingPowerHistory;
/**
* @notice A record of total token supply historical data
*
* @dev Primarily data structure to store total token supply.
*
* @dev Stores current value and entire history of its changes.
* The changes are stored as an array of checkpoints (key-value pairs).
* Checkpoint is an auxiliary data structure containing total
* token supply and block number when the checkpoint is saved
*/
KV[] public totalSupplyHistory;
/**
* @dev A record of nonces for signing/validating signatures in EIP-2612 `permit`
*
* @dev Note: EIP2612 doesn't imply a possibility for nonce randomization like in EIP-3009
*
* @dev Maps delegate address => delegate nonce
*/
mapping(address => uint256) public override nonces;
/**
* @dev A record of used nonces for EIP-3009 transactions
*
* @dev A record of used nonces for signing/validating signatures
* in `delegateWithAuthorization` for every delegate
*
* @dev Maps authorizer address => nonce => true/false (used unused)
*/
mapping(address => mapping(bytes32 => bool)) private usedNonces;
/**
* @notice A record of all the allowances to spend tokens on behalf
* @dev Maps token owner address to an address approved to spend
* some tokens on behalf, maps approved address to that amount
* @dev owner => spender => value
*/
mapping(address => mapping(address => uint256)) private transferAllowances;
/**
* @notice Enables ERC20 transfers of the tokens
* (transfer by the token owner himself)
* @dev Feature FEATURE_TRANSFERS must be enabled in order for
* `transfer()` function to succeed
*/
uint32 public constant FEATURE_TRANSFERS = 0x0000_0001;
/**
* @notice Enables ERC20 transfers on behalf
* (transfer by someone else on behalf of token owner)
* @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for
* `transferFrom()` function to succeed
* @dev Token owner must call `approve()` first to authorize
* the transfer on behalf
*/
uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002;
/**
* @dev Defines if the default behavior of `transfer` and `transferFrom`
* checks if the receiver smart contract supports ERC20 tokens
* @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not
* check if the receiver smart contract supports ERC20 tokens,
* i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom`
* @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers
* check if the receiver smart contract supports ERC20 tokens,
* i.e. `transfer` and `transferFrom` behave like `transferFromAndCall`
*/
uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004;
/**
* @notice Enables token owners to burn their own tokens
*
* @dev Feature FEATURE_OWN_BURNS must be enabled in order for
* `burn()` function to succeed when called by token owner
*/
uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008;
/**
* @notice Enables approved operators to burn tokens on behalf of their owners
*
* @dev Feature FEATURE_BURNS_ON_BEHALF must be enabled in order for
* `burn()` function to succeed when called by approved operator
*/
uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010;
/**
* @notice Enables delegators to elect delegates
* @dev Feature FEATURE_DELEGATIONS must be enabled in order for
* `delegate()` function to succeed
*/
uint32 public constant FEATURE_DELEGATIONS = 0x0000_0020;
/**
* @notice Enables delegators to elect delegates on behalf
* (via an EIP712 signature)
* @dev Feature FEATURE_DELEGATIONS_ON_BEHALF must be enabled in order for
* `delegateWithAuthorization()` function to succeed
*/
uint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040;
/**
* @notice Enables ERC-1363 transfers with callback
* @dev Feature FEATURE_ERC1363_TRANSFERS must be enabled in order for
* ERC-1363 `transferFromAndCall` functions to succeed
*/
uint32 public constant FEATURE_ERC1363_TRANSFERS = 0x0000_0080;
/**
* @notice Enables ERC-1363 approvals with callback
* @dev Feature FEATURE_ERC1363_APPROVALS must be enabled in order for
* ERC-1363 `approveAndCall` functions to succeed
*/
uint32 public constant FEATURE_ERC1363_APPROVALS = 0x0000_0100;
/**
* @notice Enables approvals on behalf (EIP2612 permits
* via an EIP712 signature)
* @dev Feature FEATURE_EIP2612_PERMITS must be enabled in order for
* `permit()` function to succeed
*/
uint32 public constant FEATURE_EIP2612_PERMITS = 0x0000_0200;
/**
* @notice Enables meta transfers on behalf (EIP3009 transfers
* via an EIP712 signature)
* @dev Feature FEATURE_EIP3009_TRANSFERS must be enabled in order for
* `transferWithAuthorization()` function to succeed
*/
uint32 public constant FEATURE_EIP3009_TRANSFERS = 0x0000_0400;
/**
* @notice Enables meta transfers on behalf (EIP3009 transfers
* via an EIP712 signature)
* @dev Feature FEATURE_EIP3009_RECEPTIONS must be enabled in order for
* `receiveWithAuthorization()` function to succeed
*/
uint32 public constant FEATURE_EIP3009_RECEPTIONS = 0x0000_0800;
/**
* @notice Token creator is responsible for creating (minting)
* tokens to an arbitrary address
* @dev Role ROLE_TOKEN_CREATOR allows minting tokens
* (calling `mint` function)
*/
uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000;
/**
* @notice Token destroyer is responsible for destroying (burning)
* tokens owned by an arbitrary address
* @dev Role ROLE_TOKEN_DESTROYER allows burning tokens
* (calling `burn` function)
*/
uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000;
/**
* @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks,
* which may be useful to simplify tokens transfers into "legacy" smart contracts
* @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having
* `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens
* via `transfer` and `transferFrom` functions in the same way they
* would via `unsafeTransferFrom` function
* @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission
* doesn't affect the transfer behaviour since
* `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver
* @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER
*/
uint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000;
/**
* @notice ERC20 senders are allowed to send tokens without ERC20 safety checks,
* which may be useful to simplify tokens transfers into "legacy" smart contracts
* @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having
* `ROLE_ERC20_SENDER` permission are allowed to send tokens
* via `transfer` and `transferFrom` functions in the same way they
* would via `unsafeTransferFrom` function
* @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission
* doesn't affect the transfer behaviour since
* `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver
* @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER
*/
uint32 public constant ROLE_ERC20_SENDER = 0x0008_0000;
/**
* @notice EIP-712 contract's domain typeHash,
* see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*
* @dev Note: we do not include version into the domain typehash/separator,
* it is implied version is concatenated to the name field, like "AdvancedERC20"
*/
// keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)")
bytes32 public constant DOMAIN_TYPEHASH = 0x8cad95687ba82c2ce50e74f7b754645e5117c3a5bec8151c0726d5857980a866;
/**
* @notice EIP-712 contract domain separator,
* see https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator
* note: we specify contract version in its name
*/
function DOMAIN_SEPARATOR() public view override returns(bytes32) {
// build the EIP-712 contract domain separator, see https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator
// note: we specify contract version in its name
return keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes("AdvancedERC20")), block.chainid, address(this)));
}
/**
* @notice EIP-712 delegation struct typeHash,
* see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
// keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)")
bytes32 public constant DELEGATION_TYPEHASH = 0xff41620983935eb4d4a3c7384a066ca8c1d10cef9a5eca9eb97ca735cd14a755;
/**
* @notice EIP-712 permit (EIP-2612) struct typeHash,
* see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/**
* @notice EIP-712 TransferWithAuthorization (EIP-3009) struct typeHash,
* see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
/**
* @notice EIP-712 ReceiveWithAuthorization (EIP-3009) struct typeHash,
* see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
// keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;
/**
* @notice EIP-712 CancelAuthorization (EIP-3009) struct typeHash,
* see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
// keccak256("CancelAuthorization(address authorizer,bytes32 nonce)")
bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;
/**
* @dev Fired in mint() function
*
* @param by an address which minted some tokens (transaction sender)
* @param to an address the tokens were minted to
* @param value an amount of tokens minted
*/
event Minted(address indexed by, address indexed to, uint256 value);
/**
* @dev Fired in burn() function
*
* @param by an address which burned some tokens (transaction sender)
* @param from an address the tokens were burnt from
* @param value an amount of tokens burnt
*/
event Burnt(address indexed by, address indexed from, uint256 value);
/**
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903)
*
* @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer
*
* @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions
*
* @param by an address which performed the transfer
* @param from an address tokens were consumed from
* @param to an address tokens were sent to
* @param value number of tokens transferred
*/
event Transfer(address indexed by, address indexed from, address indexed to, uint256 value);
/**
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903)
*
* @dev Similar to ERC20 Approve event, but also logs old approval value
*
* @dev Fired in approve(), increaseAllowance(), decreaseAllowance() functions,
* may get fired in transfer functions
*
* @param owner an address which granted a permission to transfer
* tokens on its behalf
* @param spender an address which received a permission to transfer
* tokens on behalf of the owner `_owner`
* @param oldValue previously granted amount of tokens to transfer on behalf
* @param value new granted amount of tokens to transfer on behalf
*/
event Approval(address indexed owner, address indexed spender, uint256 oldValue, uint256 value);
/**
* @dev Notifies that a key-value pair in `votingDelegates` mapping has changed,
* i.e. a delegator address has changed its delegate address
*
* @param source delegator address, a token owner, effectively transaction sender (`by`)
* @param from old delegate, an address which delegate right is revoked
* @param to new delegate, an address which received the voting power
*/
event DelegateChanged(address indexed source, address indexed from, address indexed to);
/**
* @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed,
* i.e. a delegate's voting power has changed.
*
* @param by an address which executed delegate, mint, burn, or transfer operation
* which had led to delegate voting power change
* @param target delegate whose voting power has changed
* @param fromVal previous number of votes delegate had
* @param toVal new number of votes delegate has
*/
event VotingPowerChanged(address indexed by, address indexed target, uint256 fromVal, uint256 toVal);
/**
* @dev Deploys the token smart contract,
* assigns initial token supply to the address specified
*
* @param _contractOwner smart contract owner (has minting/burning and all other permissions)
* @param _name token name to set
* @param _symbol token symbol to set
* @param _initialHolder owner of the initial token supply
* @param _initialSupply initial token supply
* @param _initialFeatures RBAC features enabled initially
*/
constructor(
address _contractOwner,
string memory _name,
string memory _symbol,
address _initialHolder,
uint256 _initialSupply,
uint256 _initialFeatures
) {
// delegate to the same `postConstruct` function which would be used
// by all the proxies to be deployed and to be pointing to this impl
postConstruct(_contractOwner, _name, _symbol, _initialHolder, _initialSupply, _initialFeatures);
}
/**
* @dev "Constructor replacement" for a smart contract with a delayed initialization (post-deployment initialization)
*
* @param _contractOwner smart contract owner (has minting/burning and all other permissions)
* @param _name token name to set
* @param _symbol token symbol to set
* @param _initialHolder owner of the initial token supply
* @param _initialSupply initial token supply value
* @param _initialFeatures RBAC features enabled initially
*/
function postConstruct(
address _contractOwner,
string memory _name,
string memory _symbol,
address _initialHolder,
uint256 _initialSupply,
uint256 _initialFeatures
) public initializer {
// this function can be executed only once,
// we're checking if token name and symbol are already set
// to check if the contract was already initialized
require(bytes(name).length == 0, "already initialized");
// verify name and symbol are set
require(bytes(_name).length > 0, "token name is not set");
require(bytes(_symbol).length > 0, "token symbol is not set");
// assign token name and symbol
name = _name;
symbol = _symbol;
// verify initial holder address non-zero (is set) if there is an initial supply to mint
require(_initialSupply == 0 || _initialHolder != address(0), "_initialHolder not set (zero address)");
// if there is an initial supply to mint
if(_initialSupply != 0) {
// mint the initial supply
__mint(_initialHolder, _initialSupply);
}
// if initial contract owner is specified
if(_contractOwner != address(0) || _initialFeatures != 0) {
// initialize the RBAC module
_postConstruct(_contractOwner, _initialFeatures);
}
}
/**
* @inheritdoc ERC165
*/
function supportsInterface(bytes4 interfaceId) public pure virtual override returns (bool) {
// reconstruct from current interface(s) and super interface(s) (if any)
return interfaceId == type(ERC165).interfaceId
|| interfaceId == type(ERC20).interfaceId
|| interfaceId == type(ERC1363).interfaceId
|| interfaceId == type(EIP2612).interfaceId
|| interfaceId == type(EIP3009).interfaceId;
}
// ===== Start: ERC-1363 functions =====
/**
* @notice Transfers some tokens and then executes `onTransferReceived` callback on the receiver
*
* @inheritdoc ERC1363
*
* @dev Called by token owner (an address which has a
* positive token balance tracked by this smart contract)
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * EOA or smart contract which doesn't support ERC1363Receiver interface
* @dev Returns true on success, throws otherwise
*
* @param _to an address to transfer tokens to,
* must be a smart contract, implementing ERC1363Receiver
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @return true unless throwing
*/
function transferAndCall(address _to, uint256 _value) public override returns (bool) {
// delegate to `transferFromAndCall` passing `msg.sender` as `_from`
return transferFromAndCall(msg.sender, _to, _value);
}
/**
* @notice Transfers some tokens and then executes `onTransferReceived` callback on the receiver
*
* @inheritdoc ERC1363
*
* @dev Called by token owner (an address which has a
* positive token balance tracked by this smart contract)
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * EOA or smart contract which doesn't support ERC1363Receiver interface
* @dev Returns true on success, throws otherwise
*
* @param _to an address to transfer tokens to,
* must be a smart contract, implementing ERC1363Receiver
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @param _data [optional] additional data with no specified format,
* sent in onTransferReceived call to `_to`
* @return true unless throwing
*/
function transferAndCall(address _to, uint256 _value, bytes memory _data) public override returns (bool) {
// delegate to `transferFromAndCall` passing `msg.sender` as `_from`
return transferFromAndCall(msg.sender, _to, _value, _data);
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to` and then executes `onTransferReceived` callback on the receiver
*
* @inheritdoc ERC1363
*
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * EOA or smart contract which doesn't support ERC1363Receiver interface
* @dev Returns true on success, throws otherwise
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be a smart contract, implementing ERC1363Receiver
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @return true unless throwing
*/
function transferFromAndCall(address _from, address _to, uint256 _value) public override returns (bool) {
// delegate to `transferFromAndCall` passing empty data param
return transferFromAndCall(_from, _to, _value, "");
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to` and then executes a `onTransferReceived` callback on the receiver
*
* @inheritdoc ERC1363
*
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * EOA or smart contract which doesn't support ERC1363Receiver interface
* @dev Returns true on success, throws otherwise
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be a smart contract, implementing ERC1363Receiver
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @param _data [optional] additional data with no specified format,
* sent in onTransferReceived call to `_to`
* @return true unless throwing
*/
function transferFromAndCall(address _from, address _to, uint256 _value, bytes memory _data) public override returns (bool) {
// ensure ERC-1363 transfers are enabled
require(isFeatureEnabled(FEATURE_ERC1363_TRANSFERS), "ERC1363 transfers are disabled");
// first delegate call to `unsafeTransferFrom` to perform the unsafe token(s) transfer
unsafeTransferFrom(_from, _to, _value);
// after the successful transfer - check if receiver supports
// ERC1363Receiver and execute a callback handler `onTransferReceived`,
// reverting whole transaction on any error
_notifyTransferred(_from, _to, _value, _data, false);
// function throws on any error, so if we're here - it means operation successful, just return true
return true;
}
/**
* @notice Approves address called `_spender` to transfer some amount
* of tokens on behalf of the owner, then executes a `onApprovalReceived` callback on `_spender`
*
* @inheritdoc ERC1363
*
* @dev Caller must not necessarily own any tokens to grant the permission
*
* @dev Throws if `_spender` is an EOA or a smart contract which doesn't support ERC1363Spender interface
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens spender `_spender` is allowed to
* transfer on behalf of the token owner
* @return true unless throwing
*/
function approveAndCall(address _spender, uint256 _value) public override returns (bool) {
// delegate to `approveAndCall` passing empty data
return approveAndCall(_spender, _value, "");
}
/**
* @notice Approves address called `_spender` to transfer some amount
* of tokens on behalf of the owner, then executes a callback on `_spender`
*
* @inheritdoc ERC1363
*
* @dev Caller must not necessarily own any tokens to grant the permission
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens spender `_spender` is allowed to
* transfer on behalf of the token owner
* @param _data [optional] additional data with no specified format,
* sent in onApprovalReceived call to `_spender`
* @return true unless throwing
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _data) public override returns (bool) {
// ensure ERC-1363 approvals are enabled
require(isFeatureEnabled(FEATURE_ERC1363_APPROVALS), "ERC1363 approvals are disabled");
// execute regular ERC20 approve - delegate to `approve`
approve(_spender, _value);
// after the successful approve - check if receiver supports
// ERC1363Spender and execute a callback handler `onApprovalReceived`,
// reverting whole transaction on any error
_notifyApproved(_spender, _value, _data);
// function throws on any error, so if we're here - it means operation successful, just return true
return true;
}
/**
* @dev Auxiliary function to invoke `onTransferReceived` on a target address
* The call is not executed if the target address is not a contract; in such
* a case function throws if `allowEoa` is set to false, succeeds if it's true
*
* @dev Throws on any error; returns silently on success
*
* @param _from representing the previous owner of the given token value
* @param _to target address that will receive the tokens
* @param _value the amount mount of tokens to be transferred
* @param _data [optional] data to send along with the call
* @param allowEoa indicates if function should fail if `_to` is an EOA
*/
function _notifyTransferred(address _from, address _to, uint256 _value, bytes memory _data, bool allowEoa) private {
// if recipient `_to` is EOA
if(!AddressUtils.isContract(_to)) {
// ensure EOA recipient is allowed
require(allowEoa, "EOA recipient");
// exit if successful
return;
}
// otherwise - if `_to` is a contract - execute onTransferReceived
bytes4 response = ERC1363Receiver(_to).onTransferReceived(msg.sender, _from, _value, _data);
// expected response is ERC1363Receiver(_to).onTransferReceived.selector
// bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))
require(response == ERC1363Receiver(_to).onTransferReceived.selector, "invalid onTransferReceived response");
}
/**
* @dev Auxiliary function to invoke `onApprovalReceived` on a target address
* The call is not executed if the target address is not a contract; in such
* a case function throws if `allowEoa` is set to false, succeeds if it's true
*
* @dev Throws on any error; returns silently on success
*
* @param _spender the address which will spend the funds
* @param _value the amount of tokens to be spent
* @param _data [optional] data to send along with the call
*/
function _notifyApproved(address _spender, uint256 _value, bytes memory _data) private {
// ensure recipient is not EOA
require(AddressUtils.isContract(_spender), "EOA spender");
// otherwise - if `_to` is a contract - execute onApprovalReceived
bytes4 response = ERC1363Spender(_spender).onApprovalReceived(msg.sender, _value, _data);
// expected response is ERC1363Spender(_to).onApprovalReceived.selector
// bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
require(response == ERC1363Spender(_spender).onApprovalReceived.selector, "invalid onApprovalReceived response");
}
// ===== End: ERC-1363 functions =====
// ===== Start: ERC20 functions =====
/**
* @notice Gets the balance of a particular address
*
* @inheritdoc ERC20
*
* @param _owner the address to query the the balance for
* @return balance an amount of tokens owned by the address specified
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
// read the balance and return
return tokenBalances[_owner];
}
/**
* @notice Transfers some tokens to an external address or a smart contract
*
* @inheritdoc ERC20
*
* @dev Called by token owner (an address which has a
* positive token balance tracked by this smart contract)
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * self address or
* * smart contract which doesn't support ERC20
*
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @return success true on success, throws otherwise
*/
function transfer(address _to, uint256 _value) public override returns (bool success) {
// just delegate call to `transferFrom`,
// `FEATURE_TRANSFERS` is verified inside it
return transferFrom(msg.sender, _to, _value);
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @inheritdoc ERC20
*
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * smart contract which doesn't support ERC20
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @return success true on success, throws otherwise
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool success) {
// depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default)
// or unsafe transfer
// if `FEATURE_UNSAFE_TRANSFERS` is enabled
// or receiver has `ROLE_ERC20_RECEIVER` permission
// or sender has `ROLE_ERC20_SENDER` permission
if(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS)
|| isOperatorInRole(_to, ROLE_ERC20_RECEIVER)
|| isSenderInRole(ROLE_ERC20_SENDER)) {
// we execute unsafe transfer - delegate call to `unsafeTransferFrom`,
// `FEATURE_TRANSFERS` is verified inside it
unsafeTransferFrom(_from, _to, _value);
}
// otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled
// and receiver doesn't have `ROLE_ERC20_RECEIVER` permission
else {
// we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`,
// `FEATURE_TRANSFERS` is verified inside it
safeTransferFrom(_from, _to, _value, "");
}
// both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so
// if we're here - it means operation successful,
// just return true
return true;
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to` and then executes `onTransferReceived` callback
* on the receiver if it is a smart contract (not an EOA)
*
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * smart contract which doesn't support ERC1363Receiver interface
* @dev Returns true on success, throws otherwise
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* implementing ERC1363Receiver
* @param _value amount of tokens to be transferred,, zero
* value is allowed
* @param _data [optional] additional data with no specified format,
* sent in onTransferReceived call to `_to` in case if its a smart contract
* @return true unless throwing
*/
function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public returns (bool) {
// first delegate call to `unsafeTransferFrom` to perform the unsafe token(s) transfer
unsafeTransferFrom(_from, _to, _value);
// after the successful transfer - check if receiver supports
// ERC1363Receiver and execute a callback handler `onTransferReceived`,
// reverting whole transaction on any error
_notifyTransferred(_from, _to, _value, _data, true);
// function throws on any error, so if we're here - it means operation successful, just return true
return true;
}