package tezos-protocol-018-Proxford

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file storage.ml

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
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
(*****************************************************************************)
(*                                                                           *)
(* Open Source License                                                       *)
(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com>     *)
(* Copyright (c) 2022 Trili Tech, <contact@trili.tech>                       *)
(*                                                                           *)
(* Permission is hereby granted, free of charge, to any person obtaining a   *)
(* copy of this software and associated documentation files (the "Software"),*)
(* to deal in the Software without restriction, including without limitation *)
(* the rights to use, copy, modify, merge, publish, distribute, sublicense,  *)
(* and/or sell copies of the Software, and to permit persons to whom the     *)
(* Software is furnished to do so, subject to the following conditions:      *)
(*                                                                           *)
(* The above copyright notice and this permission notice shall be included   *)
(* in all copies or substantial portions of the Software.                    *)
(*                                                                           *)
(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL   *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING   *)
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER       *)
(* DEALINGS IN THE SOFTWARE.                                                 *)
(*                                                                           *)
(*****************************************************************************)

open Storage_functors
open Storage_sigs

module Encoding = struct
  module UInt16 : VALUE with type t = int = struct
    type t = int

    let encoding = Data_encoding.uint16
  end

  module Int32 : VALUE with type t = Int32.t = struct
    type t = Int32.t

    let encoding = Data_encoding.int32
  end

  module Int64 : VALUE with type t = Int64.t = struct
    type t = Int64.t

    let encoding = Data_encoding.int64
  end

  module Z : VALUE with type t = Z.t = struct
    type t = Z.t

    let encoding = Data_encoding.z
  end

  module Manager_counter : VALUE with type t = Manager_counter_repr.t = struct
    type t = Manager_counter_repr.t

    let encoding = Manager_counter_repr.encoding_for_storage
  end
end

module Int31_index : INDEX with type t = int = struct
  type t = int

  let path_length = 1

  let to_path c l = string_of_int c :: l

  let of_path = function [] | _ :: _ :: _ -> None | [c] -> int_of_string_opt c

  type 'a ipath = 'a * t

  let args =
    Storage_description.One
      {
        rpc_arg = RPC_arg.int;
        encoding = Data_encoding.int31;
        compare = Compare.Int.compare;
      }
end

module Make_index (H : Storage_description.INDEX) :
  INDEX with type t = H.t and type 'a ipath = 'a * H.t = struct
  include H

  type 'a ipath = 'a * t

  let args = Storage_description.One {rpc_arg; encoding; compare}
end

module type Simple_single_data_storage = sig
  type value

  val get : Raw_context.t -> value tzresult Lwt.t

  val update : Raw_context.t -> value -> Raw_context.t tzresult Lwt.t

  val init : Raw_context.t -> value -> Raw_context.t tzresult Lwt.t
end

module Block_round : Simple_single_data_storage with type value = Round_repr.t =
  Make_single_data_storage (Registered) (Raw_context)
    (struct
      let name = ["block_round"]
    end)
    (Round_repr)

module Tenderbake = struct
  module First_level_of_protocol =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["first_level_of_protocol"]
      end)
      (Raw_level_repr)

  module Branch = struct
    type t = Block_hash.t * Block_payload_hash.t

    let encoding =
      Data_encoding.(
        obj2
          (req "grand_parent_hash" Block_hash.encoding)
          (req "predecessor_payload" Block_payload_hash.encoding))
  end

  module Endorsement_branch =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["endorsement_branch"]
      end)
      (Branch)

  module Attestation_branch =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["attestation_branch"]
      end)
      (Branch)

  module Forbidden_delegates =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["forbidden_delegates"]
      end)
      (Signature.Public_key_hash.Set)
end

(** Contracts handling *)

type missed_attestations_info = {remaining_slots : int; missed_levels : int}

module Missed_attestations_info = struct
  type t = missed_attestations_info

  let encoding =
    let open Data_encoding in
    conv
      (fun {remaining_slots; missed_levels} -> (remaining_slots, missed_levels))
      (fun (remaining_slots, missed_levels) -> {remaining_slots; missed_levels})
      (obj2 (req "remaining_slots" int31) (req "missed_levels" int31))
end

module Slashed_deposits_history = struct
  type slashed_percentage = Int_percentage.t

  (* invariant: sorted list *)
  type t = (Cycle_repr.t * slashed_percentage) list

  let encoding =
    let open Data_encoding in
    list
      (obj2
         (req "cycle" Cycle_repr.encoding)
         (req "slashed_percentage" Int_percentage.encoding))

  let add cycle percentage history =
    let rec loop rev_prefix = function
      | (c, p) :: tl when Cycle_repr.(cycle = c) ->
          let p = Int_percentage.add_bounded p percentage in
          (* cycle found, do not change the order *)
          List.rev_append rev_prefix ((c, p) :: tl)
      | ((c, _) as hd) :: tl when Cycle_repr.(cycle > c) ->
          (* [cycle] must be inserted later *)
          loop (hd :: rev_prefix) tl
      | suffix ->
          (* [cycle] between [rev_prefix] and [suffix] *)
          List.rev_append rev_prefix ((cycle, percentage) :: suffix)
    in
    loop [] history

  let rec get cycle = function
    | (c, p) :: _ when Cycle_repr.(cycle = c) -> p
    | (c, _) :: tl when Cycle_repr.(cycle > c) -> get cycle tl
    | _ -> Int_percentage.p0
end

module Unstake_request = struct
  type request = Cycle_repr.t * Tez_repr.t

  type requests = request list

  type t = {delegate : Signature.Public_key_hash.t; requests : requests}

  let request_encoding =
    let open Data_encoding in
    obj2
      (req "cycle" Cycle_repr.encoding)
      (req "requested_amount" Tez_repr.encoding)

  let requests_encoding = Data_encoding.list request_encoding

  let encoding =
    let open Data_encoding in
    conv
      (fun {delegate; requests} -> (delegate, requests))
      (fun (delegate, requests) -> {delegate; requests})
      (obj2
         (req "delegate" Contract_repr.implicit_encoding)
         (req "requests" requests_encoding))

  let add cycle amount requests =
    let open Result_syntax in
    let rec loop rev_prefix = function
      | [] ->
          (* cycle does not exist -> add at the head *)
          Ok ((cycle, amount) :: requests)
      | (c, a) :: tl when Cycle_repr.(c = cycle) ->
          let+ a = Tez_repr.(a +? amount) in
          (* cycle found, do not change the order *)
          List.rev_append rev_prefix ((c, a) :: tl)
      | hd :: tl -> loop (hd :: rev_prefix) tl
    in
    loop [] requests
end

