File size: 70,429 Bytes
f998fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
// This contract is part of Zellic’s smart contract dataset, which is a collection of publicly available contract code gathered as of March 2023.

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.17;

/// @notice Simple single owner authorization mixin.

/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)
abstract contract Owned {
    /*//////////////////////////////////////////////////////////////

                                 EVENTS

    //////////////////////////////////////////////////////////////*/

    event OwnershipTransferred(address indexed user, address indexed newOwner);

    /*//////////////////////////////////////////////////////////////

                            OWNERSHIP STORAGE

    //////////////////////////////////////////////////////////////*/

    address public owner;

    modifier onlyOwner() virtual {
        require(msg.sender == owner, "UNAUTHORIZED");

        _;
    }

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/



    constructor(address _owner) {

        owner = _owner;



        emit OwnershipTransferred(address(0), _owner);

    }



    /*//////////////////////////////////////////////////////////////
                             OWNERSHIP LOGIC
    //////////////////////////////////////////////////////////////*/



    function transferOwnership(address newOwner) public virtual onlyOwner {

        owner = newOwner;



        emit OwnershipTransferred(msg.sender, newOwner);

    }

}



/*
▄▄▄█████▓ ██░ ██ ▓█████     ██░ ██ ▓█████  ██▀███  ▓█████▄ 
▓  ██▒ ▓▒▓██░ ██▒▓█   ▀    ▓██░ ██▒▓█   ▀ ▓██ ▒ ██▒▒██▀ ██▌
▒ ▓██░ ▒░▒██▀▀██░▒███      ▒██▀▀██░▒███   ▓██ ░▄█ ▒░██   █▌
░ ▓██▓ ░ ░▓█ ░██ ▒▓█  ▄    ░▓█ ░██ ▒▓█  ▄ ▒██▀▀█▄  ░▓█▄   ▌
  ▒██▒ ░ ░▓█▒░██▓░▒████▒   ░▓█▒░██▓░▒████▒░██▓ ▒██▒░▒████▓ 
  ▒ ░░    ▒ ░░▒░▒░░ ▒░ ░    ▒ ░░▒░▒░░ ▒░ ░░ ▒▓ ░▒▓░ ▒▒▓  ▒ 
    ░     ▒ ░▒░ ░ ░ ░  ░    ▒ ░▒░ ░ ░ ░  ░  ░▒ ░ ▒░ ░ ▒  ▒ 
  ░       ░  ░░ ░   ░       ░  ░░ ░   ░     ░░   ░  ░ ░  ░ 
          ░  ░  ░   ░  ░    ░  ░  ░   ░  ░   ░        ░    
                                                    ░      
              .,;>>%%%%%>>;,.
           .>%%%%%%%%%%%%%%%%%%%%>,.
         .>%%%%%%%%%%%%%%%%%%>>,%%%%%%;,.
       .>>>>%%%%%%%%%%%%%>>,%%%%%%%%%%%%,>>%%,.
     .>>%>>>>%%%%%%%%%>>,%%%%%%%%%%%%%%%%%,>>%%%%%,.
   .>>%%%%%>>%%%%>>,%%>>%%%%%%%%%%%%%%%%%%%%,>>%%%%%%%,
  .>>%%%%%%%%%%>>,%%%%%%>>%%%%%%%%%%%%%%%%%%,>>%%%%%%%%%%.
  .>>%%%%%%%%%%>>,>>>>%%%%%%%%%%'..`%%%%%%%%,;>>%%%%%%%%%>%%.

.>>%%%>>>%%%%%>,%%%%%%%%%%%%%%.%%%,`%%%%%%,;>>%%%%%%%%>>>%%%%.

>>%%>%>>>%>%%%>,%%%%%>>%%%%%%%%%%%%%`%%%%%%,>%%%%%%%>>>>%%%%%%%.

>>%>>>%%>>>%%%%>,%>>>%%%%%%%%%%%%%%%%`%%%%%%%%%%%%%%%%%%%%%%%%%%.

>>%%%%%%%%%%%%%%,>%%%%%%%%%%%%%%%%%%%'%%%,>>%%%%%%%%%%%%%%%%%%%%%.
>>%%%%%%%%%%%%%%%,>%%%>>>%%%%%%%%%%%%%%%,>>%%%%%%%%>>>>%%%%%%%%%%%.
>>%%%%%%%%;%;%;%%;,%>>>>%%%%%%%%%%%%%%%,>>>%%%%%%>>;";>>%%%%%%%%%%%%.

`>%%%%%%%%%;%;;;%;%,>%%%%%%%%%>>%%%%%%%%,>>>%%%%%%%%%%%%%%%%%%%%%%%%%%.

 >>%%%%%%%%%,;;;;;%%>,%%%%%%%%>>>>%%%%%%%%,>>%%%%%%%%%%%%%%%%%%%%%%%%%%%.

 `>>%%%%%%%%%,%;;;;%%%>,%%%%%%%%>>>>%%%%%%%%,>%%%%%%'%%%%%%%%%%%%%%%%%%%>>.

  `>>%%%%%%%%%%>,;;%%%%%>>,%%%%%%%%>>%%%%%%';;;>%%%%%,`%%%%%%%%%%%%%%%>>%%>.

   >>>%%%%%%%%%%>> %%%%%%%%>>,%%%%>>>%%%%%';;;;;;>>,%%%,`%     `;>%%%%%%>>%%

   `>>%%%%%%%%%%>> %%%%%%%%%>>>>>>>>;;;;'.;;;;;>>%%'  `%%'          ;>%%%%%>

    >>%%%%%%%%%>>; %%%%%%%%>>;;;;;;''    ;;;;;>>%%%                   ;>%%%%

    `>>%%%%%%%>>>, %%%%%%%%%>>;;'        ;;;;>>%%%'                    ;>%%%

     >>%%%%%%>>>':.%%%%%%%%%%>>;        .;;;>>%%%%                    ;>%%%'

     `>>%%%%%>>> ::`%%%%%%%%%%>>;.      ;;;>>%%%%'                   ;>%%%'

      `>>%%%%>>> `:::`%%%%%%%%%%>;.     ;;>>%%%%%                   ;>%%'

       `>>%%%%>>, `::::`%%%%%%%%%%>,   .;>>%%%%%'                   ;>%'

        `>>%%%%>>, `:::::`%%%%%%%%%>>. ;;>%%%%%%                    ;>%,

         `>>%%%%>>, :::::::`>>>%%%%>>> ;;>%%%%%'                     ;>%,

          `>>%%%%>>,::::::,>>>>>>>>>>' ;;>%%%%%                       ;%%,

            >>%%%%>>,:::,%%>>>>>>>>'   ;>%%%%%.                        ;%%

             >>%%%%>>``%%%%%>>>>>'     `>%%%%%%.

             >>%%%%>> `@@a%%%%%%'     .%%%%%%%%%.

             `a@@a%@'    `%a@@'       `a@@a%a@@a

 */



interface Factory {

    function feeCollector() external view returns (address);



    function platformFeeManager(address) external view returns (address);



    function recipient(address, address) external view returns (address);

}



interface GaugeController {

    struct VotedSlope {

        uint256 slope;

        uint256 power;

        uint256 end;

    }



    struct Point {

        uint256 bias;

        uint256 slope;

    }



    function vote_user_slopes(address, address) external view returns (VotedSlope memory);



    function add_gauge(address, int128) external;



