-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathProfile.sol
386 lines (322 loc) · 12 KB
/
Profile.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
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import {Attestation} from "@eas/contracts/IEAS.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {Multicall} from "@openzeppelin/contracts/utils/Multicall.sol";
import {IProfile} from "../interfaces/IProfile.sol";
import {IProfileRegistry} from "../interfaces/IProfileRegistry.sol";
import {IScrollBadgeResolver} from "../interfaces/IScrollBadgeResolver.sol";
import {MAX_ATTACHED_BADGE_NUM} from "../Common.sol";
import {
AttestationOwnerMismatch,
BadgeCountReached,
LengthMismatch,
TokenNotOwnedByUser,
Unauthorized
} from "../Errors.sol";
contract Profile is IProfile, Initializable, Multicall {
/**
*
* Constants *
*
*/
/// @notice The address of `ScrollBadgeResolver` contract.
address public immutable resolver;
/**
*
* Structs *
*
*/
/// @dev The struct holding profile avatar information.
/// @param token The address of ERC721 token.
/// @param tokenId The token id.
struct Avatar {
address token;
uint256 tokenId;
}
/**
*
* Variables *
*
*/
/// @notice The address of profile registry.
address public registry;
/// @notice The address of profile owner.
address public owner;
/// @notice The name of the profile.
string public username;
/// @notice The profile avatar information.
Avatar public avatar;
/// @dev The list of uids for attached badges.
bytes32[] private uids;
/// @dev Position of the value in the `uids` array, plus 1
// because index 0 means a value is not in the set.
mapping(bytes32 => uint256) indexes;
/// @dev The unique index for the order of all attached badges (including invalid ones).
/// Assume the actual order of the badges are: `p[1], p[2], ..., p[n]` and let `a[i]` be
/// the number of `j` such that `i < j` and `p[i] > p[j]`. Then, the index is defined as:
/// `index = a[1] * (n-1)! + a[2] * (n-2)! + ... + a[n-1] * 1! + a[n] * 0!`
///
/// see here for more details: https://www.cnblogs.com/sinkinben/p/15847869.html
uint256 private badgeOrderEncoding;
/**
*
* Modifiers *
*
*/
modifier onlyOwner() {
if (msg.sender != owner) {
revert Unauthorized();
}
_;
}
modifier onlyResolver() {
if (msg.sender != resolver) {
revert Unauthorized();
}
_;
}
/**
*
* Constructor *
*
*/
/// @param resolver_ The address of `ScrollBadgeResolver` contract.
constructor(address resolver_) {
resolver = resolver_;
_disableInitializers();
}
/// @notice Initialize the storage of this contract.
/// @param owner_ The address of profile owner.
/// @param username_ The name of the profile.
function initialize(address owner_, string memory username_) external initializer {
registry = msg.sender;
owner = owner_;
username = username_;
IProfileRegistry(msg.sender).registerUsername(username_);
}
/**
*
* Public View Functions *
*
*/
/// @notice Return the attestation information for the given badge uid.
/// @param uid The badge uid to query.
function getAndValidateBadge(bytes32 uid) public view returns (Attestation memory) {
Attestation memory badge = IScrollBadgeResolver(resolver).getAndValidateBadge(uid);
if (badge.recipient != owner) {
revert AttestationOwnerMismatch(badge.uid);
}
return badge;
}
/// @notice Check whether a badge is valid.
/// @param uid The badge uid to query.
function isBadgeValid(bytes32 uid) public view returns (bool) {
try this.getAndValidateBadge(uid) {
return true;
} catch {
return false;
}
}
/// @notice Return the uid list of all attached badges, including invalid ones.
function getAttachedBadges() external view returns (bytes32[] memory) {
return uids;
}
/// @notice Return the orders of all attached badges, including invalid ones.
function getBadgeOrder() external view returns (uint256[] memory) {
return _decodeOrder(badgeOrderEncoding, uids.length);
}
/// @notice Return the list of valid badge uids.
function getValidBadges() external view returns (bytes32[] memory) {
bytes32[] memory _uids = uids;
uint256 isValid;
uint256 length;
for (uint256 i = 0; i < _uids.length; i++) {
if (isBadgeValid(_uids[i])) {
length++;
isValid |= 1 << i;
}
}
bytes32[] memory result = new bytes32[](length);
length = 0;
for (uint256 i = 0; i < _uids.length; i++) {
if (((isValid >> i) & 1) == 1) {
result[length++] = _uids[i];
}
}
return result;
}
/// @notice Return the token URI for profile avatar.
function getAvatar() external view returns (string memory) {
Avatar memory _avatar = avatar;
if (_avatar.token != address(0) && IERC721(_avatar.token).ownerOf(_avatar.tokenId) == owner) {
try IERC721Metadata(_avatar.token).tokenURI(_avatar.tokenId) returns (string memory uri) {
return uri;
} catch {
// no logic here
}
}
return IProfileRegistry(registry).getDefaultProfileAvatar();
}
/**
*
* Public Mutating Functions *
*
*/
/// @inheritdoc IProfile
function attach(bytes32[] memory _uids) external onlyOwner {
uint256 numAttached = uids.length + _uids.length;
if (numAttached > MAX_ATTACHED_BADGE_NUM) {
revert BadgeCountReached();
}
for (uint256 i = 0; i < _uids.length; i++) {
getAndValidateBadge(_uids[i]); // validate
_attachOne(_uids[i]);
}
}
/// @inheritdoc IProfile
function autoAttach(bytes32 _uid) external onlyResolver {
if (uids.length >= MAX_ATTACHED_BADGE_NUM) {
return;
}
_attachOne(_uid);
}
/// @notice Detach a list of badges to this profile.
/// @param _uids The list of badge uids to detach.
function detach(bytes32[] memory _uids) external onlyOwner {
for (uint256 i = 0; i < _uids.length; i++) {
_detachOne(_uids[i]);
}
}
/// @notice Reorder attached badges.
/// @dev The given order should be a permutation of `1` to `uids.length`, and `_orders[i]`
/// means `uids[i]` should be put in `_orders[i]`-th place.
///
/// @param _orders The order of the badges.
function reorderBadges(uint256[] memory _orders) external onlyOwner {
if (_orders.length != uids.length) revert LengthMismatch();
uint256 oldOrder = badgeOrderEncoding;
uint256 newOrder = _encodeOrder(_orders);
badgeOrderEncoding = newOrder;
emit ReorderBadges(oldOrder, newOrder);
}
/// @notice Change the username.
/// @param newUsername The new username.
function changeUsername(string memory newUsername) external onlyOwner {
address _registry = registry;
string memory oldUsername = username;
IProfileRegistry(_registry).unregisterUsername(oldUsername);
IProfileRegistry(_registry).registerUsername(newUsername);
username = newUsername;
emit ChangeUsername(oldUsername, newUsername);
}
/// @notice Change the avatar.
/// @param token The address of ERC721 token.
/// @param tokenId The token id.
function changeAvatar(address token, uint256 tokenId) external onlyOwner {
if (IERC721(token).ownerOf(tokenId) != owner) {
revert TokenNotOwnedByUser(token, tokenId);
}
Avatar memory oldAvatar = avatar;
avatar = Avatar(token, tokenId);
emit ChangeAvatar(oldAvatar.token, oldAvatar.tokenId, token, tokenId);
}
/**
*
* Internal Functions *
*
*/
/// @dev Internal function to attach one batch to this profile.
/// @param uid The badge uid to attach.
function _attachOne(bytes32 uid) private {
// @note This will possible cause re-emit an existing badge, used for off-chain to index any attach tx.
emit AttachBadge(uid);
if (indexes[uid] > 0) return;
uids.push(uid);
uint256 length = uids.length;
indexes[uid] = length;
uint256[] memory _oldOrders = _decodeOrder(badgeOrderEncoding, length - 1);
uint256[] memory _newOrders = new uint256[](length);
for (uint256 i = 0; i < length - 1; i++) {
_newOrders[i] = _oldOrders[i];
}
_newOrders[length - 1] = length;
badgeOrderEncoding = _encodeOrder(_newOrders);
}
/// @dev Internal function to detach one batch from this profile.
/// @param uid The badge uid to detach.
function _detachOne(bytes32 uid) private {
uint256 valueIndex = indexes[uid];
if (valueIndex == 0) return;
emit DetachBadge(uid);
uint256 length = uids.length;
uint256[] memory _oldOrders = _decodeOrder(badgeOrderEncoding, length);
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = length - 1;
uint256 deletedOrder = _oldOrders[toDeleteIndex];
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = uids[lastIndex];
// Move the last value to the index where the value to delete is
uids[toDeleteIndex] = lastValue;
_oldOrders[toDeleteIndex] = _oldOrders[lastIndex];
// Update the index for the moved value
indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
uids.pop();
delete indexes[uid];
uint256[] memory _newOrders = new uint256[](lastIndex);
for (uint256 i = 0; i < lastIndex; i++) {
_newOrders[i] = _oldOrders[i];
if (_newOrders[i] > deletedOrder) {
_newOrders[i] -= 1;
}
}
badgeOrderEncoding = _encodeOrder(_newOrders);
}
/// @dev Internal function to encode order array to an integer.
///
/// Caller should make sure `factorial(orders.length)` does not exceed `uint256.max`.
/// @return encoding The expected encoding in range `[0, factorial(orders.length))`
function _encodeOrder(uint256[] memory orders) internal pure returns (uint256 encoding) {
uint256 n = orders.length;
if (n == 0) return 0;
uint256[] memory fact = new uint256[](n);
unchecked {
fact[0] = 1;
for (uint256 i = 1; i < n; i++) {
fact[i] = fact[i - 1] * i;
}
for (uint256 i = 0; i < n; i++) {
uint256 cnt;
for (uint256 j = i + 1; j < n; j++) {
if (orders[j] < orders[i]) cnt += 1;
}
encoding += fact[n - i - 1] * cnt;
}
}
}
/// @dev Internal function to decode order encoding to order array.
function _decodeOrder(uint256 encoding, uint256 n) internal pure returns (uint256[] memory orders) {
orders = new uint256[](n);
if (n == 0) return orders;
uint256[] memory fact = new uint256[](n);
uint256[] memory nums = new uint256[](n);
unchecked {
nums[0] = fact[0] = 1;
for (uint256 i = 1; i < n; i++) {
fact[i] = fact[i - 1] * i;
nums[i] = i + 1;
}
for (uint256 i = 0; i < n; i++) {
uint256 cnt = encoding / fact[n - i - 1];
orders[i] = nums[cnt];
for (uint256 j = cnt; j + 1 < n - i; j++) {
nums[j] = nums[j + 1];
}
encoding -= cnt * fact[n - i - 1];
}
}
}
}