module Contract = struct
  module Raw_context =
    Make_subcontext (Registered) (Raw_context)
      (struct
        let name = ["contracts"]
      end)

  module Global_counter :
    Simple_single_data_storage with type value = Manager_counter_repr.t =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["global_counter"]
      end)
      (Encoding.Manager_counter)

  module Indexed_context =
    Make_indexed_subcontext
      (Make_subcontext (Registered) (Raw_context)
         (struct
           let name = ["index"]
         end))
         (Make_index (Contract_repr.Index))

  let fold = Indexed_context.fold_keys

  let list = Indexed_context.keys

  type local_context = Indexed_context.local_context

  let with_local_context = Indexed_context.with_local_context

  module Spendable_balance =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["balance"]
      end)
      (Tez_repr)

  module Missed_attestations =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["missed_attestations"]
      end)
      (Missed_attestations_info)

  module Manager =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["manager"]
      end)
      (Manager_repr)

  module Consensus_key =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["consensus_key"; "active"]
      end)
      (Signature.Public_key)

  (* TODO: remove this in P *)
  module Pending_consensus_keys_up_to_Nairobi =
    Make_indexed_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["consensus_key"; "pendings"]
         end))
         (Make_index (Cycle_repr.Index))
      (Signature.Public_key)

  module Staking_parameters =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["staking_parameters"; "active"]
      end)
      (Staking_parameters_repr)

  module Delegate =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["delegate"]
      end)
      (Signature.Public_key_hash)

  module Inactive_delegate =
    Indexed_context.Make_set
      (Registered)
      (struct
        let name = ["inactive_delegate"]
      end)

  module Delegate_last_cycle_before_deactivation =
    Indexed_context.Make_map
      (Registered)
      (struct
        (* FIXME? Change the key name to reflect the functor's name *)
        let name = ["delegate_desactivation"]
      end)
      (Cycle_repr)

  module Delegated =
    Make_data_set_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["delegated"]
         end))
         (Make_index (Contract_repr.Index))

  module Counter =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["counter"]
      end)
      (Encoding.Manager_counter)

  (* Consume gas for serialization and deserialization of expr in this
     module *)
  module Make_carbonated_map_expr (N : Storage_sigs.NAME) :
    Storage_sigs.Non_iterable_indexed_carbonated_data_storage
      with type key = Contract_repr.t
       and type value = Script_repr.lazy_expr
       and type t := Raw_context.t = struct
    module I =
      Indexed_context.Make_carbonated_map (Registered) (N)
        (struct
          type t = Script_repr.lazy_expr

          let encoding = Script_repr.lazy_expr_encoding
        end)

    type context = I.context

    type key = I.key

    type value = I.value

    let mem = I.mem

    let remove_existing = I.remove_existing

    let remove = I.remove

    let consume_deserialize_gas ctxt value =
      Raw_context.consume_gas ctxt (Script_repr.force_decode_cost value)

    let consume_serialize_gas ctxt value =
      Raw_context.consume_gas ctxt (Script_repr.force_bytes_cost value)

    let get ctxt contract =
      let open Lwt_result_syntax in
      let* ctxt, value = I.get ctxt contract in
      let*? ctxt = consume_deserialize_gas ctxt value in
      return (ctxt, value)

    let find ctxt contract =
      let open Lwt_result_syntax in
      let* ctxt, value_opt = I.find ctxt contract in
      match value_opt with
      | None -> return (ctxt, None)
      | Some value ->
          let*? ctxt = consume_deserialize_gas ctxt value in
          return (ctxt, value_opt)

    let update ctxt contract value =
      let open Lwt_result_syntax in
      let*? ctxt = consume_serialize_gas ctxt value in
      I.update ctxt contract value

    let add_or_remove ctxt contract value_opt =
      let open Lwt_result_syntax in
      match value_opt with
      | None -> I.add_or_remove ctxt contract None
      | Some value ->
          let*? ctxt = consume_serialize_gas ctxt value in
          I.add_or_remove ctxt contract value_opt

    let init ctxt contract value =
      let open Lwt_result_syntax in
      let*? ctxt = consume_serialize_gas ctxt value in
      I.init ctxt contract value

    let add ctxt contract value =
      let open Lwt_result_syntax in
      let*? ctxt = consume_serialize_gas ctxt value in
      I.add ctxt contract value

    let keys_unaccounted = I.keys_unaccounted
  end

  module Code = Make_carbonated_map_expr (struct
    let name = ["code"]
  end)

  module Storage = Make_carbonated_map_expr (struct
    let name = ["storage"]
  end)

  module Paid_storage_space =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["paid_bytes"]
      end)
      (Encoding.Z)

  module Used_storage_space =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["used_bytes"]
      end)
      (Encoding.Z)

  (* Remove me in P. *)
  module Frozen_deposits_up_to_Nairobi =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["frozen_deposits"]
      end)
      (Deposits_repr)

  module Unstaked_frozen_deposits =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["unstaked_frozen_deposits"]
      end)
      (Unstaked_frozen_deposits_repr)

  module Unstake_requests =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["unstake_requests"]
      end)
      (Unstake_request)

  module Frozen_deposits_pseudotokens =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["frozen_deposits_pseudotokens"]
      end)
      (Staking_pseudotoken_repr)

  module Staking_pseudotokens =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["staking_pseudotokens"]
      end)
      (Staking_pseudotoken_repr)

  module Frozen_deposits_limit =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["frozen_deposits_limit"]
      end)
      (Tez_repr)

  module Slashed_deposits =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["slashed_deposits"]
      end)
      (Slashed_deposits_history)

  module Bond_id_index =
    Make_indexed_subcontext
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["bond_id_index"]
         end))
         (Make_index (Bond_id_repr.Index))

  module Frozen_bonds =
    Bond_id_index.Make_carbonated_map
      (Registered)
      (struct
        let name = ["frozen_bonds"]
      end)
      (Tez_repr)

  let fold_bond_ids = Bond_id_index.fold_keys

  module Total_frozen_bonds =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["total_frozen_bonds"]
      end)
      (Tez_repr)

  module Total_supply =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["total_supply"]
      end)
      (Tez_repr)
end

module type NEXT = sig
  type id

  val init : Raw_context.t -> Raw_context.t tzresult Lwt.t

  val incr : Raw_context.t -> (Raw_context.t * id) tzresult Lwt.t
end

module Global_constants = struct
  module Map :
    Non_iterable_indexed_carbonated_data_storage
      with type t := Raw_context.t
       and type key = Script_expr_hash.t
       and type value = Script_repr.expr =
    Make_indexed_carbonated_data_storage
      (Make_subcontext (Registered) (Raw_context)
         (struct
           let name = ["global_constant"]
         end))
         (Make_index (Script_expr_hash))
      (struct
        type t = Script_repr.expr

        let encoding = Script_repr.expr_encoding
      end)
end

(** Big maps handling *)