    function WEIGHT_VOTE_DELAY() external view returns (uint256);



    function last_user_vote(address, address) external view returns (uint256);



    function points_weight(address, uint256) external view returns (Point memory);



    function checkpoint_gauge(address) external;



    //solhint-disable-next-line

    function gauge_types(address addr) external view returns (int128);



    //solhint-disable-next-line

    function gauge_relative_weight_write(address addr, uint256 timestamp) external returns (uint256);



    //solhint-disable-next-line

    function gauge_relative_weight(address addr) external view returns (uint256);



    //solhint-disable-next-line

    function gauge_relative_weight(address addr, uint256 timestamp) external view returns (uint256);



    //solhint-disable-next-line

    function get_total_weight() external view returns (uint256);



    //solhint-disable-next-line

    function get_gauge_weight(address addr) external view returns (uint256);



    function vote_for_gauge_weights(address, uint256) external;



    function add_type(string memory, uint256) external;



    function admin() external view returns (address);

}



/// @notice Gas optimized reentrancy protection for smart contracts.

/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ReentrancyGuard.sol)

/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)

abstract contract ReentrancyGuard {

    uint256 private locked = 1;



    modifier nonReentrant() virtual {

        require(locked == 1, "REENTRANCY");



        locked = 2;



        _;



        locked = 1;

    }

}



/// @notice Arithmetic library with operations for fixed-point numbers.

/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)

/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)

library FixedPointMathLib {

    /*//////////////////////////////////////////////////////////////

                    SIMPLIFIED FIXED POINT OPERATIONS

    //////////////////////////////////////////////////////////////*/



    uint256 internal constant MAX_UINT256 = 2**256 - 1;



    uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.



    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {

        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.

    }



    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {

        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.

    }



    function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {

        return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.

    }



    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {

        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.

    }



    /*//////////////////////////////////////////////////////////////

                    LOW LEVEL FIXED POINT OPERATIONS

    //////////////////////////////////////////////////////////////*/



    function mulDivDown(

        uint256 x,

        uint256 y,

        uint256 denominator

    ) internal pure returns (uint256 z) {

        /// @solidity memory-safe-assembly

        assembly {

            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))

            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {

                revert(0, 0)

            }



            // Divide x * y by the denominator.

            z := div(mul(x, y), denominator)

        }

    }



    function mulDivUp(

        uint256 x,

        uint256 y,

        uint256 denominator

    ) internal pure returns (uint256 z) {

        /// @solidity memory-safe-assembly

        assembly {

            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))

            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {

                revert(0, 0)

            }



            // If x * y modulo the denominator is strictly greater than 0,

            // 1 is added to round up the division of x * y by the denominator.

            z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))

        }

    }



    function rpow(

        uint256 x,

        uint256 n,

        uint256 scalar

    ) internal pure returns (uint256 z) {

        /// @solidity memory-safe-assembly

        assembly {

            switch x

            case 0 {

                switch n

                case 0 {

                    // 0 ** 0 = 1

                    z := scalar

                }

                default {

                    // 0 ** n = 0

                    z := 0

                }

            }

            default {

                switch mod(n, 2)

                case 0 {

                    // If n is even, store scalar in z for now.

                    z := scalar

                }

                default {

                    // If n is odd, store x in z for now.

                    z := x

                }



                // Shifting right by 1 is like dividing by 2.

                let half := shr(1, scalar)



                for {

                    // Shift n right by 1 before looping to halve it.

                    n := shr(1, n)

                } n {

                    // Shift n right by 1 each iteration to halve it.

                    n := shr(1, n)

                } {

                    // Revert immediately if x ** 2 would overflow.

                    // Equivalent to iszero(eq(div(xx, x), x)) here.

                    if shr(128, x) {

                        revert(0, 0)

                    }



                    // Store x squared.

                    let xx := mul(x, x)



                    // Round to the nearest number.

                    let xxRound := add(xx, half)



                    // Revert if xx + half overflowed.

                    if lt(xxRound, xx) {

                        revert(0, 0)

                    }



                    // Set x to scaled xxRound.

                    x := div(xxRound, scalar)



                    // If n is even:

                    if mod(n, 2) {

                        // Compute z * x.

                        let zx := mul(z, x)



                        // If z * x overflowed:

                        if iszero(eq(div(zx, x), z)) {

                            // Revert if x is non-zero.

                            if iszero(iszero(x)) {

                                revert(0, 0)

                            }

                        }



                        // Round to the nearest number.

                        let zxRound := add(zx, half)



                        // Revert if zx + half overflowed.

                        if lt(zxRound, zx) {

                            revert(0, 0)

                        }



                        // Return properly scaled zxRound.

                        z := div(zxRound, scalar)

                    }

                }

            }

        }

    }



    /*//////////////////////////////////////////////////////////////

                        GENERAL NUMBER UTILITIES

    //////////////////////////////////////////////////////////////*/



    function sqrt(uint256 x) internal pure returns (uint256 z) {

        /// @solidity memory-safe-assembly

        assembly {

            let y := x // We start y at x, which will help us make our initial estimate.



            z := 181 // The "correct" value is 1, but this saves a multiplication later.



            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad

            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.



            // We check y >= 2^(k + 8) but shift right by k bits

            // each branch to ensure that if x >= 256, then y >= 256.

            if iszero(lt(y, 0x10000000000000000000000000000000000)) {

                y := shr(128, y)

                z := shl(64, z)

            }

            if iszero(lt(y, 0x1000000000000000000)) {

                y := shr(64, y)

                z := shl(32, z)

            }

            if iszero(lt(y, 0x10000000000)) {

                y := shr(32, y)

                z := shl(16, z)

            }

            if iszero(lt(y, 0x1000000)) {

                y := shr(16, y)

                z := shl(8, z)

            }



            // Goal was to get z*z*y within a small factor of x. More iterations could

            // get y in a tighter range. Currently, we will have y in [256, 256*2^16).

            // We ensured y >= 256 so that the relative difference between y and y+1 is small.

            // That's not possible if x < 256 but we can just verify those cases exhaustively.



            // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.

            // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.

            // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.



            // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range

            // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.



            // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate

            // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.



            // There is no overflow risk here since y < 2^136 after the first branch above.

            z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.



            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.

            z := shr(1, add(z, div(x, z)))

            z := shr(1, add(z, div(x, z)))

            z := shr(1, add(z, div(x, z)))

            z := shr(1, add(z, div(x, z)))

            z := shr(1, add(z, div(x, z)))

            z := shr(1, add(z, div(x, z)))

            z := shr(1, add(z, div(x, z)))



            // If x+1 is a perfect square, the Babylonian method cycles between

            // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.

            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division

            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.

            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.

            z := sub(z, lt(div(x, z), z))

        }

    }



    function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {

        /// @solidity memory-safe-assembly

        assembly {

            // Mod x by y. Note this will return

            // 0 instead of reverting if y is zero.

            z := mod(x, y)

        }

    }



    function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {

        /// @solidity memory-safe-assembly

        assembly {

            // Divide x by y. Note this will return

            // 0 instead of reverting if y is zero.

            r := div(x, y)

        }

    }



    function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {

        /// @solidity memory-safe-assembly

        assembly {

            // Add 1 to x * y if x % y > 0. Note this will

            // return 0 instead of reverting if y is zero.

            z := add(gt(mod(x, y), 0), div(x, y))

        }

    }

}



/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.

/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)

/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)

