1
// SPDX-License-Identifier: MIT
2
3
pragma solidity ^0.8.0;
4
5
/**
6
* @dev Provides information about the current execution context, including the
7
* sender of the transaction and its data. While these are generally available
8
* via msg.sender and msg.data, they should not be accessed in such a direct
9
* manner, since when dealing with meta-transactions the account sending and
10
* paying for execution may not be the actual sender (as far as an application
11
* is concerned).
12
*
13
* This contract is only required for intermediate, library-like contracts.
14
*/
15
abstract contract Context {
16
function _msgSender() internal view virtual returns (address) {
17
return msg.sender;
18
}
19
20
function _msgData() internal view virtual returns (bytes calldata) {
21
return msg.data;
22
}
23
}
24
25
pragma solidity ^0.8.0;
26
27
/**
28
* @dev Interface of the ERC165 standard, as defined in the
29
* https://eips.ethereum.org/EIPS/eip-165[EIP].
30
*
31
* Implementers can declare support of contract interfaces, which can then be
32
* queried by others ({ERC165Checker}).
33
*
34
* For an implementation, see {ERC165}.
35
*/
36
interface IERC165 {
37
/**
38
* @dev Returns true if this contract implements the interface defined by
39
* `interfaceId`. See the corresponding
40
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
41
* to learn more about how these ids are created.
42
*
43
* This function call must use less than 30 000 gas.
44
*/
45
function supportsInterface(bytes4 interfaceId) external view returns (bool);
46
}
47
48
pragma solidity ^0.8.0;
49
50
/**
51
* @dev Implementation of the {IERC165} interface.
52
*
53
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
54
* for the additional interface id that will be supported. For example:
55
*
56
* ```solidity
57
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
58
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
59
* }
60
* ```
61
*
62
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
63
*/
64
abstract contract ERC165 is IERC165 {
65
/**
66
* @dev See {IERC165-supportsInterface}.
67
*/
68
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
69
return interfaceId == type(IERC165).interfaceId;
70
}
71
}
72
73
pragma solidity ^0.8.0;
74
75
/**
76
* @dev External interface of AccessControl declared to support ERC165 detection.
77
*/
78
interface IAccessControl {
79
/**
80
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
81
*
82
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
83
* {RoleAdminChanged} not being emitted signaling this.
84
*
85
* _Available since v3.1._
86
*/
87
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
88
89
/**
90
* @dev Emitted when `account` is granted `role`.
91
*
92
* `sender` is the account that originated the contract call, an admin role
93
* bearer except when using {AccessControl-_setupRole}.
94
*/
95
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
96
97
/**
98
* @dev Emitted when `account` is revoked `role`.
99
*
100
* `sender` is the account that originated the contract call:
101
* - if using `revokeRole`, it is the admin role bearer
102
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
103
*/
104
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
105
106
/**
107
* @dev Returns `true` if `account` has been granted `role`.
108
*/
109
function hasRole(bytes32 role, address account) external view returns (bool);
110
111
/**
112
* @dev Returns the admin role that controls `role`. See {grantRole} and
113
* {revokeRole}.
114
*
115
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
116
*/
117
function getRoleAdmin(bytes32 role) external view returns (bytes32);
118
119
/**
120
* @dev Grants `role` to `account`.
121
*
122
* If `account` had not been already granted `role`, emits a {RoleGranted}
123
* event.
124
*
125
* Requirements:
126
*
127
* - the caller must have ``role``'s admin role.
128
*/
129
function grantRole(bytes32 role, address account) external;
130
131
/**
132
* @dev Revokes `role` from `account`.
133
*
134
* If `account` had been granted `role`, emits a {RoleRevoked} event.
135
*
136
* Requirements:
137
*
138
* - the caller must have ``role``'s admin role.
139
*/
140
function revokeRole(bytes32 role, address account) external;
141
142
/**
143
* @dev Revokes `role` from the calling account.
144
*
145
* Roles are often managed via {grantRole} and {revokeRole}: this function's
146
* purpose is to provide a mechanism for accounts to lose their privileges
147
* if they are compromised (such as when a trusted device is misplaced).
148
*
149
* If the calling account had been granted `role`, emits a {RoleRevoked}
150
* event.
151
*
152
* Requirements:
153
*
154
* - the caller must be `account`.
155
*/
156
function renounceRole(bytes32 role, address account) external;
157
}
158
159
pragma solidity ^0.8.0;
160
161
/**
162
* @dev String operations.
163
*/
164
library Strings {
165
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
166
167
/**
168
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
169
*/
170
function toString(uint256 value) internal pure returns (string memory) {
171
// Inspired by OraclizeAPI's implementation - MIT licence
172
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
173
174
if (value == 0) {
175
return "0";
176
}
177
uint256 temp = value;
178
uint256 digits;
179
while (temp != 0) {
180
digits++;
181
temp /= 10;
182
}
183
bytes memory buffer = new bytes(digits);
184
while (value != 0) {
185
digits -= 1;
186
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
187
value /= 10;
188
}
189
return string(buffer);
190
}
191
192
/**
193
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
194
*/
195
function toHexString(uint256 value) internal pure returns (string memory) {
196
if (value == 0) {
197
return "0x00";
198
}
199
uint256 temp = value;
200
uint256 length = 0;
201
while (temp != 0) {
202
length++;
203
temp >>= 8;
204
}
205
return toHexString(value, length);
206
}
207
208
/**
209
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
210
*/
211
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
212
bytes memory buffer = new bytes(2 * length + 2);
213
buffer[0] = "0";
214
buffer[1] = "x";
215
for (uint256 i = 2 * length + 1; i > 1; --i) {
216
buffer[i] = _HEX_SYMBOLS[value & 0xf];
217
value >>= 4;
218
}
219
require(value == 0, "Strings: hex length insufficient");
220
return string(buffer);
221
}
222
}
223
224
225
pragma solidity ^0.8.0;
226
227
/**
228
* @dev Contract module that allows children to implement role-based access
229
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
230
* members except through off-chain means by accessing the contract event logs. Some
231
* applications may benefit from on-chain enumerability, for those cases see
232
* {AccessControlEnumerable}.
233
*
234
* Roles are referred to by their `bytes32` identifier. These should be exposed
235
* in the external API and be unique. The best way to achieve this is by
236
* using `public constant` hash digests:
237
*
238
* ```
239
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
240
* ```
241
*
242
* Roles can be used to represent a set of permissions. To restrict access to a
243
* function call, use {hasRole}:
244
*
245
* ```
246
* function foo() public {
247
* require(hasRole(MY_ROLE, msg.sender));
248
* ...
249
* }
250
* ```
251
*
252
* Roles can be granted and revoked dynamically via the {grantRole} and
253
* {revokeRole} functions. Each role has an associated admin role, and only
254
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
255
*
256
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
257
* that only accounts with this role will be able to grant or revoke other
258
* roles. More complex role relationships can be created by using
259
* {_setRoleAdmin}.
260
*
261
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
262
* grant and revoke this role. Extra precautions should be taken to secure
263
* accounts that have been granted it.
264
*/
265
abstract contract AccessControl is Context, IAccessControl, ERC165 {
266
struct RoleData {
267
mapping(address => bool) members;
268
bytes32 adminRole;
269
}
270
271
mapping(bytes32 => RoleData) private _roles;
272
273
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
274
275
/**
276
* @dev Modifier that checks that an account has a specific role. Reverts
277
* with a standardized message including the required role.
278
*
279
* The format of the revert reason is given by the following regular expression:
280
*
281
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
282
*
283
* _Available since v4.1._
284
*/
285
modifier onlyRole(bytes32 role) {
286
_checkRole(role, _msgSender());
287
_;
288
}
289
290
/**
291
* @dev See {IERC165-supportsInterface}.
292
*/
293
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
294
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
295
}
296
297
/**
298
* @dev Returns `true` if `account` has been granted `role`.
299
*/
300
function hasRole(bytes32 role, address account) public view override returns (bool) {
301
return _roles[role].members[account];
302
}
303
304
/**
305
* @dev Revert with a standard message if `account` is missing `role`.
306
*
307
* The format of the revert reason is given by the following regular expression:
308
*
309
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
310
*/
311
function _checkRole(bytes32 role, address account) internal view {
312
if (!hasRole(role, account)) {
313
revert(
314
string(
315
abi.encodePacked(
316
"AccessControl: account ",
317
Strings.toHexString(uint160(account), 20),
318
" is missing role ",
319
Strings.toHexString(uint256(role), 32)
320
)
321
)
322
);
323
}
324
}
325
326
/**
327
* @dev Returns the admin role that controls `role`. See {grantRole} and
328
* {revokeRole}.
329
*
330
* To change a role's admin, use {_setRoleAdmin}.
331
*/
332
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
333
return _roles[role].adminRole;
334
}
335
336
/**
337
* @dev Grants `role` to `account`.
338
*
339
* If `account` had not been already granted `role`, emits a {RoleGranted}
340
* event.
341
*
342
* Requirements:
343
*
344
* - the caller must have ``role``'s admin role.
345
*/
346
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
347
_grantRole(role, account);
348
}
349
350
/**
351
* @dev Revokes `role` from `account`.
352
*
353
* If `account` had been granted `role`, emits a {RoleRevoked} event.
354
*
355
* Requirements:
356
*
357
* - the caller must have ``role``'s admin role.
358
*/
359
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
360
_revokeRole(role, account);
361
}
362
363
/**
364
* @dev Revokes `role` from the calling account.
365
*
366
* Roles are often managed via {grantRole} and {revokeRole}: this function's
367
* purpose is to provide a mechanism for accounts to lose their privileges
368
* if they are compromised (such as when a trusted device is misplaced).
369
*
370
* If the calling account had been granted `role`, emits a {RoleRevoked}
371
* event.
372
*
373
* Requirements:
374
*
375
* - the caller must be `account`.
376
*/
377
function renounceRole(bytes32 role, address account) public virtual override {
378
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
379
380
_revokeRole(role, account);
381
}
382
383
/**
384
* @dev Grants `role` to `account`.
385
*
386
* If `account` had not been already granted `role`, emits a {RoleGranted}
387
* event. Note that unlike {grantRole}, this function doesn't perform any
388
* checks on the calling account.
389
*
390
* [WARNING]
391
* ====
392
* This function should only be called from the constructor when setting
393
* up the initial roles for the system.
394
*
395
* Using this function in any other way is effectively circumventing the admin
396
* system imposed by {AccessControl}.
397
* ====
398
*/
399
function _setupRole(bytes32 role, address account) internal virtual {
400
_grantRole(role, account);
401
}
402
403
/**
404
* @dev Sets `adminRole` as ``role``'s admin role.
405
*
406
* Emits a {RoleAdminChanged} event.
407
*/
408
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
409
bytes32 previousAdminRole = getRoleAdmin(role);
410
_roles[role].adminRole = adminRole;
411
emit RoleAdminChanged(role, previousAdminRole, adminRole);
412
}
413
414
function _grantRole(bytes32 role, address account) private {
415
if (!hasRole(role, account)) {
416
_roles[role].members[account] = true;
417
emit RoleGranted(role, account, _msgSender());
418
}
419
}
420
421
function _revokeRole(bytes32 role, address account) private {
422
if (hasRole(role, account)) {
423
_roles[role].members[account] = false;
424
emit RoleRevoked(role, account, _msgSender());
425
}
426
}
427
}
428
429
pragma solidity ^0.8.0;
430
431
/**
432
* @dev Library for managing
433
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
434
* types.
435
*
436
* Sets have the following properties:
437
*
438
* - Elements are added, removed, and checked for existence in constant time
439
* (O(1)).
440
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
441
*
442
* ```
443
* contract Example {
444
* // Add the library methods
445
* using EnumerableSet for EnumerableSet.AddressSet;
446
*
447
* // Declare a set state variable
448
* EnumerableSet.AddressSet private mySet;
449
* }
450
* ```
451
*
452
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
453
* and `uint256` (`UintSet`) are supported.
454
*/
455
library EnumerableSet {
456
// To implement this library for multiple types with as little code
457
// repetition as possible, we write it in terms of a generic Set type with
458
// bytes32 values.
459
// The Set implementation uses private functions, and user-facing
460
// implementations (such as AddressSet) are just wrappers around the
461
// underlying Set.
462
// This means that we can only create new EnumerableSets for types that fit
463
// in bytes32.
464
465
struct Set {
466
// Storage of set values
467
bytes32[] _values;
468
// Position of the value in the `values` array, plus 1 because index 0
469
// means a value is not in the set.
470
mapping(bytes32 => uint256) _indexes;
471
}
472
473
/**
474
* @dev Add a value to a set. O(1).
475
*
476
* Returns true if the value was added to the set, that is if it was not
477
* already present.
478
*/
479
function _add(Set storage set, bytes32 value) private returns (bool) {
480
if (!_contains(set, value)) {
481
set._values.push(value);
482
// The value is stored at length-1, but we add 1 to all indexes
483
// and use 0 as a sentinel value
484
set._indexes[value] = set._values.length;
485
return true;
486
} else {
487
return false;
488
}
489
}
490
491
/**
492
* @dev Removes a value from a set. O(1).
493
*
494
* Returns true if the value was removed from the set, that is if it was
495
* present.
496
*/
497
function _remove(Set storage set, bytes32 value) private returns (bool) {
498
// We read and store the value's index to prevent multiple reads from the same storage slot
499
uint256 valueIndex = set._indexes[value];
500
501
if (valueIndex != 0) {
502
// Equivalent to contains(set, value)
503
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
504
// the array, and then remove the last element (sometimes called as 'swap and pop').
505
// This modifies the order of the array, as noted in {at}.
506
507
uint256 toDeleteIndex = valueIndex - 1;
508
uint256 lastIndex = set._values.length - 1;
509
510
if (lastIndex != toDeleteIndex) {
511
bytes32 lastvalue = set._values[lastIndex];
512
513
// Move the last value to the index where the value to delete is
514
set._values[toDeleteIndex] = lastvalue;
515
// Update the index for the moved value
516
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
517
}
518
519
// Delete the slot where the moved value was stored
520
set._values.pop();
521
522
// Delete the index for the deleted slot
523
delete set._indexes[value];
524
525
return true;
526
} else {
527
return false;
528
}
529
}
530
531
/**
532
* @dev Returns true if the value is in the set. O(1).
533
*/
534
function _contains(Set storage set, bytes32 value) private view returns (bool) {
535
return set._indexes[value] != 0;
536
}
537
538
/**
539
* @dev Returns the number of values on the set. O(1).
540
*/
541
function _length(Set storage set) private view returns (uint256) {
542
return set._values.length;
543
}
544
545
/**
546
* @dev Returns the value stored at position `index` in the set. O(1).
547
*
548
* Note that there are no guarantees on the ordering of values inside the
549
* array, and it may change when more values are added or removed.
550
*
551
* Requirements:
552
*
553
* - `index` must be strictly less than {length}.
554
*/
555
function _at(Set storage set, uint256 index) private view returns (bytes32) {
556
return set._values[index];
557
}
558
559
/**
560
* @dev Return the entire set in an array
561
*
562
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
563
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
564
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
565
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
566
*/
567
function _values(Set storage set) private view returns (bytes32[] memory) {
568
return set._values;
569
}
570
571
// Bytes32Set
572
573
struct Bytes32Set {
574
Set _inner;
575
}
576
577
/**
578
* @dev Add a value to a set. O(1).
579
*
580
* Returns true if the value was added to the set, that is if it was not
581
* already present.
582
*/
583
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
584
return _add(set._inner, value);
585
}
586
587
/**
588
* @dev Removes a value from a set. O(1).
589
*
590
* Returns true if the value was removed from the set, that is if it was
591
* present.
592
*/
593
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
594
return _remove(set._inner, value);
595
}
596
597
/**
598
* @dev Returns true if the value is in the set. O(1).
599
*/
600
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
601
return _contains(set._inner, value);
602
}
603
604
/**
605
* @dev Returns the number of values in the set. O(1).
606
*/
607
function length(Bytes32Set storage set) internal view returns (uint256) {
608
return _length(set._inner);
609
}
610
611
/**
612
* @dev Returns the value stored at position `index` in the set. O(1).
613
*
614
* Note that there are no guarantees on the ordering of values inside the
615
* array, and it may change when more values are added or removed.
616
*
617
* Requirements:
618
*
619
* - `index` must be strictly less than {length}.
620
*/
621
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
622
return _at(set._inner, index);
623
}
624
625
/**
626
* @dev Return the entire set in an array
627
*
628
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
629
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
630
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
631
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
632
*/
633
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
634
return _values(set._inner);
635
}
636
637
// AddressSet
638
639
struct AddressSet {
640
Set _inner;
641
}
642
643
/**
644
* @dev Add a value to a set. O(1).
645
*
646
* Returns true if the value was added to the set, that is if it was not
647
* already present.
648
*/
649
function add(AddressSet storage set, address value) internal returns (bool) {
650
return _add(set._inner, bytes32(uint256(uint160(value))));
651
}
652
653
/**
654
* @dev Removes a value from a set. O(1).
655
*
656
* Returns true if the value was removed from the set, that is if it was
657
* present.
658
*/
659
function remove(AddressSet storage set, address value) internal returns (bool) {
660
return _remove(set._inner, bytes32(uint256(uint160(value))));
661
}
662
663
/**
664
* @dev Returns true if the value is in the set. O(1).
665
*/
666
function contains(AddressSet storage set, address value) internal view returns (bool) {
667
return _contains(set._inner, bytes32(uint256(uint160(value))));
668
}
669
670
/**
671
* @dev Returns the number of values in the set. O(1).
672
*/
673
function length(AddressSet storage set) internal view returns (uint256) {
674
return _length(set._inner);
675
}
676
677
/**
678
* @dev Returns the value stored at position `index` in the set. O(1).
679
*
680
* Note that there are no guarantees on the ordering of values inside the
681
* array, and it may change when more values are added or removed.
682
*
683
* Requirements:
684
*
685
* - `index` must be strictly less than {length}.
686
*/
687
function at(AddressSet storage set, uint256 index) internal view returns (address) {
688
return address(uint160(uint256(_at(set._inner, index))));
689
}
690
691
/**
692
* @dev Return the entire set in an array
693
*
694
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
695
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
696
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
697
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
698
*/
699
function values(AddressSet storage set) internal view returns (address[] memory) {
700
bytes32[] memory store = _values(set._inner);
701
address[] memory result;
702
703
assembly {
704
result := store
705
}
706
707
return result;
708
}
709
710
// UintSet
711
712
struct UintSet {
713
Set _inner;
714
}
715
716
/**
717
* @dev Add a value to a set. O(1).
718
*
719
* Returns true if the value was added to the set, that is if it was not
720
* already present.
721
*/
722
function add(UintSet storage set, uint256 value) internal returns (bool) {
723
return _add(set._inner, bytes32(value));
724
}
725
726
/**
727
* @dev Removes a value from a set. O(1).
728
*
729
* Returns true if the value was removed from the set, that is if it was
730
* present.
731
*/
732
function remove(UintSet storage set, uint256 value) internal returns (bool) {
733
return _remove(set._inner, bytes32(value));
734
}
735
736
/**
737
* @dev Returns true if the value is in the set. O(1).
738
*/
739
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
740
return _contains(set._inner, bytes32(value));
741
}
742
743
/**
744
* @dev Returns the number of values on the set. O(1).
745
*/
746
function length(UintSet storage set) internal view returns (uint256) {
747
return _length(set._inner);
748
}
749
750
/**
751
* @dev Returns the value stored at position `index` in the set. O(1).
752
*
753
* Note that there are no guarantees on the ordering of values inside the
754
* array, and it may change when more values are added or removed.
755
*
756
* Requirements:
757
*
758
* - `index` must be strictly less than {length}.
759
*/
760
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
761
return uint256(_at(set._inner, index));
762
}
763
764
/**
765
* @dev Return the entire set in an array
766
*
767
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
768
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
769
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
770
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
771
*/
772
function values(UintSet storage set) internal view returns (uint256[] memory) {
773
bytes32[] memory store = _values(set._inner);
774
uint256[] memory result;
775
776
assembly {
777
result := store
778
}
779
780
return result;
781
}
782
}
783
784
785
pragma solidity ^0.8.0;
786
787
/**
788
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
789
*/
790
interface IAccessControlEnumerable is IAccessControl {
791
/**
792
* @dev Returns one of the accounts that have `role`. `index` must be a
793
* value between 0 and {getRoleMemberCount}, non-inclusive.
794
*
795
* Role bearers are not sorted in any particular way, and their ordering may
796
* change at any point.
797
*
798
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
799
* you perform all queries on the same block. See the following
800
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
801
* for more information.
802
*/
803
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
804
805
/**
806
* @dev Returns the number of accounts that have `role`. Can be used
807
* together with {getRoleMember} to enumerate all bearers of a role.
808
*/
809
function getRoleMemberCount(bytes32 role) external view returns (uint256);
810
}
811
812
813
pragma solidity ^0.8.0;
814
815
/**
816
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
817
*/
818
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
819
using EnumerableSet for EnumerableSet.AddressSet;
820
821
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
822
823
/**
824
* @dev See {IERC165-supportsInterface}.
825
*/
826
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
827
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
828
}
829
830
/**
831
* @dev Returns one of the accounts that have `role`. `index` must be a
832
* value between 0 and {getRoleMemberCount}, non-inclusive.
833
*
834
* Role bearers are not sorted in any particular way, and their ordering may
835
* change at any point.
836
*
837
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
838
* you perform all queries on the same block. See the following
839
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
840
* for more information.
841
*/
842
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
843
return _roleMembers[role].at(index);
844
}
845
846
/**
847
* @dev Returns the number of accounts that have `role`. Can be used
848
* together with {getRoleMember} to enumerate all bearers of a role.
849
*/
850
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
851
return _roleMembers[role].length();
852
}
853
854
/**
855
* @dev Overload {grantRole} to track enumerable memberships
856
*/
857
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
858
super.grantRole(role, account);
859
_roleMembers[role].add(account);
860
}
861
862
/**
863
* @dev Overload {revokeRole} to track enumerable memberships
864
*/
865
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
866
super.revokeRole(role, account);
867
_roleMembers[role].remove(account);
868
}
869
870
/**
871
* @dev Overload {renounceRole} to track enumerable memberships
872
*/
873
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
874
super.renounceRole(role, account);
875
_roleMembers[role].remove(account);
876
}
877
878
/**
879
* @dev Overload {_setupRole} to track enumerable memberships
880
*/
881
function _setupRole(bytes32 role, address account) internal virtual override {
882
super._setupRole(role, account);
883
_roleMembers[role].add(account);
884
}
885
}
886
887
888
pragma solidity ^0.8.6;
889
890
/**
891
* @title KYCContract
892
* @dev KYC (Know Your Customer) system contract allowing users to submit KYC requests,
893
* which are processed by approved KYC centers.
894
*/
895
contract KYCContract is AccessControlEnumerable {
896
897
// Tracks the KYC level of each user (0 = no KYC).
898
mapping(address => uint) public level;
899
900
// prices for each KYC level.
901
mapping(uint => uint) public levelPrices;
902
903
// Role identifier for KYC centers.
904
bytes32 public constant KYCCentre = keccak256("KYCCentre");
905
906
907
/**
908
* @dev Emitted when a user's KYC level is updated.
909
* @param _address The user's address.
910
* @param level The updated KYC level.
911
*/
912
event KYCLevelChanged(address indexed _address, uint indexed level);
913
914
/**
915
* @dev Emitted when a new KYC request is created.
916
* @param index The global index of the created request.
917
*/
918
event RequestCreated(uint indexed index);
919
920
/**
921
* @dev Emitted when a KYC request is approved by a KYC center.
922
* @param index The global index of the approved request.
923
*/
924
event RequestApproved(uint indexed index);
925
926
/**
927
* @dev Emitted when a KYC request is declined by a KYC center.
928
* @param index The global index of the declined request.
929
*/
930
event RequestDeclined(uint indexed index);
931
932
/**
933
* @dev Emitted when a KYC request is withdrawn.
934
* @param index The global index of the withdrawn request.
935
*/
936
event RequestWithdrawn(uint indexed index);
937
938
/**
939
* @dev Emitted when the price of a KYC level is updated.
940
* @param level The KYC level.
941
* @param price The updated price for the level.
942
*/
943
event SetLevelPrice(uint indexed level, uint indexed price);
944
945
946
// Requests assigned to KYC centers.
947
mapping(address => uint[]) public kycCentreRequests;
948
949
// User-specific requests.
950
mapping(address => uint[]) public userKYCRequests;
951
952
// Enum for representing the status of a KYC request.
953
enum Status {
954
Pending,
955
Declined,
956
Approved,
957
Withdrawn
958
}
959
960
// Struct representing a KYC request.
961
struct KYCRequest {
962
address user; // User who submitted the request.
963
bytes32 data; // Encrypted data provided by the user.
964
uint level; // Requested KYC level.
965
Status status; // Current status of the request.
966
address centre; // Assigned KYC center.
967
uint deposit; // Fee paid for the request.
968
}
969
970
// List of all KYC requests.
971
KYCRequest[] public kycRequests;
972
973
/**
974
* @notice Modifier to ensure the user pays the required amount or more.
975
* @param _amount The required amount to proceed.
976
*/
977
modifier costs(uint _amount) {
978
require(msg.value >= _amount, "G001");
979
_;
980
if (msg.value > _amount)
981
payable(msg.sender).transfer(msg.value - _amount); // Refund excess.
982
}
983
984
/**
985
* @notice Sets the price for a specific KYC level.
986
* @param _level The KYC level to update.
987
* @param price The new price for the level.
988
* @dev Only callable by an admin.
989
*/
990
function setLevelPrice(uint _level, uint price) external {
991
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "G053");
992
levelPrices[_level] = price;
993
emit SetLevelPrice(_level, price);
994
}
995
996
/**
997
* @notice Creates a new KYC request.
998
* @param _level The requested KYC level.
999
* @param _data The encrypted KYC data.
1000
* @dev Selects a random KYC center for processing and assigns the request.
1001
*/
1002
function createKYCRequest(uint _level, bytes32 _data) external payable costs(levelPrices[_level]) {
1003
require(level[msg.sender] < _level, "G002");
1004
1005
uint length = userKYCRequests[msg.sender].length;
1006
if (length > 0) {
1007
uint requestIndex = userKYCRequests[msg.sender][length-1];
1008
require(kycRequests[requestIndex].status != Status.Pending, "G120");
1009
}
1010
1011
uint count = getRoleMemberCount(KYCCentre);
1012
require(count > 0, "G111");
1013
1014
uint index = uint(blockhash(block.number-1)) % count;
1015
address chosenKYCCentre = getRoleMember(KYCCentre, index);
1016
1017
KYCRequest memory request = KYCRequest({
1018
user: msg.sender,
1019
data: _data,
1020
level: _level,
1021
status: Status.Pending,
1022
centre: chosenKYCCentre,
1023
deposit: levelPrices[_level]
1024
});
1025
1026
kycRequests.push(request);
1027
1028
uint indexInAll = kycRequests.length-1;
1029
1030
kycCentreRequests[chosenKYCCentre].push(indexInAll);
1031
1032
// Store the index in the all list.
1033
userKYCRequests[msg.sender].push(indexInAll);
1034
emit RequestCreated(kycRequests.length-1);
1035
}
1036
1037
/**
1038
* @notice Approves a KYC request.
1039
* @param _index The global index of the request.
1040
* @dev Can only be called by the assigned KYC center.
1041
*/
1042
function approveKYCRequest(uint _index) external {
1043
require(hasRole(KYCCentre, msg.sender), "G052");
1044
KYCRequest storage request = kycRequests[_index];
1045
1046
require(msg.sender == request.centre, "G114");
1047
require(request.status == Status.Pending, "G121");
1048
request.status = Status.Approved;
1049
level[request.user] = request.level;
1050
1051
// We pay half of the deposit back to user if KYC centre approved request
1052
uint halvedDeposit = request.deposit / 2;
1053
payable(request.user).transfer(halvedDeposit);
1054
payable(msg.sender).transfer(request.deposit - halvedDeposit);
1055
1056
emit KYCLevelChanged(request.user, request.level);
1057
emit RequestApproved(_index);
1058
}
1059
1060
/**
1061
* @notice Declines a KYC request.
1062
* @param _index The global index of the request.
1063
* @dev Can only be called by the assigned KYC center.
1064
*/
1065
function declineKYCRequest(uint _index) external {
1066
require(hasRole(KYCCentre, msg.sender), "G050");
1067
KYCRequest storage request = kycRequests[_index];
1068
1069
require(msg.sender == request.centre, "G114");
1070
require(request.status == Status.Pending, "G121");
1071
request.status = Status.Declined;
1072
1073
payable(msg.sender).transfer(request.deposit);
1074
emit RequestDeclined(_index);
1075
}
1076
1077
/**
1078
* @notice Decrease the KYC level of a user.
1079
* @dev Only callable by an authorized KYC centre. The caller must be the centre that processed the user's last KYC request.
1080
* @param user The address of the user whose KYC level is to be decreased.
1081
* @param _level The new KYC level for the user, which must be less than the user's current level.
1082
*/
1083
function decreaseKYCLevel(address user, uint _level) external {
1084
require(hasRole(KYCCentre, msg.sender), "G051");
1085
1086
uint length = userKYCRequests[user].length;
1087
uint requestIndex = userKYCRequests[user][length-1];
1088
require(msg.sender == kycRequests[requestIndex].centre, "G114");
1089
1090
require(_level < level[user], "G112");
1091
level[user] = _level;
1092
1093
emit KYCLevelChanged(user, _level);
1094
}
1095
1096
/**
1097
* @notice Allows a user to withdraw their KYC request if the associated KYC centre has renounced its role.
1098
* @dev This function ensures that users can recover their deposit if the KYC centre is no longer active.
1099
*/
1100
function repairLostRequest() external {
1101
uint length = userKYCRequests[msg.sender].length;
1102
uint requestIndex = userKYCRequests[msg.sender][length-1];
1103
1104
KYCRequest storage request = kycRequests[requestIndex];
1105
require(msg.sender == request.user, "G053");
1106
require(!hasRole(KYCCentre, request.centre), "G110");
1107
require(request.status == Status.Pending, "G122");
1108
1109
request.status = Status.Withdrawn;
1110
1111
payable(request.user).transfer(request.deposit);
1112
emit RequestWithdrawn(requestIndex);
1113
}
1114
1115
/**
1116
* @notice Allows a user to cancel their KYC request.
1117
* @dev The user can only cancel requests that are still in the `Pending` status and assigned to an active KYC centre.
1118
*/
1119
function cancelUsersRequest() external {
1120
uint length = userKYCRequests[msg.sender].length;
1121
uint requestIndex = userKYCRequests[msg.sender][length-1];
1122
1123
KYCRequest storage request = kycRequests[requestIndex];
1124
require(msg.sender == request.user, "G053");
1125
require(hasRole(KYCCentre, request.centre), "G113");
1126
require(request.status == Status.Pending, "G123");
1127
1128
request.status = Status.Withdrawn;
1129
1130
payable(request.centre).transfer(request.deposit);
1131
emit RequestWithdrawn(requestIndex);
1132
}
1133
1134
/**
1135
* @notice View details of a user's KYC request by index.
1136
* @param userIndex The index of the user's request in their personal request history.
1137
* @return The `KYCRequest` object corresponding to the specified index.
1138
*/
1139
function viewMyRequest(uint userIndex) external view returns(KYCRequest memory) {
1140
uint indexInAll = userKYCRequests[msg.sender][userIndex];
1141
return kycRequests[indexInAll];
1142
}
1143
1144
/**
1145
* @notice View details of a KYC request assigned to a specific centre.
1146
* @param _centre The address of the KYC centre.
1147
* @param _localIndex The local index of the request in the centre's request history.
1148
* returns atuple containing the `KYCRequest` object and its global index in the `kycRequests` array.
1149
*/
1150
function viewRequestAssignedToCentre(address _centre, uint _localIndex) external view returns (KYCRequest memory, uint) {
1151
uint globalIndex = kycCentreRequests[_centre][_localIndex];
1152
KYCRequest memory request = kycRequests[globalIndex];
1153
return (request, globalIndex);
1154
}
1155
1156
/**
1157
* @notice View the most recent KYC request submitted by the caller.
1158
* @return The `KYCRequest` object corresponding to the caller's most recent request.
1159
*/
1160
function viewMyLastRequest() external view returns(KYCRequest memory) {
1161
uint len = userKYCRequests[msg.sender].length;
1162
uint indexInAll = userKYCRequests[msg.sender][len-1];
1163
return kycRequests[indexInAll];
1164
}
1165
1166
/**
1167
* @notice Get the global index of the most recent KYC request submitted by a specified user.
1168
* @param _address The address of the user.
1169
* @return The global index of the user's most recent KYC request in the `kycRequests` array.
1170
*/
1171
function getLastGlobalRequestIndexOfAddress(address _address) external view returns(uint){
1172
uint len = userKYCRequests[_address].length;
1173
uint index = userKYCRequests[_address][len-1];
1174
return index;
1175
}
1176
}
1177