module Big_map = struct
  type id = Lazy_storage_kind.Big_map.Id.t

  module Raw_context =
    Make_subcontext (Registered) (Raw_context)
      (struct
        let name = ["big_maps"]
      end)

  module Next : NEXT with type id := id = struct
    module Storage =
      Make_single_data_storage (Registered) (Raw_context)
        (struct
          let name = ["next"]
        end)
        (Lazy_storage_kind.Big_map.Id)

    let incr ctxt =
      let open Lwt_result_syntax in
      let* i = Storage.get ctxt in
      let* ctxt = Storage.update ctxt (Lazy_storage_kind.Big_map.Id.next i) in
      return (ctxt, i)

    let init ctxt = Storage.init ctxt Lazy_storage_kind.Big_map.Id.init
  end

  module Index = Lazy_storage_kind.Big_map.Id

  module Indexed_context =
    Make_indexed_subcontext
      (Make_subcontext (Registered) (Raw_context)
         (struct
           let name = ["index"]
         end))
         (Make_index (Index))

  let rpc_arg = Index.rpc_arg

  let fold = Indexed_context.fold_keys

  let list = Indexed_context.keys

  let remove ctxt n = Indexed_context.remove ctxt n

  let copy ctxt ~from ~to_ = Indexed_context.copy ctxt ~from ~to_

  type key = Raw_context.t * Index.t

  module Total_bytes =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["total_bytes"]
      end)
      (Encoding.Z)

  module Key_type =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["key_type"]
      end)
      (struct
        type t = Script_repr.expr

        let encoding = Script_repr.expr_encoding
      end)

  module Value_type =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["value_type"]
      end)
      (struct
        type t = Script_repr.expr

        let encoding = Script_repr.expr_encoding
      end)

  module Contents = struct
    module I =
      Storage_functors.Make_indexed_carbonated_data_storage
        (Make_subcontext (Registered) (Indexed_context.Raw_context)
           (struct
             let name = ["contents"]
           end))
           (Make_index (Script_expr_hash))
        (struct
          type t = Script_repr.expr

          let encoding = Script_repr.expr_encoding
        end)

    type context = I.context

    type key = I.key

    type value = I.value

    let mem = I.mem

    let remove_existing = I.remove_existing

    let remove = I.remove

    let update = I.update

    let add_or_remove = I.add_or_remove

    let init = I.init

    let add = I.add

    let list_key_values = I.list_key_values

    let consume_deserialize_gas ctxt value =
      Raw_context.consume_gas ctxt (Script_repr.deserialized_cost value)

    let get ctxt contract =
      let open Lwt_result_syntax in
      let* ctxt, value = I.get ctxt contract in
      let*? ctxt = consume_deserialize_gas ctxt value in
      return (ctxt, value)

    let find ctxt contract =
      let open Lwt_result_syntax in
      let* ctxt, value_opt = I.find ctxt contract in
      match value_opt with
      | None -> return (ctxt, None)
      | Some value ->
          let*? ctxt = consume_deserialize_gas ctxt value in
          return (ctxt, value_opt)

    let keys_unaccounted = I.keys_unaccounted
  end
end

module Sapling = struct
  type id = Lazy_storage_kind.Sapling_state.Id.t

  module Raw_context =
    Make_subcontext (Registered) (Raw_context)
      (struct
        let name = ["sapling"]
      end)

  module Next = struct
    module Storage =
      Make_single_data_storage (Registered) (Raw_context)
        (struct
          let name = ["next"]
        end)
        (Lazy_storage_kind.Sapling_state.Id)

    let incr ctxt =
      let open Lwt_result_syntax in
      let* i = Storage.get ctxt in
      let* ctxt =
        Storage.update ctxt (Lazy_storage_kind.Sapling_state.Id.next i)
      in
      return (ctxt, i)

    let init ctxt = Storage.init ctxt Lazy_storage_kind.Sapling_state.Id.init
  end

  module Index = Lazy_storage_kind.Sapling_state.Id

  let rpc_arg = Index.rpc_arg

  module Indexed_context =
    Make_indexed_subcontext
      (Make_subcontext (Registered) (Raw_context)
         (struct
           let name = ["index"]
         end))
         (Make_index (Index))

  let remove ctxt n = Indexed_context.remove ctxt n

  let copy ctxt ~from ~to_ = Indexed_context.copy ctxt ~from ~to_

  module Total_bytes =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["total_bytes"]
      end)
      (Encoding.Z)

  module Commitments_size =
    Make_single_data_storage (Registered) (Indexed_context.Raw_context)
      (struct
        let name = ["commitments_size"]
      end)
      (Encoding.Int64)

  module Memo_size =
    Make_single_data_storage (Registered) (Indexed_context.Raw_context)
      (struct
        let name = ["memo_size"]
      end)
      (Sapling_repr.Memo_size)

  module Commitments :
    Non_iterable_indexed_carbonated_data_storage
      with type t := Raw_context.t * id
       and type key = int64
       and type value = Sapling.Hash.t =
    Make_indexed_carbonated_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["commitments"]
         end))
         (Make_index (struct
           type t = int64

           let rpc_arg =
             let construct = Int64.to_string in
             let destruct hash =
               Int64.of_string_opt hash
               |> Result.of_option ~error:"Cannot parse node position"
             in
             RPC_arg.make
               ~descr:"The position of a node in a sapling commitment tree"
               ~name:"sapling_node_position"
               ~construct
               ~destruct
               ()

           let encoding =
             Data_encoding.def
               "sapling_node_position"
               ~title:"Sapling node position"
               ~description:
                 "The position of a node in a sapling commitment tree"
               Data_encoding.int64

           let compare = Compare.Int64.compare

           let path_length = 1

           let to_path c l = Int64.to_string c :: l

           let of_path = function [c] -> Int64.of_string_opt c | _ -> None
         end))
      (Sapling.Hash)

  let commitments_init ctx id =
    let open Lwt_syntax in
    let+ ctx, (_id : id) =
      Indexed_context.Raw_context.remove (ctx, id) ["commitments"]
    in
    ctx

  module Ciphertexts :
    Non_iterable_indexed_carbonated_data_storage
      with type t := Raw_context.t * id
       and type key = int64
       and type value = Sapling.Ciphertext.t =
    Make_indexed_carbonated_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["ciphertexts"]
         end))
         (Make_index (struct
           type t = int64

           let rpc_arg =
             let construct = Int64.to_string in
             let destruct hash =
               Int64.of_string_opt hash
               |> Result.of_option ~error:"Cannot parse ciphertext position"
             in
             RPC_arg.make
               ~descr:"The position of a sapling ciphertext"
               ~name:"sapling_ciphertext_position"
               ~construct
               ~destruct
               ()

           let encoding =
             Data_encoding.def
               "sapling_ciphertext_position"
               ~title:"Sapling ciphertext position"
               ~description:"The position of a sapling ciphertext"
               Data_encoding.int64

           let compare = Compare.Int64.compare

           let path_length = 1

           let to_path c l = Int64.to_string c :: l

           let of_path = function [c] -> Int64.of_string_opt c | _ -> None
         end))
      (Sapling.Ciphertext)

  let ciphertexts_init ctx id =
    let open Lwt_syntax in
    let+ ctx, (_id : id) =
      Indexed_context.Raw_context.remove (ctx, id) ["ciphertexts"]
    in
    ctx

  module Nullifiers_size =
    Make_single_data_storage (Registered) (Indexed_context.Raw_context)
      (struct
        let name = ["nullifiers_size"]
      end)
      (Encoding.Int64)

  (* For sequential access when building a diff *)
  module Nullifiers_ordered :
    Non_iterable_indexed_data_storage
      with type t := Raw_context.t * id
       and type key = int64
       and type value = Sapling.Nullifier.t =
    Make_indexed_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["nullifiers_ordered"]
         end))
         (Make_index (struct
           type t = int64

           let rpc_arg =
             let construct = Int64.to_string in
             let destruct hash =
               Int64.of_string_opt hash
               |> Result.of_option ~error:"Cannot parse nullifier position"
             in
             RPC_arg.make
               ~descr:"A sapling nullifier position"
               ~name:"sapling_nullifier_position"
               ~construct
               ~destruct
               ()

           let encoding =
             Data_encoding.def
               "sapling_nullifier_position"
               ~title:"Sapling nullifier position"
               ~description:"Sapling nullifier position"
               Data_encoding.int64

           let compare = Compare.Int64.compare

           let path_length = 1

           let to_path c l = Int64.to_string c :: l

           let of_path = function [c] -> Int64.of_string_opt c | _ -> None
         end))
      (Sapling.Nullifier)

  (* Check membership in O(1) for verify_update *)
  module Nullifiers_hashed =
    Make_carbonated_data_set_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["nullifiers_hashed"]
         end))
         (Make_index (struct
           type t = Sapling.Nullifier.t

           let encoding = Sapling.Nullifier.encoding

           let of_string hexstring =
             Option.bind
               (Hex.to_bytes (`Hex hexstring))
               (Data_encoding.Binary.of_bytes_opt encoding)
             |> Result.of_option ~error:"Cannot parse sapling nullifier"

           let to_string nf =
             let b = Data_encoding.Binary.to_bytes_exn encoding nf in
             let (`Hex hexstring) = Hex.of_bytes b in
             hexstring

           let rpc_arg =
             RPC_arg.make
               ~descr:"A sapling nullifier"
               ~name:"sapling_nullifier"
               ~construct:to_string
               ~destruct:of_string
               ()

           let compare = Sapling.Nullifier.compare

           let path_length = 1

           let to_path c l = to_string c :: l

           let of_path = function
             | [c] -> Result.to_option (of_string c)
             | _ -> None
         end))

  let nullifiers_init ctx id =
    let open Lwt_syntax in
    let* ctx = Nullifiers_size.add (ctx, id) Int64.zero in
    let* ctx, id =
      Indexed_context.Raw_context.remove (ctx, id) ["nullifiers_ordered"]
    in
    let+ ctx, (_id : id) =
      Indexed_context.Raw_context.remove (ctx, id) ["nullifiers_hashed"]
    in
    ctx

  module Roots :
    Non_iterable_indexed_data_storage
      with type t := Raw_context.t * id
       and type key = int32
       and type value = Sapling.Hash.t =
    Make_indexed_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["roots"]
         end))
         (Make_index (struct
           type t = int32

           let rpc_arg =
             let construct = Int32.to_string in
             let destruct hash =
               Int32.of_string_opt hash
               |> Result.of_option ~error:"Cannot parse nullifier position"
             in
             RPC_arg.make
               ~descr:"A sapling root"
               ~name:"sapling_root"
               ~construct
               ~destruct
               ()

           let encoding =
             Data_encoding.def
               "sapling_root"
               ~title:"Sapling root"
               ~description:"Sapling root"
               Data_encoding.int32

           let compare = Compare.Int32.compare

           let path_length = 1

           let to_path c l = Int32.to_string c :: l

           let of_path = function [c] -> Int32.of_string_opt c | _ -> None
         end))
      (Sapling.Hash)

  module Roots_pos =
    Make_single_data_storage (Registered) (Indexed_context.Raw_context)
      (struct
        let name = ["roots_pos"]
      end)
      (Encoding.Int32)

  module Roots_level =
    Make_single_data_storage (Registered) (Indexed_context.Raw_context)
      (struct
        let name = ["roots_level"]
      end)
      (Raw_level_repr)