/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.

abstract contract ERC20 {

    /*//////////////////////////////////////////////////////////////

                                 EVENTS

    //////////////////////////////////////////////////////////////*/



    event Transfer(address indexed from, address indexed to, uint256 amount);



    event Approval(address indexed owner, address indexed spender, uint256 amount);



    /*//////////////////////////////////////////////////////////////

                            METADATA STORAGE

    //////////////////////////////////////////////////////////////*/



    string public name;



    string public symbol;



    uint8 public immutable decimals;



    /*//////////////////////////////////////////////////////////////

                              ERC20 STORAGE

    //////////////////////////////////////////////////////////////*/



    uint256 public totalSupply;



    mapping(address => uint256) public balanceOf;



    mapping(address => mapping(address => uint256)) public allowance;



    /*//////////////////////////////////////////////////////////////

                            EIP-2612 STORAGE

    //////////////////////////////////////////////////////////////*/



    uint256 internal immutable INITIAL_CHAIN_ID;



    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;



    mapping(address => uint256) public nonces;



    /*//////////////////////////////////////////////////////////////

                               CONSTRUCTOR

    //////////////////////////////////////////////////////////////*/



    constructor(

        string memory _name,

        string memory _symbol,

        uint8 _decimals

    ) {

        name = _name;

        symbol = _symbol;

        decimals = _decimals;



        INITIAL_CHAIN_ID = block.chainid;

        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();

    }



    /*//////////////////////////////////////////////////////////////

                               ERC20 LOGIC

    //////////////////////////////////////////////////////////////*/



    function approve(address spender, uint256 amount) public virtual returns (bool) {

        allowance[msg.sender][spender] = amount;



        emit Approval(msg.sender, spender, amount);



        return true;

    }



    function transfer(address to, uint256 amount) public virtual returns (bool) {

        balanceOf[msg.sender] -= amount;



        // Cannot overflow because the sum of all user

        // balances can't exceed the max uint256 value.

        unchecked {

            balanceOf[to] += amount;

        }



        emit Transfer(msg.sender, to, amount);



        return true;

    }



    function transferFrom(

        address from,

        address to,

        uint256 amount

    ) public virtual returns (bool) {

        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.



        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;



        balanceOf[from] -= amount;



        // Cannot overflow because the sum of all user

        // balances can't exceed the max uint256 value.

        unchecked {

            balanceOf[to] += amount;

        }



        emit Transfer(from, to, amount);



        return true;

    }



    /*//////////////////////////////////////////////////////////////

                             EIP-2612 LOGIC

    //////////////////////////////////////////////////////////////*/



    function permit(

        address owner,

        address spender,

        uint256 value,

        uint256 deadline,

        uint8 v,

        bytes32 r,

        bytes32 s

    ) public virtual {

        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");



        // Unchecked because the only math done is incrementing

        // the owner's nonce which cannot realistically overflow.

        unchecked {

            address recoveredAddress = ecrecover(

                keccak256(

                    abi.encodePacked(

                        "\x19\x01",

                        DOMAIN_SEPARATOR(),

                        keccak256(

                            abi.encode(

                                keccak256(

                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"

                                ),

                                owner,

                                spender,

                                value,

                                nonces[owner]++,

                                deadline

                            )

                        )

                    )

                ),

                v,

                r,

                s

            );



            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");



            allowance[recoveredAddress][spender] = value;

        }



        emit Approval(owner, spender, value);

    }



    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {

        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();

    }



    function computeDomainSeparator() internal view virtual returns (bytes32) {

        return

            keccak256(

                abi.encode(

                    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),

                    keccak256(bytes(name)),

                    keccak256("1"),

                    block.chainid,

                    address(this)

                )

            );

    }



    /*//////////////////////////////////////////////////////////////

                        INTERNAL MINT/BURN LOGIC

    //////////////////////////////////////////////////////////////*/



    function _mint(address to, uint256 amount) internal virtual {

        totalSupply += amount;



        // Cannot overflow because the sum of all user

        // balances can't exceed the max uint256 value.

        unchecked {

            balanceOf[to] += amount;

        }



        emit Transfer(address(0), to, amount);

    }



    function _burn(address from, uint256 amount) internal virtual {

        balanceOf[from] -= amount;



        // Cannot underflow because a user's balance

        // will never be larger than the total supply.

        unchecked {

            totalSupply -= amount;

        }



        emit Transfer(from, address(0), amount);

    }

}



/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.

/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)

/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.

/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.

library SafeTransferLib {

    /*//////////////////////////////////////////////////////////////

                             ETH OPERATIONS

    //////////////////////////////////////////////////////////////*/



    function safeTransferETH(address to, uint256 amount) internal {

        bool success;



        /// @solidity memory-safe-assembly

        assembly {

            // Transfer the ETH and store if it succeeded or not.

            success := call(gas(), to, amount, 0, 0, 0, 0)

        }



        require(success, "ETH_TRANSFER_FAILED");

    }



    /*//////////////////////////////////////////////////////////////

                            ERC20 OPERATIONS

    //////////////////////////////////////////////////////////////*/



    function safeTransferFrom(

        ERC20 token,

        address from,

        address to,

        uint256 amount

    ) internal {

        bool success;



        /// @solidity memory-safe-assembly

        assembly {

            // Get a pointer to some free memory.

            let freeMemoryPointer := mload(0x40)



            // Write the abi-encoded calldata into memory, beginning with the function selector.

            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)

            mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.

            mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.

            mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.



            success := and(

                // Set success to whether the call reverted, if not we check it either

                // returned exactly 1 (can't just be non-zero data), or had no return data.

                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),

                // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.

                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.

                // Counterintuitively, this call must be positioned second to the or() call in the

                // surrounding and() call or else returndatasize() will be zero during the computation.

                call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)

            )

        }



        require(success, "TRANSFER_FROM_FAILED");

    }



    function safeTransfer(

        ERC20 token,

        address to,

        uint256 amount

    ) internal {

        bool success;



        /// @solidity memory-safe-assembly

        assembly {

            // Get a pointer to some free memory.

            let freeMemoryPointer := mload(0x40)



            // Write the abi-encoded calldata into memory, beginning with the function selector.

            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)

            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.

            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.



            success := and(

                // Set success to whether the call reverted, if not we check it either

                // returned exactly 1 (can't just be non-zero data), or had no return data.

                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),

                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.

                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.

                // Counterintuitively, this call must be positioned second to the or() call in the

                // surrounding and() call or else returndatasize() will be zero during the computation.

                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)

            )

        }



        require(success, "TRANSFER_FAILED");

    }



    function safeApprove(

        ERC20 token,

        address to,

        uint256 amount

    ) internal {

        bool success;



        /// @solidity memory-safe-assembly

        assembly {

            // Get a pointer to some free memory.

            let freeMemoryPointer := mload(0x40)



            // Write the abi-encoded calldata into memory, beginning with the function selector.

            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)

            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.

            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.



            success := and(

                // Set success to whether the call reverted, if not we check it either

                // returned exactly 1 (can't just be non-zero data), or had no return data.

                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),

                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.

                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.

                // Counterintuitively, this call must be positioned second to the or() call in the

                // surrounding and() call or else returndatasize() will be zero during the computation.

                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)

            )

        }



        require(success, "APPROVE_FAILED");

    }

}



