-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathDiamondUpgradeMod.sol
More file actions
695 lines (666 loc) · 26.3 KB
/
DiamondUpgradeMod.sol
File metadata and controls
695 lines (666 loc) · 26.3 KB
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
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.30;
/* Compose
* https://compose.diamonds
*/
/**
* @title Reference implementation for upgrade function for
* ERC-8109 Diamonds, Simplified
*
* @dev
* Facets are stored as a doubly linked list and as a mapping of selectors to facet addresses.
*
* Facets are stored as a mapping of selectors to facet addresses for efficient delegatecall
* routing to facets.
*
* Facets are stored as a doubly linked list for efficient iteration over all facets,
* and for efficiently adding, replacing, and removing them.
*
* The `FacetList` struct contains information about the linked list of facets.
*
* Only the first FacetNode of each facet contains linked list pointers.
* * prevFacetNodeId - Is the selector of the first FacetNode of the previous
* facet.
* * nextFacetNodeId - Is the selector of the first FacetNode of the next
* facet.
*
* Here is a example that shows the structure:
*
* FacetList
* facetCount = 3
* firstFacetNodeId = selector1 // facetA
* lastFacetNodeId = selector7 // facetC
*
* facetNodes mapping (selector => FacetNode)
*
* selector facet prevFacetNodeId nextFacetNodeId
* ----------------------------------------------------------------
* selector1 facetA 0x00000000 selector4 ← facetA LIST NODE
* selector2 facetA 0x00000000 0x00000000
* selector3 facetA 0x00000000 0x00000000
*
* selector4 facetB selector1 selector7 ← facetB LIST NODE
* selector5 facetB 0x00000000 0x00000000
* selector6 facetB 0x00000000 0x00000000
*
* selector7 facetC selector4 0x00000000 ← facetC LIST NODE
* selector8 facetC 0x00000000 0x00000000
* selector9 facetC 0x00000000 0x00000000
*
* Linked list order of facets:
*
* facetA (selector1)
* ↓
* facetB (selector4)
* ↓
* facetC (selector7)
*
* Notes:
* - Only the first selector of each facet participates in the linked list.
* - The linked list connects facets, not individual selectors.
* - Any values in "prevFacetNodeId" in non-first FacetNodes are not used.
*
* Checked/unchecked math note:
* We use unchecked math with `facetList.selectorCount` because that variable does not affect the adding,
* replacing, and removing of selectors and facets. It is used by some introspection functions. Checked math
* is used with facetList.facetCount because that affects adding, replacing, and removing selectors and facets.
* Of course these variables should never overflow/underflow anyway.
*/
interface IFacet {
function packedSelectors() external pure returns (bytes memory);
}
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("erc8109.diamond");
struct FacetNode {
address facet;
bytes4 prevFacetNodeId;
bytes4 nextFacetNodeId;
}
struct FacetList {
uint32 facetCount;
uint32 selectorCount;
bytes4 firstFacetNodeId;
bytes4 lastFacetNodeId;
}
/**
* @custom:storage-location erc8042:erc8109.diamond
*/
struct DiamondStorage {
mapping(bytes4 functionSelector => FacetNode) facetNodes;
FacetList facetList;
}
function getDiamondStorage() pure returns (DiamondStorage storage s) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
s.slot := position
}
}
/**
* @notice Emitted when a function is added to a diamond.
*
* @param _selector The function selector being added.
* @param _facet The facet address that will handle calls to `_selector`.
*/
event DiamondFunctionAdded(bytes4 indexed _selector, address indexed _facet);
/**
* @notice Emitted when changing the facet that will handle calls to a function.
*
* @param _selector The function selector being affected.
* @param _oldFacet The facet address previously responsible for `_selector`.
* @param _newFacet The facet address that will now handle calls to `_selector`.
*/
event DiamondFunctionReplaced(bytes4 indexed _selector, address indexed _oldFacet, address indexed _newFacet);
/**
* @notice Emitted when a function is removed from a diamond.
*
* @param _selector The function selector being removed.
* @param _oldFacet The facet address that previously handled `_selector`.
*/
event DiamondFunctionRemoved(bytes4 indexed _selector, address indexed _oldFacet);
/**
* @notice Emitted when a diamond's constructor function or function from a
* facet makes a `delegatecall`.
*
* @param _delegate The contract that was delegatecalled.
* @param _delegateCalldata The function call, including function selector and
* any arguments.
*/
event DiamondDelegateCall(address indexed _delegate, bytes _delegateCalldata);
/**
* @notice Emitted to record information about a diamond.
* @dev This event records any arbitrary metadata.
* The format of `_tag` and `_data` are not specified by the
* standard.
*
* @param _tag Arbitrary metadata, such as a release version.
* @param _data Arbitrary metadata.
*/
event DiamondMetadata(bytes32 indexed _tag, bytes _data);
/**
* @notice The upgradeDiamond function below detects and reverts
* with the following errors.
*/
error NoSelectorsForFacet(address _facet);
error NoBytecodeAtAddress(address _contractAddress);
error CannotAddFunctionToDiamondThatAlreadyExists(bytes4 _selector);
error CannotRemoveFacetThatDoesNotExist(address _facet);
error CannotReplaceFacetWithSameFacet(address _facet);
error FacetToReplaceDoesNotExist(address _oldFacet);
error DelegateCallReverted(address _delegate, bytes _delegateCalldata);
error FunctionSelectorsCallFailed(address _facet);
error IncorrectSelectorsEncoding(address _facet);
/**
* @dev This error means that a function to replace exists in a
* facet other than the facet that was given to be replaced.
*/
error CannotReplaceFunctionFromNonReplacementFacet(bytes4 _selector);
function packedSelectors(address _facet) view returns (bytes memory selectors) {
(bool success, bytes memory data) = _facet.staticcall(abi.encodeWithSelector(IFacet.packedSelectors.selector));
if (success == false) {
revert FunctionSelectorsCallFailed(_facet);
}
/*
* Ensure the data is large enough.
* Offset (32 bytes) + array length (32 bytes)
*/
if (data.length < 64) {
if (_facet.code.length == 0) {
revert NoBytecodeAtAddress(_facet);
} else {
revert IncorrectSelectorsEncoding(_facet);
}
}
/**
* Validate ABI offset == 0x20 for a single dynamic return
*/
uint256 offset;
assembly ("memory-safe") {
offset := mload(add(data, 0x20))
}
if (offset != 0x20) {
revert IncorrectSelectorsEncoding(_facet);
}
/*
* ZERO-COPY DECODE
* Instead of abi.decode(wrapper, (bytes)), which copies memory,
* we use assembly to point 'selectors' to the bytes array inside 'data'.
* The length of `data` is stored at 0 and an ABI offset is located at 0x20 (32).
* We skip over those to point `selectors` to the length of the
* bytes array.
*/
assembly ("memory-safe") {
selectors := add(data, 0x40)
}
uint256 selectorsLength = selectors.length;
unchecked {
if (selectorsLength > data.length - 64) {
revert IncorrectSelectorsEncoding(_facet);
}
}
if (selectorsLength < 4) {
revert NoSelectorsForFacet(_facet);
}
/*
* Function selectors are strictly 4 bytes. We ensure the length is a multiple of 4.
*/
if (selectorsLength % 4 != 0) {
revert IncorrectSelectorsEncoding(_facet);
}
return selectors;
}
function at(bytes memory selectors, uint256 index) pure returns (bytes4 selector) {
assembly ("memory-safe") {
/**
* 1. Calculate Pointer
* add(selectors, 32) - skips the length field of the bytes array
* shl(2, index) is the same as index * 4 but cheaper
* This line executes: ptr = selectorsLength + (4 * index)
*/
let ptr := add(add(selectors, 32), shl(2, index))
/**
* 2. Load & Return
* We load 32 bytes, but Solidity truncates to 4 bytes automatically
* upon return of this function, so masking is unnecessary.
*/
selector := mload(ptr)
}
}
function addFacets(address[] calldata _facets) {
DiamondStorage storage s = getDiamondStorage();
uint256 facetLength = _facets.length;
if (facetLength == 0) {
return;
}
FacetList memory facetList = s.facetList;
/*
* Snapshot free memory pointer. We restore this at the end of every loop
* to prevent memory expansion costs from repeated `packedSelectors` calls.
*/
uint256 freeMemPtr;
assembly ("memory-safe") {
freeMemPtr := mload(0x40)
}
/* Algorithm Description:
* The first facet is handled separately to initialize the linked list pointers in the FacetNodes.
* This allows us to avoid additional conditional checks for linked list management in the main facet loop.
*
* For the first facet, we link the first selector to the previous facet or if this is the first facet in
* the diamond then we assign the first selector to facetList.firstFacetNodeId.
*
* Then we emit the DiamondFunctionAdded event for the first selector. But don't actually add the first
* selector to the diamond at this point because we don't have the nextFacetNodeId value for the facet yet.
* We emit the DiamondFunctionAdded event at this point so the event order is consistent with the order of
* selectors returned by the facet.
*
* All the selectors (except the first one) in the first facet are then added to the diamond.
*
* In the first iteration of the main facet loop the the selectors for the next facet are retrieved.
* This makes available the nextFacetNodeId value that is needed to store the first selector of the
* first facet. So then the first selector is stored.
*
* The main facet loop continues in a similar way, emitting the DiamondFunctionAdded for the first
* selector of the facet, but not adding it, adding the other selectors, and in the next iteration adding
* the first selector after nextFacetNodeId is available.
*
* After the main facet loop ends, the first selector from the last facet is added to the diamond.
*/
bytes4 prevFacetNodeId = facetList.lastFacetNodeId;
address facet = _facets[0];
bytes memory selectors = packedSelectors(facet);
/*
* Shift right by 2 is the same as dividing by 4, but cheaper.
* We do this to get the number of selectors
*/
uint256 selectorsLength = selectors.length >> 2;
unchecked {
facetList.selectorCount += uint32(selectorsLength);
}
/*
* currentFacetNodeId is the head node of the current facet.
* We cannot write it to storage yet because we don't know the `next` pointer.
*/
bytes4 currentFacetNodeId = at(selectors, 0);
if (facetList.facetCount == 0) {
facetList.firstFacetNodeId = currentFacetNodeId;
} else {
/*
* Link the previous tail of the diamond to this new batch
*/
s.facetNodes[prevFacetNodeId].nextFacetNodeId = currentFacetNodeId;
}
/*
* Emit event for the first selector now to preserve order, even though storage write is deferred.
*/
emit DiamondFunctionAdded(currentFacetNodeId, facet);
/*
* Add all selectors, except the first, to the diamond.
*/
for (uint256 selectorIndex = 1; selectorIndex < selectorsLength; selectorIndex++) {
bytes4 selector = at(selectors, selectorIndex);
if (s.facetNodes[selector].facet != address(0)) {
revert CannotAddFunctionToDiamondThatAlreadyExists(selector);
}
s.facetNodes[selector] = FacetNode(facet, bytes4(0), bytes4(0));
emit DiamondFunctionAdded(selector, facet);
}
/*
* Reset memory for the main loop.
*/
assembly ("memory-safe") {
mstore(0x40, freeMemPtr)
}
/*
* Main facet loop.
* 1. Gets the next facet's selectors.
* 2. Now that the nextFacetNodeId value for the previous facet is available, adds the previous
* facet's first selector to the diamond.
* 3. Updates facet values: facet = nextFacet, etc.
* 4. Emits the DiamondFunctionAdded for facet's first selector.
* 5. Adds all the selectors (except the first) to the diamond.
* 6. Repeat loop.
* Note: All selectors of a facet, except the first selector, are added the diamond. After that the first
* selector is added. However the DiamondEvent event for the first selector is emitted before the rest of
* the selectors. This maintains the order of events with the order given by facets.
*/
for (uint256 i = 1; i < facetLength; i++) {
address nextFacet = _facets[i];
selectors = packedSelectors(nextFacet);
/*
* Shift right by 2 is the same as dividing by 4, but cheaper.
* We do this to get the number of selectors.
*/
selectorsLength = selectors.length >> 2;
unchecked {
facetList.selectorCount += uint32(selectorsLength);
}
/*
* Check to see if the PENDING first selector (from previous iteration) already exists in the diamond.
*/
if (s.facetNodes[currentFacetNodeId].facet != address(0)) {
revert CannotAddFunctionToDiamondThatAlreadyExists(currentFacetNodeId);
}
/*
* Identify the link to the next facet
*/
bytes4 nextFacetNodeId = at(selectors, 0);
/*
* Store the previous facet's first selector.
*/
s.facetNodes[currentFacetNodeId] = FacetNode(facet, prevFacetNodeId, nextFacetNodeId);
/*
* Move pointers forward.
* These assignments switch us from processing the previous facet's first selector to
* processing the next facet's selectors.
* `currentFacetNodeId` becomes the new pending first selector.
*/
facet = nextFacet;
prevFacetNodeId = currentFacetNodeId;
currentFacetNodeId = nextFacetNodeId;
/*
* Here we emit the DiamondFunctionAdded event for for the first selector of the facet.
* But we don't actually add the selector here.
* The selector gets added in the next iteration of the loop when the nextFacetNodeId
* value is available for it.
*/
emit DiamondFunctionAdded(currentFacetNodeId, facet);
/*
* Add all the selectors of the facet to the diamond, except the first selector.
*/
for (uint256 selectorIndex = 1; selectorIndex < selectorsLength; selectorIndex++) {
bytes4 selector = at(selectors, selectorIndex);
if (s.facetNodes[selector].facet != address(0)) {
revert CannotAddFunctionToDiamondThatAlreadyExists(selector);
}
s.facetNodes[selector] = FacetNode(facet, bytes4(0), bytes4(0));
emit DiamondFunctionAdded(selector, facet);
}
/*
* Restore Free Memory Pointer to reuse memory from packedSelector() calls.
*/
assembly ("memory-safe") {
mstore(0x40, freeMemPtr)
}
}
/*
* Validates and adds the first selector of the last facet to the diamond.
*/
if (s.facetNodes[currentFacetNodeId].facet != address(0)) {
revert CannotAddFunctionToDiamondThatAlreadyExists(currentFacetNodeId);
}
s.facetNodes[currentFacetNodeId] = FacetNode(facet, prevFacetNodeId, bytes4(0));
facetList.facetCount += uint32(facetLength);
facetList.lastFacetNodeId = currentFacetNodeId;
s.facetList = facetList;
}
/**
* @notice This struct is used to replace old facets with new facets.
*/
struct FacetReplacement {
address oldFacet;
address newFacet;
}
function replaceFacets(FacetReplacement[] calldata _replaceFacets) {
DiamondStorage storage s = getDiamondStorage();
FacetList memory facetList = s.facetList;
/*
* Snapshot free memory pointer. We restore this within the loop to prevent
* memory expansion costs from repeated `packedSelectors` calls.
*/
uint256 freeMemPtr;
assembly ("memory-safe") {
freeMemPtr := mload(0x40)
}
for (uint256 i; i < _replaceFacets.length; i++) {
address oldFacet = _replaceFacets[i].oldFacet;
address newFacet = _replaceFacets[i].newFacet;
if (oldFacet == newFacet) {
revert CannotReplaceFacetWithSameFacet(oldFacet);
}
bytes memory oldSelectors = packedSelectors(oldFacet);
bytes memory newSelectors = packedSelectors(newFacet);
/*
* Shift right by 2 is the same as dividing by 4, but cheaper.
* We do this to get the number of selectors
*/
uint256 selectorsLength = newSelectors.length >> 2;
bytes4 oldCurrentFacetNodeId = at(oldSelectors, 0);
bytes4 newCurrentFacetNodeId = at(newSelectors, 0);
/**
* Validate old facet exists.
*/
FacetNode memory oldFacetNode = s.facetNodes[oldCurrentFacetNodeId];
if (oldFacetNode.facet != oldFacet) {
revert FacetToReplaceDoesNotExist(oldFacet);
}
if (oldCurrentFacetNodeId != newCurrentFacetNodeId) {
/**
* Write first selector with linking info, then process remaining.
*/
address facet = s.facetNodes[newCurrentFacetNodeId].facet;
if (facet == address(0)) {
emit DiamondFunctionAdded(newCurrentFacetNodeId, newFacet);
unchecked {
facetList.selectorCount++;
}
} else if (facet == oldFacet) {
emit DiamondFunctionReplaced(newCurrentFacetNodeId, oldFacet, newFacet);
} else {
revert CannotReplaceFunctionFromNonReplacementFacet(newCurrentFacetNodeId);
}
s.facetNodes[newCurrentFacetNodeId] =
FacetNode(newFacet, oldFacetNode.prevFacetNodeId, oldFacetNode.nextFacetNodeId);
/**
* Update linked list.
*/
if (oldCurrentFacetNodeId == facetList.firstFacetNodeId) {
facetList.firstFacetNodeId = newCurrentFacetNodeId;
} else {
s.facetNodes[oldFacetNode.prevFacetNodeId].nextFacetNodeId = newCurrentFacetNodeId;
}
if (oldCurrentFacetNodeId == facetList.lastFacetNodeId) {
facetList.lastFacetNodeId = newCurrentFacetNodeId;
} else {
s.facetNodes[oldFacetNode.nextFacetNodeId].prevFacetNodeId = newCurrentFacetNodeId;
}
} else {
/**
* Same first selector, just replace in place.
*/
s.facetNodes[newCurrentFacetNodeId] =
FacetNode(newFacet, oldFacetNode.prevFacetNodeId, oldFacetNode.nextFacetNodeId);
emit DiamondFunctionReplaced(newCurrentFacetNodeId, oldFacet, newFacet);
/*
* If the selectors are same from both facets, then we can safely and very efficiently
* replace the old facet address with the new facet address for all the selctors.
*/
if (keccak256(oldSelectors) == keccak256(newSelectors)) {
/**
* Replace remaining selectors.
*/
for (uint256 selectorIndex = 1; selectorIndex < selectorsLength; selectorIndex++) {
bytes4 selector = at(newSelectors, selectorIndex);
s.facetNodes[selector] = FacetNode(newFacet, bytes4(0), bytes4(0));
emit DiamondFunctionReplaced(selector, oldFacet, newFacet);
}
/*
* Restore Free Memory Pointer to reuse memory.
*/
assembly ("memory-safe") {
mstore(0x40, freeMemPtr)
}
continue;
}
}
/**
* Add or replace new selectors.
*/
for (uint256 selectorIndex = 1; selectorIndex < selectorsLength; selectorIndex++) {
bytes4 selector = at(newSelectors, selectorIndex);
address facet = s.facetNodes[selector].facet;
if (facet == address(0)) {
emit DiamondFunctionAdded(selector, newFacet);
unchecked {
facetList.selectorCount++;
}
} else if (facet == oldFacet) {
emit DiamondFunctionReplaced(selector, oldFacet, newFacet);
} else {
revert CannotReplaceFunctionFromNonReplacementFacet(selector);
}
s.facetNodes[selector] = FacetNode(newFacet, bytes4(0), bytes4(0));
}
/**
* Remove old selectors that were not replaced.
*
* Shift right by 2 is the same as dividing by 4, but cheaper.
* We do this to get the number of selectors.
*/
selectorsLength = oldSelectors.length >> 2;
for (uint256 selectorIndex; selectorIndex < selectorsLength; selectorIndex++) {
bytes4 selector = at(oldSelectors, selectorIndex);
address facet = s.facetNodes[selector].facet;
if (facet == oldFacet) {
delete s.facetNodes[selector];
unchecked {
facetList.selectorCount--;
}
emit DiamondFunctionRemoved(selector, oldFacet);
}
}
/*
* Restore Free Memory Pointer to reuse memory.
*/
assembly ("memory-safe") {
mstore(0x40, freeMemPtr)
}
}
s.facetList = facetList;
}
function removeFacets(address[] calldata _facets) {
DiamondStorage storage s = getDiamondStorage();
FacetList memory facetList = s.facetList;
/*
* Snapshot free memory pointer. We restore this at the end of every loop
* to prevent memory expansion costs from repeated `packedSelectors` calls.
*/
uint256 freeMemPtr;
assembly ("memory-safe") {
freeMemPtr := mload(0x40)
}
for (uint256 i = 0; i < _facets.length; i++) {
address facet = _facets[i];
bytes memory selectors = packedSelectors(facet);
/*
* Shift right by 2 is the same as dividing by 4, but cheaper.
* We do this to get the number of selectors
*/
uint256 selectorsLength = selectors.length >> 2;
unchecked {
facetList.selectorCount -= uint32(selectorsLength);
}
bytes4 currentFacetNodeId = at(selectors, 0);
FacetNode memory facetNode = s.facetNodes[currentFacetNodeId];
/*
* This verifies that the facet we are removing exists in the
* diamond, so we can trust the rest of the selectors from `facet`.
*/
if (facetNode.facet != facet) {
revert CannotRemoveFacetThatDoesNotExist(facet);
}
/**
* Remove the facet from the linked list.
*/
if (currentFacetNodeId == facetList.firstFacetNodeId) {
facetList.firstFacetNodeId = facetNode.nextFacetNodeId;
} else {
s.facetNodes[facetNode.prevFacetNodeId].nextFacetNodeId = facetNode.nextFacetNodeId;
}
if (currentFacetNodeId == facetList.lastFacetNodeId) {
facetList.lastFacetNodeId = facetNode.prevFacetNodeId;
} else {
s.facetNodes[facetNode.nextFacetNodeId].prevFacetNodeId = facetNode.prevFacetNodeId;
}
/**
* Remove facet selectors.
*/
for (uint256 selectorIndex; selectorIndex < selectorsLength; selectorIndex++) {
bytes4 selector = at(selectors, selectorIndex);
delete s.facetNodes[selector];
emit DiamondFunctionRemoved(selector, facet);
}
/*
* Restore Free Memory Pointer to reuse memory.
*/
assembly ("memory-safe") {
mstore(0x40, freeMemPtr)
}
}
facetList.facetCount -= uint32(_facets.length);
s.facetList = facetList;
}
/**
* @notice Upgrade the diamond by adding, replacing, or removing facets.
*
* @dev
* Facets are added first, then replaced, then removed.
*
* These events are emitted to record changes to functions:
* - `DiamondFunctionAdded`
* - `DiamondFunctionReplaced`
* - `DiamondFunctionRemoved`
*
* If `_delegate` is non-zero, the diamond performs a `delegatecall` to
* `_delegate` using `_delegateCalldata`. The `DiamondDelegateCall` event is
* emitted.
*
* The `delegatecall` is done to alter a diamond's state or to
* initialize, modify, or remove state after an upgrade.
*
* However, if `_delegate` is zero, no `delegatecall` is made and no
* `DiamondDelegateCall` event is emitted.
*
* If _tag is non-zero or if _metadata.length > 0 then the
* `DiamondMetadata` event is emitted.
*
* @param _addFacets Facets to add.
* @param _replaceFacets (oldFacet, newFacet) pairs, to replace old with new.
* @param _removeFacets Facets to remove.
* @param _delegate Optional contract to delegatecall (zero address to skip).
* @param _delegateCalldata Optional calldata to execute on `_delegate`.
* @param _tag Optional arbitrary metadata, such as release version.
* @param _metadata Optional arbitrary data.
*/
function upgradeDiamond(
address[] calldata _addFacets,
FacetReplacement[] calldata _replaceFacets,
address[] calldata _removeFacets,
address _delegate,
bytes calldata _delegateCalldata,
bytes32 _tag,
bytes calldata _metadata
) {
addFacets(_addFacets);
replaceFacets(_replaceFacets);
removeFacets(_removeFacets);
if (_delegate != address(0)) {
if (_delegate.code.length == 0) {
revert NoBytecodeAtAddress(_delegate);
}
(bool success, bytes memory error) = _delegate.delegatecall(_delegateCalldata);
if (!success) {
if (error.length > 0) {
/*
* bubble up error
*/
assembly ("memory-safe") {
revert(add(error, 0x20), mload(error))
}
} else {
revert DelegateCallReverted(_delegate, _delegateCalldata);
}
}
emit DiamondDelegateCall(_delegate, _delegateCalldata);
}
if (_tag != 0 || _metadata.length > 0) {
emit DiamondMetadata(_tag, _metadata);
}
}