end

module Public_key_hash = struct
  open Signature
  include Signature.Public_key_hash
  module Path_Ed25519 = Path_encoding.Make_hex (Ed25519.Public_key_hash)
  module Path_Secp256k1 = Path_encoding.Make_hex (Secp256k1.Public_key_hash)
  module Path_P256 = Path_encoding.Make_hex (P256.Public_key_hash)
  module Path_Bls = Path_encoding.Make_hex (Bls.Public_key_hash)

  let to_path (key : public_key_hash) l =
    match key with
    | Ed25519 h -> "ed25519" :: Path_Ed25519.to_path h l
    | Secp256k1 h -> "secp256k1" :: Path_Secp256k1.to_path h l
    | P256 h -> "p256" :: Path_P256.to_path h l
    | Bls h -> "bls" :: Path_Bls.to_path h l

  let of_path : _ -> public_key_hash option = function
    | "ed25519" :: rest -> (
        match Path_Ed25519.of_path rest with
        | Some pkh -> Some (Ed25519 pkh)
        | None -> None)
    | "secp256k1" :: rest -> (
        match Path_Secp256k1.of_path rest with
        | Some pkh -> Some (Secp256k1 pkh)
        | None -> None)
    | "p256" :: rest -> (
        match Path_P256.of_path rest with
        | Some pkh -> Some (P256 pkh)
        | None -> None)
    | "bls" :: rest -> (
        match Path_Bls.of_path rest with
        | Some pkh -> Some (Bls pkh)
        | None -> None)
    | _ -> None

  let path_length =
    let l1 = Path_Ed25519.path_length
    and l2 = Path_Secp256k1.path_length
    and l3 = Path_P256.path_length
    and l4 = Path_Bls.path_length in
    assert (Compare.Int.(l1 = l2 && l2 = l3 && l3 = l4)) ;
    l1 + 1
end

module Public_key_hash_index = Make_index (Public_key_hash)

module Protocol_hash_with_path_encoding = struct
  include Protocol_hash
  include Path_encoding.Make_hex (Protocol_hash)
end

module Delegates =
  Make_data_set_storage
    (Make_subcontext (Registered) (Raw_context)
       (struct
         let name = ["delegates"]
       end))
       (Public_key_hash_index)

module Consensus_keys =
  Make_data_set_storage
    (Make_subcontext (Registered) (Raw_context)
       (struct
         let name = ["consensus_keys"]
       end))
       (Public_key_hash_index)

module Current_cycle_denunciations =
  Make_indexed_data_storage
    (Make_subcontext (Registered) (Raw_context)
       (struct
         let name = ["denunciations"]
       end))
       (Public_key_hash_index)
    (Denunciations_repr)

(** Per cycle storage *)

type slashed_level = {for_double_attesting : bool; for_double_baking : bool}

let default_slashed_level =
  {for_double_attesting = false; for_double_baking = false}

module Slashed_level = struct
  type t = slashed_level

  let encoding =
    let open Data_encoding in
    conv
      (fun {for_double_attesting; for_double_baking} ->
        (for_double_attesting, for_double_baking))
      (fun (for_double_attesting, for_double_baking) ->
        {for_double_attesting; for_double_baking})
      (obj2 (req "for_double_attesting" bool) (req "for_double_baking" bool))
end