contract FeeManager is Owned {

    using SafeTransferLib for ERC20;

    uint256 public totalFee;

    uint256 internal constant _DEFAULT_FEE = 2e16; // 2%

    struct FeeRecipient {

        address recipient;

        uint256 fee;

    }

    FeeRecipient[] public recipients;



    /// @notice Thrown if the fee percentage is invalid.

    error INCORRECT_FEE();



    constructor(address _feeRecipient) Owned(_feeRecipient) {

        totalFee = _DEFAULT_FEE;

        recipients.push(FeeRecipient(_feeRecipient, _DEFAULT_FEE));

    }



    function disperseFees(address _token) external {

        uint256 length = recipients.length;

        uint256 totalBal = ERC20(_token).balanceOf(address(this));

        uint256 amount;

        for (uint256 i; i < length; ) {

            FeeRecipient memory recipient = recipients[i];

            amount = (totalBal * recipient.fee) / totalFee;

            ERC20(_token).safeTransfer(recipient.recipient, amount);

            unchecked {

                i++;

            }

        }

    }



    function addRecipient(address _recipient, uint256 _fee) external onlyOwner {

        if (_fee > 1e18) revert INCORRECT_FEE();

        recipients.push(FeeRecipient(_recipient, _fee));

        totalFee += _fee;

    }



    function removeRecipient(uint256 _index) external onlyOwner {

        totalFee -= recipients[_index].fee;

        recipients[_index] = recipients[recipients.length - 1];

        recipients.pop();

    }



    function updateRecipient(

        uint256 _index,

        address _recipient,

        uint256 _fee

    ) external onlyOwner {

        if (_fee > 1e18) revert INCORRECT_FEE();

        totalFee -= recipients[_index].fee;

        recipients[_index].recipient = _recipient;

        recipients[_index].fee = _fee;

        totalFee += _fee;

    }



    function totalFeeRecipients() external view returns (uint256) {

        return recipients.length;

    }

}



/// version 1.5.0

/// @title  Platform

/// @author Stake DAO