module Cycle = struct
  module Indexed_context =
    Make_indexed_subcontext
      (Make_subcontext (Registered) (Raw_context)
         (struct
           let name = ["cycle"]
         end))
         (Make_index (Cycle_repr.Index))

  module Slashed_deposits =
    Make_indexed_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["slashed_deposits"]
         end))
         (Pair (Make_index (Raw_level_repr.Index)) (Public_key_hash_index))
      (Slashed_level)

  (* Remove me in P. *)
  module Selected_stake_distribution_up_to_Nairobi =
    Indexed_context.Make_map
      (Ghost)
      (struct
        let name = ["selected_stake_distribution"]
      end)
      (struct
        type t = (Signature.Public_key_hash.t * Tez_repr.t) list

        let encoding =
          Data_encoding.(
            Variable.list
              (obj2
                 (req "baker" Signature.Public_key_hash.encoding)
                 (req "active_stake" Tez_repr.encoding)))
      end)

  module Selected_stake_distribution =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["selected_stake_distribution"]
      end)
      (struct
        type t = (Signature.Public_key_hash.t * Stake_repr.t) list

        let encoding =
          Data_encoding.(
            Variable.list
              (obj2
                 (req "baker" Signature.Public_key_hash.encoding)
                 (req "active_stake" Stake_repr.encoding)))
      end)

  (* Remove me in P. *)
  module Total_active_stake_up_to_Nairobi =
    Indexed_context.Make_map
      (Ghost)
      (struct
        let name = ["total_active_stake"]
      end)
      (Tez_repr)

  module Total_active_stake =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["total_active_stake"]
      end)
      (Stake_repr)

  module Delegate_sampler_state =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["delegate_sampler_state"]
      end)
      (struct
        type t = Raw_context.consensus_pk Sampler.t

        let encoding = Sampler.encoding Raw_context.consensus_pk_encoding
      end)

  module Issuance_bonus =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["issuance_bonus"]
      end)
      (Issuance_bonus_repr)

  module Issuance_coeff =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["issuance_coeff"]
      end)
      (struct
        type t = Q.t

        let encoding =
          Data_encoding.(
            conv_with_guard
              (fun Q.{num; den} -> (num, den))
              (fun (num, den) ->
                if Compare.Z.(num > Z.zero && den > Z.zero) then
                  Ok (Q.make num den)
                else
                  Error
                    "Invalid Reward Coefficient: only positive values allowed")
              (obj2 (req "numerator" n) (req "denominator" n)))
      end)

  type unrevealed_nonce = {
    nonce_hash : Nonce_hash.t;
    delegate : Signature.Public_key_hash.t;
  }

  type nonce_status =
    | Unrevealed of unrevealed_nonce
    | Revealed of Seed_repr.nonce

  let nonce_status_encoding =
    let open Data_encoding in
    union
      [
        case
          (Tag 0)
          ~title:"Unrevealed"
          (tup2 Nonce_hash.encoding Signature.Public_key_hash.encoding)
          (function
            | Unrevealed {nonce_hash; delegate} -> Some (nonce_hash, delegate)
            | _ -> None)
          (fun (nonce_hash, delegate) -> Unrevealed {nonce_hash; delegate});
        case
          (Tag 1)
          ~title:"Revealed"
          Seed_repr.nonce_encoding
          (function Revealed nonce -> Some nonce | _ -> None)
          (fun nonce -> Revealed nonce);
      ]

  module Nonce =
    Make_indexed_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["nonces"]
         end))
         (Make_index (Raw_level_repr.Index))
      (struct
        type t = nonce_status

        let encoding = nonce_status_encoding
      end)

  module Seed =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["random_seed"]
      end)
      (struct
        type t = Seed_repr.seed

        let encoding = Seed_repr.seed_encoding
      end)

  module Pending_consensus_keys =
    Make_indexed_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["pending_consensus_keys"]
         end))
         (Make_index (Contract_repr.Index))
      (Signature.Public_key)

  module Pending_staking_parameters =
    Make_indexed_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["pending_staking_parameters"]
         end))
         (Make_index (Contract_repr.Index))
      (Staking_parameters_repr)
end

module Slashed_deposits = Cycle.Slashed_deposits
module Pending_consensus_keys = Cycle.Pending_consensus_keys
module Pending_staking_parameters = Cycle.Pending_staking_parameters

module Stake = struct
  module Staking_balance_up_to_Nairobi =
    Make_indexed_data_snapshotable_storage
      (Make_subcontext (Ghost) (Raw_context)
         (struct
           let name = ["staking_balance"]
         end))
         (Int31_index)
      (Public_key_hash_index)
      (Tez_repr)

  module Staking_balance =
    Make_indexed_data_snapshotable_storage
      (Make_subcontext (Registered) (Raw_context)
         (struct
           let name = ["staking_balance"]
         end))
         (Int31_index)
      (Public_key_hash_index)
      (Full_staking_balance_repr)

  module Active_delegates_with_minimal_stake =
    Make_indexed_data_snapshotable_storage
      (Make_subcontext (Registered) (Raw_context)
         (struct
           (* This name is for historical reasons, when the stake was
              expressed in rolls (that is, pre-Ithaca). *)
           let name = ["active_delegate_with_one_roll"]
         end))
         (Int31_index)
      (Public_key_hash_index)
      (struct
        type t = unit

        let encoding = Data_encoding.unit
      end)

  module Selected_distribution_for_cycle_up_to_Nairobi =
    Cycle.Selected_stake_distribution_up_to_Nairobi
  module Selected_distribution_for_cycle = Cycle.Selected_stake_distribution
  module Total_active_stake_up_to_Nairobi =
    Cycle.Total_active_stake_up_to_Nairobi
  module Total_active_stake = Cycle.Total_active_stake

  (* This is an index that is set to 0 by calls to
     {!val:Stake_storage.selected_new_distribution_at_cycle_end} and
     incremented (by 1) by calls to {!val:Stake_storage.snapshot}.

     {!val:Stake_storage.snapshot} is called in relation with constant
     [blocks_per_stake_snapshot] in
     {!val:Level_storage.may_snapshot_stake_distribution}.

     That is, the increment is done every [blocks_per_stake_snaphot]
     blocks and reset at the end of cycles. So, it goes up to
     [blocks_per_cycle / blocks_per_stake_snaphot], which is currently
     16 (= 8192/512 -- the concrete values can be found in
     {!val:Default_parameters.constants_mainnet}), then comes back to
     0, so that a UInt16 is big enough.

     The ratio [blocks_per_cycle / blocks_per_stake_snapshot] above is
     checked in {!val:Constants_repr.check_constants} to fit in a
     UInt16. *)
  module Last_snapshot =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["last_snapshot"]
      end)
      (Encoding.UInt16)
end

module Delegate_sampler_state = Cycle.Delegate_sampler_state
module Issuance_bonus = Cycle.Issuance_bonus
module Issuance_coeff = Cycle.Issuance_coeff

(** Votes *)

module Vote = struct
  module Raw_context =
    Make_subcontext (Registered) (Raw_context)
      (struct
        let name = ["votes"]
      end)

  module Pred_period_kind =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["pred_period_kind"]
      end)
      (struct
        type t = Voting_period_repr.kind

        let encoding = Voting_period_repr.kind_encoding
      end)

  module Current_period =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["current_period"]
      end)
      (struct
        type t = Voting_period_repr.t

        let encoding = Voting_period_repr.encoding
      end)

  module Participation_ema =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["participation_ema"]
      end)
      (Encoding.Int32)

  module Current_proposal =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["current_proposal"]
      end)
      (Protocol_hash)

  module Voting_power_in_listings =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["voting_power_in_listings"]
      end)
      (Encoding.Int64)

  module Listings =
    Make_indexed_data_storage
      (Make_subcontext (Registered) (Raw_context)
         (struct
           let name = ["listings"]
         end))
         (Public_key_hash_index)
      (Encoding.Int64)

  module Proposals =
    Make_data_set_storage
      (Make_subcontext (Registered) (Raw_context)
         (struct
           let name = ["proposals"]
         end))
         (Pair
            (Make_index
               (Protocol_hash_with_path_encoding))
               (Public_key_hash_index))

  module Proposals_count =
    Make_indexed_data_storage
      (Make_subcontext (Registered) (Raw_context)
         (struct
           let name = ["proposals_count"]
         end))
         (Public_key_hash_index)
      (Encoding.UInt16)

  module Ballots =
    Make_indexed_data_storage
      (Make_subcontext (Registered) (Raw_context)
         (struct
           let name = ["ballots"]
         end))
         (Public_key_hash_index)
      (struct
        type t = Vote_repr.ballot

        let encoding = Vote_repr.ballot_encoding
      end)