contract Platform is ReentrancyGuard {

    using SafeTransferLib for ERC20;

    using FixedPointMathLib for uint256;



    ////////////////////////////////////////////////////////////////

    /// --- EMERGENCY SHUTDOWN

    ///////////////////////////////////////////////////////////////



    /// @notice Emergency shutdown flag

    bool public isKilled;



    ////////////////////////////////////////////////////////////////

    /// --- STRUCTS

    ///////////////////////////////////////////////////////////////



    /// @notice Bribe struct requirements.

    struct Bribe {

        // Address of the target gauge.

        address gauge;

        // Manager.

        address manager;

        // Address of the ERC20 used for rewards.

        address rewardToken;

        // Number of periods.

        uint8 numberOfPeriods;

        // Timestamp where the bribe become unclaimable.

        uint256 endTimestamp;

        // Max Price per vote.

        uint256 maxRewardPerVote;

        // Total Reward Added.

        uint256 totalRewardAmount;

        // Blacklisted addresses.

        address[] blacklist;

    }



    /// @notice Period struct.

    struct Period {

        // Period id.

        // Eg: 0 is the first period, 1 is the second period, etc.

        uint8 id;

        // Timestamp of the period start.

        uint256 timestamp;

        // Reward amount distributed during the period.

        uint256 rewardPerPeriod;

    }



    struct Upgrade {

        // Number of periods after increase.

        uint8 numberOfPeriods;

        // Total reward amount after increase.

        uint256 totalRewardAmount;

        // New max reward per vote after increase.

        uint256 maxRewardPerVote;

        // New end timestamp after increase.

        uint256 endTimestamp;

        // Blacklisted addresses.

        address[] blacklist;

    }



    ////////////////////////////////////////////////////////////////

    /// --- CONSTANTS & IMMUTABLES

    ///////////////////////////////////////////////////////////////



    /// @notice Week in seconds.

    uint256 private constant _WEEK = 1 weeks;



    /// @notice Base unit for fixed point compute.

    uint256 private constant _BASE_UNIT = 1e18;



    /// @notice Minimum duration a Bribe.

    uint8 public constant MINIMUM_PERIOD = 2;



    /// @notice Factory contract.

    Factory public immutable factory;



    /// @notice Gauge Controller.

    GaugeController public immutable gaugeController;



    ////////////////////////////////////////////////////////////////

    /// --- STORAGE VARS

    ///////////////////////////////////////////////////////////////



    /// @notice Bribe ID Counter.

    uint256 public nextID;



    /// @notice ID => Bribe.

    mapping(uint256 => Bribe) public bribes;



    /// @notice ID => Bribe In Queue to be upgraded.

    mapping(uint256 => Upgrade) public upgradeBribeQueue;



    /// @notice ID => Period running.

    mapping(uint256 => Period) public activePeriod;



    /// @notice BribeId => isUpgradeable. If true, the bribe can be upgraded.

    mapping(uint256 => bool) public isUpgradeable;



    /// @notice ID => Amount Claimed per Bribe.

    mapping(uint256 => uint256) public amountClaimed;



    /// @notice ID => Amount of reward per vote distributed.

    mapping(uint256 => uint256) public rewardPerVote;



    /// @notice Blacklisted addresses per bribe that aren't counted for rewards arithmetics.

    mapping(uint256 => mapping(address => bool)) public isBlacklisted;



    /// @notice Last time a user claimed

    mapping(address => mapping(uint256 => uint256)) public lastUserClaim;



    ////////////////////////////////////////////////////////////////

    /// --- MODIFIERS

    ///////////////////////////////////////////////////////////////



    modifier onlyManager(uint256 _id) {

        if (msg.sender != bribes[_id].manager) revert AUTH_MANAGER_ONLY();

        _;

    }



    modifier notKilled() {

        if (isKilled) revert KILLED();

        _;

    }



    ////////////////////////////////////////////////////////////////

    /// --- EVENTS

    ///////////////////////////////////////////////////////////////



    /// @notice Emitted when a new bribe is created.

    event BribeCreated(

        uint256 indexed id,

        address indexed gauge,

        address manager,

        address indexed rewardToken,

        uint8 numberOfPeriods,

        uint256 maxRewardPerVote,

        uint256 rewardPerPeriod,

        uint256 totalRewardAmount,

        bool isUpgradeable

    );



    /// @notice Emitted when a bribe is closed.

    event BribeClosed(uint256 id, uint256 remainingReward);



    /// @notice Emitted when a bribe period is rolled over.

    event PeriodRolledOver(

        uint256 id,

        uint256 periodId,

        uint256 timestamp,

        uint256 rewardPerPeriod

    );



    /// @notice Emitted on claim.

    event Claimed(

        address indexed user,

        address indexed rewardToken,

        uint256 indexed bribeId,

        uint256 amount,

        uint256 protocolFees,

        uint256 period

    );



    /// @notice Emitted when a bribe is queued to upgrade.

    event BribeDurationIncreaseQueued(

        uint256 id,

        uint8 numberOfPeriods,

        uint256 totalRewardAmount,

        uint256 maxRewardPerVote

    );



    /// @notice Emitted when a bribe is upgraded.

    event BribeDurationIncreased(

        uint256 id,

        uint8 numberOfPeriods,

        uint256 totalRewardAmount,

        uint256 maxRewardPerVote

    );



    /// @notice Emitted when a bribe manager is updated.

    event ManagerUpdated(uint256 id, address indexed manager);



    ////////////////////////////////////////////////////////////////

    /// --- ERRORS

    ///////////////////////////////////////////////////////////////



    error KILLED();

    error WRONG_INPUT();

    error ZERO_ADDRESS();

    error NO_PERIODS_LEFT();

    error NOT_UPGRADEABLE();

    error AUTH_MANAGER_ONLY();

    error ALREADY_INCREASED();

    error NOT_ALLOWED_OPERATION();

    error INVALID_NUMBER_OF_PERIODS();



    ////////////////////////////////////////////////////////////////

    /// --- CONSTRUCTOR

    ///////////////////////////////////////////////////////////////



    /// @notice Create Bribe platform.

    /// @param _gaugeController Address of the gauge controller.

    constructor(address _gaugeController, address _factory) {

        factory = Factory(_factory);

        gaugeController = GaugeController(_gaugeController);

    }



    ////////////////////////////////////////////////////////////////

    /// --- BRIBE CREATION LOGIC

    ///////////////////////////////////////////////////////////////



    /// @notice Create a new bribe.

    /// @param gauge Address of the target gauge.

    /// @param rewardToken Address of the ERC20 used or rewards.

    /// @param numberOfPeriods Number of periods.

    /// @param maxRewardPerVote Target Bias for the Gauge.

    /// @param totalRewardAmount Total Reward Added.

    /// @param blacklist Array of addresses to blacklist.

    /// @return newBribeID of the bribe created.

    function createBribe(

        address gauge,

        address manager,

        address rewardToken,

        uint8 numberOfPeriods,

        uint256 maxRewardPerVote,

        uint256 totalRewardAmount,

        address[] calldata blacklist,

        bool upgradeable

    ) external nonReentrant notKilled returns (uint256 newBribeID) {

        if (rewardToken == address(0)) revert ZERO_ADDRESS();

        if (gaugeController.gauge_types(gauge) < 0) return newBribeID;

        if (numberOfPeriods < MINIMUM_PERIOD)

            revert INVALID_NUMBER_OF_PERIODS();

        if (totalRewardAmount == 0 || maxRewardPerVote == 0)

            revert WRONG_INPUT();



        // Transfer the rewards to the contracts.

        ERC20(rewardToken).safeTransferFrom(

            msg.sender,

            address(this),

            totalRewardAmount

        );



        unchecked {

            // Get the ID for that new Bribe and increment the nextID counter.

            newBribeID = nextID;



            ++nextID;

        }



        uint256 rewardPerPeriod = totalRewardAmount.mulDivDown(

            1,

            numberOfPeriods

        );

        uint256 currentPeriod = getCurrentPeriod();



        bribes[newBribeID] = Bribe({

            gauge: gauge,

            manager: manager,

            rewardToken: rewardToken,

            numberOfPeriods: numberOfPeriods,

            endTimestamp: currentPeriod + ((numberOfPeriods + 1) * _WEEK),

            maxRewardPerVote: maxRewardPerVote,

            totalRewardAmount: totalRewardAmount,

            blacklist: blacklist

        });



        emit BribeCreated(

            newBribeID,

            gauge,

            manager,

            rewardToken,

            numberOfPeriods,

            maxRewardPerVote,

            rewardPerPeriod,

            totalRewardAmount,

            upgradeable

        );



        // Set Upgradeable status.

        isUpgradeable[newBribeID] = upgradeable;

        // Starting from next period.

        activePeriod[newBribeID] = Period(

            0,

            currentPeriod + _WEEK,

            rewardPerPeriod

        );



        // Add the addresses to the blacklist.

        uint256 length = blacklist.length;

        for (uint256 i = 0; i < length; ) {

            isBlacklisted[newBribeID][blacklist[i]] = true;

            unchecked {

                ++i;

            }

        }

    }



    /// @notice Claim rewards for a given bribe.

    /// @param bribeId ID of the bribe.

    /// @return Amount of rewards claimed.

    function claimFor(address user, uint256 bribeId)

        external

        returns (uint256)

    {

        address recipient = factory.recipient(user, address(gaugeController));

        return

            _claim(user, recipient != address(0) ? recipient : user, bribeId);

    }



    function claimAllFor(address user, uint256[] calldata ids) external {

        address recipient = factory.recipient(user, address(gaugeController));

        uint256 length = ids.length;



        for (uint256 i = 0; i < length; ) {

            uint256 id = ids[i];

            _claim(user, recipient != address(0) ? recipient : user, id);

            unchecked {

                ++i;

            }

        }

    }



    /// @notice Claim rewards for a given bribe.

    /// @param bribeId ID of the bribe.

    /// @return Amount of rewards claimed.

    function claim(uint256 bribeId) external returns (uint256) {

        address recipient = factory.recipient(

            msg.sender,

            address(gaugeController)

        );

        return

            _claim(

                msg.sender,

                recipient != address(0) ? recipient : msg.sender,

                bribeId

            );

    }



    /// @notice Update Bribe for a given id.

    /// @param bribeId ID of the bribe.

    function updateBribePeriod(uint256 bribeId) external nonReentrant {

        _updateBribePeriod(bribeId);

    }



    /// @notice Update multiple bribes for given ids.

    /// @param ids Array of Bribe IDs.

    function updateBribePeriods(uint256[] calldata ids) external nonReentrant {

        uint256 length = ids.length;

        for (uint256 i = 0; i < length; ) {

            _updateBribePeriod(ids[i]);

            unchecked {

                ++i;

            }

        }

    }



    /// @notice Claim all rewards for multiple bribes.

    /// @param ids Array of bribe IDs to claim.

    function claimAll(uint256[] calldata ids) external {

        address recipient = factory.recipient(

            msg.sender,

            address(gaugeController)

        );

        recipient = recipient != address(0) ? recipient : msg.sender;



        uint256 length = ids.length;



        for (uint256 i = 0; i < length; ) {

            uint256 id = ids[i];

            _claim(msg.sender, recipient, id);



            unchecked {

                ++i;

            }

        }

    }



    ////////////////////////////////////////////////////////////////

    /// --- INTERNAL LOGIC

    ///////////////////////////////////////////////////////////////



    /// @notice Claim rewards for a given bribe.

    /// @param user Address of the user.

    /// @param bribeId ID of the bribe.

    /// @return amount of rewards claimed.

    function _claim(

        address user,

        address recipient,

        uint256 bribeId

    ) internal nonReentrant notKilled returns (uint256 amount) {

        if (isBlacklisted[bribeId][user]) return 0;

        // Update if needed the current period.

        uint256 currentPeriod = _updateBribePeriod(bribeId);



        Bribe storage bribe = bribes[bribeId];



        // Get the last_vote timestamp.

        uint256 lastVote = gaugeController.last_user_vote(user, bribe.gauge);



        GaugeController.VotedSlope memory userSlope = gaugeController

            .vote_user_slopes(user, bribe.gauge);



        if (

            userSlope.slope == 0 ||

            lastUserClaim[user][bribeId] >= currentPeriod ||

            currentPeriod >= userSlope.end ||

            currentPeriod <= lastVote ||

            currentPeriod >= bribe.endTimestamp ||

            currentPeriod != getCurrentPeriod() ||

            amountClaimed[bribeId] == bribe.totalRewardAmount

        ) return 0;



        // Update User last claim period.

        lastUserClaim[user][bribeId] = currentPeriod;



        // Voting Power = userSlope * dt

        // with dt = lock_end - period.

        uint256 _bias = _getAddrBias(

            userSlope.slope,

            userSlope.end,

            currentPeriod

        );

        // Compute the reward amount based on

        // Reward / Total Votes.

        amount = _bias.mulWadDown(rewardPerVote[bribeId]);

        // Compute the reward amount based on

        // the max price to pay.

        uint256 _amountWithMaxPrice = _bias.mulWadDown(bribe.maxRewardPerVote);

        // Distribute the _min between the amount based on votes, and price.

        amount = _min(amount, _amountWithMaxPrice);



        // Update the amount claimed.

        uint256 _amountClaimed = amountClaimed[bribeId];



        if (amount + _amountClaimed > bribe.totalRewardAmount) {

            amount = bribe.totalRewardAmount - _amountClaimed;

        }



        amountClaimed[bribeId] += amount;



        uint256 feeAmount;

        address feeManager = factory.platformFeeManager(

            address(gaugeController)

        );

        uint256 platformFee = FeeManager(feeManager).totalFee();



        if (platformFee != 0) {

            feeAmount = amount.mulWadDown(platformFee);

            amount -= feeAmount;



            // Transfer fees.

            ERC20(bribe.rewardToken).safeTransfer(feeManager, feeAmount);

        }



        // Transfer to user.

        ERC20(bribe.rewardToken).safeTransfer(recipient, amount);



        emit Claimed(

            user,

            bribe.rewardToken,

            bribeId,

            amount,

            feeAmount,

            currentPeriod

        );

    }



    /// @notice Update the current period for a given bribe.

    /// @param bribeId Bribe ID.

    /// @return current/updated period.

    function _updateBribePeriod(uint256 bribeId) internal returns (uint256) {

        Period storage _activePeriod = activePeriod[bribeId];



        uint256 currentPeriod = getCurrentPeriod();



        if (_activePeriod.id == 0 && currentPeriod == _activePeriod.timestamp) {

            // Checkpoint gauge to have up to date gauge weight.

            gaugeController.checkpoint_gauge(bribes[bribeId].gauge);

            // Initialize reward per token.

            // Only for the first period, and if not already initialized.

            _updateRewardPerToken(bribeId, currentPeriod);

        }



        // Increase Period

        if (block.timestamp >= _activePeriod.timestamp + _WEEK) {

            // Checkpoint gauge to have up to date gauge weight.

            gaugeController.checkpoint_gauge(bribes[bribeId].gauge);

            // Roll to next period.

            _rollOverToNextPeriod(bribeId, currentPeriod);



            return currentPeriod;

        }



        return _activePeriod.timestamp;

    }



    /// @notice Roll over to next period.

    /// @param bribeId Bribe ID.

    /// @param currentPeriod Next period timestamp.

    function _rollOverToNextPeriod(uint256 bribeId, uint256 currentPeriod)

        internal

    {

        uint8 index = getActivePeriodPerBribe(bribeId);



        Upgrade storage upgradedBribe = upgradeBribeQueue[bribeId];



        // Check if there is an upgrade in queue.

        if (upgradedBribe.totalRewardAmount != 0) {

            // Save new values.

            bribes[bribeId].numberOfPeriods = upgradedBribe.numberOfPeriods;

            bribes[bribeId].totalRewardAmount = upgradedBribe.totalRewardAmount;

            bribes[bribeId].maxRewardPerVote = upgradedBribe.maxRewardPerVote;

            bribes[bribeId].endTimestamp = upgradedBribe.endTimestamp;



            if (upgradedBribe.blacklist.length > 0) {

                bribes[bribeId].blacklist = upgradedBribe.blacklist;

            }



            emit BribeDurationIncreased(

                bribeId,

                upgradedBribe.numberOfPeriods,

                upgradedBribe.totalRewardAmount,

                upgradedBribe.maxRewardPerVote

            );



            // Reset the next values.

            delete upgradeBribeQueue[bribeId];

        }



        Bribe storage bribe = bribes[bribeId];



        uint256 periodsLeft = getPeriodsLeft(bribeId);

        uint256 rewardPerPeriod;

        rewardPerPeriod = bribe.totalRewardAmount - amountClaimed[bribeId];



        if (bribe.endTimestamp > currentPeriod + _WEEK && periodsLeft > 1) {

            rewardPerPeriod = rewardPerPeriod.mulDivDown(1, periodsLeft);

        }



        // Get adjusted slope without blacklisted addresses.

        uint256 gaugeBias = _getAdjustedBias(

            bribe.gauge,

            bribe.blacklist,

            currentPeriod

        );



        rewardPerVote[bribeId] = rewardPerPeriod.mulDivDown(

            _BASE_UNIT,

            gaugeBias

        );

        activePeriod[bribeId] = Period(index, currentPeriod, rewardPerPeriod);



        emit PeriodRolledOver(bribeId, index, currentPeriod, rewardPerPeriod);

    }



    /// @notice Update the amount of reward per token for a given bribe.

    /// @dev This function is only called once per Bribe.

    function _updateRewardPerToken(uint256 bribeId, uint256 currentPeriod)

        internal

    {

        if (rewardPerVote[bribeId] == 0) {

            uint256 gaugeBias = _getAdjustedBias(

                bribes[bribeId].gauge,

                bribes[bribeId].blacklist,

                currentPeriod

            );

            if (gaugeBias != 0) {

                rewardPerVote[bribeId] = activePeriod[bribeId]

                    .rewardPerPeriod

                    .mulDivDown(_BASE_UNIT, gaugeBias);

            }

        }

    }



    ////////////////////////////////////////////////////////////////

    /// ---  VIEWS

    ///////////////////////////////////////////////////////////////



    /// @notice Get an estimate of the reward amount for a given user.

    /// @param user Address of the user.

    /// @param bribeId ID of the bribe.

    /// @return amount of rewards.

    /// Mainly used for UI.

    function claimable(address user, uint256 bribeId)

        external

        view

        returns (uint256 amount)

    {

        if (isBlacklisted[bribeId][user]) return 0;



        Bribe memory bribe = bribes[bribeId];

        // If there is an upgrade in progress but period hasn't been rolled over yet.

        Upgrade storage upgradedBribe = upgradeBribeQueue[bribeId];



        // Update if needed the current period.

        uint256 currentPeriod = getCurrentPeriod();

        // End timestamp of the bribe.

        uint256 endTimestamp = _max(

            bribe.endTimestamp,

            upgradedBribe.endTimestamp

        );

        // Get the last_vote timestamp.

        uint256 lastVote = gaugeController.last_user_vote(user, bribe.gauge);



        GaugeController.VotedSlope memory userSlope = gaugeController

            .vote_user_slopes(user, bribe.gauge);



        if (

            userSlope.slope == 0 ||

            lastUserClaim[user][bribeId] >= currentPeriod ||

            currentPeriod >= userSlope.end ||

            currentPeriod <= lastVote ||

            currentPeriod >= endTimestamp ||

            currentPeriod < getActivePeriod(bribeId).timestamp ||

            amountClaimed[bribeId] >= bribe.totalRewardAmount

        ) return 0;



        uint256 _rewardPerVote = rewardPerVote[bribeId];

        // If period updated.

        if (

            _rewardPerVote == 0 ||

            (_rewardPerVote > 0 &&

                getActivePeriod(bribeId).timestamp != currentPeriod)

        ) {

            uint256 _rewardPerPeriod;



            if (upgradedBribe.numberOfPeriods != 0) {

                // Update max reward per vote.

                bribe.maxRewardPerVote = upgradedBribe.maxRewardPerVote;

                bribe.totalRewardAmount = upgradedBribe.totalRewardAmount;

            }



            uint256 periodsLeft = endTimestamp > currentPeriod

                ? (endTimestamp - currentPeriod) / _WEEK

                : 0;

            _rewardPerPeriod = bribe.totalRewardAmount - amountClaimed[bribeId];



            if (endTimestamp > currentPeriod + _WEEK && periodsLeft > 1) {

                _rewardPerPeriod = _rewardPerPeriod.mulDivDown(1, periodsLeft);

            }



            // Get Adjusted Slope without blacklisted addresses weight.

            uint256 gaugeBias = _getAdjustedBias(

                bribe.gauge,

                bribe.blacklist,

                currentPeriod

            );

            _rewardPerVote = _rewardPerPeriod.mulDivDown(_BASE_UNIT, gaugeBias);

        }

        // Get user voting power.

        uint256 _bias = _getAddrBias(

            userSlope.slope,

            userSlope.end,

            currentPeriod

        );

        // Estimation of the amount of rewards.

        amount = _bias.mulWadDown(_rewardPerVote);

        // Compute the reward amount based on

        // the max price to pay.

        uint256 _amountWithMaxPrice = _bias.mulWadDown(bribe.maxRewardPerVote);

        // Distribute the _min between the amount based on votes, and price.

        amount = _min(amount, _amountWithMaxPrice);



        uint256 _amountClaimed = amountClaimed[bribeId];

        // Update the amount claimed.

        if (amount + _amountClaimed > bribe.totalRewardAmount) {

            amount = bribe.totalRewardAmount - _amountClaimed;

        }

        // Substract fees.

        uint256 platformFee = FeeManager(

            factory.platformFeeManager(address(gaugeController))

        ).totalFee();

        if (platformFee != 0) {

            amount = amount.mulWadDown(_BASE_UNIT - platformFee);

        }

    }



    ////////////////////////////////////////////////////////////////

    /// --- INTERNAL VIEWS

    ///////////////////////////////////////////////////////////////



    /// @notice Get adjusted slope from Gauge Controller for a given gauge address.

    /// Remove the weight of blacklisted addresses.

    /// @param gauge Address of the gauge.

    /// @param _addressesBlacklisted Array of blacklisted addresses.

    /// @param period   Timestamp to check vote weight.

    function _getAdjustedBias(

        address gauge,

        address[] memory _addressesBlacklisted,

        uint256 period

    ) internal view returns (uint256 gaugeBias) {

        // Cache the user slope.

        GaugeController.VotedSlope memory userSlope;

        // Bias

        uint256 _bias;

        // Last Vote

        uint256 _lastVote;

        // Cache the length of the array.

        uint256 length = _addressesBlacklisted.length;

        // Cache blacklist.

        // Get the gauge slope.

        gaugeBias = gaugeController.points_weight(gauge, period).bias;



        for (uint256 i = 0; i < length; ) {

            // Get the user slope.

            userSlope = gaugeController.vote_user_slopes(

                _addressesBlacklisted[i],

                gauge

            );

            _lastVote = gaugeController.last_user_vote(

                _addressesBlacklisted[i],

                gauge

            );

            if (period > _lastVote) {

                _bias = _getAddrBias(userSlope.slope, userSlope.end, period);

                gaugeBias -= _bias;

            }

            // Increment i.

            unchecked {

                ++i;

            }

        }

    }



    ////////////////////////////////////////////////////////////////

    /// --- MANAGEMENT LOGIC

    ///////////////////////////////////////////////////////////////



    /// @notice Increase Bribe duration.

    /// @param _bribeId ID of the bribe.

    /// @param _additionnalPeriods Number of periods to add.

    /// @param _increasedAmount Total reward amount to add.

    /// @param _newMaxPricePerVote Total reward amount to add.

    function increaseBribeDuration(

        uint256 _bribeId,

        uint8 _additionnalPeriods,

        uint256 _increasedAmount,

        uint256 _newMaxPricePerVote,

        address[] calldata _addressesBlacklisted

    ) external nonReentrant notKilled onlyManager(_bribeId) {

        if (!isUpgradeable[_bribeId]) revert NOT_UPGRADEABLE();

        if (getPeriodsLeft(_bribeId) < 1) revert NO_PERIODS_LEFT();

        if (_increasedAmount == 0 || _newMaxPricePerVote == 0)

            revert WRONG_INPUT();



        Bribe storage bribe = bribes[_bribeId];

        Upgrade memory upgradedBribe = upgradeBribeQueue[_bribeId];



        ERC20(bribe.rewardToken).safeTransferFrom(

            msg.sender,

            address(this),

            _increasedAmount

        );



        if (upgradedBribe.totalRewardAmount != 0) {

            upgradedBribe = Upgrade({

                numberOfPeriods: upgradedBribe.numberOfPeriods +

                    _additionnalPeriods,

                totalRewardAmount: upgradedBribe.totalRewardAmount +

                    _increasedAmount,

                maxRewardPerVote: _newMaxPricePerVote,

                endTimestamp: upgradedBribe.endTimestamp +

                    (_additionnalPeriods * _WEEK),

                blacklist: _addressesBlacklisted

            });

        } else {

            upgradedBribe = Upgrade({

                numberOfPeriods: bribe.numberOfPeriods + _additionnalPeriods,

                totalRewardAmount: bribe.totalRewardAmount + _increasedAmount,

                maxRewardPerVote: _newMaxPricePerVote,

                endTimestamp: bribe.endTimestamp +

                    (_additionnalPeriods * _WEEK),

                blacklist: _addressesBlacklisted

            });

        }



        upgradeBribeQueue[_bribeId] = upgradedBribe;



        emit BribeDurationIncreaseQueued(

            _bribeId,

            upgradedBribe.numberOfPeriods,

            upgradedBribe.totalRewardAmount,

            _newMaxPricePerVote

        );

    }



    /// @notice Close Bribe if there is remaining.

    /// @param bribeId ID of the bribe to close.

    function closeBribe(uint256 bribeId)

        external

        nonReentrant

        onlyManager(bribeId)

    {

        // Check if the currentPeriod is the last one.

        // If not, we can increase the duration.

        Bribe storage bribe = bribes[bribeId];



        if (getCurrentPeriod() >= bribe.endTimestamp || isKilled) {

            uint256 leftOver;

            Upgrade memory upgradedBribe = upgradeBribeQueue[bribeId];

            if (upgradedBribe.totalRewardAmount != 0) {

                leftOver =

                    upgradedBribe.totalRewardAmount -

                    amountClaimed[bribeId];

                delete upgradeBribeQueue[bribeId];

            } else {

                leftOver =

                    bribes[bribeId].totalRewardAmount -

                    amountClaimed[bribeId];

            }

            // Transfer the left over to the owner.

            ERC20(bribe.rewardToken).safeTransfer(bribe.manager, leftOver);

            delete bribes[bribeId].manager;



            emit BribeClosed(bribeId, leftOver);

        }

    }



    /// @notice Update Bribe Manager.

    /// @param bribeId ID of the bribe.

    /// @param newManager Address of the new manager.

    function updateManager(uint256 bribeId, address newManager)

        external

        nonReentrant

        onlyManager(bribeId)

    {

        emit ManagerUpdated(bribeId, bribes[bribeId].manager = newManager);

    }



    function kill() external {

        if (msg.sender != address(factory)) revert NOT_ALLOWED_OPERATION();

        isKilled = true;

    }



    ////////////////////////////////////////////////////////////////

    /// --- UTILS FUNCTIONS

    ///////////////////////////////////////////////////////////////



    /// @notice Returns the number of periods left for a given bribe.

    /// @param bribeId ID of the bribe.

    function getPeriodsLeft(uint256 bribeId)

        public

        view

        returns (uint256 periodsLeft)

    {

        Bribe storage bribe = bribes[bribeId];



        uint256 currentPeriod = getCurrentPeriod();

        periodsLeft = bribe.endTimestamp > currentPeriod

            ? (bribe.endTimestamp - currentPeriod) / _WEEK

            : 0;

    }



    /// @notice Return the bribe object for a given ID.

    /// @param bribeId ID of the bribe.

    function getBribe(uint256 bribeId) external view returns (Bribe memory) {

        return bribes[bribeId];

    }



    /// @notice Return the bribe in queue for a given ID.

    /// @dev Can return an empty bribe if there is no upgrade.

    /// @param bribeId ID of the bribe.

    function getUpgradedBribeQueued(uint256 bribeId)

        external

        view

        returns (Upgrade memory)

    {

        return upgradeBribeQueue[bribeId];

    }



    /// @notice Return the blacklisted addresses of a bribe for a given ID.

    /// @param bribeId ID of the bribe.

    function getBlacklistedAddressesForBribe(uint256 bribeId)

        external

        view

        returns (address[] memory)

    {

        return bribes[bribeId].blacklist;

    }



    /// @notice Return the active period running of bribe given an ID.

    /// @param bribeId ID of the bribe.

    function getActivePeriod(uint256 bribeId)

        public

        view

        returns (Period memory)

    {

        return activePeriod[bribeId];

    }



    /// @notice Return the expected current period id.

    /// @param bribeId ID of the bribe.

    function getActivePeriodPerBribe(uint256 bribeId)

        public

        view

        returns (uint8)

    {

        Bribe storage bribe = bribes[bribeId];



        uint256 currentPeriod = getCurrentPeriod();

        uint256 periodsLeft = bribe.endTimestamp > currentPeriod

            ? (bribe.endTimestamp - currentPeriod) / _WEEK

            : 0;

        // If periodsLeft is superior, then the bribe didn't start yet.

        return

            uint8(

                periodsLeft > bribe.numberOfPeriods

                    ? 0

                    : bribe.numberOfPeriods - periodsLeft

            );

    }



    /// @notice Return the current period based on Gauge Controller rounding.

    function getCurrentPeriod() public view returns (uint256) {

        return (block.timestamp / _WEEK) * _WEEK;

    }



    /// @notice Return the minimum between two numbers.

    /// @param a First number.

    /// @param b Second number.

    function _min(uint256 a, uint256 b) private pure returns (uint256 min) {

        min = a < b ? a : b;

    }



    /// @notice Return the maximum between two numbers.

    /// @param a First number.

    /// @param b Second number.

    function _max(uint256 a, uint256 b) private pure returns (uint256 max) {

        max = a < b ? b : a;

    }



    /// @notice Return the bias of a given address based on its lock end date and the current period.

    /// @param userSlope User slope.

    /// @param endLockTime Lock end date of the address.

    /// @param currentPeriod Current period.

    function _getAddrBias(

        uint256 userSlope,

        uint256 endLockTime,

        uint256 currentPeriod

    ) internal pure returns (uint256) {

        if (currentPeriod + _WEEK >= endLockTime) return 0;

        return userSlope * (endLockTime - currentPeriod);

    }

}