end

module type FOR_CYCLE = sig
  val init :
    Raw_context.t ->
    Cycle_repr.t ->
    Seed_repr.seed ->
    Raw_context.t tzresult Lwt.t

  val mem : Raw_context.t -> Cycle_repr.t -> bool Lwt.t

  val get : Raw_context.t -> Cycle_repr.t -> Seed_repr.seed tzresult Lwt.t

  val update :
    Raw_context.t ->
    Cycle_repr.t ->
    Seed_repr.seed ->
    Seed_repr.seed_status ->
    Raw_context.t tzresult Lwt.t

  val remove_existing :
    Raw_context.t -> Cycle_repr.t -> Raw_context.t tzresult Lwt.t
end

(** Seed *)

module Seed_status =
  Make_single_data_storage (Registered) (Raw_context)
    (struct
      let name = ["seed_status"]
    end)
    (struct
      type t = Seed_repr.seed_status

      let encoding = Seed_repr.seed_status_encoding
    end)

module Seed = struct
  type unrevealed_nonce = Cycle.unrevealed_nonce = {
    nonce_hash : Nonce_hash.t;
    delegate : Signature.Public_key_hash.t;
  }

  type nonce_status = Cycle.nonce_status =
    | Unrevealed of unrevealed_nonce
    | Revealed of Seed_repr.nonce

  module Nonce :
    Non_iterable_indexed_data_storage
      with type key := Level_repr.t
       and type value := nonce_status
       and type t := Raw_context.t = struct
    open Level_repr

    type context = Raw_context.t

    let mem ctxt (l : Level_repr.t) = Cycle.Nonce.mem (ctxt, l.cycle) l.level

    let get ctxt (l : Level_repr.t) = Cycle.Nonce.get (ctxt, l.cycle) l.level

    let find ctxt (l : Level_repr.t) = Cycle.Nonce.find (ctxt, l.cycle) l.level

    let update ctxt (l : Level_repr.t) v =
      Cycle.Nonce.update (ctxt, l.cycle) l.level v

    let init ctxt (l : Level_repr.t) v =
      Cycle.Nonce.init (ctxt, l.cycle) l.level v

    let add ctxt (l : Level_repr.t) v =
      Cycle.Nonce.add (ctxt, l.cycle) l.level v

    let add_or_remove ctxt (l : Level_repr.t) v =
      Cycle.Nonce.add_or_remove (ctxt, l.cycle) l.level v

    let remove_existing ctxt (l : Level_repr.t) =
      Cycle.Nonce.remove_existing (ctxt, l.cycle) l.level

    let remove ctxt (l : Level_repr.t) =
      Cycle.Nonce.remove (ctxt, l.cycle) l.level
  end

  module VDF_setup =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["vdf_challenge"]
      end)
      (struct
        type t = Seed_repr.vdf_setup

        let encoding = Seed_repr.vdf_setup_encoding
      end)

  module For_cycle : FOR_CYCLE = struct
    let init ctxt cycle seed =
      let open Lwt_result_syntax in
      let* ctxt = Cycle.Seed.init ctxt cycle seed in
      let*! ctxt = Seed_status.add ctxt Seed_repr.RANDAO_seed in
      return ctxt

    let mem = Cycle.Seed.mem

    let get = Cycle.Seed.get

    let update ctxt cycle seed status =
      let open Lwt_result_syntax in
      let* ctxt = Cycle.Seed.update ctxt cycle seed in
      Seed_status.update ctxt status

    let remove_existing = Cycle.Seed.remove_existing
  end

  let get_status = Seed_status.get
end

(** Commitments *)

module Commitments =
  Make_indexed_data_storage
    (Make_subcontext (Registered) (Raw_context)
       (struct
         let name = ["commitments"]
       end))
       (Make_index (Blinded_public_key_hash.Index))
    (Tez_repr)

(** Ramp up rewards... *)

module Ramp_up = struct
  type reward = {
    baking_reward_fixed_portion : Tez_repr.t;
    baking_reward_bonus_per_slot : Tez_repr.t;
    attesting_reward_per_slot : Tez_repr.t;
  }

  module Rewards =
    Make_indexed_data_storage
      (Make_subcontext (Registered) (Raw_context)
         (struct
           let name = ["ramp_up"; "rewards"]
         end))
         (Make_index (Cycle_repr.Index))
      (struct
        type t = reward

        let encoding =
          Data_encoding.(
            conv
              (fun {
                     baking_reward_fixed_portion;
                     baking_reward_bonus_per_slot;
                     attesting_reward_per_slot;
                   } ->
                ( baking_reward_fixed_portion,
                  baking_reward_bonus_per_slot,
                  attesting_reward_per_slot ))
              (fun ( baking_reward_fixed_portion,
                     baking_reward_bonus_per_slot,
                     attesting_reward_per_slot ) ->
                {
                  baking_reward_fixed_portion;
                  baking_reward_bonus_per_slot;
                  attesting_reward_per_slot;
                })
              (obj3
                 (req "baking_reward_fixed_portion" Tez_repr.encoding)
                 (req "baking_reward_bonus_per_slot" Tez_repr.encoding)
                 (req "attesting_reward_per_slot" Tez_repr.encoding)))
      end)
end

module Pending_migration = struct
  module Balance_updates =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["pending_migration_balance_updates"]
      end)
      (struct
        type t = Receipt_repr.balance_updates

        let encoding =
          Receipt_repr.balance_updates_encoding_with_legacy_attestation_name
      end)

  module Operation_results =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["pending_migration_operation_results"]
      end)
      (struct
        type t = Migration_repr.origination_result list

        let encoding = Migration_repr.origination_result_list_encoding
      end)

  let remove ctxt =
    let open Lwt_result_syntax in
    let balance_updates ctxt =
      let* balance_updates_opt = Balance_updates.find ctxt in
      match balance_updates_opt with
      | Some balance_updates ->
          let*! ctxt = Balance_updates.remove ctxt in
          (* When applying balance updates in a migration, we must attach receipts.
             The balance updates returned from here will be applied in the first
             block of the new protocol. *)
          return (ctxt, balance_updates)
      | None -> return (ctxt, [])
    in
    let operation_results ctxt =
      let* operation_results_opt = Operation_results.find ctxt in
      match operation_results_opt with
      | Some operation_results ->
          let*! ctxt = Operation_results.remove ctxt in
          return (ctxt, operation_results)
      | None -> return (ctxt, [])
    in
    let* ctxt, balance_updates = balance_updates ctxt in
    let* ctxt, operation_results = operation_results ctxt in
    return (ctxt, balance_updates, operation_results)
end

module Liquidity_baking = struct
  module Toggle_ema =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        (* The old "escape" name is kept here to avoid migrating this. *)
        let name = ["liquidity_baking_escape_ema"]
      end)
      (Encoding.Int32)

  module Cpmm_address =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["liquidity_baking_cpmm_address"]
      end)
      (struct
        type t = Contract_hash.t

        (* Keeping contract-compatible encoding to avoid migrating this. *)
        let encoding = Contract_repr.originated_encoding
      end)
end

module Adaptive_issuance = struct
  module Launch_ema =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["adaptive_issuance_ema"]
      end)
      (Encoding.Int32)

  module Activation =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["adaptive_issuance_launch_cycle"]
      end)
      (struct
        type t = Cycle_repr.t option

        let encoding = Data_encoding.option Cycle_repr.encoding
      end)
end

module Ticket_balance = struct
  module Name = struct
    let name = ["ticket_balance"]
  end

  module Raw_context = Make_subcontext (Registered) (Raw_context) (Name)

  module Paid_storage_space =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["paid_bytes"]
      end)
      (Encoding.Z)

  module Used_storage_space =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["used_bytes"]
      end)
      (Encoding.Z)

  module Table_context =
    Make_subcontext (Registered) (Raw_context)
      (struct
        let name = ["table"]
      end)

  module Index = Make_index (Ticket_hash_repr.Index)
  module Table =
    Make_indexed_carbonated_data_storage (Table_context) (Index) (Encoding.Z)
end

module Sc_rollup = struct
  module Raw_context =
    Make_subcontext (Registered) (Raw_context)
      (struct
        let name = ["smart_rollup"]
      end)

  module Indexed_context =
    Make_indexed_subcontext
      (Make_subcontext (Registered) (Raw_context)
         (struct
           let name = ["index"]
         end))
         (Make_index (Sc_rollup_repr.Index))

  module Make_versioned
      (Versioned_value : Sc_rollup_data_version_sig.S) (Data_storage : sig
        type context

        type key

        type value = Versioned_value.versioned

        val get : context -> key -> (Raw_context.t * value) tzresult Lwt.t

        val find :
          context -> key -> (Raw_context.t * value option) tzresult Lwt.t

        val update :
          context -> key -> value -> (Raw_context.t * int) tzresult Lwt.t

        val init :
          context -> key -> value -> (Raw_context.t * int) tzresult Lwt.t

        val add :
          context -> key -> value -> (Raw_context.t * int * bool) tzresult Lwt.t

        val add_or_remove :
          context ->
          key ->
          value option ->
          (Raw_context.t * int * bool) tzresult Lwt.t
      end) =
  struct
    include Data_storage

    type value = Versioned_value.t

    let get ctxt key =
      let open Lwt_result_syntax in
      let* ctxt, versioned = get ctxt key in
      return (ctxt, Versioned_value.of_versioned versioned)

    let find ctxt key =
      let open Lwt_result_syntax in
      let* ctxt, versioned = find ctxt key in
      return (ctxt, Option.map Versioned_value.of_versioned versioned)

    let update ctxt key value =
      update ctxt key (Versioned_value.to_versioned value)

    let init ctxt key value = init ctxt key (Versioned_value.to_versioned value)

    let add ctxt key value = add ctxt key (Versioned_value.to_versioned value)

    let add_or_remove ctxt key value =
      add_or_remove ctxt key (Option.map Versioned_value.to_versioned value)
  end

  module PVM_kind =
    Indexed_context.Make_carbonated_map
      (Registered)
      (struct
        let name = ["kind"]
      end)
      (struct
        type t = Sc_rollups.Kind.t

        let encoding = Sc_rollups.Kind.encoding
      end)

  module Parameters_type =
    Indexed_context.Make_carbonated_map
      (Registered)
      (struct
        let name = ["parameters_type"]
      end)
      (struct
        type t = Script_repr.lazy_expr

        let encoding = Script_repr.lazy_expr_encoding
      end)

  module Genesis_info =
    Indexed_context.Make_carbonated_map
      (Registered)
      (struct
        let name = ["genesis_info"]
      end)
      (struct
        type t = Sc_rollup_commitment_repr.genesis_info

        let encoding = Sc_rollup_commitment_repr.genesis_info_encoding
      end)

  module Inbox = struct
    include
      Make_single_data_storage (Registered) (Raw_context)
        (struct
          let name = ["inbox"]
        end)
        (struct
          type t = Sc_rollup_inbox_repr.versioned

          let encoding = Sc_rollup_inbox_repr.versioned_encoding
        end)

    type value = Sc_rollup_inbox_repr.t

    let of_versioned = Sc_rollup_inbox_repr.of_versioned

    let to_versioned = Sc_rollup_inbox_repr.to_versioned

    let get ctxt =
      let open Lwt_result_syntax in
      let* versioned = get ctxt in
      return (of_versioned versioned)

    let find ctxt =
      let open Lwt_result_syntax in
      let* versioned = find ctxt in
      return (Option.map of_versioned versioned)

    let init ctxt value = init ctxt (to_versioned value)

    let update ctxt value = update ctxt (to_versioned value)

    let add ctxt value =
      let versioned = to_versioned value in
      add ctxt versioned

    let add_or_remove ctxt value =
      add_or_remove ctxt (Option.map to_versioned value)
  end

  module Last_cemented_commitment =
    Indexed_context.Make_carbonated_map
      (Registered)
      (struct
        let name = ["last_cemented_commitment"]
      end)
      (struct
        type t = Sc_rollup_commitment_repr.Hash.t

        let encoding = Sc_rollup_commitment_repr.Hash.encoding
      end)

  module Staker_index_counter =
    Make_single_data_storage (Registered) (Indexed_context.Raw_context)
      (struct
        let name = ["staker_index_counter"]
      end)
      (Sc_rollup_staker_index_repr)

  module Staker_index =
    Make_indexed_carbonated_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["staker_index"]
         end))
         (Public_key_hash_index)
      (Sc_rollup_staker_index_repr)

  module Stakers =
    Make_indexed_carbonated_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["stakers"]
         end))
         (Make_index (Sc_rollup_staker_index_repr.Index))
      (Raw_level_repr)

  module Commitments_versioned =
    Make_indexed_carbonated_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["commitments"]
         end))
         (Make_index (Sc_rollup_commitment_repr.Hash))
      (struct
        type t = Sc_rollup_commitment_repr.versioned

        let encoding = Sc_rollup_commitment_repr.versioned_encoding
      end)

  module Commitments = struct
    include Commitments_versioned
    include Make_versioned (Sc_rollup_commitment_repr) (Commitments_versioned)
  end

  module Commitment_indexed_context =
    Make_indexed_subcontext
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["commitment_index"]
         end))
         (Make_index (Sc_rollup_commitment_repr.Hash))

  module Commitment_stakers =
    Make_indexed_carbonated_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["commitments_stakers"]
         end))
         (Make_index (Sc_rollup_commitment_repr.Hash))
      (struct
        type t = Sc_rollup_staker_index_repr.t list

        let encoding = Data_encoding.list Sc_rollup_staker_index_repr.encoding
      end)

  module Commitments_per_inbox_level =
    Make_indexed_carbonated_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["commitments_per_inbox_level"]
         end))
         (Make_index (Raw_level_repr.Index))
      (struct
        type t = Sc_rollup_commitment_repr.Hash.t list

        let encoding =
          Data_encoding.list Sc_rollup_commitment_repr.Hash.encoding
      end)

  module Commitment_first_publication_level =
    Make_indexed_carbonated_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["commitment_first_publication_level"]
         end))
         (Make_index (Raw_level_repr.Index))
      (Raw_level_repr)

  module Commitment_added =
    Make_indexed_carbonated_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["commitment_added"]
         end))
         (Make_index (Sc_rollup_commitment_repr.Hash))
      (Raw_level_repr)

  module Game_info_versioned =
    Make_indexed_carbonated_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["refutation_game_info"]
         end))
         (Make_index (Sc_rollup_game_repr.Index))
      (struct
        type t = Sc_rollup_game_repr.versioned

        let encoding = Sc_rollup_game_repr.versioned_encoding
      end)

  module Game_info = struct
    include Game_info_versioned
    include Make_versioned (Sc_rollup_game_repr) (Game_info_versioned)
  end

  module Games_per_staker =
    Make_indexed_subcontext
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["game"]
         end))
         (Public_key_hash_index)

  module Game =
    Make_indexed_carbonated_data_storage
      (Make_subcontext (Registered) (Games_per_staker.Raw_context)
         (struct
           let name = ["opponents"]
         end))
         (Public_key_hash_index)
      (struct
        type t = Sc_rollup_game_repr.Index.t

        let encoding = Sc_rollup_game_repr.Index.encoding
      end)

  module Game_timeout =
    Make_indexed_carbonated_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["game_timeout"]
         end))
         (Make_index (Sc_rollup_game_repr.Index))
      (struct
        type t = Sc_rollup_game_repr.timeout

        let encoding = Sc_rollup_game_repr.timeout_encoding
      end)

  (** An index used for a SCORU's outbox levels. An outbox level is mapped to
     the index through: [outbox_level % sc_rollup_max_active_outbox_levels].
     That way we keep a limited number of entries. The current value of an
     entry contains the most recently added level that maps to the index. *)
  module Level_index = struct
    type t = int32

    let rpc_arg =
      let construct = Int32.to_string in
      let destruct hash =
        Int32.of_string_opt hash
        |> Result.of_option ~error:"Cannot parse level index"
      in
      RPC_arg.make
        ~descr:"The level index for applied outbox message records"
        ~name:"level_index"
        ~construct
        ~destruct
        ()

    let encoding =
      Data_encoding.def
        "level_index"
        ~title:"Level index"
        ~description:"The level index for applied outbox message records"
        Data_encoding.int32

    let compare = Compare.Int32.compare

    let path_length = 1

    let to_path c l = Int32.to_string c :: l

    let of_path = function [c] -> Int32.of_string_opt c | _ -> None
  end

  module Level_index_context =
    Make_indexed_subcontext
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["level_index"]
         end))
         (Make_index (Level_index))

  module Bitset_and_level = struct
    type t = Raw_level_repr.t * Bitset.t

    let encoding =
      Data_encoding.(
        obj2
          (req "level" Raw_level_repr.encoding)
          (req "bitset" Bitset.encoding))
  end

  module Applied_outbox_messages =
    Level_index_context.Make_carbonated_map
      (Registered)
      (struct
        let name = ["applied_outbox_messages"]
      end)
      (Bitset_and_level)

  module Whitelist =
    Make_carbonated_data_set_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["whitelist"]
         end))
         (Public_key_hash_index)

  module Whitelist_paid_storage_space =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["whitelist_paid_bytes"]
      end)
      (Encoding.Z)

  module Whitelist_used_storage_space =
    Indexed_context.Make_map
      (Registered)
      (struct
        let name = ["whitelist_use_bytes"]
      end)
      (Encoding.Z)

  module Last_whitelist_update =
    Indexed_context.Make_carbonated_map
      (Registered)
      (struct
        let name = ["last_whitelist_update"]
      end)
      (struct
        type t = Sc_rollup_whitelist_repr.last_whitelist_update

        let encoding = Sc_rollup_whitelist_repr.last_whitelist_update_encoding
      end)