/// @notice Library for converting between addresses and bytes32 values.

/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Bytes32AddressLib.sol)

library Bytes32AddressLib {

    function fromLast20Bytes(bytes32 bytesValue) internal pure returns (address) {

        return address(uint160(uint256(bytesValue)));

    }



    function fillLast12Bytes(address addressValue) internal pure returns (bytes32) {

        return bytes32(bytes20(addressValue));

    }

}



contract PlatformFactory is Owned, Factory {

    using Bytes32AddressLib for address;

    using Bytes32AddressLib for bytes32;



    /// @notice Fee recipient.

    address public feeCollector;



    /// @notice Fee Manager per gaugeController.

    mapping(address => address) public feeManagerPerGaugeController;



    /// @notice Recipient per address per gaugeController.

    mapping(address => mapping(address => address)) public recipient;



    /// @notice Emitted when a new platform is deployed.

    event PlatformDeployed(

        Platform indexed platform,

        address indexed gaugeController,

        FeeManager indexed feeManager

    );



    /// @notice Emitted when a platform is killed.

    event PlatformKilled(

        Platform indexed platform,

        address indexed gaugeController

    );



    /// @notice Emitted when a recipient is set for an address.

    event RecipientSet(address indexed sender, address indexed recipient);



    ////////////////////////////////////////////////////////////////

    /// --- CONSTRUCTOR

    ///////////////////////////////////////////////////////////////



    /// @notice Creates a Platform factory.

    /// @param _owner The owner of the factory.

    constructor(address _owner, address _feeCollector) Owned(_owner) {

        feeCollector = _feeCollector;

    }



    function deploy(address _gaugeController)

        external

        returns (Platform platform)

    {

        // Deploy the platform.

        platform = new Platform{

            salt: address(_gaugeController).fillLast12Bytes()

        }(_gaugeController, address(this));

        FeeManager feeManager = new FeeManager{

            salt: address(_gaugeController).fillLast12Bytes()

        }(feeCollector);

        feeManagerPerGaugeController[_gaugeController] = address(feeManager);



        emit PlatformDeployed(platform, _gaugeController, feeManager);

    }



    /// @notice Computes a Platform address from its gauge controller.

    function getPlatformFromGaugeController(address gaugeController)

        external

        view

        returns (Platform)

    {

        return

            Platform(

                payable(

                    keccak256(

                        abi.encodePacked(

                            bytes1(0xFF),

                            address(this),

                            address(gaugeController).fillLast12Bytes(),

                            keccak256(

                                abi.encodePacked(

                                    type(Platform).creationCode,

                                    abi.encode(gaugeController, address(this))

                                )

                            )

                        )

                    ).fromLast20Bytes() // Convert the CREATE2 hash into an address.

                )

            );

    }



    function setRecipient(address _recipient, address _gaugeController)

        external

    {

        recipient[msg.sender][_gaugeController] = _recipient;



        emit RecipientSet(msg.sender, _recipient);

    }



    function setRecipientFor(

        address _recipient,

        address _gaugeController,

        address _for

    ) external onlyOwner {

        recipient[_for][_gaugeController] = _recipient;



        emit RecipientSet(_for, _recipient);

    }



    function setFeeManager(address _gaugeController, address _feeManager)

        external

        onlyOwner

    {

        feeManagerPerGaugeController[_gaugeController] = _feeManager;

    }



    function platformFeeManager(address _gaugeController)

        external

        view

        returns (address)

    {

        return feeManagerPerGaugeController[_gaugeController];

    }



    function setFeeCollector(address _feeCollector) external onlyOwner {

        feeCollector = _feeCollector;

    }



    function kill(address platform) external onlyOwner {

        Platform(platform).kill();

        emit PlatformKilled(

            Platform(platform),

            address(Platform(platform).gaugeController())

        );

    }

}