end

module Dal = struct
  module Raw_context =
    Make_subcontext (Registered) (Raw_context)
      (struct
        let name = ["dal"]
      end)

  (* DAL/FIXME https://gitlab.com/tezos/tezos/-/issues/3113

     This is only for prototyping. Probably something smarter would be
     to index each header directly. *)
  (* DAL/FIXME: https://gitlab.com/tezos/tezos/-/issues/3684

     This storage should be carbonated. *)
  module Slot = struct
    module Slot_context =
      Make_subcontext (Registered) (Raw_context)
        (struct
          let name = ["slot"]
        end)

    module Level_context =
      Make_indexed_subcontext
        (Make_subcontext (Registered) (Raw_context)
           (struct
             let name = ["level"]
           end))
           (Make_index (Raw_level_repr.Index))

    module Headers =
      Level_context.Make_map
        (Registered)
        (struct
          let name = ["slot_headers"]
        end)
        (struct
          type t = Dal_slot_repr.Header.t list

          let encoding = Data_encoding.(list Dal_slot_repr.Header.encoding)
        end)

    module History =
      Make_single_data_storage (Registered) (Raw_context)
        (struct
          let name = ["slot_headers_history"]
        end)
        (struct
          type t = Dal_slot_repr.History.t

          let encoding = Dal_slot_repr.History.encoding
        end)
  end
end

module Zk_rollup = struct
  module Indexed_context =
    Make_indexed_subcontext
      (Make_subcontext (Registered) (Raw_context)
         (struct
           let name = ["zk_rollup"]
         end))
         (Make_index (Zk_rollup_repr.Index))

  module Account :
    Non_iterable_indexed_carbonated_data_storage
      with type t := Raw_context.t
       and type key = Zk_rollup_repr.t
       and type value = Zk_rollup_account_repr.t =
    Indexed_context.Make_carbonated_map
      (Registered)
      (struct
        let name = ["account"]
      end)
      (Zk_rollup_account_repr)

  module Pending_list =
    Indexed_context.Make_carbonated_map
      (Registered)
      (struct
        let name = ["pending_list"]
      end)
      (struct
        type t = Zk_rollup_repr.pending_list

        let encoding = Zk_rollup_repr.pending_list_encoding
      end)

  module Pending_operation :
    Non_iterable_indexed_carbonated_data_storage
      with type t := Raw_context.t * Zk_rollup_repr.t
       and type key = int64
       and type value = Zk_rollup_operation_repr.t * Ticket_hash_repr.t option =
    Make_indexed_carbonated_data_storage
      (Make_subcontext (Registered) (Indexed_context.Raw_context)
         (struct
           let name = ["pending_operations"]
         end))
         (Make_index (struct
           type t = int64

           let rpc_arg =
             let construct = Int64.to_string in
             let destruct hash =
               Int64.of_string_opt hash
               |> Result.of_option
                    ~error:"Cannot parse pending operation position"
             in
             RPC_arg.make
               ~descr:
                 "The position of an operation in a pending operations list"
               ~name:"zkru_pending_op_position"
               ~construct
               ~destruct
               ()

           let encoding =
             Data_encoding.def
               "zkru_pending_op_position"
               ~title:"Zkru pending operation position"
               ~description:
                 "The position of an operation in a pending operations list"
               Data_encoding.Compact.(make ~tag_size:`Uint8 int64)

           let compare = Compare.Int64.compare

           let path_length = 1

           let to_path c l = Int64.to_string c :: l

           let of_path = function [c] -> Int64.of_string_opt c | _ -> None
         end))
      (struct
        type t = Zk_rollup_operation_repr.t * Ticket_hash_repr.t option

        let encoding =
          Data_encoding.(
            tup2
              Zk_rollup_operation_repr.encoding
              (option Ticket_hash_repr.encoding))
      end)
end

module Legacy = struct
  module Grand_parent_branch =
    Make_single_data_storage (Registered) (Raw_context)
      (struct
        let name = ["grand_parent_branch"]
      end)
      (Tenderbake.Branch)
end
OCaml

Innovation. Community. Security.