Snippets

chromawallet Testnet Chromunity

Created by Riccardo Sibani last modified
   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
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dict>
    <entry key="blockstrategy">
        <dict>
            <entry key="name">
                <string>net.postchain.base.BaseBlockBuildingStrategy</string>
            </entry>
        </dict>
    </entry>
    <entry key="configurationfactory">
        <string>net.postchain.gtx.GTXBlockchainConfigurationFactory</string>
    </entry>
    <entry key="gtx">
        <dict>
            <entry key="modules">
                <array>
                    <string>net.postchain.rell.module.RellPostchainModuleFactory</string>
                    <string>net.postchain.gtx.StandardOpsGTXModule</string>
                </array>
            </entry>
            <entry key="rell">
                <dict>
                    <entry key="moduleArgs">
                        <dict>
                            <entry key="lib.ft3.core">
                                <dict>
                                    <entry key="my_blockchain_description">
                                        <string>Decentralized reddit</string>
                                    </entry>
                                    <entry key="my_blockchain_name">
                                        <string>Chromunity</string>
                                    </entry>
                                    <entry key="my_blockchain_website">
                                        <string>testnet.chromunity.com</string>
                                    </entry>
                                    <entry key="rate_limit_active">
                                        <int>1</int>
                                    </entry>
                                    <entry key="rate_limit_max_points">
                                        <int>5</int>
                                    </entry>
                                    <entry key="rate_limit_points_at_account_creation">
                                        <int>3</int>
                                    </entry>
                                    <entry key="rate_limit_recovery_time">
                                        <int>600000</int>
                                    </entry>
                                </dict>
                            </entry>
                        </dict>
                    </entry>
                    <entry key="modules">
                        <array>
                            <string></string>
                        </array>
                    </entry>
                    <entry key="sources_v0.10">
                        <dict>
                            <entry key="channel/index.rell">
                                <string>import user;
import topic;

entity channel {
    key name, topic.topic;
    index timestamp;
    display_name: name;
}

entity channel_following {
    key user.user, name;
}
</string>
                            </entry>
                            <entry key="channel/operations.rell">
                                <string>import user;

operation follow_channel(username: text, descriptor_id: byte_array, name) {
    val user = user.get_verified_user(username, descriptor_id);
    create channel_following(user, name.lower_case());
}

operation unfollow_channel(username: text, descriptor_id: byte_array, name) {
    val user = user.get_verified_user(username, descriptor_id);
    delete channel_following@{ user, name.lower_case()};
}</string>
                            </entry>
                            <entry key="channel/queries.rell">
                                <string>import user;
import topic;

query get_topics_by_channel_prior_to_timestamp(name, timestamp, page_size: integer) {
    val topics = channel@*{
        .name == name,
        .topic.last_modified &lt; timestamp
    } (
        id = .topic.id,
        author = .topic.author.display_name,
        title = .topic.title,
        message = .topic.message,
        timestamp = .topic.timestamp,
        @sort_desc last_modified = .topic.last_modified
    ) limit page_size;
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query get_topics_by_channel_after_timestamp(name, timestamp) {
    val topics = channel@*{
        .name == name,
        .topic.last_modified &gt; timestamp
    } (
        id = .topic.id,
        author = .topic.author.display_name,
        title = .topic.title,
        message = .topic.message,
        timestamp = .topic.timestamp,
        @sort_desc last_modified = .topic.last_modified
    );
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query count_topics_by_channel(name) {
    return channel@*{ .name == name } ( .name ).size();
}

query count_channel_followers(name) {
    return channel_following@*{ .name == name } ( .user.name ).size();
}

query get_topics_by_followed_channels_prior_to_timestamp(username: text, timestamp, page_size: integer) {
    val user = user.user@{ .name == username};
    val topics = (channel, channel_following)@*{
        channel_following.user == user,
        channel_following.name == channel.name,
        channel.topic.last_modified &lt; timestamp
    }
    (
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        timestamp = channel.topic.timestamp,
        @sort_desc last_modified = channel.topic.last_modified
    ) limit page_size;
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query get_topics_by_followed_channels_after_timestamp(username: text, timestamp, page_size: integer) {
    val user = user.user@{ .name == username};
    val topics = (channel, channel_following)@*{
        channel_following.user == user,
        channel_following.name == channel.name,
        channel.topic.last_modified &gt; timestamp
    }
    (
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        timestamp = channel.topic.timestamp,
        @sort_desc last_modified = channel.topic.last_modified
    ) limit page_size;
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query get_followed_channels(username: text) {
    val user = user.user@{ .name == username};
    return channel_following@*{ user } ( .name );
}

query get_all_channels() {
    return channel@*{} ( .display_name );
}

query get_channels_since(timestamp) {
    return channel@*{ .timestamp &gt; timestamp }( .display_name );
}

query get_topic_channels_belongings(topic_id: text) {
    return channel@*{ topic.topic@{ .id == topic_id }} ( .display_name );
}
</string>
                            </entry>
                            <entry key="chat/index.rell">
                                <string>import user;

entity chat {
	key id: text;
	mutable title: text;
	timestamp;
}

entity chat_user {
	key user.user;
	rsa_pubkey: text;
}

entity chat_membership {
	key chat, member: chat_user;
	encrypted_chat_key: text;
	mutable last_opened: timestamp = 0;
}

entity chat_message {
	index chat;
	index sender: chat_user;
	index timestamp;
	encrypted_msg: text;
}

struct chat_record {
	id: text;
	title: text;
	last_message: message_record?;
	encrypted_chat_key: text;
	timestamp;
	last_opened: timestamp;
}

struct message_record {
	sender: name;
	timestamp;
	encrypted_msg: text;
}
</string>
                            </entry>
                            <entry key="chat/operations.rell">
                                <string>import user;
import util;

operation create_chat(chat_id: text, descriptor_id: byte_array, username: text, title: text, encrypted_chat_key: text) {
	val founder = user.get_verified_user(username, descriptor_id);

	val chat = create chat(id = chat_id, title = title, timestamp = op_context.last_block_time);
	create chat_membership(chat, chat_user@{ .user == founder }, encrypted_chat_key);
}

operation create_chat_user(descriptor_id: byte_array, username: text, rsa_pubkey: text) {
	val user = user.get_verified_user(username, descriptor_id);
	create chat_user(user, rsa_pubkey);
}

operation delete_chat_user(descriptor_id: byte_array, username: text) {
	val user = user.get_verified_user(username, descriptor_id);
	val chat_user = chat_user@?{ user };

	if (chat_user != null) {
		delete chat_membership@*{ .member == chat_user };
		delete chat_message@*{ .sender == chat_user };
		delete chat_user;
	}
}

operation add_user_to_chat(descriptor_id: byte_array, username: text, chat_id: text, target_user: text, encrypted_chat_key: text) {
	val user_already_in_chat = user.get_verified_user(username, descriptor_id);
	val chat = chat@{ .id == chat_id };

	if (chat_membership@?{ chat, .member.user.name == target_user.lower_case() } == null) {
		create chat_membership(chat, chat_user@{ .user.name == target_user.lower_case() }, encrypted_chat_key);
	}
}

operation leave_chat(descriptor_id: byte_array, username: text, chat_id: text) {
	val user = user.get_verified_user(username, descriptor_id);
	val chat = chat@{ .id == chat_id };

	delete chat_membership@{ chat, chat_user@{ user }};

	if (chat_membership@*{ chat } ( .member ).size() == 0) {
		delete chat_message@*{ chat };
		delete chat;
	}
}

operation modify_chat_title(descriptor_id: byte_array, username: text, chat_id: text, title: text) {
	val user = user.get_verified_user(username, descriptor_id);
	val chat = chat@{ .id == chat_id };
	chat_membership@{ chat, chat_user@{ user }};
	update chat(title = title);
}

operation send_chat_message(chat_id: text, descriptor_id: byte_array, username: name, encrypted_msg: text) {
	val user = user.get_verified_user(username, descriptor_id);

	val chat = chat@{ .id == chat_id };
	val chat_user = chat_user@{ user };
	val chat_member = chat_membership@?{ chat, chat_user };
	require(chat_member != null, util.app_error(util.error_type.USER_UNAUTHORIZED, "Only a chat member can send a message"));

	create chat_message(chat, chat_user, op_context.last_block_time, encrypted_msg);
}

operation update_last_opened_timestamp(chat_id: text, descriptor_id: byte_array, username: name) {
	val user = user.get_verified_user(username, descriptor_id);
	update chat_membership@{
		.chat.id == chat_id,
		.member.user == user
	} ( last_opened = op_context.last_block_time );
}
</string>
                            </entry>
                            <entry key="chat/queries.rell">
                                <string>import follow;

query get_chat_user_pubkey(username: name): text? {
	return chat_user@?{ .user.name == username.lower_case() } ( .rsa_pubkey );
}

query get_user_chats(username: name): list&lt;chat_record&gt; {

	val member_chats = chat_membership@*{ .member.user.name == username.lower_case() };
	val chat_records = list&lt;chat_record&gt;();

	for (member_chat in member_chats) {
		val latest_message = chat_message@?{ .chat == member_chat.chat } ( .sender, @sort_desc .timestamp, .encrypted_msg, @sort_desc .chat.timestamp ) limit 1;

		if (latest_message != null) {
			val message = message_record(sender = latest_message.sender.user.display_name, timestamp = latest_message.timestamp, encrypted_msg = latest_message.encrypted_msg);
			chat_records.add(chat_record(
				id = member_chat.chat.id,
				title = member_chat.chat.title,
				last_message = message,
				encrypted_chat_key = member_chat.encrypted_chat_key,
				timestamp = member_chat.chat.timestamp,
				last_opened = member_chat.last_opened
			));
		} else {
			chat_records.add(chat_record(
				id = member_chat.chat.id,
				title = member_chat.chat.title,
				last_message = null,
				encrypted_chat_key = member_chat.encrypted_chat_key,
				timestamp = member_chat.chat.timestamp,
				last_opened = member_chat.last_opened
			));
		}

	}

	return chat_records;
}

query get_chat_messages(id: text, prior_to: timestamp, page_size: integer) {
	return chat_message@*{ .chat.id == id, .timestamp &lt; prior_to } (
		sender = chat_message.sender.user.display_name,
		@sort_desc timestamp = chat_message.timestamp,
		encrypted_msg = chat_message.encrypted_msg
	) limit page_size;
}

query get_chat_messages_after(id: text, after_timestamp: timestamp, page_size: integer) {
	return chat_message@*{ .chat.id == id, .timestamp &gt; after_timestamp } (
		sender = chat_message.sender.user.display_name,
		@sort timestamp = chat_message.timestamp,
		encrypted_msg = chat_message.encrypted_msg
	) limit page_size;
}

query get_chat_participants(id: text) {
	return chat_membership@*{ .chat.id == id } ( .member.user.display_name );
}

query get_followed_chat_users(username: name) {
	return (chat_user, follow.follow)@*{
		follow.follower.name == username.lower_case(),
		follow.follows == chat_user.user
	} ( chat_user.user.display_name );
}

query get_chat_users() {
	return chat_user@*{} ( chat_user.user.display_name );
}

query count_unread_chats(username: name) {
	val my_user = username.lower_case();
	return set&lt;chat&gt;((chat_membership, chat_message)@*{
		chat_membership.member.user.name == my_user,
		chat_message.timestamp &gt; chat_membership.last_opened,
		chat_membership.chat == chat_message.chat,
		chat_message.sender.user.name != my_user
	} ( chat_membership.chat )).size();
}</string>
                            </entry>
                            <entry key="election/index.rell">
                                <string>import user;
import topic;

entity representative_election {
    key id: integer;
    index timestamp;
    mutable completed: boolean;
    index completed;
}

entity election_block_details {
	key started_height: integer;
	mutable finished_height: integer = -1;
	index representative_election;
}

entity representative_election_candidate {
  key representative_election, user.user;
}

entity representative_election_vote {
    key user.user, representative_election_candidate;
}

entity temp_votes_counter {
	key representative_election_candidate;
	mutable votes: integer;
}

function is_eligible_to_vote(user.user): boolean {
	val prev_election_id = get_latest_completed_election_id();
	
	val current_election_id = get_current_election_id();
	
	if (current_election_id == null) {
		return false;
	} else if (prev_election_id == null) {
		return true;
	}
	
	val current_election_start = (election_block_details, block)@{ 
		election_block_details.representative_election.id == current_election_id,
		election_block_details.started_height == block.block_height
	} ( 
		block.timestamp
	);
	
	if (user.registered &gt; current_election_start) {
		log("Not elgible for voting: User registered after election start");
		return false; 
	}
	
	val previous_election_completed = (representative_election, election_block_details, block)@?{
		representative_election == election_block_details.representative_election,
		representative_election.completed == true,
		block.block_height == election_block_details.finished_height
	} ( 
		block.timestamp,
		@omit @sort_desc representative_election.timestamp
	) limit 1;
	
	if (previous_election_completed != null) {
		log("A previous election was held, so verifying correct number of posts");
		val number_of_topics = topic.topic@*{ 
			.author == user,
			.last_modified &gt; previous_election_completed,
			.last_modified &lt; current_election_start
		}( .id ).size();
		
		val number_of_replies = topic.topic_reply@*{
			.author == user,
			.timestamp &gt; previous_election_completed,
			.timestamp &lt; current_election_start
		}( .id ).size();
		
		return number_of_topics + number_of_replies &gt;= 5;
	}
	
	return true;
}

function governing_period_in_blocks(): integer {
	return 75000;
}

function election_duration_in_blocks(): integer {
	return 25000;
}

function get_current_election_id(): integer? {
	return representative_election@?{ .completed == false } ( @omit @sort_desc .timestamp, .id ) limit 1;
}

function get_latest_completed_election_id(): integer? {
	return representative_election@?{ .completed == true } ( .id, @omit @sort_desc .timestamp ) limit 1;
}</string>
                            </entry>
                            <entry key="election/operations.rell">
                                <string>import user;
import util;
import representative;

operation process_election() {
	var something_done = false;
	
	val current_block = op_context.block_height;
	val election_period_in_blocks = election_duration_in_blocks();
	val governing_period_in_blocks = governing_period_in_blocks();
	
	val election_block_details = election_block_details@?{} ( @sort_desc .started_height, .finished_height ) limit 1;
	
	if (election_block_details == null) {
		log("No election held yet, triggering new one");
		create_election_at_height(current_block);
		something_done = true;
	} else if (election_block_details.finished_height &gt;= 0 and election_block_details.finished_height + governing_period_in_blocks &lt; current_block) {
		log("Triggering a new election");
		create_election_at_height(current_block);
		something_done = true;
	} else if (election_block_details.finished_height == -1 
		and election_block_details.started_height + election_period_in_blocks &lt; current_block
	) {
		log("Wrapping up election");
		complete_election();
		something_done = true;
	}
	
	require(something_done, util.app_error(util.error_type.EXPECTED_ERROR, "Nothing done while processing of elections"));
}

function create_election_at_height(height: integer) {
	val election = create representative_election(
			id = height,
			timestamp = op_context.last_block_time, 
			false
		);
		create election_block_details(started_height = height, election);
}

function complete_election() {
	val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
	
    val current_election = representative_election@{ .id == current_election_id };
    update current_election ( completed = true );
    update election_block_details@{ current_election } ( finished_height = op_context.block_height );
    
    val nr_of_participants = temp_votes_counter@*{} ( 
    	.representative_election_candidate.user.name
    ).size();
    
    val new_representatives = temp_votes_counter@*{ 
    	.representative_election_candidate.representative_election == current_election
    } (
    	@sort_desc @omit .votes,
    	.representative_election_candidate.user
    ) limit integer((nr_of_participants * 0.1).ceil());

    for (user in new_representatives) {
        create representative.representative(user, current_election);
    }
}

operation vote_for_candidate(voter: name, descriptor_id: byte_array, candidate: name) {
	require(voter != candidate, util.app_error(util.error_type.ILLEGAL_ACTION, "You can't vote for yourself"));
    val user = user.get_verified_user(voter, descriptor_id);

	require(is_eligible_to_vote(user), util.app_error(util.error_type.ILLEGAL_ACTION, "Not eligible for voting in the election"));

    val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
    
    clean_up_votes(user, current_election_id);
    
    val vote = create representative_election_vote(
        user,
        representative_election_candidate@{ 
        	user.user@{ .name == candidate }, 
        	.representative_election.id == current_election_id
        }
    );
    
    update temp_votes_counter@ {
    	vote.representative_election_candidate
    } ( votes += 1 );
}

operation sign_up_for_election(name, descriptor_id: byte_array) {
    val user = user.get_verified_user(name, descriptor_id);
	val election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));

    val candidate = create representative_election_candidate(
    	representative_election@{ .id == election_id }, 
    	user
    );
    
    create temp_votes_counter(candidate, 0);
}

function clean_up_votes(user.user, id: integer) {
	val old_candidate_votes = representative_election_vote@*{ 
    	user,
    	.representative_election_candidate.representative_election.id == id
    };
	for (old_candidate_vote in old_candidate_votes) {
	    
	    update temp_votes_counter@ {
	    	old_candidate_vote.representative_election_candidate
	    } ( votes -= 1 );
	    
	   	delete old_candidate_vote;
	}
}</string>
                            </entry>
                            <entry key="election/queries.rell">
                                <string>import user;
import util;

query eligible_for_voting(name): boolean {
	val user = user.user@{ .name == name.lower_case() };
	return is_eligible_to_vote(user);
}

query get_election_candidates() {
	val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
	
    return temp_votes_counter@*{
        .representative_election_candidate.representative_election.id == current_election_id
    } ( 
    	@omit @sort_desc .votes,
    	.representative_election_candidate.user.display_name
    );
}

query get_next_election() {
    return representative_election@?{ .completed == false } ( .id, @sort_desc .timestamp ) limit 1;
}

query get_uncompleted_election() {
    return get_current_election_id();
}

query get_user_vote_in_election(name) {
	val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
	
    return representative_election_vote@?{
        .user == user.user@{ .name == name },
        .representative_election_candidate.representative_election.id == current_election_id
    } ( .representative_election_candidate.user.name ) limit 1;
}

query get_current_representative_period(timestamp) {
    return representative_election @? { .timestamp &lt;= timestamp, .completed == true } ( .id, @sort_desc .timestamp ) limit 1;
}

query blocks_until_next_election() {
	val recent_election_finished = election_block_details@?{} ( 
		@omit @sort_desc .started_height, 
		.finished_height
	) limit 1;
	
	if (recent_election_finished == null) {
		return 0;
	}
	
	require(recent_election_finished != -1, "There is an ongoing election");
	
	val next_election_block = recent_election_finished + governing_period_in_blocks();
	
	var current_block = block@?{} ( @sort_desc .block_height ) limit 1;
	
	if (current_block == null) {
		current_block = 0;
	}
	
	return next_election_block - current_block;
}

query blocks_until_election_wraps_up() {
	val recent_election = election_block_details@{} ( 
		@sort_desc .started_height, 
		.finished_height
	) limit 1;
	
	require(recent_election.finished_height == -1, "There is no ongoing election");
	
	val election_finishing_block = recent_election.started_height + election_duration_in_blocks();
	
	var current_block = block@?{} ( @sort_desc .block_height ) limit 1;
	
	if (current_block == null) {
		current_block = 0;
	}
	
	return election_finishing_block - current_block;
}
</string>
                            </entry>
                            <entry key="follow/index.rell">
                                <string>import user;

entity follow {
    key follower: user.user, follows: user.user;
}
</string>
                            </entry>
                            <entry key="follow/operations.rell">
                                <string>import user;
import util;

operation create_following(follower: text, descriptor_id: byte_array, follows: text) {
    require(follower != follows, util.app_error(util.error_type.ILLEGAL_ACTION, "Follow another user"));
    val user = user.get_verified_user(follower, descriptor_id);
    create follow(follower = user, follows = user.user@{ .name == follows.lower_case() });
}

operation remove_following(follower: text, descriptor_id: byte_array, follows: text) {
    require(follower != follows, util.app_error(util.error_type.ILLEGAL_ACTION, "You can't unfollow yourself"));
    val user = user.get_verified_user(follower, descriptor_id);
    delete follow@{ .follower == user, .follows == user.user@{ .name == follows.lower_case() } };
}
</string>
                            </entry>
                            <entry key="follow/queries.rell">
                                <string>import user;

query get_user_followers(name) {
    return follow@*{ .follows == user.user @ { .name == name } }( .follower.name );
}

query get_user_follows(name) {
    return follow@*{ .follower == user.user@{ .name == name } } ( .follows.name );
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/auth_basic.rell">
                                <string>// Auth type:

// "S" - single-sig
// "M" - multi-sig

struct single_sig_args {
       flags: set&lt;text&gt;;
       pubkey;
}

struct multi_sig_args {
       flags: set&lt;text&gt;;
       signatures_required: integer;
       pubkeys: list&lt;pubkey&gt;;
}

function check_single_sig_auth(args: byte_array, participants: list&lt;byte_array&gt;, required_flags: list&lt;text&gt;): boolean {
    require(participants.size() == 1);
    val ss_args = single_sig_args.from_bytes(args);
    return
          ss_args.flags.contains_all(required_flags)
            and
          is_signer(participants[0]);
}

function check_multi_sig_auth(args: byte_array, participants: list&lt;byte_array&gt;, required_flags: list&lt;text&gt;): boolean {
   val multi_sign_args = multi_sig_args.from_bytes(args);
   if (not (multi_sign_args.flags.contains_all(required_flags))) return false;
   var num_sign = multi_sign_args.signatures_required;
   for(s in participants) {
      if(is_signer(s)) {
          num_sign -= 1;
          if(num_sign &lt; 1) {return true;}
      }
   }
   return false;
}

function check_auth_args (a_t: text, args: byte_array, participants: list&lt;byte_array&gt;, required_flags: list&lt;text&gt;): boolean {
    return when (a_t) {
        "S" -&gt; check_single_sig_auth(args, participants, required_flags);
        "M" -&gt; check_multi_sig_auth(args, participants, required_flags);
        else -&gt; false;
    };
}



function require_auth (account, descriptor_id: byte_array, required_flags: list&lt;text&gt;) {
   val account_auth_descriptor = account_auth_descriptor @ {
     account,
     .descriptor_id == descriptor_id
   };
	
	require(is_valid(account_auth_descriptor));
	
   	require(
		check_auth_args(
       		account_auth_descriptor.auth_type,
       		account_auth_descriptor.args,
       		auth_descriptor_participant @* { account_auth_descriptor } ( .id ),
       		required_flags
		)
   );
   
   update_auth_descriptor_rule_variables(account_auth_descriptor);
   delete_expired_auth_descriptors(account);
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/auth_descriptor_rule.rell">
                                <string>
enum rule_variable {
	block_height,
	block_time,
	op_count
}

enum rule_operator {
	lt,
	le,
	eq,
	ge,
	gt
}

struct rule_expression {
	variable: text;
	operator: text;
	value: gtv;
}

entity auth_descriptor_rule_variable {
	key account_auth_descriptor, name;
	mutable value: byte_array;
}

function is_valid(auth_descriptor: account_auth_descriptor): boolean {
	// check if rules is null (encoded null is equal to 0xa0020500)
	if (auth_descriptor.rules == x'a0020500') {
		return true;
	}
	
	return is_rule_valid(
		gtv.from_bytes(auth_descriptor.rules), 
		load_variables(auth_descriptor)
	);
}

function is_rule_valid(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(rule);
	val operator = text.from_gtv(parameters[1]);
	
	if (operator == "and") {
		return handle_composed_rule(rule, variables);
	} else {
		return handle_single_rule(rule, variables);
	}
}

function handle_single_rule(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	return evaluate_int_variable_rule(
		rule_expression.from_gtv(rule), 
		variables
	);	
}

 
function handle_composed_rule(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(rule);
	val operator = text.from_gtv(parameters[1]);
	if (operator == "and") {
		return is_rule_valid(parameters[0], variables) and is_rule_valid(parameters[2], variables);
	} else {
		return false;
	}
}



function is_active(account_auth_descriptor): boolean {
	if (account_auth_descriptor.rules == x'a0020500') {
		return true;
	}
	
	return is_rule_active(gtv.from_bytes(account_auth_descriptor.rules), map&lt;text, gtv&gt;());
}


function is_rule_active(r: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(r);
	val operator = text.from_gtv(parameters[1]);
	when (operator) {
		"and" -&gt; {
			return is_rule_active(parameters[0], variables) and is_rule_active(parameters[2], variables);
		}
		else -&gt; {
			return is_simple_rule_active(r, variables);
		}
	}
}

function is_simple_rule_active(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(rule);
	val variable_name = text.from_gtv(parameters[0]);
	when (rule_variable.value(variable_name)) {
		rule_variable.block_height -&gt; {
			return is_block_height_rule_active(rule);
		}
		rule_variable.block_time -&gt; {
			return is_block_time_rule_active(rule);
		}		
		rule_variable.op_count -&gt; {
			return is_op_count_rule_active(rule);
		}
	}
}

/*
 *  Variables
 */

function evaluate_int_variable_rule(rule: rule_expression, variables: map&lt;text, gtv&gt;): boolean {
	val variable = rule_variable.value(rule.variable);
	val operator = rule_operator.value(rule.operator);
	val current_value = variable_value(variable, variables);
	val defined_value = integer.from_gtv(rule.value);

	when (operator) {
		rule_operator.lt -&gt; {
			return current_value &lt; defined_value;
		}
		rule_operator.le -&gt; {
			return current_value &lt;= defined_value;
		}
		rule_operator.eq -&gt; {
			return current_value == defined_value;
		}
		rule_operator.ge -&gt; {
			return current_value &gt;= defined_value;
		}
		rule_operator.gt -&gt; {
			return current_value &gt; defined_value;
		}
	}
}


/*
 * Called from _add_auth_descriptor function
 */
function setup_auth_descriptor_variables(account_auth_descriptor) {
	
	if (account_auth_descriptor.rules == x'a0020500') {
		return;
	} 
	
	val variables = get_variable_names_set(gtv.from_bytes(account_auth_descriptor.rules));
	
	for (variable in variables) {
		when (variable) {
			rule_variable.op_count.name -&gt; {
				create auth_descriptor_rule_variable(
					account_auth_descriptor,
					name = variable,
					value = op_count_variable_initial_value().to_bytes()
				);
			}
		}
	}
}
 
function update_variables(account_auth_descriptor, variables: map&lt;text, gtv&gt;) {
	for ((name, value) in variables) {
		val variable = auth_descriptor_rule_variable @ { account_auth_descriptor, name };
		val int_value = integer.from_gtv(value);
		
		when (name) {
			rule_variable.op_count.name -&gt; {
				variable.value = (int_value + 1).to_gtv().to_bytes();
			}
		}
	}
}
 
function variable_value(variable: rule_variable, variables: map&lt;text, gtv&gt;): integer {
	when (variable) {
		rule_variable.block_height -&gt; {
			return op_context.block_height;
		}
		rule_variable.block_time -&gt; {
			return op_context.last_block_time;
		}
		rule_variable.op_count -&gt; {
			return integer.from_gtv(variables[rule_variable.op_count.name]);
		}
	}
}

/*
 * Analyze the rules before assigning them to an authenticator descriptor
 */
 function analyze_auth_descriptor_rules(rules: gtv, hop: integer) {
 	require(hop&lt;3, "too many rules");
 	val rules_bytes = rules.to_bytes(); 
 	if (rules_bytes == x'a0020500') {
		return;
	}
	
 	val params = list&lt;gtv&gt;.from_gtv(rules);
 	require(params.size() &lt;=3);
 	
 	val operator = text.from_gtv(params[1]);
 	if(operator == "and") {
 		analyze_auth_descriptor_rules(params[0], hop+1); 
 		analyze_auth_descriptor_rules(params[2], hop+1);
 	} 	
 	
	return;
 }

/*
 * Returns set of variable names used in a rule
 */
function get_variable_names_set(rules: gtv): set&lt;text&gt; {
	val parameters = list&lt;gtv&gt;.from_gtv(rules);
	val operator = text.from_gtv(parameters[1]);
	var vars = set&lt;text&gt;();
	if (operator == "and") {
		vars.add_all(get_variable_names_set(parameters[0]));
		vars.add_all(get_variable_names_set(parameters[2]));
	} else {
		vars.add(text.from_gtv(parameters[0]));
	}
	return vars;
} 

function load_variables(account_auth_descriptor): map&lt;text, gtv&gt; {
	val variables = auth_descriptor_rule_variable @* { account_auth_descriptor };
	
	val variables_map = map&lt;text, gtv&gt;();
	for (variable in variables) {
		variables_map[variable.name] = gtv.from_bytes(variable.value);
	}
	
	return variables_map;
}

function update_auth_descriptor_rule_variables(account_auth_descriptor) {
	val variables = load_variables(account_auth_descriptor);
	update_variables(account_auth_descriptor, variables);
}

/*
 * auth descriptor cleanup
 */

function delete_expired_auth_descriptors(account) {
	val auth_descriptors = account_auth_descriptor @* { account };
	
	for (auth_descriptor in auth_descriptors) {
		if (not (is_active(auth_descriptor) and is_valid(auth_descriptor))) {
			_delete_auth_descriptor(auth_descriptor);
		}
	}
}

/****************************************************************************************
 *                                     block_time                                       *
 ****************************************************************************************/

function is_block_time_rule_active(r: gtv): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(r);
	val operator = rule_operator.value(text.from_gtv(parameters[1]));
	val value = integer.from_gtv(parameters[2]);
	when (operator) {
		rule_operator.gt -&gt; {
			return op_context.last_block_time &gt; value;
		}
		rule_operator.ge,
		rule_operator.eq -&gt; {
			return op_context.last_block_time &gt;= value;
		}
		else -&gt; {
			return true;
		}
	}
}


/****************************************************************************************
 *                                  block_height                                        *
 ****************************************************************************************/

function is_block_height_rule_active(r: gtv): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(r);
	val operator = rule_operator.value(text.from_gtv(parameters[1]));
	val value = integer.from_gtv(parameters[2]);
	when (operator) {
		rule_operator.gt -&gt; {
			return op_context.block_height &gt; value;
		}
		rule_operator.ge,
		rule_operator.eq -&gt; {
			return op_context.block_height &gt;= value;
		}
		else -&gt; {
			return true;
		}
	}
}


/****************************************************************************************
 *                                     op_count                                         *
 ****************************************************************************************/
 
 function op_count_variable_initial_value(): gtv {
 	return (1).to_gtv();
 }
 
 function is_op_count_rule_active(rule: gtv): boolean {
 	return true;
 }</string>
                            </entry>
                            <entry key="lib/ft3/account/module.rell">
                                <string>@mount('ft3')
module;

import core: ^.core;

struct auth_descriptor {
    auth_type: text;
    participants: list&lt;byte_array&gt;;
    args: list&lt;gtv&gt;;
    rules: gtv;
}

entity account {
    key id: byte_array;
}

entity account_meta {
    meta_key: text;
    value: byte_array;
    index account, meta_key;
    index meta_key, value;
}

entity account_auth_descriptor {
     descriptor_id: byte_array;
     key account, descriptor_id;
     index descriptor_id;
     auth_type: text;
     args: byte_array;
     rules: byte_array;
}

entity auth_descriptor_participant {
    key account_auth_descriptor, id: byte_array;
}


// rate limiter
entity rl_state {
    key account;
    mutable points: integer;
    mutable last_update: timestamp;
    mutable max_points: integer;
    mutable recovery_time: timestamp;
}

function _add_auth_descriptor (account, auth_descriptor) {
     val descriptor_id = auth_descriptor.hash();
     
     analyze_auth_descriptor_rules(auth_descriptor.rules, 0);
     
     val account_auth_descriptor = create account_auth_descriptor (
        account, descriptor_id,
        auth_descriptor.auth_type,
        args = auth_descriptor.args.to_gtv().to_bytes(),
        rules = auth_descriptor.rules.to_gtv().to_bytes()
     );
     
     for (participant in auth_descriptor.participants) {
        require(is_signer(participant));
        create auth_descriptor_participant(account_auth_descriptor, id = participant);
     }
     
     setup_auth_descriptor_variables(account_auth_descriptor);
}

function _delete_auth_descriptor(auth_descriptor: account_auth_descriptor) {
	delete auth_descriptor_rule_variable @* { auth_descriptor };
	delete auth_descriptor_participant @* { auth_descriptor };
	delete auth_descriptor;
}

function _delete_all_auth_descriptors_exclude(account, auth_descriptor_id: byte_array) {
	delete (adrv: auth_descriptor_rule_variable, ad: account_auth_descriptor) @* {
		ad.account == account, ad.descriptor_id != auth_descriptor_id, adrv.account_auth_descriptor == ad		
	};
	
	delete (adp: auth_descriptor_participant, ad: account_auth_descriptor) @* {
        ad.account == account and ad.descriptor_id != auth_descriptor_id and adp.account_auth_descriptor == ad
    };

    delete account_auth_descriptor @* {
       .account == account,
       .descriptor_id != auth_descriptor_id
    };
}

function create_account_with_auth (auth_descriptor): byte_array {
     val id = auth_descriptor.hash();
     val acc = create account (id);
     _add_auth_descriptor(
        acc, auth_descriptor
     );
     val max_points = core.my_blockchain_info.rate_limit_max_points;
     val recovery_time = core.my_blockchain_info.rate_limit_recovery_time;
     val points_at_start = core.my_blockchain_info.rate_limit_points_at_account_creation;
     
	create rl_state(acc, .points = points_at_start, .last_update = op_context.last_block_time, max_points, recovery_time);
    
    return id;
}

function auth_and_log(account_id: byte_array, auth_descriptor_id: byte_array, required_flags: list&lt;text&gt;): account {
	val account = account @ { .id == account_id };
	rate_limit(account);
	require_auth(account, auth_descriptor_id, required_flags);
	return account;
}

query is_auth_descriptor_valid(account_id: byte_array, auth_descriptor_id: byte_array) {
    return is_valid(account_auth_descriptor @ {
        .account.id == account_id,
        .descriptor_id == auth_descriptor_id
    });
}

query get_account_auth_descriptors(id: byte_array) {
    return account_auth_descriptor @* {
        .account.id == id
    } (
        id = .descriptor_id,
        type = .auth_type,
        args = .args
    );
}

query get_account_by_id(id: byte_array) {
    return account @? { id } ( .id );
}

query get_account_by_auth_descriptor(auth_descriptor) {
    return account @? { .id == auth_descriptor.hash() } ( .id );
}

query get_accounts_by_participant_id(id: byte_array) {
    return auth_descriptor_participant @* { id } ( .account_auth_descriptor.account.id );
}

query get_accounts_by_auth_descriptor_id(descriptor_id: byte_array) {
    return account_auth_descriptor @* { descriptor_id } ( .account.id );
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/operations/module.rell">
                                <string>@mount('ft3')
module;

import acc: ^^.account;
import core: ^^.core;


operation delete_auth_descriptor(account_id: byte_array, auth_descriptor_id: byte_array, delete_descriptor_id: byte_array) {
    val flags = if (auth_descriptor_id == delete_descriptor_id) list&lt;text&gt;() else ["A"];

    val account = acc.auth_and_log(account_id, auth_descriptor_id, flags);

    acc._delete_auth_descriptor(acc.account_auth_descriptor @ {
        .account == account,
        .descriptor_id == delete_descriptor_id
    });
}

operation delete_all_auth_descriptors_exclude(account_id: byte_array, auth_descriptor_id: byte_array) {
    val account = acc.auth_and_log(account_id, auth_descriptor_id, ["A"]);

	acc._delete_all_auth_descriptors_exclude(account, auth_descriptor_id);
}

operation add_auth_descriptor (account_id: byte_array, auth_id: byte_array, new_desc: acc.auth_descriptor) {
      val account = acc.auth_and_log(account_id, auth_id, ["A"]);
      acc._add_auth_descriptor(account, new_desc);
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/rate_limit.rell">
                                <string>import ^.core;


function rate_limit (account) {
	if(core.my_blockchain_info.rate_limit_active == false ) return;
    val max_counter = core.my_blockchain_info.rate_limit_max_points;
    val recovery_time = core.my_blockchain_info.rate_limit_recovery_time;
    val stat = rl_state@{account} (.points, .last_update);
    val delta = op_context.last_block_time - stat.last_update;
    var got_points = 0;
    var update_time = stat.last_update;

    if (delta &gt; recovery_time)
    {
        got_points = delta / recovery_time;
        update_time = stat.last_update + got_points * recovery_time;
        if (got_points + stat.points &gt; max_counter) {
            got_points = max_counter - stat.points;
            // if user is at maximum reset his 
            // timer
            update_time = op_context.last_block_time;
        }
    }
    
    require(stat.points + got_points &gt; 0);
    
    update rl_state@{account} (
        .points += got_points - 1,
        .last_update = update_time
    );
}


query get_account_rate_limit_last_update(account_id: byte_array) {
	if(core.my_blockchain_info.rate_limit_active == false ) return (points = 0, last_update = 0);
	val t= rl_state@{.account.id == account_id}
	(
		.points, 
		.last_update
	);
	
	return t;
}

query get_last_timestamp(): integer {
	return (block@{.timestamp&gt;0}(@sort_desc .timestamp) limit 1);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/asset.rell">
                                <string>import acc: ^.account;

entity asset {
    id: byte_array;
    key id;
    name;
    issuing_chain_rid: byte_array;
}

entity balance {
    key acc.account, asset;
    mutable amount: integer = 0;
}

function ensure_balance(acc.account, asset): balance {
    val balance = balance @? {asset, account};
    if (balance != null) {
       return balance;
    }
    else return create balance(account, asset, amount = 0);
}

function register_asset (name, issuing_chain_rid: byte_array): asset {
   val id = (name, issuing_chain_rid).hash();
   return create asset (id, name, issuing_chain_rid);
}

function _get_asset_balances(account_id: byte_array): list&lt;(id:byte_array,name:text,amount:integer,chain_id:byte_array)&gt; {
    return balance @* { .account.id == account_id } (
      id = .asset.id,
      name = .asset.name,
      amount = .amount,
      chain_id = .asset.issuing_chain_rid
    );
}

query get_asset_balances(account_id: byte_array) {
    return _get_asset_balances(account_id);
}

query get_asset_balance(account_id: byte_array, asset_id: byte_array) {
    return balance @? {
        .account.id == account_id,
        .asset.id == asset_id
    } (
        id = .asset.id,
        name = .asset.name,
        amount = .amount,
        chain_id = .asset.issuing_chain_rid
    );
}

query get_asset_by_name(name) {
    return asset @* { name } (
        .id,
        .name,
        .issuing_chain_rid
    );
    
}

query get_asset_by_id(asset_id: byte_array) {
	return asset@{
		.id == asset_id
	}(
		id = .id,
		name = .name,
		issuing_chain_rid = .issuing_chain_rid
		
	);
}

query get_all_assets() {
	return asset@*{}(
		id = .id,
		name = .name,
		issuing_chain_rid = .issuing_chain_rid	
	);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/dev_op.rell">
                                <string>module;

import ft3: ^^.core;
import acc: ^^.account;

object dev_state {
   mutable allow_dev_ops: boolean = true;
}

function require_dev() {
    require(dev_state.allow_dev_ops);
}

function dev_give_points_(account: acc.account, amount: integer) {
	require_dev();
	update acc.rl_state@{account}(.points += amount);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/history.rell">
                                <string>import acc: ^.account;

@log entity payment_history_entry {
    index acc.account, asset;
    delta: integer;

    // helps to locate exact position of payment entry in transaction
    op_index: integer;
    is_input: boolean;
    entry_index: integer;
}

query get_payment_history(account_id: byte_array, after_block: integer) {
    return payment_history_entry @* {
        acc.account @ { account_id },
        .transaction.block.block_height &gt; after_block
    } (
        delta = .delta,
        asset = .asset.name,
        asset_id = .asset.id,
        is_input = .is_input,
        timestamp = .transaction.block.timestamp,
        block_height = .transaction.block.block_height,
        entry_index = .entry_index,
        tx_rid = .transaction.tx_rid,
        tx_data = .transaction.tx_data
    );
}
</string>
                            </entry>
                            <entry key="lib/ft3/core/module.rell">
                                <string>@mount('ft3')
module;

struct module_args {
	my_blockchain_name: text;
	my_blockchain_website: text;
	my_blockchain_description: text;
	rate_limit_active: boolean;
	rate_limit_max_points: integer;
    rate_limit_recovery_time: integer;
    rate_limit_points_at_account_creation: integer;    
}</string>
                            </entry>
                            <entry key="lib/ft3/core/my_blockchain_info.rell">
                                <string>
object my_blockchain_info {
    mutable name: text = chain_context.args.my_blockchain_name;
    mutable website: text = chain_context.args.my_blockchain_website;
    mutable description: text = chain_context.args.my_blockchain_description;
    mutable rate_limit_active: boolean = chain_context.args.rate_limit_active;
    mutable rate_limit_max_points: integer = chain_context.args.rate_limit_max_points;
    mutable rate_limit_recovery_time: integer = chain_context.args.rate_limit_recovery_time;
    mutable rate_limit_points_at_account_creation: integer = chain_context.args.rate_limit_points_at_account_creation;
}


//operation update_blockchain(name, website: text, description: text) {
//    blockchain.name = name;
//    blockchain.website = website;
//    blockchain.description = description;
//}

query get_blockchain_info() {
    return (
        name = my_blockchain_info.name,
        website = my_blockchain_info.website,
        description = my_blockchain_info.description,
        rate_limit_active = my_blockchain_info.rate_limit_active,
        rate_limit_max_points = my_blockchain_info.rate_limit_max_points,
        rate_limit_recovery_time = my_blockchain_info.rate_limit_recovery_time,
        rate_limit_points_at_account_creation = chain_context.args.rate_limit_points_at_account_creation
    );
}

</string>
                            </entry>
                            <entry key="lib/ft3/core/operations/transfer.rell">
                                <string>@mount('ft3')
module;

import ft3: ^^;


operation transfer (inputs: list&lt;ft3.xfer_input&gt;, outputs: list&lt;ft3.xfer_output&gt;) {
    ft3._transfer(inputs, outputs);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/transfer.rell">
                                <string>import acc: ^.account;

struct xfer_input {
   account_id: byte_array;
   asset_id: byte_array;
   auth_descriptor_id: byte_array;
   amount: integer;
   extra: map&lt;text, gtv&gt;;
}

struct xfer_output {
   account_id: byte_array;
   asset_id: byte_array;
   amount: integer;
   extra: map&lt;text, gtv&gt;;
}

function deduct_balance (acc.account, asset, d_amount: integer) {
    val b = balance @ { account, asset };
    require( b.amount &gt;= d_amount, "Balance is too low");
    update b (amount -= d_amount);
}

function consume_input (i: xfer_input, idx: integer, assets: map&lt;asset, integer&gt;): payment_history_entry {
      val asset = asset @ { .id == i.asset_id };
      val account = acc.auth_and_log(i.account_id, i.auth_descriptor_id, ["T"]);
      require( i.amount &gt; 0, "Amount should be non 0 positive." );

      deduct_balance(account, asset, i.amount);
      assets[asset] = i.amount + if (asset in assets) assets[asset] else 0;
      return create payment_history_entry (
        account,
        asset,
        .delta = i.amount,
        .op_index = 500, //op_context ???
        .is_input = true,
        .entry_index = idx
      );
}

function process_transfer_output (o: xfer_output, idx: integer, available_assets: map&lt;asset, integer&gt;): payment_history_entry {
      if (o.extra.contains("reg_auth_desc")) {
          val auth_desc = acc.auth_descriptor.from_gtv(o.extra["reg_auth_desc"]);
          require(o.account_id
           == acc.create_account_with_auth(auth_desc));
      }

      val target_account = acc.account @ { .id == o.account_id };
      val asset = asset @ { .id == o.asset_id };
      require(o.amount &gt; 0, "You cannot tx output negative numbers");
      require( available_assets[asset] &gt;= o.amount );
      available_assets[asset] -= o.amount;
      require(available_assets[asset] &gt;= 0);
      val balance = ensure_balance(target_account, asset);
      balance.amount += o.amount;

      return create payment_history_entry (
        .account = target_account,
        asset,
        .delta = o.amount,

        .op_index = 500, // something from op_context,
        .is_input = false,
        .entry_index = idx
      );
}

function _transfer (inputs: list&lt;xfer_input&gt;, outputs: list&lt;xfer_output&gt;) {
   val sum_inputs = map&lt;asset, integer&gt;();
   var idx = 0;
   for (i in inputs) {
      consume_input(i, idx, sum_inputs);
      idx += 1;
   }

   idx = 0;
   for (o in outputs) {
      process_transfer_output(o, idx, sum_inputs);
      idx += 1;
   }
}
</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/blockchain.rell">
                                <string>import ft3: ^.core;
import acc: ^.account;


entity asset_origin {
    key ft3.asset;
    origin_chain_rid: byte_array;
}

entity linked_chain {
    key chain_rid: byte_array;
}

function blockchain_account_id (blockchain_rid: byte_array): byte_array {
   return ("B", blockchain_rid).hash();
}

function ensure_blockchain_account (blockchain_rid: byte_array): acc.account {
   val blockchain_account_id = blockchain_account_id(blockchain_rid);
   val acc = acc.account @? { .id == blockchain_account_id };
   return if (acc??)  acc
   else create acc.account (id = blockchain_account_id);
}

function get_blockchain_account (blockchain_rid: byte_array): acc.account {
   return acc.account @ { .id == blockchain_account_id(blockchain_rid) };
}


query get_linked_chains() {
    return linked_chain @* {} ( .chain_rid );
}

query is_linked_with_chain(chain_rid: byte_array) {
    return linked_chain @? { chain_rid } != null;
}
</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/module.rell">
                                <string>@mount('ft3.xc')
module;
</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/structures.rell">
                                <string>struct operation_rec {
   name;
   args: list&lt;gtv&gt;;
}

struct transaction_body_rec {
    blockchain_rid: byte_array;
    operations: list&lt;operation_rec&gt;;
    signers: list&lt;gtv&gt;;
}

struct transaction_rec {
   body: transaction_body_rec;
   signatures: list&lt;gtv&gt;;
}

struct transaction_proof {
     tx: virtual&lt;transaction_rec&gt;;
     // block_header: byte_array;
     // merkle_path: virtual&lt;list&lt;byte_array&gt;&gt;;
     // tx_index: integer;
     block_rid: byte_array;
     block_signers: list&lt;byte_array&gt;;
     signatures: list&lt;byte_array&gt;;     
}

function verify_transaction_proof( p: transaction_proof ) {
   // TODO
}</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/transfer.rell">
                                <string>import ft3: ^.core;

struct xc_target {
    account_id: byte_array;
    extra: map&lt;text, gtv&gt;;
}

function add_to_blockchain_balance (blockchain_rid: byte_array, ft3.asset, amount: integer) {
    require( chain_context.blockchain_rid != blockchain_rid ); // cannot add to own account

    val origin_chain_rid = asset_origin @? { asset } .origin_chain_rid;

    if (exists(origin_chain_rid) and (blockchain_rid == origin_chain_rid)) {
       // do nothing. in future we might track origin
    } else {
         val bc_acc = ensure_blockchain_account(blockchain_rid);
         ft3.ensure_balance(bc_acc, asset).amount += amount;
    }
}


struct init_xfer_args {
          source: ft3.xfer_input;
          target: xc_target;
          hops: list&lt;byte_array&gt;;
}

entity applied_transfers { key tx_rid: byte_array; }


</string>
                            </entry>
                            <entry key="lib/ft3/ft3_basic_dev.rell">
                                <string>module;

namespace ft3 {
	import acc: lib.ft3.account;
	import acc_op: lib.ft3.account.operations;
	import core: lib.ft3.ft3_basic_dev;
	import transfer_op: lib.ft3.core.operations.transfer;
//	import lib.ft3.crosschain;
//	import lib.ft3.crosschain.operations;
	
	import lib.ft3.operations.dev_op_account;
	import lib.ft3.operations.dev_op_asset;
	import lib.ft3.operations.dev_op_balance;
	import lib.ft3.operations.dev_op_rate_limit;
}

</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_account.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import acc: ^^.account; 


operation dev_register_account (acc.auth_descriptor) {
    dev_op.require_dev();
    acc.create_account_with_auth( auth_descriptor );
}
</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_asset.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import ft3: ^^.core;

import xft3: ^^.crosschain; 

operation dev_register_asset (name, issuing_chain_rid: byte_array) {
    dev_op.require_dev();
    ft3.register_asset(name, issuing_chain_rid);
}

operation dev_register_xc_asset (name, issuing_chain_rid: byte_array, origin_chain_rid: byte_array) {
    dev_op.require_dev();   
    val asset = ft3.register_asset(name, issuing_chain_rid);
    create xft3.asset_origin (asset, origin_chain_rid);
}
</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_balance.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import ft3: ^^.core;
import acc: ^^.account;


operation dev_give_balance (asset_id: byte_array, account_id: byte_array, amount: integer) {
    dev_op.require_dev();
    require(amount &gt;= 0);
    ft3.ensure_balance( acc.account @ { account_id }, ft3.asset @ { .id == asset_id } ).amount += amount;
}</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_rate_limit.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import acc: ^^.account;



/*
 * Can be negative
 */
operation dev_give_points(account_id: byte_array, amount: integer){
	val account = acc.account@{.id == account_id};
	dev_op.dev_give_points_(account, amount);
}

operation dev_free_op(account_id: byte_array) {
	// this operation does not cost points in the rate limit
	val account = acc.account@{.id == account_id};
	dev_op.dev_give_points_(account, 1);
	acc.rate_limit(account);
}</string>
                            </entry>
                            <entry key="main.rell">
                                <string>import lib.ft3.ft3_basic_dev;

// Remove for production
// ---

import user;
import topic;
import notifications;
import channel;
import follow;
import election;
import representative;
import chat;</string>
                            </entry>
                            <entry key="notifications/index.rell">
                                <string>import user;

entity notification {
    key id: text, user.user;
    trigger: text;
    content: text;
    mutable read: boolean;
    index timestamp;
}
</string>
                            </entry>
                            <entry key="notifications/operations.rell">
                                <string>import user;
import user.distrust;

operation create_notifications_for_users(name, descriptor_id: byte_array, id: text, trigger: text, content: text, usernames: set&lt;text&gt;) {
    val opr_user = user.get_verified_user(name, descriptor_id);

    for (username in usernames) {
        val toUser = user.user@?{ .name == username.lower_case() };
        if (toUser != null and distrust.user_distrust@?{ .distruster == toUser, .distrusted == opr_user } == null) {
            create notification(
                id = id,
                toUser,
                trigger = trigger,
                content = content,
                false,
                op_context.last_block_time
            );
        }
    }
}

operation remove_notifications_for_users(name, descriptor_id: byte_array, id: text, usernames: set&lt;text&gt;) {
    val user = user.get_verified_user(name, descriptor_id);

    for (username in usernames) {
        val to_user = user.user@?{ .name == username };
        if (to_user != null) {
            delete notification@?{ id, .user == to_user };
        }
    }
}

operation mark_notifications_since_timestamp_read(name, descriptor_id: byte_array, timestamp) {
    val user = user.get_verified_user(name, descriptor_id);
    update notification@*{ .user == user, .timestamp &gt; timestamp } ( read = true );
}</string>
                            </entry>
                            <entry key="notifications/queries.rell">
                                <string>import user;

query count_unread_user_notifications(name) {
    val user = user.user@{ .name == name };
    return notification@*{ .user == user, .read == false } ( .id );
}

query get_user_notifications_prior_to_timestamp(name, timestamp, page_size: integer) {
    val user = user.user@{ .name == name };
    return notification@*{ .user == user, .timestamp &lt; timestamp } (
        .id,
        .trigger,
        .content,
        .read,
        @sort_desc .timestamp
    ) limit page_size;
}
</string>
                            </entry>
                            <entry key="representative/functions.rell">
                                <string>import user;
import election;

function is_username_representative(name): boolean {
	val user = user.user@?{ .name == name};
	
	if (user == null) {
		return false;
	}
	
	val prev_election = election.get_latest_completed_election_id();
	
	if (prev_election == null) {
		return false;
	}
	
	return representative@?{ .user == user, .representative_election.id == prev_election } != null;
}

function is_user_suspended(rep: user.user, suspendee: user.user, timestamp): boolean {
	return user.user_suspension@?{ 
		.user == suspendee, 
		.suspended_by == rep,
		.suspended_until &gt;= timestamp
	} != null;
} </string>
                            </entry>
                            <entry key="representative/index.rell">
                                <string>import election;
import user;

entity representative {
    key user.user, election.representative_election;
}

entity representative_action {
    key id: byte_array;
    index representative;
    index timestamp;
    action: text;
}

entity representative_distrust {
	key distruster: user.user, representative;
}

import representative.report;
</string>
                            </entry>
                            <entry key="representative/operations.rell">
                                <string>import election;
import topic;
import user;
import util;

operation remove_topic(username: text, descriptor_id: byte_array, topic_id: text) {
    val user = user.get_verified_user(username, descriptor_id);

    val recent_election = election.representative_election@{ .completed == true } ( .id, @sort_desc .timestamp ) limit 1;
    val representative = representative @{ user, .representative_election.id == recent_election.id };

    val the_topic = topic.topic @{ .id == topic_id };
    
    create topic.topic_moderation(representative.user, the_topic);

    create representative_action(
        id = op_context.transaction.tx_rid,
        representative,
        op_context.last_block_time,
        action = "Topic /t/" + the_topic.id + " was removed by @" + user.display_name
    );
}

operation remove_topic_reply(username: text, descriptor_id: byte_array, topic_reply_id: text) {
    val user = user.get_verified_user(username, descriptor_id);

    val recent_election_id = require(election.get_latest_completed_election_id(), "No election has been held yet");
    val representative = representative @{ user, .representative_election.id == recent_election_id };

    val the_reply = topic.topic_reply @{ .id == topic_reply_id };
    
    create topic.topic_reply_moderation(representative.user, the_reply);

    create representative_action(
        id = op_context.transaction.tx_rid,
        representative,
        op_context.last_block_time,
        action = "Reply in topic /t/" + the_reply.topic.id + " was removed by @" + user.display_name
    );
}

operation suspend_user(username: text, descriptor_id: byte_array, user_to_be_suspended: text) {
    val user = user.get_verified_user(username, descriptor_id);

    val recent_election_id = require(election.get_latest_completed_election_id(), "No election has been held yet");
    val representative = representative @{ user, .representative_election.id == recent_election_id };

    val suspendee = user.user@{ .name == user_to_be_suspended };
    
    val action_id = "suspend_user:" + user_to_be_suspended;
	
	require(
		not is_user_suspended(user, suspendee, op_context.last_block_time), 
		"User already suspended"
	);
	
    val updated_times_suspended = user.user_suspension@*{
    	.user == suspendee,
    	.suspended_by == user
    }( .user ).size() + 1;
    
    val one_day_millis = 86400000;
    val days_suspended = updated_times_suspended * updated_times_suspended;
    val suspension_time_millis = days_suspended * one_day_millis;
	val suspended_until = op_context.last_block_time + suspension_time_millis;

	create user.user_suspension(user = suspendee, suspended_by = user, suspended_until);

    var daysString = " days ";
    if (days_suspended == 1) {
        daysString = " day ";
    }

    create representative_action(
        id = op_context.transaction.tx_rid,
        representative,
        op_context.last_block_time,
        action = "@" + suspendee.display_name + " was suspended for " + days_suspended + daysString +  "by @" + user.display_name
    );
}

operation distrust_representative(name, descriptor_id: byte_array, distrusted: name) {
	val user = user.get_verified_user(name, descriptor_id);
	
	val recent_election_id = require(election.get_latest_completed_election_id(), "No election has been held yet");
	
	require(is_eligible_to_distrust(user, recent_election_id), "User is not eligible to distrust");
	
    val representative = representative @{ 
    	.user.name == distrusted.lower_case(), 
    	.representative_election.id == recent_election_id
    };
    
    val required_votes = election.temp_votes_counter@{
    	.representative_election_candidate.representative_election.id == recent_election_id
    } ( @sort_desc .votes ) limit 1;
    
    val distrusts = representative_distrust@*{ 
    	representative
    }( .distruster ).size();
    
    if (distrusts &gt;= 10 and distrusts &gt; required_votes) {
    	delete representative;
    } else {
    	create representative_distrust(user, representative);
    }
}

function is_eligible_to_distrust(user.user, prev_election_id: integer): boolean {	
	val recent_election_start = election.election_block_details@{
		.representative_election.id == prev_election_id
	} ( .started_height );
	
	if (user.registered &gt; recent_election_start) {
		log("User must have registered before the previous election started");
		return false;
	}
	
	val previous_election_completed = (election: election.representative_election, details: election.election_block_details)@?{
		election.id != prev_election_id,
		election == details.representative_election,
		election.completed == true
	} ( 
		details.finished_height,
		@omit @sort_desc election.timestamp
	) limit 1;
	
	if (previous_election_completed == null) {
		return true;
	}
	
	val number_of_topics = topic.topic@*{ 
		.author == user,
		.last_modified &gt; previous_election_completed,
		.last_modified &lt; recent_election_start
	}( .id ).size();
	
	val number_of_replies = topic.topic_reply@*{
		.author == user,
		.timestamp &gt; previous_election_completed,
		.timestamp &lt; recent_election_start
	}( .id ).size();
	
	return number_of_topics + number_of_replies &gt;= 5;
}</string>
                            </entry>
                            <entry key="representative/queries.rell">
                                <string>import election;
import user;

query get_representatives(): list&lt;name&gt; {
    val election = election.representative_election@?{ .completed == true } ( .id, @sort_desc .timestamp ) limit 1;

    if (election == null) {
        return list&lt;name&gt;();
    }

    return representative@*{
        .representative_election.id == election.id
    } ( .user.name );
}

query get_all_representative_actions(timestamp, page_size: integer) {
    return representative_action@*{
        .timestamp &lt; timestamp
    } (
        .id,
        representative = .representative.user.name,
        @sort_desc .timestamp,
        .action
    ) limit page_size;
}

query get_number_of_times_representative(name) {
    return representative@*{ .user.name == name } ( .representative_election.id ).size();
}

query is_user_suspended_by_me(username: name, user_to_be_suspended: name, timestamp) {
	val user = user.user@{ .name == username.lower_case() };
	val suspendee = user.user@{ .name == user_to_be_suspended.lower_case() };
	return is_user_suspended(user, suspendee, timestamp);
}</string>
                            </entry>
                            <entry key="representative/report/index.rell">
                                <string>import user;

entity representative_report {
    key id: text;
    index timestamp;
    text;
}
</string>
                            </entry>
                            <entry key="representative/report/operations.rell">
                                <string>import election;
import user;
import representative;
import util;

operation create_representative_report(username: text, descriptor_id: byte_array, id: text, text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create representative_report(id = id, op_context.last_block_time, text = text);
}
</string>
                            </entry>
                            <entry key="representative/report/queries.rell">
                                <string>query get_unhandled_representative_reports(timestamp) {
    return representative_report@*{
    	.timestamp &gt; timestamp
    } ( 
    	.id, 
    	@sort_desc .timestamp, 
    	.text
    ) limit 25;
}</string>
                            </entry>
                            <entry key="topic/functions.rell">
                                <string>import util;

function find_topic_by_id(id: text): topic {
    return topic@{ .id == id };
}

function require_mutable(post_timestamp: timestamp, op_timestamp: timestamp, action: text) {
	val fiveMinutesInMillis = 300000;
    require(
    	op_timestamp &lt; post_timestamp + fiveMinutesInMillis,
    	util.app_error(util.error_type.TOPIC_IMMUTABLE, action)
    );
}

function get_latest_poster_in_topic(id: text, topic_author: name): text {
	val latest_reply = topic_reply@?{ .topic.id == id} (
		@sort_desc .timestamp,
		.author
	) limit 1;
	
	if (latest_reply != null) {
		return latest_reply.author.display_name;
	} else {
		return topic_author;
	}
}</string>
                            </entry>
                            <entry key="topic/index.rell">
                                <string>import user;

entity topic {
    key id: text;
    index author: user.user;
    timestamp;
    mutable last_modified: timestamp;
    index last_modified;
    title: name;
    mutable message: text;
}

entity topic_moderation {
	key user.user, topic;
}

entity topic_reply {
    key id: text;
    index topic;
    index author: user.user;
    index timestamp;
    is_sub_reply: boolean = false;
    index is_sub_reply;
    mutable message: text;
}

entity topic_reply_moderation {
	key user.user, topic_reply;
}

entity sub_reply {
    key parent_reply: topic_reply, child_reply: topic_reply;
}

struct ext_topic {
	id: text;
	author: text;
	title: text;
	message: text;
	timestamp;
	last_modified: timestamp;
	latest_poster: name;
	moderated_by: list&lt;name&gt;;
}

struct ext_topic_reply {
	id: text;
	author: text;
	message: text;
	is_sub_reply: boolean;
	timestamp;
	moderated_by: list&lt;name&gt;;
}

import topic.rating;
import topic.subscription;
</string>
                            </entry>
                            <entry key="topic/operations.rell">
                                <string>import channel;
import topic.rating;
import user;
import topic.subscription;
import topic.poll;

operation create_topic(id: text, descriptor_id: byte_array, username: text, channel_key: name, channel_name: name, title: name, message: text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);

    val topic = create topic(
        id = id,
        author,
        timestamp = op_context.last_block_time,
        last_modified = op_context.last_block_time,
        title = title,
        message = message
    );

    create channel.channel(name = channel_key.lower_case(), topic, op_context.last_block_time, display_name = channel_name);
    create rating.tmp_topic_rating (topic, 0);
        
    for (suspension in user.user_suspension@*{ .user == author, .suspended_until &gt; op_context.last_block_time }) {
    	create topic_moderation(suspension.suspended_by, topic);
    }
}

operation modify_topic(id: text, descriptor_id: byte_array, username: text, text) {
    val author = user.get_verified_user(username, descriptor_id);

    val topic = topic@{ .id == id, .author == author };
    require_mutable(topic.timestamp, op_context.last_block_time, "Modify topic");

    update topic ( message = text );
}

operation delete_topic(id: text, descriptor_id: byte_array, username: text) {
    val author = user.get_verified_user(username, descriptor_id);

    val topic = topic@{ .id == id, .author == author };
    require_mutable(topic.timestamp, op_context.last_block_time, "Delete topic");
    delete channel.channel@{ topic };
    delete rating.tmp_topic_rating@{ topic };
    delete subscription.subscription@?{ topic };
    
    val opt_poll = poll.poll@?{ topic };
    if (opt_poll != null) {
    	delete poll.poll_option@*{ .poll == opt_poll };
    	delete poll.poll_vote@*{ .poll == opt_poll };
    }
    
	delete topic;
}

operation create_reply(topic_id: text, descriptor_id: byte_array, id: text, username: text, message: text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);
    val topic = find_topic_by_id(topic_id);

    val reply = create topic_reply(
        id = id,
        topic,
        author,
        timestamp = op_context.last_block_time,
        message = message
    );
    
    for (suspension in user.user_suspension@*{ .user == author, .suspended_until &gt; op_context.last_block_time }) {
    	create topic_reply_moderation(suspension.suspended_by, reply);
    }

     update topic ( last_modified = op_context.last_block_time);
}

operation modify_reply(id: text, descriptor_id: byte_array, username: text, text) {
    val author = user.get_verified_user(username, descriptor_id);

    val reply = topic_reply@{ .id == id, .author == author };
    require_mutable(reply.timestamp, op_context.last_block_time, "Modify reply");

    update reply ( message = text );
}

operation delete_reply(id: text, descriptor_id: byte_array, username: text) {
	val author = user.get_verified_user(username, descriptor_id);
	val reply = topic_reply@{ id, author };
	require_mutable(reply.timestamp, op_context.last_block_time, "Delete reply");
	
	delete sub_reply@?{ .child_reply == reply };
	delete reply;
}

operation create_sub_reply(topic_id: text, descriptor_id: byte_array, parent_reply_id: text, id: text, username: text, message: text) {
    val author = user.get_verified_user(username, descriptor_id);
    val topic = find_topic_by_id(topic_id);

    val topic_reply = create topic_reply(
        id = id,
        topic,
        author,
        timestamp = op_context.last_block_time,
        is_sub_reply = true,
        message = message	
    );
    
    for (suspension in user.user_suspension@*{ .user == author, .suspended_until &gt; op_context.last_block_time }) {
    	create topic_reply_moderation(suspension.suspended_by, topic_reply);
    }

    create sub_reply(
        parent_reply = topic_reply@{ .id == parent_reply_id },
        child_reply = topic_reply
    );

    update topic ( last_modified = op_context.last_block_time);
}</string>
                            </entry>
                            <entry key="topic/poll/index.rell">
                                <string>import topic;
import user;

entity poll {
	key topic.topic;
	text;
}

entity poll_option {
	key poll, text;
	mutable votes: integer;
}

entity poll_vote {
	key poll, user.user;
	poll_option;
}

struct poll_record {
	question: text;
	options: list&lt;option_record&gt;;
}

struct option_record {
	option: text;
	votes: integer;
}</string>
                            </entry>
                            <entry key="topic/poll/operations.rell">
                                <string>import user;
import topic;

operation create_poll(id: text, descriptor_id: byte_array, 
	username: text, question: text, options: list&lt;text&gt;
) {
	val author = user.get_verified_user(username, descriptor_id);
	val topic = topic.topic@{ .id == id, author };
	
	val poll = create poll(topic, question);
	
	for (option in options) {
		create poll_option(poll, option, 0);
	}
}

operation vote_for_poll_option(id: text, descriptor_id: byte_array, username: text, option: text) {
	val user = user.get_verified_user(username, descriptor_id);
	
	val poll_opt = poll_option@{ .poll.topic.id == id, .text == option };

	create poll_vote(poll_opt.poll, user, poll_opt);
	update poll_opt ( .votes+1 );
}</string>
                            </entry>
                            <entry key="topic/poll/queries.rell">
                                <string>query get_poll(topic_id: text): poll_record? {
	val poll = poll@?{ .topic.id == topic_id };
	
	if (poll == null) {
		return null;
	}
	
	val options = list&lt;option_record&gt;();
	for (opt in poll_option@*{ .poll == poll }) {
		options.add(option_record(opt.text, opt.votes));
	}
	
	return poll_record(poll.text, options);
}

query get_poll_vote(topic_id: text, username: text): text? {
	val vote = poll_vote@?{ 
		.poll.topic.id == topic_id, 
		.user.name == username.lower_case()
	};
	
	if (vote == null) return null;
	return vote.poll_option.text;
}</string>
                            </entry>
                            <entry key="topic/queries.rell">
                                <string>import channel;
import follow;
import topic.rating;
import user;
import representative;

query get_topics_after_timestamp(timestamp, page_size: integer) {
    val topics = topic@*{ .last_modified &gt; timestamp } (
        .id,
        author=.author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_prior_to_timestamp(timestamp, page_size: integer): list&lt;ext_topic&gt; {
    val topics = topic@*{ .last_modified &lt; timestamp }(
        .id,
        author = .author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    ) limit page_size;
        
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
  	   	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topic_replies_prior_to_timestamp(username: name, topic_id: text, timestamp, page_size: integer) {	
    val replies = topic_reply@*{
        topic@{ .id == topic_id },
        .timestamp &lt; timestamp,
        .is_sub_reply == false
    }(
        .id,
        topic_id = .topic.id,
        author= .author.display_name,
        .message,
        .is_sub_reply,
        @sort_desc .timestamp
    ) limit page_size;
    
    val ext_replies = list&lt;ext_topic_reply&gt;();
    for (reply in replies) {
    	val moderated_by = topic_reply_moderation @*{ .topic_reply.id == reply.id } ( .user.name );
    	val ext_reply = ext_topic_reply (
    		id = reply.id,
    		author = reply.author,
    		message = reply.message,
    		is_sub_reply = reply.is_sub_reply,
    		timestamp = reply.timestamp,
    		moderated_by = moderated_by
    	);
    	ext_replies.add(ext_reply);
    }
    
    return ext_replies;
}

query count_topic_replies(topic_id: text) {
	return topic_reply@*{ .topic.id == topic_id }( .id ).size();
}

query get_topic_replies_after_timestamp(username: name, topic_id: text, timestamp, page_size: integer) {	
	val replies = topic_reply@*{
        topic@{ .id == topic_id },
        .timestamp &gt; timestamp,
        .is_sub_reply == false
    }(
        .id,
        topic_id = .topic.id,
        author= .author.display_name,
        .message,
        .is_sub_reply,
        @sort_desc .timestamp
    ) limit page_size;
			
    val ext_replies = list&lt;ext_topic_reply&gt;();
    for (reply in replies) {
    	val moderated_by = topic_reply_moderation @*{ .topic_reply.id == reply.id } ( .user.name );
    	val ext_reply = ext_topic_reply (
    		id = reply.id,
    		author = reply.author,
    		message = reply.message,
    		is_sub_reply = reply.is_sub_reply,
    		timestamp = reply.timestamp,
    		moderated_by = moderated_by
    	);
    	ext_replies.add(ext_reply);
    }
    
    return ext_replies;
}

query get_topic_replies_by_user_prior_to_timestamp(name, timestamp, page_size: integer) {
    return topic_reply@*{ .author.name == name, .timestamp &lt; timestamp } (
        .id,
        topic_id = .topic.id,
        author=.author.display_name,
        .message,
        .is_sub_reply,
        @sort_desc .timestamp
    ) limit page_size;
}

query count_topics_by_user(name): integer {
    return topic@*{ .author.name == name }( .id ).size();
}

query count_replies_by_user(name): integer {
    return topic_reply@*{ .author.name == name }( .id ).size();
}

query get_sub_replies(username: name, parent_reply_id: text) {	
    val replies = sub_reply@*{ .parent_reply.id == parent_reply_id } (
        id= .child_reply.id,
        author= .child_reply.author.display_name,
        message= .child_reply.message,
        is_sub_reply= .child_reply.is_sub_reply,
        @sort timestamp= .child_reply.timestamp
    );
   
   val ext_replies = list&lt;ext_topic_reply&gt;();
    for (reply in replies) {
    	val moderated_by = topic_reply_moderation @*{ .topic_reply.id == reply.id } ( .user.name );
    	val ext_reply = ext_topic_reply (
    		id = reply.id,
    		author = reply.author,
    		message = reply.message,
    		is_sub_reply = reply.is_sub_reply,
    		timestamp = reply.timestamp,
    		moderated_by = moderated_by
    	);
    	ext_replies.add(ext_reply);
    }
    
    return ext_replies;
}

query get_topics_by_user_id_prior_to_timestamp(name, timestamp, page_size: integer) {
    val topics = topic@*{
        user.user@{ .name == name },
        .last_modified &lt; timestamp
    }(
        .id,
        author= .author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_from_follows_after_timestamp(name, timestamp, page_size: integer) {
    val topics = (topic, follow.follow)@*{
            follow.follower.name == name.lower_case(),
            follow.follows == topic.author,
            topic.last_modified &gt; timestamp
    }(
        topic.id,
        author=topic.author.display_name,
        topic.title,
        topic.message,
        @sort_desc topic.last_modified,
        topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_from_follows_prior_to_timestamp(name, timestamp, page_size: integer) {
    val topics = (topic, follow.follow) @* {
        follow.follower.name == name.lower_case(),
        follow.follows == topic.author,
        topic.last_modified &lt; timestamp
    }(
        topic.id,
        author = topic.author.display_name,
        topic.title,
        topic.message,
        @sort_desc topic.last_modified,
        topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topic_by_id(username: name, id: text) {
    val topic = topic@{ .id == id }(
        .id,
        author = .author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    );
    
    val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
	return ext_topic (
		id = topic.id,
		author = topic.author,
		title = topic.title,
		message = topic.message,
		timestamp = topic.timestamp,
		last_modified = topic.last_modified,
		latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
		moderated_by = moderated_by
	);
}

query get_all_topics_by_stars_since_timestamp(timestamp, page_size: integer) {
    val topics = rating.tmp_topic_rating@*{
        .topic.last_modified &gt; timestamp
    } (
        @sort_desc .stars,
        id = .topic.id,
        author=.topic.author.display_name,
        title=.topic.title,
        message=.topic.message,
        last_modified=.topic.last_modified,
        timestamp=.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_by_follows_and_stars_since_timestamp(name, timestamp, page_size: integer) {
    val topics = (rating.tmp_topic_rating, follow.follow) @*{
            follow.follower.name == name,
            tmp_topic_rating.topic.author == follow.follows,
            tmp_topic_rating.topic.last_modified &gt; timestamp
        } (
        @sort_desc tmp_topic_rating.stars,
        id = tmp_topic_rating.topic.id,
        author = tmp_topic_rating.topic.author.display_name,
        title = tmp_topic_rating.topic.title,
        message = tmp_topic_rating.topic.message,
        last_modified = tmp_topic_rating.topic.last_modified,
        timestamp = tmp_topic_rating.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_by_channel_after_timestamp_sorted_by_popularity(name, timestamp, page_size: integer) {
    val topics = (rating.tmp_topic_rating, channel.channel)@*{
        name == channel.name,
        tmp_topic_rating.topic == channel.topic,
        tmp_topic_rating.topic.last_modified &gt; timestamp
    } (
        @sort_desc .stars,
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        last_modified = channel.topic.last_modified,
        timestamp = channel.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_by_followed_channels_after_timestamp_sorted_by_popularity(name, timestamp, page_size: integer) {
    val topics = (rating.tmp_topic_rating, channel.channel_following, channel.channel)@*{
        channel_following.user == user.user@{ name },
        channel_following.name == channel.name,
        tmp_topic_rating.topic == channel.topic,
        tmp_topic_rating.topic.last_modified &gt; timestamp
    } (
        @sort_desc .stars,
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        last_modified = channel.topic.last_modified,
        timestamp = channel.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}</string>
                            </entry>
                            <entry key="topic/rating/index.rell">
                                <string>import user;
import topic;

entity topic_star_rating {
    key topic.topic, user.user;
}

// To be deleted when GROUP BY and COUNT is supported, then will use topic_star_rating instead
entity tmp_topic_rating {
    key topic.topic;
    mutable stars: integer;
    index stars;
}

entity reply_star_rating {
    key topic.topic_reply, user.user;
}
</string>
                            </entry>
                            <entry key="topic/rating/operations.rell">
                                <string>import user;
import topic;

operation give_topic_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_verified_user(username, descriptor_id);
    create topic_star_rating(topic.topic@{ .id == id }, user);

    val topicRating = tmp_topic_rating@{ topic.topic@{ .id == id }};
    update topicRating ( stars = topicRating.stars + 1 );
}

operation remove_topic_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_verified_user(username, descriptor_id);
    delete topic_star_rating@{ topic.topic@{ .id == id }, user };

    val topicRating = tmp_topic_rating@{ topic.topic@{ .id == id }};
    update topicRating ( stars = topicRating.stars - 1 );
}

operation give_reply_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_verified_user(username, descriptor_id);
    create reply_star_rating(topic.topic_reply@{ .id == id }, user);
}

operation remove_reply_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_verified_user(username, descriptor_id);
    delete reply_star_rating@{ topic.topic_reply@{ .id == id }, user };
}</string>
                            </entry>
                            <entry key="topic/rating/queries.rell">
                                <string>import topic;

query get_star_rating_for_topic(id: text) {
    return topic_star_rating@*{ topic.topic@{ .id == id }} ( .user.name );
}

query get_star_rating_for_reply(id: text) {
    return reply_star_rating@*{ topic.topic_reply@{ .id == id }} ( .user.name );
}

query count_user_topic_star_rating(name): integer {
    return topic_star_rating@*{ .topic.author.name == name } ( .topic, .user ).size();
}

query count_user_reply_star_rating(name): integer {
    return reply_star_rating@*{ .topic_reply.author.name == name } ( .topic_reply, .user ).size();
}</string>
                            </entry>
                            <entry key="topic/subscription/index.rell">
                                <string>import user;
import topic;

entity subscription {
    key topic.topic, user.user;
}
</string>
                            </entry>
                            <entry key="topic/subscription/operations.rell">
                                <string>import user;
import topic;

operation subscribe_to_topic(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_verified_user(username, descriptor_id);
    create subscription(topic.topic@{ .id == id }, user);
}

operation unsubscribe_from_topic(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_verified_user(username, descriptor_id);
    delete subscription@{ topic.topic@{ .id == id }, user };
}</string>
                            </entry>
                            <entry key="topic/subscription/queries.rell">
                                <string>import topic;

query get_subscribers_for_topic(id: text) {
    return subscription@*{ topic.topic@{ .id == id }} ( .user.name );
}</string>
                            </entry>
                            <entry key="user/distrust/index.rell">
                                <string>import user;

entity user_distrust {
    key distruster: user.user, distrusted: user.user;
}</string>
                            </entry>
                            <entry key="user/distrust/operations.rell">
                                <string>import user;

operation toggle_distrust(username: name, descriptor_id: byte_array, name, muted: boolean) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);

    if (muted) {
        create user_distrust(distruster = user, distrusted = user.user@{ .name == name });
    } else {
        delete user_distrust@{ .distruster == user, .distrusted == user.user@{ .name == name }};
    }
}
</string>
                            </entry>
                            <entry key="user/distrust/queries.rell">
                                <string>query get_distrusted_users(name) {
    return user_distrust@*{ .distruster.name == name.lower_case() } ( .distrusted.name );
}

query times_user_was_distrusted(name): integer {
	return user_distrust@*{ .distrusted.name == name } ( .distruster ).size();
}

query times_user_distrusted_someone(name): integer {
	return user_distrust@*{ .distruster.name == name } ( .distrusted ).size();
}</string>
                            </entry>
                            <entry key="user/functions.rell">
                                <string>import ft3_acc: lib.ft3.account;
import util;

function get_verified_user(name, descriptor_id: byte_array): user {
    val user = user@{ .name == name.lower_case() };
    ft3_acc.require_auth(user.account, descriptor_id, list&lt;text&gt;());
    return user;
}

function get_and_charge_verified_user(name, descriptor_id: byte_array): user {
	val user = get_verified_user(name, descriptor_id);
	ft3_acc.rate_limit(user.account);
	return user;
}</string>
                            </entry>
                            <entry key="user/index.rell">
                                <string>import ft3_acc: lib.ft3.account;

entity user {
    key name;
    index ft3_acc.account;
    display_name: name;
    registered: integer = 0;
}

entity user_suspension {
	index user;
	index suspended_by: user;
	index suspended_until: timestamp;
}

import user.settings;
import user.distrust;
</string>
                            </entry>
                            <entry key="user/operations.rell">
                                <string>import ft3_acc: lib.ft3.account;

import user.settings;

operation register_user(name, account_id: byte_array) {
    val account = ft3_acc.account @ { account_id };

    val user = create user(name = name.lower_case(), display_name = name, account, op_context.block_height);
    
    create settings.user_settings(user, avatar = "" , description = "");
}
</string>
                            </entry>
                            <entry key="user/queries.rell">
                                <string>import ft3_acc: lib.ft3.account;

query get_user(name) {
    return user@?{ .name == name.lower_case() } ( name = .display_name );
}

query get_account_id(name) {
    return user@?{ .name == name.lower_case() } ( .account.id );
}

query get_registered_at(name) {
	return user@{ .name == name.lower_case() } ( .registered );
}

query username_by_account_id(id: byte_array): name? {
	val account = ft3_acc.account@? { id };
	if (account != null) {
		return user@?{ .account == account } ( .display_name );
	}
	
	return null;
}</string>
                            </entry>
                            <entry key="user/settings/index.rell">
                                <string>import user;

entity user_settings {
    key user.user;
    mutable avatar: text;
    mutable description: text;
}
</string>
                            </entry>
                            <entry key="user/settings/operations.rell">
                                <string>import user;

operation create_user_settings(name, descriptor_id: byte_array, avatar: text, description: text) {
    val user = user.get_verified_user(name, descriptor_id);
    create user_settings(user, avatar = avatar, description = description);
}

operation update_user_settings(name, descriptor_id: byte_array, avatar: text, description: text) {
    val user = user.get_verified_user(name, descriptor_id);
    update user_settings@{ .user == user }( avatar = avatar, description = description );
}
</string>
                            </entry>
                            <entry key="user/settings/queries.rell">
                                <string>import user;

query get_user_settings(name) {
    return user_settings@?{ user.user@{ .name == name }} ( .avatar, .description );
}
</string>
                            </entry>
                            <entry key="util/log.rell">
                                <string>enum error_type {
	USER_UNAUTHORIZED,
	USER_SUSPENDED,
	TOPIC_IMMUTABLE,
	REPRESENTATIVE_ALREADY_SUSPENDED,
	ILLEGAL_ACTION,
	EXPECTED_ERROR
}

function app_error(error_type, action: text): text {
	val msg = when(error_type) {
		USER_UNAUTHORIZED -&gt; message_with_code("CERR_10", "Requester was unauthorized", action);
		USER_SUSPENDED -&gt; message_with_code("CERR_11", "Requester was suspended", action);
		TOPIC_IMMUTABLE -&gt; message_with_code("CERR_20", "Topic is no longer mutable", action);
		REPRESENTATIVE_ALREADY_SUSPENDED -&gt; message_with_code("CERR_30", "User was already suspended", action);
		ILLEGAL_ACTION -&gt; message_with_code("CERR_40", "The attempted action was illegal", action);
		EXPECTED_ERROR -&gt; message_with_code("CERR_50", "Expected error", action);
	};
	
	log(msg);
	return msg;
}

function message_with_code(code: text, message: text, action: text): text {
	return '{"code":"' + code + '","message":"' + message + '","action":"' + action + '"}';
}</string>
                            </entry>
                        </dict>
                    </entry>
                </dict>
            </entry>
        </dict>
    </entry>
    <entry key="signers">
        <array>
            <bytea>0350FE40766BC0CE8D08B3F5B810E49A8352FDD458606BD5FAFE5ACDCDC8FF3F57</bytea>
        </array>
    </entry>
</dict>
   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
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dict>
    <entry key="blockstrategy">
        <dict>
            <entry key="name">
                <string>net.postchain.base.BaseBlockBuildingStrategy</string>
            </entry>
        </dict>
    </entry>
    <entry key="configurationfactory">
        <string>net.postchain.gtx.GTXBlockchainConfigurationFactory</string>
    </entry>
    <entry key="gtx">
        <dict>
            <entry key="modules">
                <array>
                    <string>net.postchain.rell.module.RellPostchainModuleFactory</string>
                    <string>net.postchain.gtx.StandardOpsGTXModule</string>
                </array>
            </entry>
            <entry key="rell">
                <dict>
                    <entry key="moduleArgs">
                        <dict>
                            <entry key="lib.ft3.core">
                                <dict>
                                    <entry key="my_blockchain_description">
                                        <string>Decentralized reddit</string>
                                    </entry>
                                    <entry key="my_blockchain_name">
                                        <string>Chromunity</string>
                                    </entry>
                                    <entry key="my_blockchain_website">
                                        <string>testnet.chromunity.com</string>
                                    </entry>
                                    <entry key="rate_limit_active">
                                        <int>1</int>
                                    </entry>
                                    <entry key="rate_limit_max_points">
                                        <int>10</int>
                                    </entry>
                                    <entry key="rate_limit_points_at_account_creation">
                                        <int>5</int>
                                    </entry>
                                    <entry key="rate_limit_recovery_time">
                                        <int>60000</int>
                                    </entry>
                                </dict>
                            </entry>
                        </dict>
                    </entry>
                    <entry key="modules">
                        <array>
                            <string></string>
                        </array>
                    </entry>
                    <entry key="sources_v0.10">
                        <dict>
                            <entry key="channel/index.rell">
                                <string>import user;
import topic;

entity channel {
    key name, topic.topic;
    index timestamp;
    display_name: name;
}

entity channel_following {
    key user.user, name;
}
</string>
                            </entry>
                            <entry key="channel/operations.rell">
                                <string>import user;

operation follow_channel(username: text, descriptor_id: byte_array, name) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create channel_following(user, name.lower_case());
}

operation unfollow_channel(username: text, descriptor_id: byte_array, name) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    delete channel_following@{ user, name.lower_case()};
}</string>
                            </entry>
                            <entry key="channel/queries.rell">
                                <string>import user;
import topic;

query get_topics_by_channel_prior_to_timestamp(name, timestamp, page_size: integer) {
    val topics = channel@*{
        .name == name,
        .topic.last_modified &lt; timestamp
    } (
        id = .topic.id,
        author = .topic.author.display_name,
        title = .topic.title,
        message = .topic.message,
        timestamp = .topic.timestamp,
        @sort_desc last_modified = .topic.last_modified
    ) limit page_size;
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query get_topics_by_channel_after_timestamp(name, timestamp) {
    val topics = channel@*{
        .name == name,
        .topic.last_modified &gt; timestamp
    } (
        id = .topic.id,
        author = .topic.author.display_name,
        title = .topic.title,
        message = .topic.message,
        timestamp = .topic.timestamp,
        @sort_desc last_modified = .topic.last_modified
    );
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query count_topics_by_channel(name) {
    return channel@*{ .name == name } ( .name ).size();
}

query count_channel_followers(name) {
    return channel_following@*{ .name == name } ( .user.name ).size();
}

query get_topics_by_followed_channels_prior_to_timestamp(username: text, timestamp, page_size: integer) {
    val user = user.user@{ .name == username};
    val topics = (channel, channel_following)@*{
        channel_following.user == user,
        channel_following.name == channel.name,
        channel.topic.last_modified &lt; timestamp
    }
    (
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        timestamp = channel.topic.timestamp,
        @sort_desc last_modified = channel.topic.last_modified
    ) limit page_size;
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query get_topics_by_followed_channels_after_timestamp(username: text, timestamp, page_size: integer) {
    val user = user.user@{ .name == username};
    val topics = (channel, channel_following)@*{
        channel_following.user == user,
        channel_following.name == channel.name,
        channel.topic.last_modified &gt; timestamp
    }
    (
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        timestamp = channel.topic.timestamp,
        @sort_desc last_modified = channel.topic.last_modified
    ) limit page_size;
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query get_followed_channels(username: text) {
    val user = user.user@{ .name == username};
    return channel_following@*{ user } ( .name );
}

query get_all_channels() {
    return channel@*{} ( .display_name );
}

query get_channels_since(timestamp) {
    return channel@*{ .timestamp &gt; timestamp }( .display_name );
}

query get_topic_channels_belongings(topic_id: text) {
    return channel@*{ topic.topic@{ .id == topic_id }} ( .display_name );
}
</string>
                            </entry>
                            <entry key="chat/index.rell">
                                <string>import user;

entity chat {
	key id: text;
	mutable title: text;
	timestamp;
}

entity chat_user {
	key user.user;
	rsa_pubkey: text;
}

entity chat_membership {
	key chat, member: chat_user;
	encrypted_chat_key: text;
	mutable last_opened: timestamp = 0;
}

entity chat_message {
	index chat;
	index sender: chat_user;
	index timestamp;
	encrypted_msg: text;
}

struct chat_record {
	id: text;
	title: text;
	last_message: message_record?;
	encrypted_chat_key: text;
	timestamp;
	last_opened: timestamp;
}

struct message_record {
	sender: name;
	timestamp;
	encrypted_msg: text;
}
</string>
                            </entry>
                            <entry key="chat/operations.rell">
                                <string>import user;
import util;

operation create_chat(chat_id: text, descriptor_id: byte_array, username: text, title: text, encrypted_chat_key: text) {
	val founder = user.get_and_charge_verified_user(username, descriptor_id);

	val chat = create chat(id = chat_id, title = title, timestamp = op_context.last_block_time);
	create chat_membership(chat, chat_user@{ .user == founder }, encrypted_chat_key);
}

operation create_chat_user(descriptor_id: byte_array, username: text, rsa_pubkey: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	create chat_user(user, rsa_pubkey);
}

operation delete_chat_user(descriptor_id: byte_array, username: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	val chat_user = chat_user@?{ user };

	if (chat_user != null) {
		delete chat_membership@*{ .member == chat_user };
		delete chat_message@*{ .sender == chat_user };
		delete chat_user;
	}
}

operation add_user_to_chat(descriptor_id: byte_array, username: text, chat_id: text, target_user: text, encrypted_chat_key: text) {
	val user_already_in_chat = user.get_and_charge_verified_user(username, descriptor_id);
	val chat = chat@{ .id == chat_id };

	if (chat_membership@?{ chat, .member.user.name == target_user.lower_case() } == null) {
		create chat_membership(chat, chat_user@{ .user.name == target_user.lower_case() }, encrypted_chat_key);
	}
}

operation leave_chat(descriptor_id: byte_array, username: text, chat_id: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	val chat = chat@{ .id == chat_id };

	delete chat_membership@{ chat, chat_user@{ user }};

	if (chat_membership@*{ chat } ( .member ).size() == 0) {
		delete chat_message@*{ chat };
		delete chat;
	}
}

operation modify_chat_title(descriptor_id: byte_array, username: text, chat_id: text, title: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	val chat = chat@{ .id == chat_id };
	chat_membership@{ chat, chat_user@{ user }};
	update chat(title = title);
}

operation send_chat_message(chat_id: text, descriptor_id: byte_array, username: name, encrypted_msg: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);

	val chat = chat@{ .id == chat_id };
	val chat_user = chat_user@{ user };
	val chat_member = chat_membership@?{ chat, chat_user };
	require(chat_member != null, util.app_error(util.error_type.USER_UNAUTHORIZED, "Only a chat member can send a message"));

	create chat_message(chat, chat_user, op_context.last_block_time, encrypted_msg);
}

operation update_last_opened_timestamp(chat_id: text, descriptor_id: byte_array, username: name) {
	val user = user.get_verified_user(username, descriptor_id);
	update chat_membership@{
		.chat.id == chat_id,
		.member.user == user
	} ( last_opened = op_context.last_block_time );
}
</string>
                            </entry>
                            <entry key="chat/queries.rell">
                                <string>import follow;

query get_chat_user_pubkey(username: name): text? {
	return chat_user@?{ .user.name == username.lower_case() } ( .rsa_pubkey );
}

query get_user_chats(username: name): list&lt;chat_record&gt; {

	val member_chats = chat_membership@*{ .member.user.name == username.lower_case() };
	val chat_records = list&lt;chat_record&gt;();

	for (member_chat in member_chats) {
		val latest_message = chat_message@?{ .chat == member_chat.chat } ( .sender, @sort_desc .timestamp, .encrypted_msg, @sort_desc .chat.timestamp ) limit 1;

		if (latest_message != null) {
			val message = message_record(sender = latest_message.sender.user.display_name, timestamp = latest_message.timestamp, encrypted_msg = latest_message.encrypted_msg);
			chat_records.add(chat_record(
				id = member_chat.chat.id,
				title = member_chat.chat.title,
				last_message = message,
				encrypted_chat_key = member_chat.encrypted_chat_key,
				timestamp = member_chat.chat.timestamp,
				last_opened = member_chat.last_opened
			));
		} else {
			chat_records.add(chat_record(
				id = member_chat.chat.id,
				title = member_chat.chat.title,
				last_message = null,
				encrypted_chat_key = member_chat.encrypted_chat_key,
				timestamp = member_chat.chat.timestamp,
				last_opened = member_chat.last_opened
			));
		}

	}

	return chat_records;
}

query get_chat_messages(id: text, prior_to: timestamp, page_size: integer) {
	return chat_message@*{ .chat.id == id, .timestamp &lt; prior_to } (
		sender = chat_message.sender.user.display_name,
		@sort_desc timestamp = chat_message.timestamp,
		encrypted_msg = chat_message.encrypted_msg
	) limit page_size;
}

query get_chat_messages_after(id: text, after_timestamp: timestamp, page_size: integer) {
	return chat_message@*{ .chat.id == id, .timestamp &gt; after_timestamp } (
		sender = chat_message.sender.user.display_name,
		@sort timestamp = chat_message.timestamp,
		encrypted_msg = chat_message.encrypted_msg
	) limit page_size;
}

query get_chat_participants(id: text) {
	return chat_membership@*{ .chat.id == id } ( .member.user.display_name );
}

query get_followed_chat_users(username: name) {
	return (chat_user, follow.follow)@*{
		follow.follower.name == username.lower_case(),
		follow.follows == chat_user.user
	} ( chat_user.user.display_name );
}

query get_chat_users() {
	return chat_user@*{} ( chat_user.user.display_name );
}

query count_unread_chats(username: name) {
	val my_user = username.lower_case();
	return set&lt;chat&gt;((chat_membership, chat_message)@*{
		chat_membership.member.user.name == my_user,
		chat_message.timestamp &gt; chat_membership.last_opened,
		chat_membership.chat == chat_message.chat,
		chat_message.sender.user.name != my_user
	} ( chat_membership.chat )).size();
}</string>
                            </entry>
                            <entry key="election/index.rell">
                                <string>import user;
import topic;

entity representative_election {
    key id: integer;
    index timestamp;
    mutable completed: boolean;
    index completed;
}

entity election_block_details {
	key started_height: integer;
	mutable finished_height: integer = -1;
	index representative_election;
}

entity representative_election_candidate {
  key representative_election, user.user;
}

entity representative_election_vote {
    key user.user, representative_election_candidate;
}

entity temp_votes_counter {
	key representative_election_candidate;
	mutable votes: integer;
}

function is_eligible_to_vote(user.user): boolean {
	val prev_election_id = get_latest_completed_election_id();
	
	val current_election_id = get_current_election_id();
	
	if (current_election_id == null) {
		return false;
	} else if (prev_election_id == null) {
		return true;
	}
	
	val current_election_start = (election_block_details, block)@{ 
		election_block_details.representative_election.id == current_election_id,
		election_block_details.started_height == block.block_height
	} ( 
		block.timestamp
	);
	
	if (user.registered &gt; current_election_start) {
		log("Not elgible for voting: User registered after election start");
		return false; 
	}
	
	val previous_election_completed = (representative_election, election_block_details, block)@?{
		representative_election == election_block_details.representative_election,
		representative_election.completed == true,
		block.block_height == election_block_details.finished_height
	} ( 
		block.timestamp,
		@omit @sort_desc representative_election.timestamp
	) limit 1;
	
	if (previous_election_completed != null) {
		log("A previous election was held, so verifying correct number of posts");
		val number_of_topics = topic.topic@*{ 
			.author == user,
			.last_modified &gt; previous_election_completed,
			.last_modified &lt; current_election_start
		}( .id ).size();
		
		val number_of_replies = topic.topic_reply@*{
			.author == user,
			.timestamp &gt; previous_election_completed,
			.timestamp &lt; current_election_start
		}( .id ).size();
		
		return number_of_topics + number_of_replies &gt;= 5;
	}
	
	return true;
}

function governing_period_in_blocks(): integer {
	return 75000;
}

function election_duration_in_blocks(): integer {
	return 25000;
}

function get_current_election_id(): integer? {
	return representative_election@?{ .completed == false } ( @omit @sort_desc .timestamp, .id ) limit 1;
}

function get_latest_completed_election_id(): integer? {
	return representative_election@?{ .completed == true } ( .id, @omit @sort_desc .timestamp ) limit 1;
}</string>
                            </entry>
                            <entry key="election/operations.rell">
                                <string>import user;
import util;
import representative;

operation process_election() {
	var something_done = false;
	
	val current_block = op_context.block_height;
	val election_period_in_blocks = election_duration_in_blocks();
	val governing_period_in_blocks = governing_period_in_blocks();
	
	val election_block_details = election_block_details@?{} ( @sort_desc .started_height, .finished_height ) limit 1;
	
	if (election_block_details == null) {
		log("No election held yet, triggering new one");
		create_election_at_height(current_block);
		something_done = true;
	} else if (election_block_details.finished_height &gt;= 0 and election_block_details.finished_height + governing_period_in_blocks &lt; current_block) {
		log("Triggering a new election");
		create_election_at_height(current_block);
		something_done = true;
	} else if (election_block_details.finished_height == -1 
		and election_block_details.started_height + election_period_in_blocks &lt; current_block
	) {
		log("Wrapping up election");
		complete_election();
		something_done = true;
	}
	
	require(something_done, util.app_error(util.error_type.EXPECTED_ERROR, "Nothing done while processing of elections"));
}

function create_election_at_height(height: integer) {
	val election = create representative_election(
			id = height,
			timestamp = op_context.last_block_time, 
			false
		);
		create election_block_details(started_height = height, election);
}

function complete_election() {
	val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
	
    val current_election = representative_election@{ .id == current_election_id };
    update current_election ( completed = true );
    update election_block_details@{ current_election } ( finished_height = op_context.block_height );
    
    val nr_of_participants = temp_votes_counter@*{} ( 
    	.representative_election_candidate.user.name
    ).size();
    
    val new_representatives = temp_votes_counter@*{ 
    	.representative_election_candidate.representative_election == current_election
    } (
    	@sort_desc @omit .votes,
    	.representative_election_candidate.user
    ) limit integer((nr_of_participants * 0.1).ceil());

    for (user in new_representatives) {
        create representative.representative(user, current_election);
    }
}

operation vote_for_candidate(voter: name, descriptor_id: byte_array, candidate: name) {
	require(voter != candidate, util.app_error(util.error_type.ILLEGAL_ACTION, "You can't vote for yourself"));
    val user = user.get_and_charge_verified_user(voter, descriptor_id);

	require(is_eligible_to_vote(user), util.app_error(util.error_type.ILLEGAL_ACTION, "Not eligible for voting in the election"));

    val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
    
    clean_up_votes(user, current_election_id);
    
    val vote = create representative_election_vote(
        user,
        representative_election_candidate@{ 
        	user.user@{ .name == candidate }, 
        	.representative_election.id == current_election_id
        }
    );
    
    update temp_votes_counter@ {
    	vote.representative_election_candidate
    } ( votes += 1 );
}

operation sign_up_for_election(name, descriptor_id: byte_array) {
    val user = user.get_and_charge_verified_user(name, descriptor_id);
	val election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));

    val candidate = create representative_election_candidate(
    	representative_election@{ .id == election_id }, 
    	user
    );
    
    create temp_votes_counter(candidate, 0);
}

function clean_up_votes(user.user, id: integer) {
	val old_candidate_votes = representative_election_vote@*{ 
    	user,
    	.representative_election_candidate.representative_election.id == id
    };
	for (old_candidate_vote in old_candidate_votes) {
	    
	    update temp_votes_counter@ {
	    	old_candidate_vote.representative_election_candidate
	    } ( votes -= 1 );
	    
	   	delete old_candidate_vote;
	}
}</string>
                            </entry>
                            <entry key="election/queries.rell">
                                <string>import user;
import util;

query eligible_for_voting(name): boolean {
	val user = user.user@{ .name == name.lower_case() };
	return is_eligible_to_vote(user);
}

query get_election_candidates() {
	val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
	
    return temp_votes_counter@*{
        .representative_election_candidate.representative_election.id == current_election_id
    } ( 
    	@omit @sort_desc .votes,
    	.representative_election_candidate.user.display_name
    );
}

query get_next_election() {
    return representative_election@?{ .completed == false } ( .id, @sort_desc .timestamp ) limit 1;
}

query get_uncompleted_election() {
    return get_current_election_id();
}

query get_user_vote_in_election(name) {
	val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
	
    return representative_election_vote@?{
        .user == user.user@{ .name == name },
        .representative_election_candidate.representative_election.id == current_election_id
    } ( .representative_election_candidate.user.name ) limit 1;
}

query get_current_representative_period(timestamp) {
    return representative_election @? { .timestamp &lt;= timestamp, .completed == true } ( .id, @sort_desc .timestamp ) limit 1;
}

query blocks_until_next_election() {
	val recent_election_finished = election_block_details@?{} ( 
		@omit @sort_desc .started_height, 
		.finished_height
	) limit 1;
	
	if (recent_election_finished == null) {
		return 0;
	}
	
	require(recent_election_finished != -1, "There is an ongoing election");
	
	val next_election_block = recent_election_finished + governing_period_in_blocks();
	
	var current_block = block@?{} ( @sort_desc .block_height ) limit 1;
	
	if (current_block == null) {
		current_block = 0;
	}
	
	return next_election_block - current_block;
}

query blocks_until_election_wraps_up() {
	val recent_election = election_block_details@{} ( 
		@sort_desc .started_height, 
		.finished_height
	) limit 1;
	
	require(recent_election.finished_height == -1, "There is no ongoing election");
	
	val election_finishing_block = recent_election.started_height + election_duration_in_blocks();
	
	var current_block = block@?{} ( @sort_desc .block_height ) limit 1;
	
	if (current_block == null) {
		current_block = 0;
	}
	
	return election_finishing_block - current_block;
}
</string>
                            </entry>
                            <entry key="follow/index.rell">
                                <string>import user;

entity follow {
    key follower: user.user, follows: user.user;
}
</string>
                            </entry>
                            <entry key="follow/operations.rell">
                                <string>import user;
import util;

operation create_following(follower: text, descriptor_id: byte_array, follows: text) {
    require(follower != follows, util.app_error(util.error_type.ILLEGAL_ACTION, "Follow another user"));
    val user = user.get_and_charge_verified_user(follower, descriptor_id);
    create follow(follower = user, follows = user.user@{ .name == follows.lower_case() });
}

operation remove_following(follower: text, descriptor_id: byte_array, follows: text) {
    require(follower != follows, util.app_error(util.error_type.ILLEGAL_ACTION, "You can't unfollow yourself"));
    val user = user.get_and_charge_verified_user(follower, descriptor_id);
    delete follow@{ .follower == user, .follows == user.user@{ .name == follows.lower_case() } };
}
</string>
                            </entry>
                            <entry key="follow/queries.rell">
                                <string>import user;

query get_user_followers(name) {
    return follow@*{ .follows == user.user @ { .name == name } }( .follower.name );
}

query get_user_follows(name) {
    return follow@*{ .follower == user.user@{ .name == name } } ( .follows.name );
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/auth_basic.rell">
                                <string>// Auth type:

// "S" - single-sig
// "M" - multi-sig

struct single_sig_args {
       flags: set&lt;text&gt;;
       pubkey;
}

struct multi_sig_args {
       flags: set&lt;text&gt;;
       signatures_required: integer;
       pubkeys: list&lt;pubkey&gt;;
}

function check_single_sig_auth(args: byte_array, participants: list&lt;byte_array&gt;, required_flags: list&lt;text&gt;): boolean {
    require(participants.size() == 1);
    val ss_args = single_sig_args.from_bytes(args);
    return
          ss_args.flags.contains_all(required_flags)
            and
          is_signer(participants[0]);
}

function check_multi_sig_auth(args: byte_array, participants: list&lt;byte_array&gt;, required_flags: list&lt;text&gt;): boolean {
   val multi_sign_args = multi_sig_args.from_bytes(args);
   if (not (multi_sign_args.flags.contains_all(required_flags))) return false;
   var num_sign = multi_sign_args.signatures_required;
   for(s in participants) {
      if(is_signer(s)) {
          num_sign -= 1;
          if(num_sign &lt; 1) {return true;}
      }
   }
   return false;
}

function check_auth_args (a_t: text, args: byte_array, participants: list&lt;byte_array&gt;, required_flags: list&lt;text&gt;): boolean {
    return when (a_t) {
        "S" -&gt; check_single_sig_auth(args, participants, required_flags);
        "M" -&gt; check_multi_sig_auth(args, participants, required_flags);
        else -&gt; false;
    };
}



function require_auth (account, descriptor_id: byte_array, required_flags: list&lt;text&gt;) {
   val account_auth_descriptor = account_auth_descriptor @ {
     account,
     .descriptor_id == descriptor_id
   };
	
	require(is_valid(account_auth_descriptor));
	
   	require(
		check_auth_args(
       		account_auth_descriptor.auth_type,
       		account_auth_descriptor.args,
       		auth_descriptor_participant @* { account_auth_descriptor } ( .id ),
       		required_flags
		)
   );
   
   update_auth_descriptor_rule_variables(account_auth_descriptor);
   delete_expired_auth_descriptors(account);
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/auth_descriptor_rule.rell">
                                <string>
enum rule_variable {
	block_height,
	block_time,
	op_count
}

enum rule_operator {
	lt,
	le,
	eq,
	ge,
	gt
}

struct rule_expression {
	variable: text;
	operator: text;
	value: gtv;
}

entity auth_descriptor_rule_variable {
	key account_auth_descriptor, name;
	mutable value: byte_array;
}

function is_valid(auth_descriptor: account_auth_descriptor): boolean {
	// check if rules is null (encoded null is equal to 0xa0020500)
	if (auth_descriptor.rules == x'a0020500') {
		return true;
	}
	
	return is_rule_valid(
		gtv.from_bytes(auth_descriptor.rules), 
		load_variables(auth_descriptor)
	);
}

function is_rule_valid(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(rule);
	val operator = text.from_gtv(parameters[1]);
	
	if (operator == "and") {
		return handle_composed_rule(rule, variables);
	} else {
		return handle_single_rule(rule, variables);
	}
}

function handle_single_rule(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	return evaluate_int_variable_rule(
		rule_expression.from_gtv(rule), 
		variables
	);	
}

 
function handle_composed_rule(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(rule);
	val operator = text.from_gtv(parameters[1]);
	if (operator == "and") {
		return is_rule_valid(parameters[0], variables) and is_rule_valid(parameters[2], variables);
	} else {
		return false;
	}
}



function is_active(account_auth_descriptor): boolean {
	if (account_auth_descriptor.rules == x'a0020500') {
		return true;
	}
	
	return is_rule_active(gtv.from_bytes(account_auth_descriptor.rules), map&lt;text, gtv&gt;());
}


function is_rule_active(r: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(r);
	val operator = text.from_gtv(parameters[1]);
	when (operator) {
		"and" -&gt; {
			return is_rule_active(parameters[0], variables) and is_rule_active(parameters[2], variables);
		}
		else -&gt; {
			return is_simple_rule_active(r, variables);
		}
	}
}

function is_simple_rule_active(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(rule);
	val variable_name = text.from_gtv(parameters[0]);
	when (rule_variable.value(variable_name)) {
		rule_variable.block_height -&gt; {
			return is_block_height_rule_active(rule);
		}
		rule_variable.block_time -&gt; {
			return is_block_time_rule_active(rule);
		}		
		rule_variable.op_count -&gt; {
			return is_op_count_rule_active(rule);
		}
	}
}

/*
 *  Variables
 */

function evaluate_int_variable_rule(rule: rule_expression, variables: map&lt;text, gtv&gt;): boolean {
	val variable = rule_variable.value(rule.variable);
	val operator = rule_operator.value(rule.operator);
	val current_value = variable_value(variable, variables);
	val defined_value = integer.from_gtv(rule.value);

	when (operator) {
		rule_operator.lt -&gt; {
			return current_value &lt; defined_value;
		}
		rule_operator.le -&gt; {
			return current_value &lt;= defined_value;
		}
		rule_operator.eq -&gt; {
			return current_value == defined_value;
		}
		rule_operator.ge -&gt; {
			return current_value &gt;= defined_value;
		}
		rule_operator.gt -&gt; {
			return current_value &gt; defined_value;
		}
	}
}


/*
 * Called from _add_auth_descriptor function
 */
function setup_auth_descriptor_variables(account_auth_descriptor) {
	
	if (account_auth_descriptor.rules == x'a0020500') {
		return;
	} 
	
	val variables = get_variable_names_set(gtv.from_bytes(account_auth_descriptor.rules));
	
	for (variable in variables) {
		when (variable) {
			rule_variable.op_count.name -&gt; {
				create auth_descriptor_rule_variable(
					account_auth_descriptor,
					name = variable,
					value = op_count_variable_initial_value().to_bytes()
				);
			}
		}
	}
}
 
function update_variables(account_auth_descriptor, variables: map&lt;text, gtv&gt;) {
	for ((name, value) in variables) {
		val variable = auth_descriptor_rule_variable @ { account_auth_descriptor, name };
		val int_value = integer.from_gtv(value);
		
		when (name) {
			rule_variable.op_count.name -&gt; {
				variable.value = (int_value + 1).to_gtv().to_bytes();
			}
		}
	}
}
 
function variable_value(variable: rule_variable, variables: map&lt;text, gtv&gt;): integer {
	when (variable) {
		rule_variable.block_height -&gt; {
			return op_context.block_height;
		}
		rule_variable.block_time -&gt; {
			return op_context.last_block_time;
		}
		rule_variable.op_count -&gt; {
			return integer.from_gtv(variables[rule_variable.op_count.name]);
		}
	}
}

/*
 * Analyze the rules before assigning them to an authenticator descriptor
 */
 function analyze_auth_descriptor_rules(rules: gtv, hop: integer) {
 	require(hop&lt;3, "too many rules");
 	val rules_bytes = rules.to_bytes(); 
 	if (rules_bytes == x'a0020500') {
		return;
	}
	
 	val params = list&lt;gtv&gt;.from_gtv(rules);
 	require(params.size() &lt;=3);
 	
 	val operator = text.from_gtv(params[1]);
 	if(operator == "and") {
 		analyze_auth_descriptor_rules(params[0], hop+1); 
 		analyze_auth_descriptor_rules(params[2], hop+1);
 	} 	
 	
	return;
 }

/*
 * Returns set of variable names used in a rule
 */
function get_variable_names_set(rules: gtv): set&lt;text&gt; {
	val parameters = list&lt;gtv&gt;.from_gtv(rules);
	val operator = text.from_gtv(parameters[1]);
	var vars = set&lt;text&gt;();
	if (operator == "and") {
		vars.add_all(get_variable_names_set(parameters[0]));
		vars.add_all(get_variable_names_set(parameters[2]));
	} else {
		vars.add(text.from_gtv(parameters[0]));
	}
	return vars;
} 

function load_variables(account_auth_descriptor): map&lt;text, gtv&gt; {
	val variables = auth_descriptor_rule_variable @* { account_auth_descriptor };
	
	val variables_map = map&lt;text, gtv&gt;();
	for (variable in variables) {
		variables_map[variable.name] = gtv.from_bytes(variable.value);
	}
	
	return variables_map;
}

function update_auth_descriptor_rule_variables(account_auth_descriptor) {
	val variables = load_variables(account_auth_descriptor);
	update_variables(account_auth_descriptor, variables);
}

/*
 * auth descriptor cleanup
 */

function delete_expired_auth_descriptors(account) {
	val auth_descriptors = account_auth_descriptor @* { account };
	
	for (auth_descriptor in auth_descriptors) {
		if (not (is_active(auth_descriptor) and is_valid(auth_descriptor))) {
			_delete_auth_descriptor(auth_descriptor);
		}
	}
}

/****************************************************************************************
 *                                     block_time                                       *
 ****************************************************************************************/

function is_block_time_rule_active(r: gtv): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(r);
	val operator = rule_operator.value(text.from_gtv(parameters[1]));
	val value = integer.from_gtv(parameters[2]);
	when (operator) {
		rule_operator.gt -&gt; {
			return op_context.last_block_time &gt; value;
		}
		rule_operator.ge,
		rule_operator.eq -&gt; {
			return op_context.last_block_time &gt;= value;
		}
		else -&gt; {
			return true;
		}
	}
}


/****************************************************************************************
 *                                  block_height                                        *
 ****************************************************************************************/

function is_block_height_rule_active(r: gtv): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(r);
	val operator = rule_operator.value(text.from_gtv(parameters[1]));
	val value = integer.from_gtv(parameters[2]);
	when (operator) {
		rule_operator.gt -&gt; {
			return op_context.block_height &gt; value;
		}
		rule_operator.ge,
		rule_operator.eq -&gt; {
			return op_context.block_height &gt;= value;
		}
		else -&gt; {
			return true;
		}
	}
}


/****************************************************************************************
 *                                     op_count                                         *
 ****************************************************************************************/
 
 function op_count_variable_initial_value(): gtv {
 	return (1).to_gtv();
 }
 
 function is_op_count_rule_active(rule: gtv): boolean {
 	return true;
 }</string>
                            </entry>
                            <entry key="lib/ft3/account/module.rell">
                                <string>@mount('ft3')
module;

import core: ^.core;

struct auth_descriptor {
    auth_type: text;
    participants: list&lt;byte_array&gt;;
    args: list&lt;gtv&gt;;
    rules: gtv;
}

entity account {
    key id: byte_array;
}

entity account_meta {
    meta_key: text;
    value: byte_array;
    index account, meta_key;
    index meta_key, value;
}

entity account_auth_descriptor {
     descriptor_id: byte_array;
     key account, descriptor_id;
     index descriptor_id;
     auth_type: text;
     args: byte_array;
     rules: byte_array;
}

entity auth_descriptor_participant {
    key account_auth_descriptor, id: byte_array;
}


// rate limiter
entity rl_state {
    key account;
    mutable points: integer;
    mutable last_update: timestamp;
    mutable max_points: integer;
    mutable recovery_time: timestamp;
}

function _add_auth_descriptor (account, auth_descriptor) {
     val descriptor_id = auth_descriptor.hash();
     
     analyze_auth_descriptor_rules(auth_descriptor.rules, 0);
     
     val account_auth_descriptor = create account_auth_descriptor (
        account, descriptor_id,
        auth_descriptor.auth_type,
        args = auth_descriptor.args.to_gtv().to_bytes(),
        rules = auth_descriptor.rules.to_gtv().to_bytes()
     );
     
     for (participant in auth_descriptor.participants) {
        require(is_signer(participant));
        create auth_descriptor_participant(account_auth_descriptor, id = participant);
     }
     
     setup_auth_descriptor_variables(account_auth_descriptor);
}

function _delete_auth_descriptor(auth_descriptor: account_auth_descriptor) {
	delete auth_descriptor_rule_variable @* { auth_descriptor };
	delete auth_descriptor_participant @* { auth_descriptor };
	delete auth_descriptor;
}

function _delete_all_auth_descriptors_exclude(account, auth_descriptor_id: byte_array) {
	delete (adrv: auth_descriptor_rule_variable, ad: account_auth_descriptor) @* {
		ad.account == account, ad.descriptor_id != auth_descriptor_id, adrv.account_auth_descriptor == ad		
	};
	
	delete (adp: auth_descriptor_participant, ad: account_auth_descriptor) @* {
        ad.account == account and ad.descriptor_id != auth_descriptor_id and adp.account_auth_descriptor == ad
    };

    delete account_auth_descriptor @* {
       .account == account,
       .descriptor_id != auth_descriptor_id
    };
}

function create_account_with_auth (auth_descriptor): byte_array {
     val id = auth_descriptor.hash();
     val acc = create account (id);
     _add_auth_descriptor(
        acc, auth_descriptor
     );
     val max_points = core.my_blockchain_info.rate_limit_max_points;
     val recovery_time = core.my_blockchain_info.rate_limit_recovery_time;
     val points_at_start = core.my_blockchain_info.rate_limit_points_at_account_creation;
     
	create rl_state(acc, .points = points_at_start, .last_update = op_context.last_block_time, max_points, recovery_time);
    
    return id;
}

function auth_and_log(account_id: byte_array, auth_descriptor_id: byte_array, required_flags: list&lt;text&gt;): account {
	val account = account @ { .id == account_id };
	rate_limit(account);
	require_auth(account, auth_descriptor_id, required_flags);
	return account;
}

query is_auth_descriptor_valid(account_id: byte_array, auth_descriptor_id: byte_array) {
    return is_valid(account_auth_descriptor @ {
        .account.id == account_id,
        .descriptor_id == auth_descriptor_id
    });
}

query get_account_auth_descriptors(id: byte_array) {
    return account_auth_descriptor @* {
        .account.id == id
    } (
        id = .descriptor_id,
        type = .auth_type,
        args = .args
    );
}

query get_account_by_id(id: byte_array) {
    return account @? { id } ( .id );
}

query get_account_by_auth_descriptor(auth_descriptor) {
    return account @? { .id == auth_descriptor.hash() } ( .id );
}

query get_accounts_by_participant_id(id: byte_array) {
    return auth_descriptor_participant @* { id } ( .account_auth_descriptor.account.id );
}

query get_accounts_by_auth_descriptor_id(descriptor_id: byte_array) {
    return account_auth_descriptor @* { descriptor_id } ( .account.id );
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/operations/module.rell">
                                <string>@mount('ft3')
module;

import acc: ^^.account;
import core: ^^.core;


operation delete_auth_descriptor(account_id: byte_array, auth_descriptor_id: byte_array, delete_descriptor_id: byte_array) {
    val flags = if (auth_descriptor_id == delete_descriptor_id) list&lt;text&gt;() else ["A"];

    val account = acc.auth_and_log(account_id, auth_descriptor_id, flags);

    acc._delete_auth_descriptor(acc.account_auth_descriptor @ {
        .account == account,
        .descriptor_id == delete_descriptor_id
    });
}

operation delete_all_auth_descriptors_exclude(account_id: byte_array, auth_descriptor_id: byte_array) {
    val account = acc.auth_and_log(account_id, auth_descriptor_id, ["A"]);

	acc._delete_all_auth_descriptors_exclude(account, auth_descriptor_id);
}

operation add_auth_descriptor (account_id: byte_array, auth_id: byte_array, new_desc: acc.auth_descriptor) {
      val account = acc.auth_and_log(account_id, auth_id, ["A"]);
      acc._add_auth_descriptor(account, new_desc);
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/rate_limit.rell">
                                <string>import ^.core;


function rate_limit (account) {
	if(core.my_blockchain_info.rate_limit_active == false ) return;
    val max_counter = core.my_blockchain_info.rate_limit_max_points;
    val recovery_time = core.my_blockchain_info.rate_limit_recovery_time;
    val stat = rl_state@{account} (.points, .last_update);
    val delta = op_context.last_block_time - stat.last_update;
    var got_points = 0;
    var update_time = stat.last_update;

    if (delta &gt; recovery_time)
    {
        got_points = delta / recovery_time;
        update_time = stat.last_update + got_points * recovery_time;
        if (got_points + stat.points &gt; max_counter) {
            got_points = max_counter - stat.points;
            // if user is at maximum reset his 
            // timer
            update_time = op_context.last_block_time;
        }
    }
    
    require(stat.points + got_points &gt; 0);
    
    update rl_state@{account} (
        .points += got_points - 1,
        .last_update = update_time
    );
}


query get_account_rate_limit_last_update(account_id: byte_array) {
	if(core.my_blockchain_info.rate_limit_active == false ) return (points = 0, last_update = 0);
	val t= rl_state@{.account.id == account_id}
	(
		.points, 
		.last_update
	);
	
	return t;
}

query get_last_timestamp(): integer {
	return (block@{.timestamp&gt;0}(@sort_desc .timestamp) limit 1);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/asset.rell">
                                <string>import acc: ^.account;

entity asset {
    id: byte_array;
    key id;
    name;
    issuing_chain_rid: byte_array;
}

entity balance {
    key acc.account, asset;
    mutable amount: integer = 0;
}

function ensure_balance(acc.account, asset): balance {
    val balance = balance @? {asset, account};
    if (balance != null) {
       return balance;
    }
    else return create balance(account, asset, amount = 0);
}

function register_asset (name, issuing_chain_rid: byte_array): asset {
   val id = (name, issuing_chain_rid).hash();
   return create asset (id, name, issuing_chain_rid);
}

function _get_asset_balances(account_id: byte_array): list&lt;(id:byte_array,name:text,amount:integer,chain_id:byte_array)&gt; {
    return balance @* { .account.id == account_id } (
      id = .asset.id,
      name = .asset.name,
      amount = .amount,
      chain_id = .asset.issuing_chain_rid
    );
}

query get_asset_balances(account_id: byte_array) {
    return _get_asset_balances(account_id);
}

query get_asset_balance(account_id: byte_array, asset_id: byte_array) {
    return balance @? {
        .account.id == account_id,
        .asset.id == asset_id
    } (
        id = .asset.id,
        name = .asset.name,
        amount = .amount,
        chain_id = .asset.issuing_chain_rid
    );
}

query get_asset_by_name(name) {
    return asset @* { name } (
        .id,
        .name,
        .issuing_chain_rid
    );
    
}

query get_asset_by_id(asset_id: byte_array) {
	return asset@{
		.id == asset_id
	}(
		id = .id,
		name = .name,
		issuing_chain_rid = .issuing_chain_rid
		
	);
}

query get_all_assets() {
	return asset@*{}(
		id = .id,
		name = .name,
		issuing_chain_rid = .issuing_chain_rid	
	);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/dev_op.rell">
                                <string>module;

import ft3: ^^.core;
import acc: ^^.account;

object dev_state {
   mutable allow_dev_ops: boolean = true;
}

function require_dev() {
    require(dev_state.allow_dev_ops);
}

function dev_give_points_(account: acc.account, amount: integer) {
	require_dev();
	update acc.rl_state@{account}(.points += amount);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/history.rell">
                                <string>import acc: ^.account;

@log entity payment_history_entry {
    index acc.account, asset;
    delta: integer;

    // helps to locate exact position of payment entry in transaction
    op_index: integer;
    is_input: boolean;
    entry_index: integer;
}

query get_payment_history(account_id: byte_array, after_block: integer) {
    return payment_history_entry @* {
        acc.account @ { account_id },
        .transaction.block.block_height &gt; after_block
    } (
        delta = .delta,
        asset = .asset.name,
        asset_id = .asset.id,
        is_input = .is_input,
        timestamp = .transaction.block.timestamp,
        block_height = .transaction.block.block_height,
        entry_index = .entry_index,
        tx_rid = .transaction.tx_rid,
        tx_data = .transaction.tx_data
    );
}
</string>
                            </entry>
                            <entry key="lib/ft3/core/module.rell">
                                <string>@mount('ft3')
module;

struct module_args {
	my_blockchain_name: text;
	my_blockchain_website: text;
	my_blockchain_description: text;
	rate_limit_active: boolean;
	rate_limit_max_points: integer;
    rate_limit_recovery_time: integer;
    rate_limit_points_at_account_creation: integer;    
}</string>
                            </entry>
                            <entry key="lib/ft3/core/my_blockchain_info.rell">
                                <string>
object my_blockchain_info {
    mutable name: text = chain_context.args.my_blockchain_name;
    mutable website: text = chain_context.args.my_blockchain_website;
    mutable description: text = chain_context.args.my_blockchain_description;
    mutable rate_limit_active: boolean = chain_context.args.rate_limit_active;
    mutable rate_limit_max_points: integer = chain_context.args.rate_limit_max_points;
    mutable rate_limit_recovery_time: integer = chain_context.args.rate_limit_recovery_time;
    mutable rate_limit_points_at_account_creation: integer = chain_context.args.rate_limit_points_at_account_creation;
}


//operation update_blockchain(name, website: text, description: text) {
//    blockchain.name = name;
//    blockchain.website = website;
//    blockchain.description = description;
//}

query get_blockchain_info() {
    return (
        name = my_blockchain_info.name,
        website = my_blockchain_info.website,
        description = my_blockchain_info.description,
        rate_limit_active = my_blockchain_info.rate_limit_active,
        rate_limit_max_points = my_blockchain_info.rate_limit_max_points,
        rate_limit_recovery_time = my_blockchain_info.rate_limit_recovery_time,
        rate_limit_points_at_account_creation = chain_context.args.rate_limit_points_at_account_creation
    );
}

</string>
                            </entry>
                            <entry key="lib/ft3/core/operations/transfer.rell">
                                <string>@mount('ft3')
module;

import ft3: ^^;


operation transfer (inputs: list&lt;ft3.xfer_input&gt;, outputs: list&lt;ft3.xfer_output&gt;) {
    ft3._transfer(inputs, outputs);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/transfer.rell">
                                <string>import acc: ^.account;

struct xfer_input {
   account_id: byte_array;
   asset_id: byte_array;
   auth_descriptor_id: byte_array;
   amount: integer;
   extra: map&lt;text, gtv&gt;;
}

struct xfer_output {
   account_id: byte_array;
   asset_id: byte_array;
   amount: integer;
   extra: map&lt;text, gtv&gt;;
}

function deduct_balance (acc.account, asset, d_amount: integer) {
    val b = balance @ { account, asset };
    require( b.amount &gt;= d_amount, "Balance is too low");
    update b (amount -= d_amount);
}

function consume_input (i: xfer_input, idx: integer, assets: map&lt;asset, integer&gt;): payment_history_entry {
      val asset = asset @ { .id == i.asset_id };
      val account = acc.auth_and_log(i.account_id, i.auth_descriptor_id, ["T"]);
      require( i.amount &gt; 0, "Amount should be non 0 positive." );

      deduct_balance(account, asset, i.amount);
      assets[asset] = i.amount + if (asset in assets) assets[asset] else 0;
      return create payment_history_entry (
        account,
        asset,
        .delta = i.amount,
        .op_index = 500, //op_context ???
        .is_input = true,
        .entry_index = idx
      );
}

function process_transfer_output (o: xfer_output, idx: integer, available_assets: map&lt;asset, integer&gt;): payment_history_entry {
      if (o.extra.contains("reg_auth_desc")) {
          val auth_desc = acc.auth_descriptor.from_gtv(o.extra["reg_auth_desc"]);
          require(o.account_id
           == acc.create_account_with_auth(auth_desc));
      }

      val target_account = acc.account @ { .id == o.account_id };
      val asset = asset @ { .id == o.asset_id };
      require(o.amount &gt; 0, "You cannot tx output negative numbers");
      require( available_assets[asset] &gt;= o.amount );
      available_assets[asset] -= o.amount;
      require(available_assets[asset] &gt;= 0);
      val balance = ensure_balance(target_account, asset);
      balance.amount += o.amount;

      return create payment_history_entry (
        .account = target_account,
        asset,
        .delta = o.amount,

        .op_index = 500, // something from op_context,
        .is_input = false,
        .entry_index = idx
      );
}

function _transfer (inputs: list&lt;xfer_input&gt;, outputs: list&lt;xfer_output&gt;) {
   val sum_inputs = map&lt;asset, integer&gt;();
   var idx = 0;
   for (i in inputs) {
      consume_input(i, idx, sum_inputs);
      idx += 1;
   }

   idx = 0;
   for (o in outputs) {
      process_transfer_output(o, idx, sum_inputs);
      idx += 1;
   }
}
</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/blockchain.rell">
                                <string>import ft3: ^.core;
import acc: ^.account;


entity asset_origin {
    key ft3.asset;
    origin_chain_rid: byte_array;
}

entity linked_chain {
    key chain_rid: byte_array;
}

function blockchain_account_id (blockchain_rid: byte_array): byte_array {
   return ("B", blockchain_rid).hash();
}

function ensure_blockchain_account (blockchain_rid: byte_array): acc.account {
   val blockchain_account_id = blockchain_account_id(blockchain_rid);
   val acc = acc.account @? { .id == blockchain_account_id };
   return if (acc??)  acc
   else create acc.account (id = blockchain_account_id);
}

function get_blockchain_account (blockchain_rid: byte_array): acc.account {
   return acc.account @ { .id == blockchain_account_id(blockchain_rid) };
}


query get_linked_chains() {
    return linked_chain @* {} ( .chain_rid );
}

query is_linked_with_chain(chain_rid: byte_array) {
    return linked_chain @? { chain_rid } != null;
}
</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/module.rell">
                                <string>@mount('ft3.xc')
module;
</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/structures.rell">
                                <string>struct operation_rec {
   name;
   args: list&lt;gtv&gt;;
}

struct transaction_body_rec {
    blockchain_rid: byte_array;
    operations: list&lt;operation_rec&gt;;
    signers: list&lt;gtv&gt;;
}

struct transaction_rec {
   body: transaction_body_rec;
   signatures: list&lt;gtv&gt;;
}

struct transaction_proof {
     tx: virtual&lt;transaction_rec&gt;;
     // block_header: byte_array;
     // merkle_path: virtual&lt;list&lt;byte_array&gt;&gt;;
     // tx_index: integer;
     block_rid: byte_array;
     block_signers: list&lt;byte_array&gt;;
     signatures: list&lt;byte_array&gt;;     
}

function verify_transaction_proof( p: transaction_proof ) {
   // TODO
}</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/transfer.rell">
                                <string>import ft3: ^.core;

struct xc_target {
    account_id: byte_array;
    extra: map&lt;text, gtv&gt;;
}

function add_to_blockchain_balance (blockchain_rid: byte_array, ft3.asset, amount: integer) {
    require( chain_context.blockchain_rid != blockchain_rid ); // cannot add to own account

    val origin_chain_rid = asset_origin @? { asset } .origin_chain_rid;

    if (exists(origin_chain_rid) and (blockchain_rid == origin_chain_rid)) {
       // do nothing. in future we might track origin
    } else {
         val bc_acc = ensure_blockchain_account(blockchain_rid);
         ft3.ensure_balance(bc_acc, asset).amount += amount;
    }
}


struct init_xfer_args {
          source: ft3.xfer_input;
          target: xc_target;
          hops: list&lt;byte_array&gt;;
}

entity applied_transfers { key tx_rid: byte_array; }


</string>
                            </entry>
                            <entry key="lib/ft3/ft3_basic_dev.rell">
                                <string>module;

namespace ft3 {
	import acc: lib.ft3.account;
	import acc_op: lib.ft3.account.operations;
	import core: lib.ft3.ft3_basic_dev;
	import transfer_op: lib.ft3.core.operations.transfer;
//	import lib.ft3.crosschain;
//	import lib.ft3.crosschain.operations;
	
	import lib.ft3.operations.dev_op_account;
	import lib.ft3.operations.dev_op_asset;
	import lib.ft3.operations.dev_op_balance;
	import lib.ft3.operations.dev_op_rate_limit;
}

</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_account.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import acc: ^^.account; 


operation dev_register_account (acc.auth_descriptor) {
    dev_op.require_dev();
    acc.create_account_with_auth( auth_descriptor );
}
</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_asset.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import ft3: ^^.core;

import xft3: ^^.crosschain; 

operation dev_register_asset (name, issuing_chain_rid: byte_array) {
    dev_op.require_dev();
    ft3.register_asset(name, issuing_chain_rid);
}

operation dev_register_xc_asset (name, issuing_chain_rid: byte_array, origin_chain_rid: byte_array) {
    dev_op.require_dev();   
    val asset = ft3.register_asset(name, issuing_chain_rid);
    create xft3.asset_origin (asset, origin_chain_rid);
}
</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_balance.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import ft3: ^^.core;
import acc: ^^.account;


operation dev_give_balance (asset_id: byte_array, account_id: byte_array, amount: integer) {
    dev_op.require_dev();
    require(amount &gt;= 0);
    ft3.ensure_balance( acc.account @ { account_id }, ft3.asset @ { .id == asset_id } ).amount += amount;
}</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_rate_limit.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import acc: ^^.account;



/*
 * Can be negative
 */
operation dev_give_points(account_id: byte_array, amount: integer){
	val account = acc.account@{.id == account_id};
	dev_op.dev_give_points_(account, amount);
}

operation dev_free_op(account_id: byte_array) {
	// this operation does not cost points in the rate limit
	val account = acc.account@{.id == account_id};
	dev_op.dev_give_points_(account, 1);
	acc.rate_limit(account);
}</string>
                            </entry>
                            <entry key="main.rell">
                                <string>import lib.ft3.ft3_basic_dev;

// Remove for production
// ---

import user;
import topic;
import notifications;
import channel;
import follow;
import election;
import representative;
import chat;</string>
                            </entry>
                            <entry key="notifications/index.rell">
                                <string>import user;

entity notification {
    key id: text, user.user;
    trigger: text;
    content: text;
    mutable read: boolean;
    index timestamp;
}
</string>
                            </entry>
                            <entry key="notifications/operations.rell">
                                <string>import user;
import user.distrust;

operation create_notifications_for_users(name, descriptor_id: byte_array, id: text, trigger: text, content: text, usernames: set&lt;text&gt;) {
    val opr_user = user.get_verified_user(name, descriptor_id);

    for (username in usernames) {
        val toUser = user.user@?{ .name == username.lower_case() };
        if (toUser != null and distrust.user_distrust@?{ .distruster == toUser, .distrusted == opr_user } == null) {
            create notification(
                id = id,
                toUser,
                trigger = trigger,
                content = content,
                false,
                op_context.last_block_time
            );
        }
    }
}

operation remove_notifications_for_users(name, descriptor_id: byte_array, id: text, usernames: set&lt;text&gt;) {
    val user = user.get_verified_user(name, descriptor_id);

    for (username in usernames) {
        val to_user = user.user@?{ .name == username };
        if (to_user != null) {
            delete notification@?{ id, .user == to_user };
        }
    }
}

operation mark_notifications_since_timestamp_read(name, descriptor_id: byte_array, timestamp) {
    val user = user.get_verified_user(name, descriptor_id);
    update notification@*{ .user == user, .timestamp &gt; timestamp } ( read = true );
}</string>
                            </entry>
                            <entry key="notifications/queries.rell">
                                <string>import user;

query count_unread_user_notifications(name) {
    val user = user.user@{ .name == name };
    return notification@*{ .user == user, .read == false } ( .id );
}

query get_user_notifications_prior_to_timestamp(name, timestamp, page_size: integer) {
    val user = user.user@{ .name == name };
    return notification@*{ .user == user, .timestamp &lt; timestamp } (
        .id,
        .trigger,
        .content,
        .read,
        @sort_desc .timestamp
    ) limit page_size;
}
</string>
                            </entry>
                            <entry key="representative/functions.rell">
                                <string>import user;
import election;

function is_username_representative(name): boolean {
	val user = user.user@?{ .name == name};
	
	if (user == null) {
		return false;
	}
	
	val prev_election = election.get_latest_completed_election_id();
	
	if (prev_election == null) {
		return false;
	}
	
	return representative@?{ .user == user, .representative_election.id == prev_election } != null;
}

function is_user_suspended(rep: user.user, suspendee: user.user, timestamp): boolean {
	return user.user_suspension@?{ 
		.user == suspendee, 
		.suspended_by == rep,
		.suspended_until &gt;= timestamp
	} != null;
} </string>
                            </entry>
                            <entry key="representative/index.rell">
                                <string>import election;
import user;

entity representative {
    key user.user, election.representative_election;
}

entity representative_action {
    key id: byte_array;
    index representative;
    index timestamp;
    action: text;
}

entity representative_distrust {
	key distruster: user.user, representative;
}

import representative.report;
</string>
                            </entry>
                            <entry key="representative/operations.rell">
                                <string>import election;
import topic;
import user;
import util;

operation remove_topic(username: text, descriptor_id: byte_array, topic_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);

    val recent_election = election.representative_election@{ .completed == true } ( .id, @sort_desc .timestamp ) limit 1;
    val representative = representative @{ user, .representative_election.id == recent_election.id };

    val the_topic = topic.topic @{ .id == topic_id };
    
    create topic.topic_moderation(representative.user, the_topic);

    create representative_action(
        id = op_context.transaction.tx_rid,
        representative,
        op_context.last_block_time,
        action = "Topic /t/" + the_topic.id + " was removed by @" + user.display_name
    );
}

operation remove_topic_reply(username: text, descriptor_id: byte_array, topic_reply_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);

    val recent_election_id = require(election.get_latest_completed_election_id(), "No election has been held yet");
    val representative = representative @{ user, .representative_election.id == recent_election_id };

    val the_reply = topic.topic_reply @{ .id == topic_reply_id };
    
    create topic.topic_reply_moderation(representative.user, the_reply);

    create representative_action(
        id = op_context.transaction.tx_rid,
        representative,
        op_context.last_block_time,
        action = "Reply in topic /t/" + the_reply.topic.id + " was removed by @" + user.display_name
    );
}

operation suspend_user(username: text, descriptor_id: byte_array, user_to_be_suspended: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);

    val recent_election_id = require(election.get_latest_completed_election_id(), "No election has been held yet");
    val representative = representative @{ user, .representative_election.id == recent_election_id };

    val suspendee = user.user@{ .name == user_to_be_suspended };
    
    val action_id = "suspend_user:" + user_to_be_suspended;
	
	require(
		not is_user_suspended(user, suspendee, op_context.last_block_time), 
		"User already suspended"
	);
	
    val updated_times_suspended = user.user_suspension@*{
    	.user == suspendee,
    	.suspended_by == user
    }( .user ).size() + 1;
    
    val one_day_millis = 86400000;
    val days_suspended = updated_times_suspended * updated_times_suspended;
    val suspension_time_millis = days_suspended * one_day_millis;
	val suspended_until = op_context.last_block_time + suspension_time_millis;

	create user.user_suspension(user = suspendee, suspended_by = user, suspended_until);

    var daysString = " days ";
    if (days_suspended == 1) {
        daysString = " day ";
    }

    create representative_action(
        id = op_context.transaction.tx_rid,
        representative,
        op_context.last_block_time,
        action = "@" + suspendee.display_name + " was suspended for " + days_suspended + daysString +  "by @" + user.display_name
    );
}

operation distrust_representative(name, descriptor_id: byte_array, distrusted: name) {
	val user = user.get_and_charge_verified_user(name, descriptor_id);
	
	val recent_election_id = require(election.get_latest_completed_election_id(), "No election has been held yet");
	
	require(is_eligible_to_distrust(user, recent_election_id), "User is not eligible to distrust");
	
    val representative = representative @{ 
    	.user.name == distrusted.lower_case(), 
    	.representative_election.id == recent_election_id
    };
    
    val required_votes = election.temp_votes_counter@{
    	.representative_election_candidate.representative_election.id == recent_election_id
    } ( @sort_desc .votes ) limit 1;
    
    val distrusts = representative_distrust@*{ 
    	representative
    }( .distruster ).size();
    
    if (distrusts &gt;= 10 and distrusts &gt; required_votes) {
    	delete representative;
    } else {
    	create representative_distrust(user, representative);
    }
}

function is_eligible_to_distrust(user.user, prev_election_id: integer): boolean {	
	val recent_election_start = election.election_block_details@{
		.representative_election.id == prev_election_id
	} ( .started_height );
	
	if (user.registered &gt; recent_election_start) {
		log("User must have registered before the previous election started");
		return false;
	}
	
	val previous_election_completed = (election: election.representative_election, details: election.election_block_details)@?{
		election.id != prev_election_id,
		election == details.representative_election,
		election.completed == true
	} ( 
		details.finished_height,
		@omit @sort_desc election.timestamp
	) limit 1;
	
	if (previous_election_completed == null) {
		return true;
	}
	
	val number_of_topics = topic.topic@*{ 
		.author == user,
		.last_modified &gt; previous_election_completed,
		.last_modified &lt; recent_election_start
	}( .id ).size();
	
	val number_of_replies = topic.topic_reply@*{
		.author == user,
		.timestamp &gt; previous_election_completed,
		.timestamp &lt; recent_election_start
	}( .id ).size();
	
	return number_of_topics + number_of_replies &gt;= 5;
}</string>
                            </entry>
                            <entry key="representative/queries.rell">
                                <string>import election;
import user;

query get_representatives(): list&lt;name&gt; {
    val election = election.representative_election@?{ .completed == true } ( .id, @sort_desc .timestamp ) limit 1;

    if (election == null) {
        return list&lt;name&gt;();
    }

    return representative@*{
        .representative_election.id == election.id
    } ( .user.name );
}

query get_all_representative_actions(timestamp, page_size: integer) {
    return representative_action@*{
        .timestamp &lt; timestamp
    } (
        .id,
        representative = .representative.user.name,
        @sort_desc .timestamp,
        .action
    ) limit page_size;
}

query get_number_of_times_representative(name) {
    return representative@*{ .user.name == name } ( .representative_election.id ).size();
}

query is_user_suspended_by_me(username: name, user_to_be_suspended: name, timestamp) {
	val user = user.user@{ .name == username.lower_case() };
	val suspendee = user.user@{ .name == user_to_be_suspended.lower_case() };
	return is_user_suspended(user, suspendee, timestamp);
}</string>
                            </entry>
                            <entry key="representative/report/index.rell">
                                <string>import user;

entity representative_report {
    key id: text;
    index timestamp;
    text;
}
</string>
                            </entry>
                            <entry key="representative/report/operations.rell">
                                <string>import election;
import user;
import representative;
import util;

operation create_representative_report(username: text, descriptor_id: byte_array, id: text, text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create representative_report(id = id, op_context.last_block_time, text = text);
}
</string>
                            </entry>
                            <entry key="representative/report/queries.rell">
                                <string>query get_unhandled_representative_reports(timestamp) {
    return representative_report@*{
    	.timestamp &gt; timestamp
    } ( 
    	.id, 
    	@sort_desc .timestamp, 
    	.text
    ) limit 25;
}</string>
                            </entry>
                            <entry key="topic/functions.rell">
                                <string>import util;

function find_topic_by_id(id: text): topic {
    return topic@{ .id == id };
}

function require_mutable(post_timestamp: timestamp, op_timestamp: timestamp, action: text) {
	val fiveMinutesInMillis = 300000;
    require(
    	op_timestamp &lt; post_timestamp + fiveMinutesInMillis,
    	util.app_error(util.error_type.TOPIC_IMMUTABLE, action)
    );
}

function get_latest_poster_in_topic(id: text, topic_author: name): text {
	val latest_reply = topic_reply@?{ .topic.id == id} (
		@sort_desc .timestamp,
		.author
	) limit 1;
	
	if (latest_reply != null) {
		return latest_reply.author.display_name;
	} else {
		return topic_author;
	}
}</string>
                            </entry>
                            <entry key="topic/index.rell">
                                <string>import user;

entity topic {
    key id: text;
    index author: user.user;
    timestamp;
    mutable last_modified: timestamp;
    index last_modified;
    title: name;
    mutable message: text;
}

entity topic_moderation {
	key user.user, topic;
}

entity topic_reply {
    key id: text;
    index topic;
    index author: user.user;
    index timestamp;
    is_sub_reply: boolean = false;
    index is_sub_reply;
    mutable message: text;
}

entity topic_reply_moderation {
	key user.user, topic_reply;
}

entity sub_reply {
    key parent_reply: topic_reply, child_reply: topic_reply;
}

struct ext_topic {
	id: text;
	author: text;
	title: text;
	message: text;
	timestamp;
	last_modified: timestamp;
	latest_poster: name;
	moderated_by: list&lt;name&gt;;
}

struct ext_topic_reply {
	id: text;
	topic_id: text;
	author: text;
	message: text;
	is_sub_reply: boolean;
	timestamp;
	moderated_by: list&lt;name&gt;;
}

import topic.rating;
import topic.subscription;
</string>
                            </entry>
                            <entry key="topic/operations.rell">
                                <string>import channel;
import topic.rating;
import user;
import topic.subscription;
import topic.poll;

operation create_topic(id: text, descriptor_id: byte_array, username: text, channel_key: name, channel_name: name, title: name, message: text) {
    val pattern = ".{3,40}";
    require(title.matches(pattern), "Title [" + title + "] is invalid, must match: " + pattern);
    
    val author = user.get_and_charge_verified_user(username, descriptor_id);

    val topic = create topic(
        id = id,
        author,
        timestamp = op_context.last_block_time,
        last_modified = op_context.last_block_time,
        title = title,
        message = message
    );

    create channel.channel(name = channel_key.lower_case(), topic, op_context.last_block_time, display_name = channel_name);
    create rating.tmp_topic_rating (topic, 0);
        
    for (suspension in user.user_suspension@*{ .user == author, .suspended_until &gt; op_context.last_block_time }) {
    	create topic_moderation(suspension.suspended_by, topic);
    }
}

operation modify_topic(id: text, descriptor_id: byte_array, username: text, text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);

    val topic = topic@{ .id == id, .author == author };
    require_mutable(topic.timestamp, op_context.last_block_time, "Modify topic");

    update topic ( message = text );
}

operation delete_topic(id: text, descriptor_id: byte_array, username: text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);

    val topic = topic@{ .id == id, .author == author };
    require_mutable(topic.timestamp, op_context.last_block_time, "Delete topic");
    delete channel.channel@{ topic };
    delete rating.tmp_topic_rating@{ topic };
    delete subscription.subscription@?{ topic };
    
    val opt_poll = poll.poll@?{ topic };
    if (opt_poll != null) {
    	delete poll.poll_option@*{ .poll == opt_poll };
    	delete poll.poll_vote@*{ .poll == opt_poll };
    	delete opt_poll;
    }
    
	delete topic;
}

operation create_reply(topic_id: text, descriptor_id: byte_array, id: text, username: text, message: text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);
    val topic = find_topic_by_id(topic_id);

    val reply = create topic_reply(
        id = id,
        topic,
        author,
        timestamp = op_context.last_block_time,
        message = message
    );
    
    for (suspension in user.user_suspension@*{ .user == author, .suspended_until &gt; op_context.last_block_time }) {
    	create topic_reply_moderation(suspension.suspended_by, reply);
    }

     update topic ( last_modified = op_context.last_block_time);
}

operation modify_reply(id: text, descriptor_id: byte_array, username: text, text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);

    val reply = topic_reply@{ .id == id, .author == author };
    require_mutable(reply.timestamp, op_context.last_block_time, "Modify reply");

    update reply ( message = text );
}

operation delete_reply(id: text, descriptor_id: byte_array, username: text) {
	val author = user.get_and_charge_verified_user(username, descriptor_id);
	val reply = topic_reply@{ id, author };
	require_mutable(reply.timestamp, op_context.last_block_time, "Delete reply");
	
	delete sub_reply@?{ .child_reply == reply };
	delete reply;
}

operation create_sub_reply(topic_id: text, descriptor_id: byte_array, parent_reply_id: text, id: text, username: text, message: text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);
    val topic = find_topic_by_id(topic_id);

    val topic_reply = create topic_reply(
        id = id,
        topic,
        author,
        timestamp = op_context.last_block_time,
        is_sub_reply = true,
        message = message	
    );
    
    for (suspension in user.user_suspension@*{ .user == author, .suspended_until &gt; op_context.last_block_time }) {
    	create topic_reply_moderation(suspension.suspended_by, topic_reply);
    }

    create sub_reply(
        parent_reply = topic_reply@{ .id == parent_reply_id },
        child_reply = topic_reply
    );

    update topic ( last_modified = op_context.last_block_time);
}</string>
                            </entry>
                            <entry key="topic/poll/index.rell">
                                <string>import topic;
import user;

entity poll {
	key topic.topic;
	text;
}

entity poll_option {
	key poll, text;
	mutable votes: integer;
}

entity poll_vote {
	key poll, user.user;
	poll_option;
}

struct poll_record {
	question: text;
	options: list&lt;option_record&gt;;
}

struct option_record {
	option: text;
	votes: integer;
}</string>
                            </entry>
                            <entry key="topic/poll/operations.rell">
                                <string>import user;
import topic;

operation create_poll(id: text, descriptor_id: byte_array, 
	username: text, question: text, options: list&lt;text&gt;
) {
	val author = user.get_and_charge_verified_user(username, descriptor_id);
	val topic = topic.topic@{ .id == id, author };
	
	val poll = create poll(topic, question);
	
	for (option in options) {
		create poll_option(poll, option, 0);
	}
}

operation vote_for_poll_option(id: text, descriptor_id: byte_array, username: text, option: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	
	val poll_opt = poll_option@{ .poll.topic.id == id, .text == option };

	create poll_vote(poll_opt.poll, user, poll_opt);
	update poll_opt ( .votes+1 );
}</string>
                            </entry>
                            <entry key="topic/poll/queries.rell">
                                <string>query get_poll(topic_id: text): poll_record? {
	val poll = poll@?{ .topic.id == topic_id };
	
	if (poll == null) {
		return null;
	}
	
	val options = list&lt;option_record&gt;();
	for (opt in poll_option@*{ .poll == poll }) {
		options.add(option_record(opt.text, opt.votes));
	}
	
	return poll_record(poll.text, options);
}

query get_poll_vote(topic_id: text, username: text): text? {
	val vote = poll_vote@?{ 
		.poll.topic.id == topic_id, 
		.user.name == username.lower_case()
	};
	
	if (vote == null) return null;
	return vote.poll_option.text;
}</string>
                            </entry>
                            <entry key="topic/queries.rell">
                                <string>import channel;
import follow;
import topic.rating;
import user;
import representative;

query get_topics_after_timestamp(timestamp, page_size: integer) {
    val topics = topic@*{ .last_modified &gt; timestamp } (
        .id,
        author=.author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_prior_to_timestamp(timestamp, page_size: integer): list&lt;ext_topic&gt; {
    val topics = topic@*{ .last_modified &lt; timestamp }(
        .id,
        author = .author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    ) limit page_size;
        
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
  	   	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topic_replies_prior_to_timestamp(username: name, topic_id: text, timestamp, page_size: integer) {	
    val replies = topic_reply@*{
        topic@{ .id == topic_id },
        .timestamp &lt; timestamp,
        .is_sub_reply == false
    }(
        .id,
        topic_id = .topic.id,
        author= .author.display_name,
        .message,
        .is_sub_reply,
        @sort_desc .timestamp
    ) limit page_size;
    
    val ext_replies = list&lt;ext_topic_reply&gt;();
    for (reply in replies) {
    	val moderated_by = topic_reply_moderation @*{ .topic_reply.id == reply.id } ( .user.name );
    	val ext_reply = ext_topic_reply (
    		id = reply.id,
    		topic_id = reply.topic_id,
    		author = reply.author,
    		message = reply.message,
    		is_sub_reply = reply.is_sub_reply,
    		timestamp = reply.timestamp,
    		moderated_by = moderated_by
    	);
    	ext_replies.add(ext_reply);
    }
    
    return ext_replies;
}

query count_topic_replies(topic_id: text) {
	return topic_reply@*{ .topic.id == topic_id }( .id ).size();
}

query get_topic_replies_after_timestamp(username: name, topic_id: text, timestamp, page_size: integer) {	
	val replies = topic_reply@*{
        topic@{ .id == topic_id },
        .timestamp &gt; timestamp,
        .is_sub_reply == false
    }(
        .id,
        topic_id = .topic.id,
        author= .author.display_name,
        .message,
        .is_sub_reply,
        @sort_desc .timestamp
    ) limit page_size;
			
    val ext_replies = list&lt;ext_topic_reply&gt;();
    for (reply in replies) {
    	val moderated_by = topic_reply_moderation @*{ .topic_reply.id == reply.id } ( .user.name );
    	val ext_reply = ext_topic_reply (
    		id = reply.id,
    		topic_id = reply.topic_id,
    		author = reply.author,
    		message = reply.message,
    		is_sub_reply = reply.is_sub_reply,
    		timestamp = reply.timestamp,
    		moderated_by = moderated_by
    	);
    	ext_replies.add(ext_reply);
    }
    
    return ext_replies;
}

query get_topic_replies_by_user_prior_to_timestamp(name, timestamp, page_size: integer) {
    return topic_reply@*{ .author.name == name, .timestamp &lt; timestamp } (
        .id,
        topic_id = .topic.id,
        author=.author.display_name,
        .message,
        .is_sub_reply,
        @sort_desc .timestamp
    ) limit page_size;
}

query count_topics_by_user(name): integer {
    return topic@*{ .author.name == name }( .id ).size();
}

query count_replies_by_user(name): integer {
    return topic_reply@*{ .author.name == name }( .id ).size();
}

query get_sub_replies(username: name, parent_reply_id: text) {	
    val replies = sub_reply@*{ .parent_reply.id == parent_reply_id } (
        id = .child_reply.id,
        topic_id = .child_reply.topic.id,
        author = .child_reply.author.display_name,
        message = .child_reply.message,
        is_sub_reply = .child_reply.is_sub_reply,
        @sort timestamp= .child_reply.timestamp
    );
   
   val ext_replies = list&lt;ext_topic_reply&gt;();
    for (reply in replies) {
    	val moderated_by = topic_reply_moderation @*{ .topic_reply.id == reply.id } ( .user.name );
    	val ext_reply = ext_topic_reply (
    		id = reply.id,
    		topic_id = reply.topic_id,
    		author = reply.author,
    		message = reply.message,
    		is_sub_reply = reply.is_sub_reply,
    		timestamp = reply.timestamp,
    		moderated_by = moderated_by
    	);
    	ext_replies.add(ext_reply);
    }
    
    return ext_replies;
}

query get_topics_by_user_id_prior_to_timestamp(name, timestamp, page_size: integer) {
    val topics = topic@*{
        user.user@{ .name == name },
        .last_modified &lt; timestamp
    }(
        .id,
        author= .author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_from_follows_after_timestamp(name, timestamp, page_size: integer) {
    val topics = (topic, follow.follow)@*{
            follow.follower.name == name.lower_case(),
            follow.follows == topic.author,
            topic.last_modified &gt; timestamp
    }(
        topic.id,
        author=topic.author.display_name,
        topic.title,
        topic.message,
        @sort_desc topic.last_modified,
        topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_from_follows_prior_to_timestamp(name, timestamp, page_size: integer) {
    val topics = (topic, follow.follow) @* {
        follow.follower.name == name.lower_case(),
        follow.follows == topic.author,
        topic.last_modified &lt; timestamp
    }(
        topic.id,
        author = topic.author.display_name,
        topic.title,
        topic.message,
        @sort_desc topic.last_modified,
        topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topic_by_id(username: name, id: text) {
    val topic = topic@{ .id == id }(
        .id,
        author = .author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    );
    
    val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
	return ext_topic (
		id = topic.id,
		author = topic.author,
		title = topic.title,
		message = topic.message,
		timestamp = topic.timestamp,
		last_modified = topic.last_modified,
		latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
		moderated_by = moderated_by
	);
}

query get_all_topics_by_stars_since_timestamp(timestamp, page_size: integer) {
    val topics = rating.tmp_topic_rating@*{
        .topic.last_modified &gt; timestamp
    } (
        @sort_desc .stars,
        id = .topic.id,
        author=.topic.author.display_name,
        title=.topic.title,
        message=.topic.message,
        last_modified=.topic.last_modified,
        timestamp=.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_by_follows_and_stars_since_timestamp(name, timestamp, page_size: integer) {
    val topics = (rating.tmp_topic_rating, follow.follow) @*{
            follow.follower.name == name,
            tmp_topic_rating.topic.author == follow.follows,
            tmp_topic_rating.topic.last_modified &gt; timestamp
        } (
        @sort_desc tmp_topic_rating.stars,
        id = tmp_topic_rating.topic.id,
        author = tmp_topic_rating.topic.author.display_name,
        title = tmp_topic_rating.topic.title,
        message = tmp_topic_rating.topic.message,
        last_modified = tmp_topic_rating.topic.last_modified,
        timestamp = tmp_topic_rating.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_by_channel_after_timestamp_sorted_by_popularity(name, timestamp, page_size: integer) {
    val topics = (rating.tmp_topic_rating, channel.channel)@*{
        name == channel.name,
        tmp_topic_rating.topic == channel.topic,
        tmp_topic_rating.topic.last_modified &gt; timestamp
    } (
        @sort_desc .stars,
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        last_modified = channel.topic.last_modified,
        timestamp = channel.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_by_followed_channels_after_timestamp_sorted_by_popularity(name, timestamp, page_size: integer) {
    val topics = (rating.tmp_topic_rating, channel.channel_following, channel.channel)@*{
        channel_following.user == user.user@{ name },
        channel_following.name == channel.name,
        tmp_topic_rating.topic == channel.topic,
        tmp_topic_rating.topic.last_modified &gt; timestamp
    } (
        @sort_desc .stars,
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        last_modified = channel.topic.last_modified,
        timestamp = channel.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}</string>
                            </entry>
                            <entry key="topic/rating/index.rell">
                                <string>import user;
import topic;

entity topic_star_rating {
    key topic.topic, user.user;
}

// To be deleted when GROUP BY and COUNT is supported, then will use topic_star_rating instead
entity tmp_topic_rating {
    key topic.topic;
    mutable stars: integer;
    index stars;
}

entity reply_star_rating {
    key topic.topic_reply, user.user;
}
</string>
                            </entry>
                            <entry key="topic/rating/operations.rell">
                                <string>import user;
import topic;

operation give_topic_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create topic_star_rating(topic.topic@{ .id == id }, user);

    val topicRating = tmp_topic_rating@{ topic.topic@{ .id == id }};
    update topicRating ( stars = topicRating.stars + 1 );
}

operation remove_topic_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    delete topic_star_rating@{ topic.topic@{ .id == id }, user };

    val topicRating = tmp_topic_rating@{ topic.topic@{ .id == id }};
    update topicRating ( stars = topicRating.stars - 1 );
}

operation give_reply_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create reply_star_rating(topic.topic_reply@{ .id == id }, user);
}

operation remove_reply_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    delete reply_star_rating@{ topic.topic_reply@{ .id == id }, user };
}</string>
                            </entry>
                            <entry key="topic/rating/queries.rell">
                                <string>import topic;

query get_star_rating_for_topic(id: text) {
    return topic_star_rating@*{ topic.topic@{ .id == id }} ( .user.name );
}

query get_star_rating_for_reply(id: text) {
    return reply_star_rating@*{ topic.topic_reply@{ .id == id }} ( .user.name );
}

query count_user_topic_star_rating(name): integer {
    return topic_star_rating@*{ .topic.author.name == name } ( .topic, .user ).size();
}

query count_user_reply_star_rating(name): integer {
    return reply_star_rating@*{ .topic_reply.author.name == name } ( .topic_reply, .user ).size();
}</string>
                            </entry>
                            <entry key="topic/subscription/index.rell">
                                <string>import user;
import topic;

entity subscription {
    key topic.topic, user.user;
}
</string>
                            </entry>
                            <entry key="topic/subscription/operations.rell">
                                <string>import user;
import topic;

operation subscribe_to_topic(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create subscription(topic.topic@{ .id == id }, user);
}

operation unsubscribe_from_topic(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    delete subscription@{ topic.topic@{ .id == id }, user };
}</string>
                            </entry>
                            <entry key="topic/subscription/queries.rell">
                                <string>import topic;

query get_subscribers_for_topic(id: text) {
    return subscription@*{ topic.topic@{ .id == id }} ( .user.name );
}</string>
                            </entry>
                            <entry key="user/distrust/index.rell">
                                <string>import user;

entity user_distrust {
    key distruster: user.user, distrusted: user.user;
}</string>
                            </entry>
                            <entry key="user/distrust/operations.rell">
                                <string>import user;

operation toggle_distrust(username: name, descriptor_id: byte_array, name, muted: boolean) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);

    if (muted) {
        create user_distrust(distruster = user, distrusted = user.user@{ .name == name });
    } else {
        delete user_distrust@{ .distruster == user, .distrusted == user.user@{ .name == name }};
    }
}
</string>
                            </entry>
                            <entry key="user/distrust/queries.rell">
                                <string>query get_distrusted_users(name) {
    return user_distrust@*{ .distruster.name == name.lower_case() } ( .distrusted.name );
}

query times_user_was_distrusted(name): integer {
	return user_distrust@*{ .distrusted.name == name } ( .distruster ).size();
}

query times_user_distrusted_someone(name): integer {
	return user_distrust@*{ .distruster.name == name } ( .distrusted ).size();
}</string>
                            </entry>
                            <entry key="user/functions.rell">
                                <string>import ft3_acc: lib.ft3.account;
import util;

function get_verified_user(name, descriptor_id: byte_array): user {
    val user = user@{ .name == name.lower_case() };
    ft3_acc.require_auth(user.account, descriptor_id, list&lt;text&gt;());
    return user;
}

function get_and_charge_verified_user(name, descriptor_id: byte_array): user {
	val user = get_verified_user(name, descriptor_id);
	ft3_acc.rate_limit(user.account);
	return user;
}</string>
                            </entry>
                            <entry key="user/index.rell">
                                <string>import ft3_acc: lib.ft3.account;

entity user {
    key name;
    index ft3_acc.account;
    display_name: name;
    registered: integer = 0;
}

entity user_suspension {
	index user;
	index suspended_by: user;
	index suspended_until: timestamp;
}

import user.settings;
import user.distrust;
</string>
                            </entry>
                            <entry key="user/operations.rell">
                                <string>import ft3_acc: lib.ft3.account;

import user.settings;

operation register_user(name, account_id: byte_array) {
	val pattern = "[a-zA-Z0-9]{3,16}";
	require(name.matches(pattern), "Not a valid username, must match: " + pattern);
	
    val account = ft3_acc.account @ { account_id };
    val user = create user(name = name.lower_case(), display_name = name, account, op_context.block_height);
    
    create settings.user_settings(user, avatar = "" , description = "");
}
</string>
                            </entry>
                            <entry key="user/queries.rell">
                                <string>import ft3_acc: lib.ft3.account;

query get_user(name) {
    return user@?{ .name == name.lower_case() } ( name = .display_name );
}

query get_account_id(name) {
    return user@?{ .name == name.lower_case() } ( .account.id );
}

query get_registered_at(name) {
	return user@{ .name == name.lower_case() } ( .registered );
}

query username_by_account_id(id: byte_array): name? {
	val account = ft3_acc.account@? { id };
	if (account != null) {
		return user@?{ .account == account } ( .display_name );
	}
	
	return null;
}</string>
                            </entry>
                            <entry key="user/settings/index.rell">
                                <string>import user;

entity user_settings {
    key user.user;
    mutable avatar: text;
    mutable description: text;
}
</string>
                            </entry>
                            <entry key="user/settings/operations.rell">
                                <string>import user;

operation create_user_settings(name, descriptor_id: byte_array, avatar: text, description: text) {
    val user = user.get_and_charge_verified_user(name, descriptor_id);
    create user_settings(user, avatar = avatar, description = description);
}

operation update_user_settings(name, descriptor_id: byte_array, avatar: text, description: text) {
    val user = user.get_and_charge_verified_user(name, descriptor_id);
    update user_settings@{ .user == user }( avatar = avatar, description = description );
}
</string>
                            </entry>
                            <entry key="user/settings/queries.rell">
                                <string>import user;

query get_user_settings(name) {
    return user_settings@?{ user.user@{ .name == name }} ( .avatar, .description );
}
</string>
                            </entry>
                            <entry key="util/log.rell">
                                <string>enum error_type {
	USER_UNAUTHORIZED,
	USER_SUSPENDED,
	TOPIC_IMMUTABLE,
	REPRESENTATIVE_ALREADY_SUSPENDED,
	ILLEGAL_ACTION,
	EXPECTED_ERROR
}

function app_error(error_type, action: text): text {
	val msg = when(error_type) {
		USER_UNAUTHORIZED -&gt; message_with_code("CERR_10", "Requester was unauthorized", action);
		USER_SUSPENDED -&gt; message_with_code("CERR_11", "Requester was suspended", action);
		TOPIC_IMMUTABLE -&gt; message_with_code("CERR_20", "Topic is no longer mutable", action);
		REPRESENTATIVE_ALREADY_SUSPENDED -&gt; message_with_code("CERR_30", "User was already suspended", action);
		ILLEGAL_ACTION -&gt; message_with_code("CERR_40", "The attempted action was illegal", action);
		EXPECTED_ERROR -&gt; message_with_code("CERR_50", "Expected error", action);
	};
	
	log(msg);
	return msg;
}

function message_with_code(code: text, message: text, action: text): text {
	return '{"code":"' + code + '","message":"' + message + '","action":"' + action + '"}';
}</string>
                            </entry>
                        </dict>
                    </entry>
                </dict>
            </entry>
        </dict>
    </entry>
    <entry key="signers">
        <array>
            <bytea>0350FE40766BC0CE8D08B3F5B810E49A8352FDD458606BD5FAFE5ACDCDC8FF3F57</bytea>
        </array>
    </entry>
</dict>
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
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dict>
    <entry key="blockstrategy">
        <dict>
            <entry key="name">
                <string>net.postchain.base.BaseBlockBuildingStrategy</string>
            </entry>
        </dict>
    </entry>
    <entry key="configurationfactory">
        <string>net.postchain.gtx.GTXBlockchainConfigurationFactory</string>
    </entry>
    <entry key="gtx">
        <dict>
            <entry key="modules">
                <array>
                    <string>net.postchain.rell.module.RellPostchainModuleFactory</string>
                    <string>net.postchain.gtx.StandardOpsGTXModule</string>
                </array>
            </entry>
            <entry key="rell">
                <dict>
                    <entry key="moduleArgs">
                        <dict>
                            <entry key="lib.ft3.core">
                                <dict>
                                    <entry key="my_blockchain_description">
                                        <string>Decentralized reddit</string>
                                    </entry>
                                    <entry key="my_blockchain_name">
                                        <string>Chromunity</string>
                                    </entry>
                                    <entry key="my_blockchain_website">
                                        <string>testnet.chromunity.com</string>
                                    </entry>
                                    <entry key="rate_limit_active">
                                        <int>1</int>
                                    </entry>
                                    <entry key="rate_limit_max_points">
                                        <int>10</int>
                                    </entry>
                                    <entry key="rate_limit_points_at_account_creation">
                                        <int>5</int>
                                    </entry>
                                    <entry key="rate_limit_recovery_time">
                                        <int>30000</int>
                                    </entry>
                                </dict>
                            </entry>
                        </dict>
                    </entry>
                    <entry key="modules">
                        <array>
                            <string></string>
                        </array>
                    </entry>
                    <entry key="sources_v0.10">
                        <dict>
                            <entry key="channel/index.rell">
                                <string>import user;
import topic;

entity channel {
    key name, topic.topic;
    index timestamp;
    display_name: name;
}

entity channel_following {
    key user.user, name;
}
</string>
                            </entry>
                            <entry key="channel/operations.rell">
                                <string>import user;

operation follow_channel(username: text, descriptor_id: byte_array, name) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create channel_following(user, name.lower_case());
}

operation unfollow_channel(username: text, descriptor_id: byte_array, name) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    delete channel_following@{ user, name.lower_case()};
}</string>
                            </entry>
                            <entry key="channel/queries.rell">
                                <string>import user;
import topic;

query get_topics_by_channel_prior_to_timestamp(name, timestamp, page_size: integer) {
    val topics = channel@*{
        .name == name,
        .topic.last_modified &lt; timestamp
    } (
        id = .topic.id,
        author = .topic.author.display_name,
        title = .topic.title,
        message = .topic.message,
        timestamp = .topic.timestamp,
        @sort_desc last_modified = .topic.last_modified
    ) limit page_size;
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query get_topics_by_channel_after_timestamp(name, timestamp) {
    val topics = channel@*{
        .name == name,
        .topic.last_modified &gt; timestamp
    } (
        id = .topic.id,
        author = .topic.author.display_name,
        title = .topic.title,
        message = .topic.message,
        timestamp = .topic.timestamp,
        @sort_desc last_modified = .topic.last_modified
    );
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query count_topics_by_channel(name) {
    return channel@*{ .name == name } ( .name ).size();
}

query count_channel_followers(name) {
    return channel_following@*{ .name == name } ( .user.name ).size();
}

query get_topics_by_followed_channels_prior_to_timestamp(username: text, timestamp, page_size: integer) {
    val user = user.user@{ .name == username};
    val topics = (channel, channel_following)@*{
        channel_following.user == user,
        channel_following.name == channel.name,
        channel.topic.last_modified &lt; timestamp
    }
    (
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        timestamp = channel.topic.timestamp,
        @sort_desc last_modified = channel.topic.last_modified
    ) limit page_size;
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query get_topics_by_followed_channels_after_timestamp(username: text, timestamp, page_size: integer) {
    val user = user.user@{ .name == username};
    val topics = (channel, channel_following)@*{
        channel_following.user == user,
        channel_following.name == channel.name,
        channel.topic.last_modified &gt; timestamp
    }
    (
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        timestamp = channel.topic.timestamp,
        @sort_desc last_modified = channel.topic.last_modified
    ) limit page_size;
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query get_followed_channels(username: text) {
    val user = user.user@{ .name == username};
    return channel_following@*{ user } ( .name );
}

query get_all_channels() {
    return channel@*{} ( .display_name );
}

query get_channels_since(timestamp) {
    return channel@*{ .timestamp &gt; timestamp }( .display_name );
}

query get_topic_channels_belongings(topic_id: text) {
    return channel@*{ topic.topic@{ .id == topic_id }} ( .display_name );
}
</string>
                            </entry>
                            <entry key="chat/index.rell">
                                <string>import user;

entity chat {
	key id: text;
	mutable title: text;
	timestamp;
}

entity chat_user {
	key user.user;
	rsa_pubkey: text;
}

entity chat_membership {
	key chat, member: chat_user;
	encrypted_chat_key: text;
	mutable last_opened: timestamp = 0;
}

entity chat_message {
	index chat;
	index sender: chat_user;
	index timestamp;
	encrypted_msg: text;
}

struct chat_record {
	id: text;
	title: text;
	last_message: message_record?;
	encrypted_chat_key: text;
	timestamp;
	last_opened: timestamp;
}

struct message_record {
	sender: name;
	timestamp;
	encrypted_msg: text;
}
</string>
                            </entry>
                            <entry key="chat/operations.rell">
                                <string>import user;
import util;

operation create_chat(chat_id: text, descriptor_id: byte_array, username: text, title: text, encrypted_chat_key: text) {
	val founder = user.get_and_charge_verified_user(username, descriptor_id);

	val chat = create chat(id = chat_id, title = title, timestamp = op_context.last_block_time);
	create chat_membership(chat, chat_user@{ .user == founder }, encrypted_chat_key);
}

operation create_chat_user(descriptor_id: byte_array, username: text, rsa_pubkey: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	create chat_user(user, rsa_pubkey);
}

operation delete_chat_user(descriptor_id: byte_array, username: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	val chat_user = chat_user@?{ user };

	if (chat_user != null) {
		delete chat_membership@*{ .member == chat_user };
		delete chat_message@*{ .sender == chat_user };
		delete chat_user;
	}
}

operation add_user_to_chat(descriptor_id: byte_array, username: text, chat_id: text, target_user: text, encrypted_chat_key: text) {
	val user_already_in_chat = user.get_and_charge_verified_user(username, descriptor_id);
	val chat = chat@{ .id == chat_id };

	if (chat_membership@?{ chat, .member.user.name == target_user.lower_case() } == null) {
		create chat_membership(chat, chat_user@{ .user.name == target_user.lower_case() }, encrypted_chat_key);
	}
}

operation leave_chat(descriptor_id: byte_array, username: text, chat_id: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	val chat = chat@{ .id == chat_id };

	delete chat_membership@{ chat, chat_user@{ user }};

	if (chat_membership@*{ chat } ( .member ).size() == 0) {
		delete chat_message@*{ chat };
		delete chat;
	}
}

operation modify_chat_title(descriptor_id: byte_array, username: text, chat_id: text, title: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	val chat = chat@{ .id == chat_id };
	chat_membership@{ chat, chat_user@{ user }};
	update chat(title = title);
}

operation send_chat_message(chat_id: text, descriptor_id: byte_array, username: name, encrypted_msg: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);

	val chat = chat@{ .id == chat_id };
	val chat_user = chat_user@{ user };
	val chat_member = chat_membership@?{ chat, chat_user };
	require(chat_member != null, util.app_error(util.error_type.USER_UNAUTHORIZED, "Only a chat member can send a message"));

	create chat_message(chat, chat_user, op_context.last_block_time, encrypted_msg);
}

operation update_last_opened_timestamp(chat_id: text, descriptor_id: byte_array, username: name) {
	val user = user.get_verified_user(username, descriptor_id);
	update chat_membership@{
		.chat.id == chat_id,
		.member.user == user
	} ( last_opened = op_context.last_block_time );
}
</string>
                            </entry>
                            <entry key="chat/queries.rell">
                                <string>import follow;

query get_chat_user_pubkey(username: name): text? {
	return chat_user@?{ .user.name == username.lower_case() } ( .rsa_pubkey );
}

query get_user_chats(username: name): list&lt;chat_record&gt; {

	val member_chats = chat_membership@*{ .member.user.name == username.lower_case() };
	val chat_records = list&lt;chat_record&gt;();

	for (member_chat in member_chats) {
		val latest_message = chat_message@?{ .chat == member_chat.chat } ( .sender, @sort_desc .timestamp, .encrypted_msg, @sort_desc .chat.timestamp ) limit 1;

		if (latest_message != null) {
			val message = message_record(sender = latest_message.sender.user.display_name, timestamp = latest_message.timestamp, encrypted_msg = latest_message.encrypted_msg);
			chat_records.add(chat_record(
				id = member_chat.chat.id,
				title = member_chat.chat.title,
				last_message = message,
				encrypted_chat_key = member_chat.encrypted_chat_key,
				timestamp = member_chat.chat.timestamp,
				last_opened = member_chat.last_opened
			));
		} else {
			chat_records.add(chat_record(
				id = member_chat.chat.id,
				title = member_chat.chat.title,
				last_message = null,
				encrypted_chat_key = member_chat.encrypted_chat_key,
				timestamp = member_chat.chat.timestamp,
				last_opened = member_chat.last_opened
			));
		}

	}

	return chat_records;
}

query get_chat_messages(id: text, prior_to: timestamp, page_size: integer) {
	return chat_message@*{ .chat.id == id, .timestamp &lt; prior_to } (
		sender = chat_message.sender.user.display_name,
		@sort_desc timestamp = chat_message.timestamp,
		encrypted_msg = chat_message.encrypted_msg
	) limit page_size;
}

query get_chat_messages_after(id: text, after_timestamp: timestamp, page_size: integer) {
	return chat_message@*{ .chat.id == id, .timestamp &gt; after_timestamp } (
		sender = chat_message.sender.user.display_name,
		@sort timestamp = chat_message.timestamp,
		encrypted_msg = chat_message.encrypted_msg
	) limit page_size;
}

query get_chat_participants(id: text) {
	return chat_membership@*{ .chat.id == id } ( .member.user.display_name );
}

query get_followed_chat_users(username: name) {
	return (chat_user, follow.follow)@*{
		follow.follower.name == username.lower_case(),
		follow.follows == chat_user.user
	} ( chat_user.user.display_name );
}

query get_chat_users() {
	return chat_user@*{} ( chat_user.user.display_name );
}

query count_unread_chats(username: name) {
	val my_user = username.lower_case();
	return set&lt;chat&gt;((chat_membership, chat_message)@*{
		chat_membership.member.user.name == my_user,
		chat_message.timestamp &gt; chat_membership.last_opened,
		chat_membership.chat == chat_message.chat,
		chat_message.sender.user.name != my_user
	} ( chat_membership.chat )).size();
}</string>
                            </entry>
                            <entry key="election/index.rell">
                                <string>import user;
import topic;

entity representative_election {
    key id: integer;
    index timestamp;
    mutable completed: boolean;
    index completed;
}

entity election_block_details {
	key started_height: integer;
	mutable finished_height: integer = -1;
	index representative_election;
}

entity representative_election_candidate {
  key representative_election, user.user;
}

entity representative_election_vote {
    key user.user, representative_election_candidate;
}

entity temp_votes_counter {
	key representative_election_candidate;
	mutable votes: integer;
}

function is_eligible_to_vote(user.user): boolean {
	val prev_election_id = get_latest_completed_election_id();
	
	val current_election_id = get_current_election_id();
	
	if (current_election_id == null) {
		return false;
	} else if (prev_election_id == null) {
		return true;
	}
	
	val current_election_start = (election_block_details, block)@{ 
		election_block_details.representative_election.id == current_election_id,
		election_block_details.started_height == block.block_height
	} ( 
		block.timestamp
	);
	
	if (user.registered &gt; current_election_start) {
		log("Not elgible for voting: User registered after election start");
		return false; 
	}
	
	val previous_election_completed = (representative_election, election_block_details, block)@?{
		representative_election == election_block_details.representative_election,
		representative_election.completed == true,
		block.block_height == election_block_details.finished_height
	} ( 
		block.timestamp,
		@omit @sort_desc representative_election.timestamp
	) limit 1;
	
	if (previous_election_completed != null) {
		log("A previous election was held, so verifying correct number of posts");
		val number_of_topics = topic.topic@*{ 
			.author == user,
			.last_modified &gt; previous_election_completed,
			.last_modified &lt; current_election_start
		}( .id ).size();
		
		val number_of_replies = topic.topic_reply@*{
			.author == user,
			.timestamp &gt; previous_election_completed,
			.timestamp &lt; current_election_start
		}( .id ).size();
		
		return number_of_topics + number_of_replies &gt;= 5;
	}
	
	return true;
}

function governing_period_in_blocks(): integer {
	return 75000;
}

function election_duration_in_blocks(): integer {
	return 25000;
}

function get_current_election_id(): integer? {
	return representative_election@?{ .completed == false } ( @omit @sort_desc .timestamp, .id ) limit 1;
}

function get_latest_completed_election_id(): integer? {
	return representative_election@?{ .completed == true } ( .id, @omit @sort_desc .timestamp ) limit 1;
}</string>
                            </entry>
                            <entry key="election/operations.rell">
                                <string>import user;
import util;
import representative;

operation process_election() {
	var something_done = false;
	
	val current_block = op_context.block_height;
	val election_period_in_blocks = election_duration_in_blocks();
	val governing_period_in_blocks = governing_period_in_blocks();
	
	val election_block_details = election_block_details@?{} ( @sort_desc .started_height, .finished_height ) limit 1;
	
	if (election_block_details == null) {
		log("No election held yet, triggering new one");
		create_election_at_height(current_block);
		something_done = true;
	} else if (election_block_details.finished_height &gt;= 0 and election_block_details.finished_height + governing_period_in_blocks &lt; current_block) {
		log("Triggering a new election");
		create_election_at_height(current_block);
		something_done = true;
	} else if (election_block_details.finished_height == -1 
		and election_block_details.started_height + election_period_in_blocks &lt; current_block
	) {
		log("Wrapping up election");
		complete_election();
		something_done = true;
	}
	
	require(something_done, util.app_error(util.error_type.EXPECTED_ERROR, "Nothing done while processing of elections"));
}

function create_election_at_height(height: integer) {
	val election = create representative_election(
			id = height,
			timestamp = op_context.last_block_time, 
			false
		);
		create election_block_details(started_height = height, election);
}

function complete_election() {
	val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
	
    val current_election = representative_election@{ .id == current_election_id };
    update current_election ( completed = true );
    update election_block_details@{ current_election } ( finished_height = op_context.block_height );
    
    val nr_of_participants = temp_votes_counter@*{} ( 
    	.representative_election_candidate.user.name
    ).size();
    
    val new_representatives = temp_votes_counter@*{ 
    	.representative_election_candidate.representative_election == current_election
    } (
    	@sort_desc @omit .votes,
    	.representative_election_candidate.user
    ) limit integer((nr_of_participants * 0.1).ceil());

    for (user in new_representatives) {
        create representative.representative(user, current_election);
    }
}

operation vote_for_candidate(voter: name, descriptor_id: byte_array, candidate: name) {
	require(voter != candidate, util.app_error(util.error_type.ILLEGAL_ACTION, "You can't vote for yourself"));
    val user = user.get_and_charge_verified_user(voter, descriptor_id);

	require(is_eligible_to_vote(user), util.app_error(util.error_type.ILLEGAL_ACTION, "Not eligible for voting in the election"));

    val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
    
    clean_up_votes(user, current_election_id);
    
    val vote = create representative_election_vote(
        user,
        representative_election_candidate@{ 
        	user.user@{ .name == candidate }, 
        	.representative_election.id == current_election_id
        }
    );
    
    update temp_votes_counter@ {
    	vote.representative_election_candidate
    } ( votes += 1 );
}

operation sign_up_for_election(name, descriptor_id: byte_array) {
    val user = user.get_and_charge_verified_user(name, descriptor_id);
	val election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));

    val candidate = create representative_election_candidate(
    	representative_election@{ .id == election_id }, 
    	user
    );
    
    create temp_votes_counter(candidate, 0);
}

function clean_up_votes(user.user, id: integer) {
	val old_candidate_votes = representative_election_vote@*{ 
    	user,
    	.representative_election_candidate.representative_election.id == id
    };
	for (old_candidate_vote in old_candidate_votes) {
	    
	    update temp_votes_counter@ {
	    	old_candidate_vote.representative_election_candidate
	    } ( votes -= 1 );
	    
	   	delete old_candidate_vote;
	}
}</string>
                            </entry>
                            <entry key="election/queries.rell">
                                <string>import user;
import util;

query eligible_for_voting(name): boolean {
	val user = user.user@{ .name == name.lower_case() };
	return is_eligible_to_vote(user);
}

query get_election_candidates() {
	val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
	
    return temp_votes_counter@*{
        .representative_election_candidate.representative_election.id == current_election_id
    } ( 
    	@omit @sort_desc .votes,
    	.representative_election_candidate.user.display_name
    );
}

query get_next_election() {
    return representative_election@?{ .completed == false } ( .id, @sort_desc .timestamp ) limit 1;
}

query get_uncompleted_election() {
    return get_current_election_id();
}

query get_user_vote_in_election(name) {
	val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
	
    return representative_election_vote@?{
        .user == user.user@{ .name == name },
        .representative_election_candidate.representative_election.id == current_election_id
    } ( .representative_election_candidate.user.name ) limit 1;
}

query get_current_representative_period(timestamp) {
    return representative_election @? { .timestamp &lt;= timestamp, .completed == true } ( .id, @sort_desc .timestamp ) limit 1;
}

query blocks_until_next_election() {
	val recent_election_finished = election_block_details@?{} ( 
		@omit @sort_desc .started_height, 
		.finished_height
	) limit 1;
	
	if (recent_election_finished == null) {
		return 0;
	}
	
	require(recent_election_finished != -1, "There is an ongoing election");
	
	val next_election_block = recent_election_finished + governing_period_in_blocks();
	
	var current_block = block@?{} ( @sort_desc .block_height ) limit 1;
	
	if (current_block == null) {
		current_block = 0;
	}
	
	return next_election_block - current_block;
}

query blocks_until_election_wraps_up() {
	val recent_election = election_block_details@{} ( 
		@sort_desc .started_height, 
		.finished_height
	) limit 1;
	
	require(recent_election.finished_height == -1, "There is no ongoing election");
	
	val election_finishing_block = recent_election.started_height + election_duration_in_blocks();
	
	var current_block = block@?{} ( @sort_desc .block_height ) limit 1;
	
	if (current_block == null) {
		current_block = 0;
	}
	
	return election_finishing_block - current_block;
}
</string>
                            </entry>
                            <entry key="follow/index.rell">
                                <string>import user;

entity follow {
    key follower: user.user, follows: user.user;
}
</string>
                            </entry>
                            <entry key="follow/operations.rell">
                                <string>import user;
import util;

operation create_following(follower: text, descriptor_id: byte_array, follows: text) {
    require(follower != follows, util.app_error(util.error_type.ILLEGAL_ACTION, "Follow another user"));
    val user = user.get_and_charge_verified_user(follower, descriptor_id);
    create follow(follower = user, follows = user.user@{ .name == follows.lower_case() });
}

operation remove_following(follower: text, descriptor_id: byte_array, follows: text) {
    require(follower != follows, util.app_error(util.error_type.ILLEGAL_ACTION, "You can't unfollow yourself"));
    val user = user.get_and_charge_verified_user(follower, descriptor_id);
    delete follow@{ .follower == user, .follows == user.user@{ .name == follows.lower_case() } };
}
</string>
                            </entry>
                            <entry key="follow/queries.rell">
                                <string>import user;

query get_user_followers(name) {
    return follow@*{ .follows == user.user @ { .name == name } }( .follower.name );
}

query get_user_follows(name) {
    return follow@*{ .follower == user.user@{ .name == name } } ( .follows.name );
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/auth_basic.rell">
                                <string>// Auth type:

// "S" - single-sig
// "M" - multi-sig

struct single_sig_args {
       flags: set&lt;text&gt;;
       pubkey;
}

struct multi_sig_args {
       flags: set&lt;text&gt;;
       signatures_required: integer;
       pubkeys: list&lt;pubkey&gt;;
}

function check_single_sig_auth(args: byte_array, participants: list&lt;byte_array&gt;, required_flags: list&lt;text&gt;): boolean {
    require(participants.size() == 1);
    val ss_args = single_sig_args.from_bytes(args);
    return
          ss_args.flags.contains_all(required_flags)
            and
          is_signer(participants[0]);
}

function check_multi_sig_auth(args: byte_array, participants: list&lt;byte_array&gt;, required_flags: list&lt;text&gt;): boolean {
   val multi_sign_args = multi_sig_args.from_bytes(args);
   if (not (multi_sign_args.flags.contains_all(required_flags))) return false;
   var num_sign = multi_sign_args.signatures_required;
   for(s in participants) {
      if(is_signer(s)) {
          num_sign -= 1;
          if(num_sign &lt; 1) {return true;}
      }
   }
   return false;
}

function check_auth_args (a_t: text, args: byte_array, participants: list&lt;byte_array&gt;, required_flags: list&lt;text&gt;): boolean {
    return when (a_t) {
        "S" -&gt; check_single_sig_auth(args, participants, required_flags);
        "M" -&gt; check_multi_sig_auth(args, participants, required_flags);
        else -&gt; false;
    };
}



function require_auth (account, descriptor_id: byte_array, required_flags: list&lt;text&gt;) {
   val account_auth_descriptor = account_auth_descriptor @ {
     account,
     .descriptor_id == descriptor_id
   };
	
	require(is_valid(account_auth_descriptor));
	
   	require(
		check_auth_args(
       		account_auth_descriptor.auth_type,
       		account_auth_descriptor.args,
       		auth_descriptor_participant @* { account_auth_descriptor } ( .id ),
       		required_flags
		)
   );
   
   update_auth_descriptor_rule_variables(account_auth_descriptor);
   delete_expired_auth_descriptors(account);
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/auth_descriptor_rule.rell">
                                <string>
enum rule_variable {
	block_height,
	block_time,
	op_count
}

enum rule_operator {
	lt,
	le,
	eq,
	ge,
	gt
}

struct rule_expression {
	variable: text;
	operator: text;
	value: gtv;
}

entity auth_descriptor_rule_variable {
	key account_auth_descriptor, name;
	mutable value: byte_array;
}

function is_valid(auth_descriptor: account_auth_descriptor): boolean {
	// check if rules is null (encoded null is equal to 0xa0020500)
	if (auth_descriptor.rules == x'a0020500') {
		return true;
	}
	
	return is_rule_valid(
		gtv.from_bytes(auth_descriptor.rules), 
		load_variables(auth_descriptor)
	);
}

function is_rule_valid(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(rule);
	val operator = text.from_gtv(parameters[1]);
	
	if (operator == "and") {
		return handle_composed_rule(rule, variables);
	} else {
		return handle_single_rule(rule, variables);
	}
}

function handle_single_rule(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	return evaluate_int_variable_rule(
		rule_expression.from_gtv(rule), 
		variables
	);	
}

 
function handle_composed_rule(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(rule);
	val operator = text.from_gtv(parameters[1]);
	if (operator == "and") {
		return is_rule_valid(parameters[0], variables) and is_rule_valid(parameters[2], variables);
	} else {
		return false;
	}
}



function is_active(account_auth_descriptor): boolean {
	if (account_auth_descriptor.rules == x'a0020500') {
		return true;
	}
	
	return is_rule_active(gtv.from_bytes(account_auth_descriptor.rules), map&lt;text, gtv&gt;());
}


function is_rule_active(r: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(r);
	val operator = text.from_gtv(parameters[1]);
	when (operator) {
		"and" -&gt; {
			return is_rule_active(parameters[0], variables) and is_rule_active(parameters[2], variables);
		}
		else -&gt; {
			return is_simple_rule_active(r, variables);
		}
	}
}

function is_simple_rule_active(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(rule);
	val variable_name = text.from_gtv(parameters[0]);
	when (rule_variable.value(variable_name)) {
		rule_variable.block_height -&gt; {
			return is_block_height_rule_active(rule);
		}
		rule_variable.block_time -&gt; {
			return is_block_time_rule_active(rule);
		}		
		rule_variable.op_count -&gt; {
			return is_op_count_rule_active(rule);
		}
	}
}

/*
 *  Variables
 */

function evaluate_int_variable_rule(rule: rule_expression, variables: map&lt;text, gtv&gt;): boolean {
	val variable = rule_variable.value(rule.variable);
	val operator = rule_operator.value(rule.operator);
	val current_value = variable_value(variable, variables);
	val defined_value = integer.from_gtv(rule.value);

	when (operator) {
		rule_operator.lt -&gt; {
			return current_value &lt; defined_value;
		}
		rule_operator.le -&gt; {
			return current_value &lt;= defined_value;
		}
		rule_operator.eq -&gt; {
			return current_value == defined_value;
		}
		rule_operator.ge -&gt; {
			return current_value &gt;= defined_value;
		}
		rule_operator.gt -&gt; {
			return current_value &gt; defined_value;
		}
	}
}


/*
 * Called from _add_auth_descriptor function
 */
function setup_auth_descriptor_variables(account_auth_descriptor) {
	
	if (account_auth_descriptor.rules == x'a0020500') {
		return;
	} 
	
	val variables = get_variable_names_set(gtv.from_bytes(account_auth_descriptor.rules));
	
	for (variable in variables) {
		when (variable) {
			rule_variable.op_count.name -&gt; {
				create auth_descriptor_rule_variable(
					account_auth_descriptor,
					name = variable,
					value = op_count_variable_initial_value().to_bytes()
				);
			}
		}
	}
}
 
function update_variables(account_auth_descriptor, variables: map&lt;text, gtv&gt;) {
	for ((name, value) in variables) {
		val variable = auth_descriptor_rule_variable @ { account_auth_descriptor, name };
		val int_value = integer.from_gtv(value);
		
		when (name) {
			rule_variable.op_count.name -&gt; {
				variable.value = (int_value + 1).to_gtv().to_bytes();
			}
		}
	}
}
 
function variable_value(variable: rule_variable, variables: map&lt;text, gtv&gt;): integer {
	when (variable) {
		rule_variable.block_height -&gt; {
			return op_context.block_height;
		}
		rule_variable.block_time -&gt; {
			return op_context.last_block_time;
		}
		rule_variable.op_count -&gt; {
			return integer.from_gtv(variables[rule_variable.op_count.name]);
		}
	}
}

/*
 * Analyze the rules before assigning them to an authenticator descriptor
 */
 function analyze_auth_descriptor_rules(rules: gtv, hop: integer) {
 	require(hop&lt;3, "too many rules");
 	val rules_bytes = rules.to_bytes(); 
 	if (rules_bytes == x'a0020500') {
		return;
	}
	
 	val params = list&lt;gtv&gt;.from_gtv(rules);
 	require(params.size() &lt;=3);
 	
 	val operator = text.from_gtv(params[1]);
 	if(operator == "and") {
 		analyze_auth_descriptor_rules(params[0], hop+1); 
 		analyze_auth_descriptor_rules(params[2], hop+1);
 	} 	
 	
	return;
 }

/*
 * Returns set of variable names used in a rule
 */
function get_variable_names_set(rules: gtv): set&lt;text&gt; {
	val parameters = list&lt;gtv&gt;.from_gtv(rules);
	val operator = text.from_gtv(parameters[1]);
	var vars = set&lt;text&gt;();
	if (operator == "and") {
		vars.add_all(get_variable_names_set(parameters[0]));
		vars.add_all(get_variable_names_set(parameters[2]));
	} else {
		vars.add(text.from_gtv(parameters[0]));
	}
	return vars;
} 

function load_variables(account_auth_descriptor): map&lt;text, gtv&gt; {
	val variables = auth_descriptor_rule_variable @* { account_auth_descriptor };
	
	val variables_map = map&lt;text, gtv&gt;();
	for (variable in variables) {
		variables_map[variable.name] = gtv.from_bytes(variable.value);
	}
	
	return variables_map;
}

function update_auth_descriptor_rule_variables(account_auth_descriptor) {
	val variables = load_variables(account_auth_descriptor);
	update_variables(account_auth_descriptor, variables);
}

/*
 * auth descriptor cleanup
 */

function delete_expired_auth_descriptors(account) {
	val auth_descriptors = account_auth_descriptor @* { account };
	
	for (auth_descriptor in auth_descriptors) {
		if (not (is_active(auth_descriptor) and is_valid(auth_descriptor))) {
			_delete_auth_descriptor(auth_descriptor);
		}
	}
}

/****************************************************************************************
 *                                     block_time                                       *
 ****************************************************************************************/

function is_block_time_rule_active(r: gtv): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(r);
	val operator = rule_operator.value(text.from_gtv(parameters[1]));
	val value = integer.from_gtv(parameters[2]);
	when (operator) {
		rule_operator.gt -&gt; {
			return op_context.last_block_time &gt; value;
		}
		rule_operator.ge,
		rule_operator.eq -&gt; {
			return op_context.last_block_time &gt;= value;
		}
		else -&gt; {
			return true;
		}
	}
}


/****************************************************************************************
 *                                  block_height                                        *
 ****************************************************************************************/

function is_block_height_rule_active(r: gtv): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(r);
	val operator = rule_operator.value(text.from_gtv(parameters[1]));
	val value = integer.from_gtv(parameters[2]);
	when (operator) {
		rule_operator.gt -&gt; {
			return op_context.block_height &gt; value;
		}
		rule_operator.ge,
		rule_operator.eq -&gt; {
			return op_context.block_height &gt;= value;
		}
		else -&gt; {
			return true;
		}
	}
}


/****************************************************************************************
 *                                     op_count                                         *
 ****************************************************************************************/
 
 function op_count_variable_initial_value(): gtv {
 	return (1).to_gtv();
 }
 
 function is_op_count_rule_active(rule: gtv): boolean {
 	return true;
 }</string>
                            </entry>
                            <entry key="lib/ft3/account/module.rell">
                                <string>@mount('ft3')
module;

import core: ^.core;

struct auth_descriptor {
    auth_type: text;
    participants: list&lt;byte_array&gt;;
    args: list&lt;gtv&gt;;
    rules: gtv;
}

entity account {
    key id: byte_array;
}

entity account_meta {
    meta_key: text;
    value: byte_array;
    index account, meta_key;
    index meta_key, value;
}

entity account_auth_descriptor {
     descriptor_id: byte_array;
     key account, descriptor_id;
     index descriptor_id;
     auth_type: text;
     args: byte_array;
     rules: byte_array;
}

entity auth_descriptor_participant {
    key account_auth_descriptor, id: byte_array;
}


// rate limiter
entity rl_state {
    key account;
    mutable points: integer;
    mutable last_update: timestamp;
    mutable max_points: integer;
    mutable recovery_time: timestamp;
}

function _add_auth_descriptor (account, auth_descriptor) {
     val descriptor_id = auth_descriptor.hash();
     
     analyze_auth_descriptor_rules(auth_descriptor.rules, 0);
     
     val account_auth_descriptor = create account_auth_descriptor (
        account, descriptor_id,
        auth_descriptor.auth_type,
        args = auth_descriptor.args.to_gtv().to_bytes(),
        rules = auth_descriptor.rules.to_gtv().to_bytes()
     );
     
     for (participant in auth_descriptor.participants) {
        require(is_signer(participant));
        create auth_descriptor_participant(account_auth_descriptor, id = participant);
     }
     
     setup_auth_descriptor_variables(account_auth_descriptor);
}

function _delete_auth_descriptor(auth_descriptor: account_auth_descriptor) {
	delete auth_descriptor_rule_variable @* { auth_descriptor };
	delete auth_descriptor_participant @* { auth_descriptor };
	delete auth_descriptor;
}

function _delete_all_auth_descriptors_exclude(account, auth_descriptor_id: byte_array) {
	delete (adrv: auth_descriptor_rule_variable, ad: account_auth_descriptor) @* {
		ad.account == account, ad.descriptor_id != auth_descriptor_id, adrv.account_auth_descriptor == ad		
	};
	
	delete (adp: auth_descriptor_participant, ad: account_auth_descriptor) @* {
        ad.account == account and ad.descriptor_id != auth_descriptor_id and adp.account_auth_descriptor == ad
    };

    delete account_auth_descriptor @* {
       .account == account,
       .descriptor_id != auth_descriptor_id
    };
}

function create_account_with_auth (auth_descriptor): byte_array {
     val id = auth_descriptor.hash();
     val acc = create account (id);
     _add_auth_descriptor(
        acc, auth_descriptor
     );
     val max_points = core.my_blockchain_info.rate_limit_max_points;
     val recovery_time = core.my_blockchain_info.rate_limit_recovery_time;
     val points_at_start = core.my_blockchain_info.rate_limit_points_at_account_creation;
     
	create rl_state(acc, .points = points_at_start, .last_update = op_context.last_block_time, max_points, recovery_time);
    
    return id;
}

function auth_and_log(account_id: byte_array, auth_descriptor_id: byte_array, required_flags: list&lt;text&gt;): account {
	val account = account @ { .id == account_id };
	rate_limit(account);
	require_auth(account, auth_descriptor_id, required_flags);
	return account;
}

query is_auth_descriptor_valid(account_id: byte_array, auth_descriptor_id: byte_array) {
    return is_valid(account_auth_descriptor @ {
        .account.id == account_id,
        .descriptor_id == auth_descriptor_id
    });
}

query get_account_auth_descriptors(id: byte_array) {
    return account_auth_descriptor @* {
        .account.id == id
    } (
        id = .descriptor_id,
        type = .auth_type,
        args = .args
    );
}

query get_account_by_id(id: byte_array) {
    return account @? { id } ( .id );
}

query get_account_by_auth_descriptor(auth_descriptor) {
    return account @? { .id == auth_descriptor.hash() } ( .id );
}

query get_accounts_by_participant_id(id: byte_array) {
    return auth_descriptor_participant @* { id } ( .account_auth_descriptor.account.id );
}

query get_accounts_by_auth_descriptor_id(descriptor_id: byte_array) {
    return account_auth_descriptor @* { descriptor_id } ( .account.id );
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/operations/module.rell">
                                <string>@mount('ft3')
module;

import acc: ^^.account;
import core: ^^.core;


operation delete_auth_descriptor(account_id: byte_array, auth_descriptor_id: byte_array, delete_descriptor_id: byte_array) {
    val flags = if (auth_descriptor_id == delete_descriptor_id) list&lt;text&gt;() else ["A"];

    val account = acc.auth_and_log(account_id, auth_descriptor_id, flags);

    acc._delete_auth_descriptor(acc.account_auth_descriptor @ {
        .account == account,
        .descriptor_id == delete_descriptor_id
    });
}

operation delete_all_auth_descriptors_exclude(account_id: byte_array, auth_descriptor_id: byte_array) {
    val account = acc.auth_and_log(account_id, auth_descriptor_id, ["A"]);

	acc._delete_all_auth_descriptors_exclude(account, auth_descriptor_id);
}

operation add_auth_descriptor (account_id: byte_array, auth_id: byte_array, new_desc: acc.auth_descriptor) {
      val account = acc.auth_and_log(account_id, auth_id, ["A"]);
      acc._add_auth_descriptor(account, new_desc);
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/rate_limit.rell">
                                <string>import ^.core;


function rate_limit (account) {
	if(core.my_blockchain_info.rate_limit_active == false ) return;
    val max_counter = core.my_blockchain_info.rate_limit_max_points;
    val recovery_time = core.my_blockchain_info.rate_limit_recovery_time;
    val stat = rl_state@{account} (.points, .last_update);
    val delta = op_context.last_block_time - stat.last_update;
    var got_points = 0;
    var update_time = stat.last_update;

    if (delta &gt; recovery_time)
    {
        got_points = delta / recovery_time;
        update_time = stat.last_update + got_points * recovery_time;
        if (got_points + stat.points &gt; max_counter) {
            got_points = max_counter - stat.points;
            // if user is at maximum reset his 
            // timer
            update_time = op_context.last_block_time;
        }
    }
    
    require(stat.points + got_points &gt; 0);
    
    update rl_state@{account} (
        .points += got_points - 1,
        .last_update = update_time
    );
}


query get_account_rate_limit_last_update(account_id: byte_array) {
	if(core.my_blockchain_info.rate_limit_active == false ) return (points = 0, last_update = 0);
	val t= rl_state@{.account.id == account_id}
	(
		.points, 
		.last_update
	);
	
	return t;
}

query get_last_timestamp(): integer {
	return (block@{.timestamp&gt;0}(@sort_desc .timestamp) limit 1);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/asset.rell">
                                <string>import acc: ^.account;

entity asset {
    id: byte_array;
    key id;
    name;
    issuing_chain_rid: byte_array;
}

entity balance {
    key acc.account, asset;
    mutable amount: integer = 0;
}

function ensure_balance(acc.account, asset): balance {
    val balance = balance @? {asset, account};
    if (balance != null) {
       return balance;
    }
    else return create balance(account, asset, amount = 0);
}

function register_asset (name, issuing_chain_rid: byte_array): asset {
   val id = (name, issuing_chain_rid).hash();
   return create asset (id, name, issuing_chain_rid);
}

function _get_asset_balances(account_id: byte_array): list&lt;(id:byte_array,name:text,amount:integer,chain_id:byte_array)&gt; {
    return balance @* { .account.id == account_id } (
      id = .asset.id,
      name = .asset.name,
      amount = .amount,
      chain_id = .asset.issuing_chain_rid
    );
}

query get_asset_balances(account_id: byte_array) {
    return _get_asset_balances(account_id);
}

query get_asset_balance(account_id: byte_array, asset_id: byte_array) {
    return balance @? {
        .account.id == account_id,
        .asset.id == asset_id
    } (
        id = .asset.id,
        name = .asset.name,
        amount = .amount,
        chain_id = .asset.issuing_chain_rid
    );
}

query get_asset_by_name(name) {
    return asset @* { name } (
        .id,
        .name,
        .issuing_chain_rid
    );
    
}

query get_asset_by_id(asset_id: byte_array) {
	return asset@{
		.id == asset_id
	}(
		id = .id,
		name = .name,
		issuing_chain_rid = .issuing_chain_rid
		
	);
}

query get_all_assets() {
	return asset@*{}(
		id = .id,
		name = .name,
		issuing_chain_rid = .issuing_chain_rid	
	);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/dev_op.rell">
                                <string>module;

import ft3: ^^.core;
import acc: ^^.account;

object dev_state {
   mutable allow_dev_ops: boolean = true;
}

function require_dev() {
    require(dev_state.allow_dev_ops);
}

function dev_give_points_(account: acc.account, amount: integer) {
	require_dev();
	update acc.rl_state@{account}(.points += amount);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/history.rell">
                                <string>import acc: ^.account;

@log entity payment_history_entry {
    index acc.account, asset;
    delta: integer;

    // helps to locate exact position of payment entry in transaction
    op_index: integer;
    is_input: boolean;
    entry_index: integer;
}

query get_payment_history(account_id: byte_array, after_block: integer) {
    return payment_history_entry @* {
        acc.account @ { account_id },
        .transaction.block.block_height &gt; after_block
    } (
        delta = .delta,
        asset = .asset.name,
        asset_id = .asset.id,
        is_input = .is_input,
        timestamp = .transaction.block.timestamp,
        block_height = .transaction.block.block_height,
        entry_index = .entry_index,
        tx_rid = .transaction.tx_rid,
        tx_data = .transaction.tx_data
    );
}
</string>
                            </entry>
                            <entry key="lib/ft3/core/module.rell">
                                <string>@mount('ft3')
module;

struct module_args {
	my_blockchain_name: text;
	my_blockchain_website: text;
	my_blockchain_description: text;
	rate_limit_active: boolean;
	rate_limit_max_points: integer;
    rate_limit_recovery_time: integer;
    rate_limit_points_at_account_creation: integer;    
}</string>
                            </entry>
                            <entry key="lib/ft3/core/my_blockchain_info.rell">
                                <string>
object my_blockchain_info {
    mutable name: text = chain_context.args.my_blockchain_name;
    mutable website: text = chain_context.args.my_blockchain_website;
    mutable description: text = chain_context.args.my_blockchain_description;
    mutable rate_limit_active: boolean = chain_context.args.rate_limit_active;
    mutable rate_limit_max_points: integer = chain_context.args.rate_limit_max_points;
    mutable rate_limit_recovery_time: integer = chain_context.args.rate_limit_recovery_time;
    mutable rate_limit_points_at_account_creation: integer = chain_context.args.rate_limit_points_at_account_creation;
}


//operation update_blockchain(name, website: text, description: text) {
//    blockchain.name = name;
//    blockchain.website = website;
//    blockchain.description = description;
//}

query get_blockchain_info() {
    return (
        name = my_blockchain_info.name,
        website = my_blockchain_info.website,
        description = my_blockchain_info.description,
        rate_limit_active = my_blockchain_info.rate_limit_active,
        rate_limit_max_points = my_blockchain_info.rate_limit_max_points,
        rate_limit_recovery_time = my_blockchain_info.rate_limit_recovery_time,
        rate_limit_points_at_account_creation = chain_context.args.rate_limit_points_at_account_creation
    );
}

</string>
                            </entry>
                            <entry key="lib/ft3/core/operations/transfer.rell">
                                <string>@mount('ft3')
module;

import ft3: ^^;


operation transfer (inputs: list&lt;ft3.xfer_input&gt;, outputs: list&lt;ft3.xfer_output&gt;) {
    ft3._transfer(inputs, outputs);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/transfer.rell">
                                <string>import acc: ^.account;

struct xfer_input {
   account_id: byte_array;
   asset_id: byte_array;
   auth_descriptor_id: byte_array;
   amount: integer;
   extra: map&lt;text, gtv&gt;;
}

struct xfer_output {
   account_id: byte_array;
   asset_id: byte_array;
   amount: integer;
   extra: map&lt;text, gtv&gt;;
}

function deduct_balance (acc.account, asset, d_amount: integer) {
    val b = balance @ { account, asset };
    require( b.amount &gt;= d_amount, "Balance is too low");
    update b (amount -= d_amount);
}

function consume_input (i: xfer_input, idx: integer, assets: map&lt;asset, integer&gt;): payment_history_entry {
      val asset = asset @ { .id == i.asset_id };
      val account = acc.auth_and_log(i.account_id, i.auth_descriptor_id, ["T"]);
      require( i.amount &gt; 0, "Amount should be non 0 positive." );

      deduct_balance(account, asset, i.amount);
      assets[asset] = i.amount + if (asset in assets) assets[asset] else 0;
      return create payment_history_entry (
        account,
        asset,
        .delta = i.amount,
        .op_index = 500, //op_context ???
        .is_input = true,
        .entry_index = idx
      );
}

function process_transfer_output (o: xfer_output, idx: integer, available_assets: map&lt;asset, integer&gt;): payment_history_entry {
      if (o.extra.contains("reg_auth_desc")) {
          val auth_desc = acc.auth_descriptor.from_gtv(o.extra["reg_auth_desc"]);
          require(o.account_id
           == acc.create_account_with_auth(auth_desc));
      }

      val target_account = acc.account @ { .id == o.account_id };
      val asset = asset @ { .id == o.asset_id };
      require(o.amount &gt; 0, "You cannot tx output negative numbers");
      require( available_assets[asset] &gt;= o.amount );
      available_assets[asset] -= o.amount;
      require(available_assets[asset] &gt;= 0);
      val balance = ensure_balance(target_account, asset);
      balance.amount += o.amount;

      return create payment_history_entry (
        .account = target_account,
        asset,
        .delta = o.amount,

        .op_index = 500, // something from op_context,
        .is_input = false,
        .entry_index = idx
      );
}

function _transfer (inputs: list&lt;xfer_input&gt;, outputs: list&lt;xfer_output&gt;) {
   val sum_inputs = map&lt;asset, integer&gt;();
   var idx = 0;
   for (i in inputs) {
      consume_input(i, idx, sum_inputs);
      idx += 1;
   }

   idx = 0;
   for (o in outputs) {
      process_transfer_output(o, idx, sum_inputs);
      idx += 1;
   }
}
</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/blockchain.rell">
                                <string>import ft3: ^.core;
import acc: ^.account;


entity asset_origin {
    key ft3.asset;
    origin_chain_rid: byte_array;
}

entity linked_chain {
    key chain_rid: byte_array;
}

function blockchain_account_id (blockchain_rid: byte_array): byte_array {
   return ("B", blockchain_rid).hash();
}

function ensure_blockchain_account (blockchain_rid: byte_array): acc.account {
   val blockchain_account_id = blockchain_account_id(blockchain_rid);
   val acc = acc.account @? { .id == blockchain_account_id };
   return if (acc??)  acc
   else create acc.account (id = blockchain_account_id);
}

function get_blockchain_account (blockchain_rid: byte_array): acc.account {
   return acc.account @ { .id == blockchain_account_id(blockchain_rid) };
}


query get_linked_chains() {
    return linked_chain @* {} ( .chain_rid );
}

query is_linked_with_chain(chain_rid: byte_array) {
    return linked_chain @? { chain_rid } != null;
}
</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/module.rell">
                                <string>@mount('ft3.xc')
module;
</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/structures.rell">
                                <string>struct operation_rec {
   name;
   args: list&lt;gtv&gt;;
}

struct transaction_body_rec {
    blockchain_rid: byte_array;
    operations: list&lt;operation_rec&gt;;
    signers: list&lt;gtv&gt;;
}

struct transaction_rec {
   body: transaction_body_rec;
   signatures: list&lt;gtv&gt;;
}

struct transaction_proof {
     tx: virtual&lt;transaction_rec&gt;;
     // block_header: byte_array;
     // merkle_path: virtual&lt;list&lt;byte_array&gt;&gt;;
     // tx_index: integer;
     block_rid: byte_array;
     block_signers: list&lt;byte_array&gt;;
     signatures: list&lt;byte_array&gt;;     
}

function verify_transaction_proof( p: transaction_proof ) {
   // TODO
}</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/transfer.rell">
                                <string>import ft3: ^.core;

struct xc_target {
    account_id: byte_array;
    extra: map&lt;text, gtv&gt;;
}

function add_to_blockchain_balance (blockchain_rid: byte_array, ft3.asset, amount: integer) {
    require( chain_context.blockchain_rid != blockchain_rid ); // cannot add to own account

    val origin_chain_rid = asset_origin @? { asset } .origin_chain_rid;

    if (exists(origin_chain_rid) and (blockchain_rid == origin_chain_rid)) {
       // do nothing. in future we might track origin
    } else {
         val bc_acc = ensure_blockchain_account(blockchain_rid);
         ft3.ensure_balance(bc_acc, asset).amount += amount;
    }
}


struct init_xfer_args {
          source: ft3.xfer_input;
          target: xc_target;
          hops: list&lt;byte_array&gt;;
}

entity applied_transfers { key tx_rid: byte_array; }


</string>
                            </entry>
                            <entry key="lib/ft3/ft3_basic_dev.rell">
                                <string>module;

namespace ft3 {
	import acc: lib.ft3.account;
	import acc_op: lib.ft3.account.operations;
	import core: lib.ft3.ft3_basic_dev;
	import transfer_op: lib.ft3.core.operations.transfer;
//	import lib.ft3.crosschain;
//	import lib.ft3.crosschain.operations;
	
	import lib.ft3.operations.dev_op_account;
	import lib.ft3.operations.dev_op_asset;
	import lib.ft3.operations.dev_op_balance;
	import lib.ft3.operations.dev_op_rate_limit;
}

</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_account.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import acc: ^^.account; 


operation dev_register_account (acc.auth_descriptor) {
    dev_op.require_dev();
    acc.create_account_with_auth( auth_descriptor );
}
</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_asset.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import ft3: ^^.core;

import xft3: ^^.crosschain; 

operation dev_register_asset (name, issuing_chain_rid: byte_array) {
    dev_op.require_dev();
    ft3.register_asset(name, issuing_chain_rid);
}

operation dev_register_xc_asset (name, issuing_chain_rid: byte_array, origin_chain_rid: byte_array) {
    dev_op.require_dev();   
    val asset = ft3.register_asset(name, issuing_chain_rid);
    create xft3.asset_origin (asset, origin_chain_rid);
}
</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_balance.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import ft3: ^^.core;
import acc: ^^.account;


operation dev_give_balance (asset_id: byte_array, account_id: byte_array, amount: integer) {
    dev_op.require_dev();
    require(amount &gt;= 0);
    ft3.ensure_balance( acc.account @ { account_id }, ft3.asset @ { .id == asset_id } ).amount += amount;
}</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_rate_limit.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import acc: ^^.account;



/*
 * Can be negative
 */
operation dev_give_points(account_id: byte_array, amount: integer){
	val account = acc.account@{.id == account_id};
	dev_op.dev_give_points_(account, amount);
}

operation dev_free_op(account_id: byte_array) {
	// this operation does not cost points in the rate limit
	val account = acc.account@{.id == account_id};
	dev_op.dev_give_points_(account, 1);
	acc.rate_limit(account);
}</string>
                            </entry>
                            <entry key="main.rell">
                                <string>import lib.ft3.ft3_basic_dev;

// Remove for production
// ---

import user;
import topic;
import notifications;
import channel;
import follow;
import election;
import representative;
import chat;</string>
                            </entry>
                            <entry key="notifications/index.rell">
                                <string>import user;

entity notification {
    key id: text, user.user;
    trigger: text;
    content: text;
    mutable read: boolean;
    index timestamp;
}
</string>
                            </entry>
                            <entry key="notifications/operations.rell">
                                <string>import user;
import user.distrust;

operation create_notifications_for_users(name, descriptor_id: byte_array, id: text, trigger: text, content: text, usernames: set&lt;text&gt;) {
    val opr_user = user.get_verified_user(name, descriptor_id);

    for (username in usernames) {
        val toUser = user.user@?{ .name == username.lower_case() };
        if (toUser != null and distrust.user_distrust@?{ .distruster == toUser, .distrusted == opr_user } == null) {
            create notification(
                id = id,
                toUser,
                trigger = trigger,
                content = content,
                false,
                op_context.last_block_time
            );
        }
    }
}

operation remove_notifications_for_users(name, descriptor_id: byte_array, id: text, usernames: set&lt;text&gt;) {
    val user = user.get_verified_user(name, descriptor_id);

    for (username in usernames) {
        val to_user = user.user@?{ .name == username };
        if (to_user != null) {
            delete notification@?{ id, .user == to_user };
        }
    }
}

operation mark_notifications_since_timestamp_read(name, descriptor_id: byte_array, timestamp) {
    val user = user.get_verified_user(name, descriptor_id);
    update notification@*{ .user == user, .timestamp &gt; timestamp } ( read = true );
}</string>
                            </entry>
                            <entry key="notifications/queries.rell">
                                <string>import user;

query count_unread_user_notifications(name) {
    val user = user.user@{ .name == name };
    return notification@*{ .user == user, .read == false } ( .id );
}

query get_user_notifications_prior_to_timestamp(name, timestamp, page_size: integer) {
    val user = user.user@{ .name == name };
    return notification@*{ .user == user, .timestamp &lt; timestamp } (
        .id,
        .trigger,
        .content,
        .read,
        @sort_desc .timestamp
    ) limit page_size;
}
</string>
                            </entry>
                            <entry key="representative/functions.rell">
                                <string>import user;
import election;

function is_username_representative(name): boolean {
	val user = user.user@?{ .name == name};
	
	if (user == null) {
		return false;
	}
	
	val prev_election = election.get_latest_completed_election_id();
	
	if (prev_election == null) {
		return false;
	}
	
	return representative@?{ .user == user, .representative_election.id == prev_election } != null;
}

function is_user_suspended(rep: user.user, suspendee: user.user, timestamp): boolean {
	return user.user_suspension@?{ 
		.user == suspendee, 
		.suspended_by == rep,
		.suspended_until &gt;= timestamp
	} != null;
} </string>
                            </entry>
                            <entry key="representative/index.rell">
                                <string>import election;
import user;

entity representative {
    key user.user, election.representative_election;
}

entity representative_action {
    key id: byte_array;
    index representative;
    index timestamp;
    action: text;
}

entity representative_distrust {
	key distruster: user.user, representative;
}

import representative.report;
</string>
                            </entry>
                            <entry key="representative/operations.rell">
                                <string>import election;
import topic;
import user;
import util;

operation remove_topic(username: text, descriptor_id: byte_array, topic_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);

    val recent_election = election.representative_election@{ .completed == true } ( .id, @sort_desc .timestamp ) limit 1;
    val representative = representative @{ user, .representative_election.id == recent_election.id };

    val the_topic = topic.topic @{ .id == topic_id };
    
    create topic.topic_moderation(representative.user, the_topic);

    create representative_action(
        id = op_context.transaction.tx_rid,
        representative,
        op_context.last_block_time,
        action = "Topic /t/" + the_topic.id + " was removed by @" + user.display_name
    );
}

operation remove_topic_reply(username: text, descriptor_id: byte_array, topic_reply_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);

    val recent_election_id = require(election.get_latest_completed_election_id(), "No election has been held yet");
    val representative = representative @{ user, .representative_election.id == recent_election_id };

    val the_reply = topic.topic_reply @{ .id == topic_reply_id };
    
    create topic.topic_reply_moderation(representative.user, the_reply);

    create representative_action(
        id = op_context.transaction.tx_rid,
        representative,
        op_context.last_block_time,
        action = "Reply in topic /t/" + the_reply.topic.id + " was removed by @" + user.display_name
    );
}

operation suspend_user(username: text, descriptor_id: byte_array, user_to_be_suspended: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);

    val recent_election_id = require(election.get_latest_completed_election_id(), "No election has been held yet");
    val representative = representative @{ user, .representative_election.id == recent_election_id };

    val suspendee = user.user@{ .name == user_to_be_suspended };
    
    val action_id = "suspend_user:" + user_to_be_suspended;
	
	require(
		not is_user_suspended(user, suspendee, op_context.last_block_time), 
		"User already suspended"
	);
	
    val updated_times_suspended = user.user_suspension@*{
    	.user == suspendee,
    	.suspended_by == user
    }( .user ).size() + 1;
    
    val one_day_millis = 86400000;
    val days_suspended = updated_times_suspended * updated_times_suspended;
    val suspension_time_millis = days_suspended * one_day_millis;
	val suspended_until = op_context.last_block_time + suspension_time_millis;

	create user.user_suspension(user = suspendee, suspended_by = user, suspended_until);

    var daysString = " days ";
    if (days_suspended == 1) {
        daysString = " day ";
    }

    create representative_action(
        id = op_context.transaction.tx_rid,
        representative,
        op_context.last_block_time,
        action = "@" + suspendee.display_name + " was suspended for " + days_suspended + daysString +  "by @" + user.display_name
    );
}

operation distrust_representative(name, descriptor_id: byte_array, distrusted: name) {
	val user = user.get_and_charge_verified_user(name, descriptor_id);
	
	val recent_election_id = require(election.get_latest_completed_election_id(), "No election has been held yet");
	
	require(is_eligible_to_distrust(user, recent_election_id), "User is not eligible to distrust");
	
    val representative = representative @{ 
    	.user.name == distrusted.lower_case(), 
    	.representative_election.id == recent_election_id
    };
    
    val required_votes = election.temp_votes_counter@{
    	.representative_election_candidate.representative_election.id == recent_election_id
    } ( @sort_desc .votes ) limit 1;
    
    val distrusts = representative_distrust@*{ 
    	representative
    }( .distruster ).size();
    
    if (distrusts &gt;= 10 and distrusts &gt; required_votes) {
    	delete representative;
    } else {
    	create representative_distrust(user, representative);
    }
}

function is_eligible_to_distrust(user.user, prev_election_id: integer): boolean {	
	val recent_election_start = election.election_block_details@{
		.representative_election.id == prev_election_id
	} ( .started_height );
	
	if (user.registered &gt; recent_election_start) {
		log("User must have registered before the previous election started");
		return false;
	}
	
	val previous_election_completed = (election: election.representative_election, details: election.election_block_details)@?{
		election.id != prev_election_id,
		election == details.representative_election,
		election.completed == true
	} ( 
		details.finished_height,
		@omit @sort_desc election.timestamp
	) limit 1;
	
	if (previous_election_completed == null) {
		return true;
	}
	
	val number_of_topics = topic.topic@*{ 
		.author == user,
		.last_modified &gt; previous_election_completed,
		.last_modified &lt; recent_election_start
	}( .id ).size();
	
	val number_of_replies = topic.topic_reply@*{
		.author == user,
		.timestamp &gt; previous_election_completed,
		.timestamp &lt; recent_election_start
	}( .id ).size();
	
	return number_of_topics + number_of_replies &gt;= 5;
}</string>
                            </entry>
                            <entry key="representative/queries.rell">
                                <string>import election;
import user;

query get_representatives(): list&lt;name&gt; {
    val election = election.representative_election@?{ .completed == true } ( .id, @sort_desc .timestamp ) limit 1;

    if (election == null) {
        return list&lt;name&gt;();
    }

    return representative@*{
        .representative_election.id == election.id
    } ( .user.name );
}

query get_all_representative_actions(timestamp, page_size: integer) {
    return representative_action@*{
        .timestamp &lt; timestamp
    } (
        .id,
        representative = .representative.user.name,
        @sort_desc .timestamp,
        .action
    ) limit page_size;
}

query get_number_of_times_representative(name) {
    return representative@*{ .user.name == name } ( .representative_election.id ).size();
}

query is_user_suspended_by_me(username: name, user_to_be_suspended: name, timestamp) {
	val user = user.user@{ .name == username.lower_case() };
	val suspendee = user.user@{ .name == user_to_be_suspended.lower_case() };
	return is_user_suspended(user, suspendee, timestamp);
}</string>
                            </entry>
                            <entry key="representative/report/index.rell">
                                <string>import user;

entity representative_report {
    key id: text;
    index timestamp;
    text;
}
</string>
                            </entry>
                            <entry key="representative/report/operations.rell">
                                <string>import election;
import user;
import representative;
import util;

operation create_representative_report(username: text, descriptor_id: byte_array, id: text, text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create representative_report(id = id, op_context.last_block_time, text = text);
}
</string>
                            </entry>
                            <entry key="representative/report/queries.rell">
                                <string>query get_unhandled_representative_reports(timestamp) {
    return representative_report@*{
    	.timestamp &gt; timestamp
    } ( 
    	.id, 
    	@sort_desc .timestamp, 
    	.text
    ) limit 25;
}</string>
                            </entry>
                            <entry key="topic/functions.rell">
                                <string>import util;

function find_topic_by_id(id: text): topic {
    return topic@{ .id == id };
}

function require_mutable(post_timestamp: timestamp, op_timestamp: timestamp, action: text) {
	val fiveMinutesInMillis = 300000;
    require(
    	op_timestamp &lt; post_timestamp + fiveMinutesInMillis,
    	util.app_error(util.error_type.TOPIC_IMMUTABLE, action)
    );
}

function get_latest_poster_in_topic(id: text, topic_author: name): text {
	val latest_reply = topic_reply@?{ .topic.id == id} (
		@sort_desc .timestamp,
		.author
	) limit 1;
	
	if (latest_reply != null) {
		return latest_reply.author.display_name;
	} else {
		return topic_author;
	}
}</string>
                            </entry>
                            <entry key="topic/index.rell">
                                <string>import user;

entity topic {
    key id: text;
    index author: user.user;
    timestamp;
    mutable last_modified: timestamp;
    index last_modified;
    title: name;
    mutable message: text;
}

entity topic_moderation {
	key user.user, topic;
}

entity topic_reply {
    key id: text;
    index topic;
    index author: user.user;
    index timestamp;
    is_sub_reply: boolean = false;
    index is_sub_reply;
    mutable message: text;
}

entity topic_reply_moderation {
	key user.user, topic_reply;
}

entity sub_reply {
    key parent_reply: topic_reply, child_reply: topic_reply;
}

struct ext_topic {
	id: text;
	author: text;
	title: text;
	message: text;
	timestamp;
	last_modified: timestamp;
	latest_poster: name;
	moderated_by: list&lt;name&gt;;
}

struct ext_topic_reply {
	id: text;
	topic_id: text;
	author: text;
	message: text;
	is_sub_reply: boolean;
	timestamp;
	moderated_by: list&lt;name&gt;;
}

import topic.rating;
import topic.subscription;
</string>
                            </entry>
                            <entry key="topic/operations.rell">
                                <string>import channel;
import topic.rating;
import user;
import topic.subscription;
import topic.poll;

operation create_topic(id: text, descriptor_id: byte_array, username: text, channel_key: name, channel_name: name, title: name, message: text) {
    val pattern = ".{3,40}";
    require(title.matches(pattern), "Title [" + title + "] is invalid, must match: " + pattern);
    
    val author = user.get_and_charge_verified_user(username, descriptor_id);

    val topic = create topic(
        id = id,
        author,
        timestamp = op_context.last_block_time,
        last_modified = op_context.last_block_time,
        title = title,
        message = message
    );

    create channel.channel(name = channel_key.lower_case(), topic, op_context.last_block_time, display_name = channel_name);
    create rating.tmp_topic_rating (topic, 0);
        
    for (suspension in user.user_suspension@*{ .user == author, .suspended_until &gt; op_context.last_block_time }) {
    	create topic_moderation(suspension.suspended_by, topic);
    }
}

operation modify_topic(id: text, descriptor_id: byte_array, username: text, text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);

    val topic = topic@{ .id == id, .author == author };
    require_mutable(topic.timestamp, op_context.last_block_time, "Modify topic");

    update topic ( message = text );
}

operation delete_topic(id: text, descriptor_id: byte_array, username: text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);

    val topic = topic@{ .id == id, .author == author };
    require_mutable(topic.timestamp, op_context.last_block_time, "Delete topic");
    delete channel.channel@{ topic };
    delete rating.tmp_topic_rating@{ topic };
    delete subscription.subscription@?{ topic };
    
    val opt_poll = poll.poll@?{ topic };
    if (opt_poll != null) {
    	delete poll.poll_option@*{ .poll == opt_poll };
    	delete poll.poll_vote@*{ .poll == opt_poll };
    	delete opt_poll;
    }
    
	delete topic;
}

operation create_reply(topic_id: text, descriptor_id: byte_array, id: text, username: text, message: text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);
    val topic = find_topic_by_id(topic_id);

    val reply = create topic_reply(
        id = id,
        topic,
        author,
        timestamp = op_context.last_block_time,
        message = message
    );
    
    for (suspension in user.user_suspension@*{ .user == author, .suspended_until &gt; op_context.last_block_time }) {
    	create topic_reply_moderation(suspension.suspended_by, reply);
    }

     update topic ( last_modified = op_context.last_block_time);
}

operation modify_reply(id: text, descriptor_id: byte_array, username: text, text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);

    val reply = topic_reply@{ .id == id, .author == author };
    require_mutable(reply.timestamp, op_context.last_block_time, "Modify reply");

    update reply ( message = text );
}

operation delete_reply(id: text, descriptor_id: byte_array, username: text) {
	val author = user.get_and_charge_verified_user(username, descriptor_id);
	val reply = topic_reply@{ id, author };
	require_mutable(reply.timestamp, op_context.last_block_time, "Delete reply");
	
	delete sub_reply@?{ .child_reply == reply };
	delete reply;
}

operation create_sub_reply(topic_id: text, descriptor_id: byte_array, parent_reply_id: text, id: text, username: text, message: text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);
    val topic = find_topic_by_id(topic_id);

    val topic_reply = create topic_reply(
        id = id,
        topic,
        author,
        timestamp = op_context.last_block_time,
        is_sub_reply = true,
        message = message	
    );
    
    for (suspension in user.user_suspension@*{ .user == author, .suspended_until &gt; op_context.last_block_time }) {
    	create topic_reply_moderation(suspension.suspended_by, topic_reply);
    }

    create sub_reply(
        parent_reply = topic_reply@{ .id == parent_reply_id },
        child_reply = topic_reply
    );

    update topic ( last_modified = op_context.last_block_time);
}</string>
                            </entry>
                            <entry key="topic/poll/index.rell">
                                <string>import topic;
import user;

entity poll {
	key topic.topic;
	text;
}

entity poll_option {
	key poll, text;
	mutable votes: integer;
}

entity poll_vote {
	key poll, user.user;
	poll_option;
}

struct poll_record {
	question: text;
	options: list&lt;option_record&gt;;
}

struct option_record {
	option: text;
	votes: integer;
}</string>
                            </entry>
                            <entry key="topic/poll/operations.rell">
                                <string>import user;
import topic;

operation create_poll(id: text, descriptor_id: byte_array, 
	username: text, question: text, options: list&lt;text&gt;
) {
	val author = user.get_and_charge_verified_user(username, descriptor_id);
	val topic = topic.topic@{ .id == id, author };
	
	val poll = create poll(topic, question);
	
	for (option in options) {
		create poll_option(poll, option, 0);
	}
}

operation vote_for_poll_option(id: text, descriptor_id: byte_array, username: text, option: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	
	val poll_opt = poll_option@{ .poll.topic.id == id, .text == option };

	create poll_vote(poll_opt.poll, user, poll_opt);
	update poll_opt ( .votes+1 );
}</string>
                            </entry>
                            <entry key="topic/poll/queries.rell">
                                <string>query get_poll(topic_id: text): poll_record? {
	val poll = poll@?{ .topic.id == topic_id };
	
	if (poll == null) {
		return null;
	}
	
	val options = list&lt;option_record&gt;();
	for (opt in poll_option@*{ .poll == poll }) {
		options.add(option_record(opt.text, opt.votes));
	}
	
	return poll_record(poll.text, options);
}

query get_poll_vote(topic_id: text, username: text): text? {
	val vote = poll_vote@?{ 
		.poll.topic.id == topic_id, 
		.user.name == username.lower_case()
	};
	
	if (vote == null) return null;
	return vote.poll_option.text;
}</string>
                            </entry>
                            <entry key="topic/queries.rell">
                                <string>import channel;
import follow;
import topic.rating;
import user;
import representative;

query get_topics_after_timestamp(timestamp, page_size: integer) {
    val topics = topic@*{ .last_modified &gt; timestamp } (
        .id,
        author=.author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_prior_to_timestamp(timestamp, page_size: integer): list&lt;ext_topic&gt; {
    val topics = topic@*{ .last_modified &lt; timestamp }(
        .id,
        author = .author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    ) limit page_size;
        
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
  	   	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topic_replies_prior_to_timestamp(username: name, topic_id: text, timestamp, page_size: integer) {	
    val replies = topic_reply@*{
        topic@{ .id == topic_id },
        .timestamp &lt; timestamp,
        .is_sub_reply == false
    }(
        .id,
        topic_id = .topic.id,
        author= .author.display_name,
        .message,
        .is_sub_reply,
        @sort_desc .timestamp
    ) limit page_size;
    
    val ext_replies = list&lt;ext_topic_reply&gt;();
    for (reply in replies) {
    	val moderated_by = topic_reply_moderation @*{ .topic_reply.id == reply.id } ( .user.name );
    	val ext_reply = ext_topic_reply (
    		id = reply.id,
    		topic_id = reply.topic_id,
    		author = reply.author,
    		message = reply.message,
    		is_sub_reply = reply.is_sub_reply,
    		timestamp = reply.timestamp,
    		moderated_by = moderated_by
    	);
    	ext_replies.add(ext_reply);
    }
    
    return ext_replies;
}

query count_topic_replies(topic_id: text) {
	return topic_reply@*{ .topic.id == topic_id }( .id ).size();
}

query get_topic_replies_after_timestamp(username: name, topic_id: text, timestamp, page_size: integer) {	
	val replies = topic_reply@*{
        topic@{ .id == topic_id },
        .timestamp &gt; timestamp,
        .is_sub_reply == false
    }(
        .id,
        topic_id = .topic.id,
        author= .author.display_name,
        .message,
        .is_sub_reply,
        @sort_desc .timestamp
    ) limit page_size;
			
    val ext_replies = list&lt;ext_topic_reply&gt;();
    for (reply in replies) {
    	val moderated_by = topic_reply_moderation @*{ .topic_reply.id == reply.id } ( .user.name );
    	val ext_reply = ext_topic_reply (
    		id = reply.id,
    		topic_id = reply.topic_id,
    		author = reply.author,
    		message = reply.message,
    		is_sub_reply = reply.is_sub_reply,
    		timestamp = reply.timestamp,
    		moderated_by = moderated_by
    	);
    	ext_replies.add(ext_reply);
    }
    
    return ext_replies;
}

query get_topic_replies_by_user_prior_to_timestamp(name, timestamp, page_size: integer) {
    val replies = topic_reply@*{ .author.name == name, .timestamp &lt; timestamp } (
        .id,
        topic_id = .topic.id,
        author=.author.display_name,
        .message,
        .is_sub_reply,
        @sort_desc .timestamp
    ) limit page_size;
    
    val ext_replies = list&lt;ext_topic_reply&gt;();
    for (reply in replies) {
    	val moderated_by = topic_reply_moderation @*{ .topic_reply.id == reply.id } ( .user.name );
    	val ext_reply = ext_topic_reply (
    		id = reply.id,
    		topic_id = reply.topic_id,
    		author = reply.author,
    		message = reply.message,
    		is_sub_reply = reply.is_sub_reply,
    		timestamp = reply.timestamp,
    		moderated_by = moderated_by
    	);
    	ext_replies.add(ext_reply);
    }
    
    return ext_replies;
}

query count_topics_by_user(name): integer {
    return topic@*{ .author.name == name }( .id ).size();
}

query count_replies_by_user(name): integer {
    return topic_reply@*{ .author.name == name }( .id ).size();
}

query get_sub_replies(username: name, parent_reply_id: text) {	
    val replies = sub_reply@*{ .parent_reply.id == parent_reply_id } (
        id = .child_reply.id,
        topic_id = .child_reply.topic.id,
        author = .child_reply.author.display_name,
        message = .child_reply.message,
        is_sub_reply = .child_reply.is_sub_reply,
        @sort timestamp= .child_reply.timestamp
    );
   
   val ext_replies = list&lt;ext_topic_reply&gt;();
    for (reply in replies) {
    	val moderated_by = topic_reply_moderation @*{ .topic_reply.id == reply.id } ( .user.name );
    	val ext_reply = ext_topic_reply (
    		id = reply.id,
    		topic_id = reply.topic_id,
    		author = reply.author,
    		message = reply.message,
    		is_sub_reply = reply.is_sub_reply,
    		timestamp = reply.timestamp,
    		moderated_by = moderated_by
    	);
    	ext_replies.add(ext_reply);
    }
    
    return ext_replies;
}

query get_topics_by_user_id_prior_to_timestamp(name, timestamp, page_size: integer) {
    val topics = topic@*{
        user.user@{ .name == name },
        .last_modified &lt; timestamp
    }(
        .id,
        author= .author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_from_follows_after_timestamp(name, timestamp, page_size: integer) {
    val topics = (topic, follow.follow)@*{
            follow.follower.name == name.lower_case(),
            follow.follows == topic.author,
            topic.last_modified &gt; timestamp
    }(
        topic.id,
        author=topic.author.display_name,
        topic.title,
        topic.message,
        @sort_desc topic.last_modified,
        topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_from_follows_prior_to_timestamp(name, timestamp, page_size: integer) {
    val topics = (topic, follow.follow) @* {
        follow.follower.name == name.lower_case(),
        follow.follows == topic.author,
        topic.last_modified &lt; timestamp
    }(
        topic.id,
        author = topic.author.display_name,
        topic.title,
        topic.message,
        @sort_desc topic.last_modified,
        topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topic_by_id(username: name, id: text) {
    val topic = topic@{ .id == id }(
        .id,
        author = .author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    );
    
    val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
	return ext_topic (
		id = topic.id,
		author = topic.author,
		title = topic.title,
		message = topic.message,
		timestamp = topic.timestamp,
		last_modified = topic.last_modified,
		latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
		moderated_by = moderated_by
	);
}

query get_all_topics_by_stars_since_timestamp(timestamp, page_size: integer) {
    val topics = rating.tmp_topic_rating@*{
        .topic.last_modified &gt; timestamp
    } (
        @sort_desc .stars,
        id = .topic.id,
        author=.topic.author.display_name,
        title=.topic.title,
        message=.topic.message,
        last_modified=.topic.last_modified,
        timestamp=.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_by_follows_and_stars_since_timestamp(name, timestamp, page_size: integer) {
    val topics = (rating.tmp_topic_rating, follow.follow) @*{
            follow.follower.name == name,
            tmp_topic_rating.topic.author == follow.follows,
            tmp_topic_rating.topic.last_modified &gt; timestamp
        } (
        @sort_desc tmp_topic_rating.stars,
        id = tmp_topic_rating.topic.id,
        author = tmp_topic_rating.topic.author.display_name,
        title = tmp_topic_rating.topic.title,
        message = tmp_topic_rating.topic.message,
        last_modified = tmp_topic_rating.topic.last_modified,
        timestamp = tmp_topic_rating.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_by_channel_after_timestamp_sorted_by_popularity(name, timestamp, page_size: integer) {
    val topics = (rating.tmp_topic_rating, channel.channel)@*{
        name == channel.name,
        tmp_topic_rating.topic == channel.topic,
        tmp_topic_rating.topic.last_modified &gt; timestamp
    } (
        @sort_desc .stars,
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        last_modified = channel.topic.last_modified,
        timestamp = channel.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_by_followed_channels_after_timestamp_sorted_by_popularity(name, timestamp, page_size: integer) {
    val topics = (rating.tmp_topic_rating, channel.channel_following, channel.channel)@*{
        channel_following.user == user.user@{ name },
        channel_following.name == channel.name,
        tmp_topic_rating.topic == channel.topic,
        tmp_topic_rating.topic.last_modified &gt; timestamp
    } (
        @sort_desc .stars,
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        last_modified = channel.topic.last_modified,
        timestamp = channel.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}</string>
                            </entry>
                            <entry key="topic/rating/index.rell">
                                <string>import user;
import topic;

entity topic_star_rating {
    key topic.topic, user.user;
}

// To be deleted when GROUP BY and COUNT is supported, then will use topic_star_rating instead
entity tmp_topic_rating {
    key topic.topic;
    mutable stars: integer;
    index stars;
}

entity reply_star_rating {
    key topic.topic_reply, user.user;
}
</string>
                            </entry>
                            <entry key="topic/rating/operations.rell">
                                <string>import user;
import topic;

operation give_topic_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create topic_star_rating(topic.topic@{ .id == id }, user);

    val topicRating = tmp_topic_rating@{ topic.topic@{ .id == id }};
    update topicRating ( stars = topicRating.stars + 1 );
}

operation remove_topic_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    delete topic_star_rating@{ topic.topic@{ .id == id }, user };

    val topicRating = tmp_topic_rating@{ topic.topic@{ .id == id }};
    update topicRating ( stars = topicRating.stars - 1 );
}

operation give_reply_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create reply_star_rating(topic.topic_reply@{ .id == id }, user);
}

operation remove_reply_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    delete reply_star_rating@{ topic.topic_reply@{ .id == id }, user };
}</string>
                            </entry>
                            <entry key="topic/rating/queries.rell">
                                <string>import topic;

query get_star_rating_for_topic(id: text) {
    return topic_star_rating@*{ topic.topic@{ .id == id }} ( .user.name );
}

query get_star_rating_for_reply(id: text) {
    return reply_star_rating@*{ topic.topic_reply@{ .id == id }} ( .user.name );
}

query count_user_topic_star_rating(name): integer {
    return topic_star_rating@*{ .topic.author.name == name } ( .topic, .user ).size();
}

query count_user_reply_star_rating(name): integer {
    return reply_star_rating@*{ .topic_reply.author.name == name } ( .topic_reply, .user ).size();
}</string>
                            </entry>
                            <entry key="topic/subscription/index.rell">
                                <string>import user;
import topic;

entity subscription {
    key topic.topic, user.user;
}
</string>
                            </entry>
                            <entry key="topic/subscription/operations.rell">
                                <string>import user;
import topic;

operation subscribe_to_topic(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create subscription(topic.topic@{ .id == id }, user);
}

operation unsubscribe_from_topic(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    delete subscription@{ topic.topic@{ .id == id }, user };
}</string>
                            </entry>
                            <entry key="topic/subscription/queries.rell">
                                <string>import topic;

query get_subscribers_for_topic(id: text) {
    return subscription@*{ topic.topic@{ .id == id }} ( .user.name );
}</string>
                            </entry>
                            <entry key="user/distrust/index.rell">
                                <string>import user;

entity user_distrust {
    key distruster: user.user, distrusted: user.user;
}</string>
                            </entry>
                            <entry key="user/distrust/operations.rell">
                                <string>import user;

operation toggle_distrust(username: name, descriptor_id: byte_array, name, muted: boolean) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);

    if (muted) {
        create user_distrust(distruster = user, distrusted = user.user@{ .name == name });
    } else {
        delete user_distrust@{ .distruster == user, .distrusted == user.user@{ .name == name }};
    }
}
</string>
                            </entry>
                            <entry key="user/distrust/queries.rell">
                                <string>query get_distrusted_users(name) {
    return user_distrust@*{ .distruster.name == name.lower_case() } ( .distrusted.name );
}

query times_user_was_distrusted(name): integer {
	return user_distrust@*{ .distrusted.name == name } ( .distruster ).size();
}

query times_user_distrusted_someone(name): integer {
	return user_distrust@*{ .distruster.name == name } ( .distrusted ).size();
}</string>
                            </entry>
                            <entry key="user/functions.rell">
                                <string>import ft3_acc: lib.ft3.account;
import util;

function get_verified_user(name, descriptor_id: byte_array): user {
    val user = user@{ .name == name.lower_case() };
    ft3_acc.require_auth(user.account, descriptor_id, list&lt;text&gt;());
    return user;
}

function get_and_charge_verified_user(name, descriptor_id: byte_array): user {
	val user = get_verified_user(name, descriptor_id);
	ft3_acc.rate_limit(user.account);
	return user;
}</string>
                            </entry>
                            <entry key="user/index.rell">
                                <string>import ft3_acc: lib.ft3.account;

entity user {
    key name;
    index ft3_acc.account;
    display_name: name;
    registered: integer = 0;
}

entity user_suspension {
	index user;
	index suspended_by: user;
	index suspended_until: timestamp;
}

import user.settings;
import user.distrust;
</string>
                            </entry>
                            <entry key="user/operations.rell">
                                <string>import ft3_acc: lib.ft3.account;

import user.settings;

operation register_user(name, account_id: byte_array) {
	val pattern = "[a-zA-Z0-9]{3,16}";
	require(name.matches(pattern), "Not a valid username, must match: " + pattern);
	
    val account = ft3_acc.account @ { account_id };
    val user = create user(name = name.lower_case(), display_name = name, account, op_context.block_height);
    
    create settings.user_settings(user, avatar = "" , description = "");
}
</string>
                            </entry>
                            <entry key="user/queries.rell">
                                <string>import ft3_acc: lib.ft3.account;

query get_user(name) {
    return user@?{ .name == name.lower_case() } ( name = .display_name );
}

query get_account_id(name) {
    return user@?{ .name == name.lower_case() } ( .account.id );
}

query get_registered_at(name) {
	return user@{ .name == name.lower_case() } ( .registered );
}

query username_by_account_id(id: byte_array): name? {
	val account = ft3_acc.account@? { id };
	if (account != null) {
		return user@?{ .account == account } ( .display_name );
	}
	
	return null;
}</string>
                            </entry>
                            <entry key="user/settings/index.rell">
                                <string>import user;

entity user_settings {
    key user.user;
    mutable avatar: text;
    mutable description: text;
    mutable socials: json = json("{}");
}
</string>
                            </entry>
                            <entry key="user/settings/operations.rell">
                                <string>import user;

operation create_user_settings(name, descriptor_id: byte_array, avatar: text, description: text, socials: json) {
    val user = user.get_and_charge_verified_user(name, descriptor_id);
    create user_settings(user, avatar = avatar, description = description, socials);
}

operation update_user_settings(name, descriptor_id: byte_array, avatar: text, description: text, socials: json) {
    val user = user.get_and_charge_verified_user(name, descriptor_id);
    update user_settings@{ .user == user }( avatar = avatar, description = description, socials);
}
</string>
                            </entry>
                            <entry key="user/settings/queries.rell">
                                <string>import user;

query get_user_settings(name) {
    return user_settings@?{ user.user@{ .name == name }} ( .avatar, .description, .socials );
}
</string>
                            </entry>
                            <entry key="util/log.rell">
                                <string>enum error_type {
	USER_UNAUTHORIZED,
	USER_SUSPENDED,
	TOPIC_IMMUTABLE,
	REPRESENTATIVE_ALREADY_SUSPENDED,
	ILLEGAL_ACTION,
	EXPECTED_ERROR
}

function app_error(error_type, action: text): text {
	val msg = when(error_type) {
		USER_UNAUTHORIZED -&gt; message_with_code("CERR_10", "Requester was unauthorized", action);
		USER_SUSPENDED -&gt; message_with_code("CERR_11", "Requester was suspended", action);
		TOPIC_IMMUTABLE -&gt; message_with_code("CERR_20", "Topic is no longer mutable", action);
		REPRESENTATIVE_ALREADY_SUSPENDED -&gt; message_with_code("CERR_30", "User was already suspended", action);
		ILLEGAL_ACTION -&gt; message_with_code("CERR_40", "The attempted action was illegal", action);
		EXPECTED_ERROR -&gt; message_with_code("CERR_50", "Expected error", action);
	};
	
	log(msg);
	return msg;
}

function message_with_code(code: text, message: text, action: text): text {
	return '{"code":"' + code + '","message":"' + message + '","action":"' + action + '"}';
}</string>
                            </entry>
                        </dict>
                    </entry>
                </dict>
            </entry>
        </dict>
    </entry>
    <entry key="signers">
        <array>
            <bytea>0350FE40766BC0CE8D08B3F5B810E49A8352FDD458606BD5FAFE5ACDCDC8FF3F57</bytea>
        </array>
    </entry>
</dict>
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
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dict>
    <entry key="blockstrategy">
        <dict>
            <entry key="name">
                <string>net.postchain.base.BaseBlockBuildingStrategy</string>
            </entry>
        </dict>
    </entry>
    <entry key="configurationfactory">
        <string>net.postchain.gtx.GTXBlockchainConfigurationFactory</string>
    </entry>
    <entry key="gtx">
        <dict>
            <entry key="modules">
                <array>
                    <string>net.postchain.rell.module.RellPostchainModuleFactory</string>
                    <string>net.postchain.gtx.StandardOpsGTXModule</string>
                </array>
            </entry>
            <entry key="rell">
                <dict>
                    <entry key="moduleArgs">
                        <dict>
                            <entry key="lib.ft3.core">
                                <dict>
                                    <entry key="my_blockchain_description">
                                        <string>Decentralized reddit</string>
                                    </entry>
                                    <entry key="my_blockchain_name">
                                        <string>Chromunity</string>
                                    </entry>
                                    <entry key="my_blockchain_website">
                                        <string>testnet.chromunity.com</string>
                                    </entry>
                                    <entry key="rate_limit_active">
                                        <int>1</int>
                                    </entry>
                                    <entry key="rate_limit_max_points">
                                        <int>10</int>
                                    </entry>
                                    <entry key="rate_limit_points_at_account_creation">
                                        <int>5</int>
                                    </entry>
                                    <entry key="rate_limit_recovery_time">
                                        <int>30000</int>
                                    </entry>
                                </dict>
                            </entry>
                        </dict>
                    </entry>
                    <entry key="modules">
                        <array>
                            <string></string>
                        </array>
                    </entry>
                    <entry key="sources_v0.10">
                        <dict>
                            <entry key="channel/index.rell">
                                <string>import user;
import topic;

entity channel {
    key name, topic.topic;
    index timestamp;
    display_name: name;
}

entity channel_following {
    key user.user, name;
}
</string>
                            </entry>
                            <entry key="channel/operations.rell">
                                <string>import user;

operation follow_channel(username: text, descriptor_id: byte_array, name) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create channel_following(user, name.lower_case());
}

operation unfollow_channel(username: text, descriptor_id: byte_array, name) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    delete channel_following@{ user, name.lower_case()};
}</string>
                            </entry>
                            <entry key="channel/queries.rell">
                                <string>import user;
import topic;

query get_topics_by_channel_prior_to_timestamp(name, timestamp, page_size: integer) {
    val topics = channel@*{
        .name == name,
        .topic.last_modified &lt; timestamp
    } (
        id = .topic.id,
        author = .topic.author.display_name,
        title = .topic.title,
        message = .topic.message,
        timestamp = .topic.timestamp,
        @sort_desc last_modified = .topic.last_modified
    ) limit page_size;
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query get_topics_by_channel_after_timestamp(name, timestamp) {
    val topics = channel@*{
        .name == name,
        .topic.last_modified &gt; timestamp
    } (
        id = .topic.id,
        author = .topic.author.display_name,
        title = .topic.title,
        message = .topic.message,
        timestamp = .topic.timestamp,
        @sort_desc last_modified = .topic.last_modified
    );
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query count_topics_by_channel(name) {
    return channel@*{ .name == name } ( .name ).size();
}

query count_channel_followers(name) {
    return channel_following@*{ .name == name } ( .user.name ).size();
}

query get_topics_by_followed_channels_prior_to_timestamp(username: text, timestamp, page_size: integer) {
    val user = user.user@{ .name == username};
    val topics = (channel, channel_following)@*{
        channel_following.user == user,
        channel_following.name == channel.name,
        channel.topic.last_modified &lt; timestamp
    }
    (
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        timestamp = channel.topic.timestamp,
        @sort_desc last_modified = channel.topic.last_modified
    ) limit page_size;
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query get_topics_by_followed_channels_after_timestamp(username: text, timestamp, page_size: integer) {
    val user = user.user@{ .name == username};
    val topics = (channel, channel_following)@*{
        channel_following.user == user,
        channel_following.name == channel.name,
        channel.topic.last_modified &gt; timestamp
    }
    (
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        timestamp = channel.topic.timestamp,
        @sort_desc last_modified = channel.topic.last_modified
    ) limit page_size;
    
    val ext_topics = list&lt;topic.ext_topic&gt;();
    for (t in topics) {
    	val moderated_by = topic.topic_moderation@*{ .topic.id == t.id } ( .user.name );
    	val ext_t = topic.ext_topic (
			id = t.id,
			author = t.author,
			title = t.title,
			message = t.message,
			timestamp = t.timestamp,
			last_modified = t.last_modified,
			latest_poster = topic.get_latest_poster_in_topic(t.id, t.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_t);
    }
    
    return ext_topics;
}

query get_followed_channels(username: text) {
    val user = user.user@{ .name == username};
    return channel_following@*{ user } ( .name );
}

query get_all_channels() {
    return channel@*{} ( .display_name );
}

query get_channels_since(timestamp) {
    return channel@*{ .timestamp &gt; timestamp }( .display_name );
}

query get_topic_channels_belongings(topic_id: text) {
    return channel@*{ topic.topic@{ .id == topic_id }} ( .display_name );
}
</string>
                            </entry>
                            <entry key="chat/index.rell">
                                <string>import user;

entity chat {
	key id: text;
	mutable title: text;
	timestamp;
}

entity chat_user {
	key user.user;
	rsa_pubkey: text;
}

entity chat_membership {
	key chat, member: chat_user;
	encrypted_chat_key: text;
	mutable last_opened: timestamp = 0;
}

entity chat_message {
	index chat;
	index sender: chat_user;
	index timestamp;
	encrypted_msg: text;
}

struct chat_record {
	id: text;
	title: text;
	last_message: message_record?;
	encrypted_chat_key: text;
	timestamp;
	last_opened: timestamp;
}

struct message_record {
	sender: name;
	timestamp;
	encrypted_msg: text;
}
</string>
                            </entry>
                            <entry key="chat/operations.rell">
                                <string>import user;
import util;

operation create_chat(chat_id: text, descriptor_id: byte_array, username: text, title: text, encrypted_chat_key: text) {
	val founder = user.get_and_charge_verified_user(username, descriptor_id);

	val chat = create chat(id = chat_id, title = title, timestamp = op_context.last_block_time);
	create chat_membership(chat, chat_user@{ .user == founder }, encrypted_chat_key);
}

operation create_chat_user(descriptor_id: byte_array, username: text, rsa_pubkey: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	create chat_user(user, rsa_pubkey);
}

operation delete_chat_user(descriptor_id: byte_array, username: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	val chat_user = chat_user@?{ user };

	if (chat_user != null) {
		delete chat_membership@*{ .member == chat_user };
		delete chat_message@*{ .sender == chat_user };
		delete chat_user;
	}
}

operation add_user_to_chat(descriptor_id: byte_array, username: text, chat_id: text, target_user: text, encrypted_chat_key: text) {
	val user_already_in_chat = user.get_and_charge_verified_user(username, descriptor_id);
	val chat = chat@{ .id == chat_id };

	if (chat_membership@?{ chat, .member.user.name == target_user.lower_case() } == null) {
		create chat_membership(chat, chat_user@{ .user.name == target_user.lower_case() }, encrypted_chat_key);
	}
}

operation leave_chat(descriptor_id: byte_array, username: text, chat_id: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	val chat = chat@{ .id == chat_id };

	delete chat_membership@{ chat, chat_user@{ user }};

	if (chat_membership@*{ chat } ( .member ).size() == 0) {
		delete chat_message@*{ chat };
		delete chat;
	}
}

operation modify_chat_title(descriptor_id: byte_array, username: text, chat_id: text, title: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	val chat = chat@{ .id == chat_id };
	chat_membership@{ chat, chat_user@{ user }};
	update chat(title = title);
}

operation send_chat_message(chat_id: text, descriptor_id: byte_array, username: name, encrypted_msg: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);

	val chat = chat@{ .id == chat_id };
	val chat_user = chat_user@{ user };
	val chat_member = chat_membership@?{ chat, chat_user };
	require(chat_member != null, util.app_error(util.error_type.USER_UNAUTHORIZED, "Only a chat member can send a message"));

	create chat_message(chat, chat_user, op_context.last_block_time, encrypted_msg);
}

operation update_last_opened_timestamp(chat_id: text, descriptor_id: byte_array, username: name) {
	val user = user.get_verified_user(username, descriptor_id);
	update chat_membership@{
		.chat.id == chat_id,
		.member.user == user
	} ( last_opened = op_context.last_block_time );
}
</string>
                            </entry>
                            <entry key="chat/queries.rell">
                                <string>import follow;

query get_chat_user_pubkey(username: name): text? {
	return chat_user@?{ .user.name == username.lower_case() } ( .rsa_pubkey );
}

query get_user_chats(username: name): list&lt;chat_record&gt; {

	val member_chats = chat_membership@*{ .member.user.name == username.lower_case() };
	val chat_records = list&lt;chat_record&gt;();

	for (member_chat in member_chats) {
		val latest_message = chat_message@?{ .chat == member_chat.chat } ( .sender, @sort_desc .timestamp, .encrypted_msg, @sort_desc .chat.timestamp ) limit 1;

		if (latest_message != null) {
			val message = message_record(sender = latest_message.sender.user.display_name, timestamp = latest_message.timestamp, encrypted_msg = latest_message.encrypted_msg);
			chat_records.add(chat_record(
				id = member_chat.chat.id,
				title = member_chat.chat.title,
				last_message = message,
				encrypted_chat_key = member_chat.encrypted_chat_key,
				timestamp = member_chat.chat.timestamp,
				last_opened = member_chat.last_opened
			));
		} else {
			chat_records.add(chat_record(
				id = member_chat.chat.id,
				title = member_chat.chat.title,
				last_message = null,
				encrypted_chat_key = member_chat.encrypted_chat_key,
				timestamp = member_chat.chat.timestamp,
				last_opened = member_chat.last_opened
			));
		}

	}

	return chat_records;
}

query get_chat_messages(id: text, prior_to: timestamp, page_size: integer) {
	return chat_message@*{ .chat.id == id, .timestamp &lt; prior_to } (
		sender = chat_message.sender.user.display_name,
		@sort_desc timestamp = chat_message.timestamp,
		encrypted_msg = chat_message.encrypted_msg
	) limit page_size;
}

query get_chat_messages_after(id: text, after_timestamp: timestamp, page_size: integer) {
	return chat_message@*{ .chat.id == id, .timestamp &gt; after_timestamp } (
		sender = chat_message.sender.user.display_name,
		@sort timestamp = chat_message.timestamp,
		encrypted_msg = chat_message.encrypted_msg
	) limit page_size;
}

query get_chat_participants(id: text) {
	return chat_membership@*{ .chat.id == id } ( .member.user.display_name );
}

query get_followed_chat_users(username: name) {
	return (chat_user, follow.follow)@*{
		follow.follower.name == username.lower_case(),
		follow.follows == chat_user.user
	} ( chat_user.user.display_name );
}

query get_chat_users() {
	return chat_user@*{} ( chat_user.user.display_name );
}

query count_unread_chats(username: name) {
	val my_user = username.lower_case();
	return set&lt;chat&gt;((chat_membership, chat_message)@*{
		chat_membership.member.user.name == my_user,
		chat_message.timestamp &gt; chat_membership.last_opened,
		chat_membership.chat == chat_message.chat,
		chat_message.sender.user.name != my_user
	} ( chat_membership.chat )).size();
}</string>
                            </entry>
                            <entry key="config/0_0_3.rell">
                                <string>import ft3_acc: lib.ft3.account;
import ft3_core: lib.ft3.core;

operation update_block_79000(){
  val update_at_block = 79000;
  require(op_context.block_height&gt;=update_at_block);
  require(ft3_core.my_blockchain_info.last_update &lt; update_at_block);

  update_new_users_limit();
  update_previous_users_limit();

  ft3_core.my_blockchain_info.last_update = update_at_block;
}

function update_new_users_limit() {
  val new_args = ft3_core.scan_args_my_blockchain_info();
  ft3_core.my_blockchain_info.name = new_args.my_blockchain_name;
  ft3_core.my_blockchain_info.name = new_args.my_blockchain_name;
  ft3_core.my_blockchain_info.website = new_args.my_blockchain_website;
  ft3_core.my_blockchain_info.description = new_args.my_blockchain_description;
  ft3_core.my_blockchain_info.rate_limit_active = new_args.rate_limit_active;
  ft3_core.my_blockchain_info.rate_limit_max_points = new_args.rate_limit_max_points;
  ft3_core.my_blockchain_info.rate_limit_recovery_time = new_args.rate_limit_recovery_time;
  ft3_core.my_blockchain_info.rate_limit_points_at_account_creation = new_args.rate_limit_points_at_account_creation;
}

function update_previous_users_limit() {
  update ft3_acc.rl_state@*{
    .recovery_time &gt; ft3_core.my_blockchain_info.rate_limit_recovery_time,
    .max_points &lt; ft3_core.my_blockchain_info.rate_limit_max_points
  }(
    .recovery_time = ft3_core.my_blockchain_info.rate_limit_recovery_time,
    .max_points = ft3_core.my_blockchain_info.rate_limit_max_points
  );
}</string>
                            </entry>
                            <entry key="election/index.rell">
                                <string>import user;
import topic;

entity representative_election {
    key id: integer;
    index timestamp;
    mutable completed: boolean;
    index completed;
}

entity election_block_details {
	key started_height: integer;
	mutable finished_height: integer = -1;
	index representative_election;
}

entity representative_election_candidate {
  key representative_election, user.user;
}

entity representative_election_vote {
    key user.user, representative_election_candidate;
}

entity temp_votes_counter {
	key representative_election_candidate;
	mutable votes: integer;
}

function is_eligible_to_vote(user.user): boolean {
	val prev_election_id = get_latest_completed_election_id();
	
	val current_election_id = get_current_election_id();
	
	if (current_election_id == null) {
		return false;
	} else if (prev_election_id == null) {
		return true;
	}
	
	val current_election_start = (election_block_details, block)@{ 
		election_block_details.representative_election.id == current_election_id,
		election_block_details.started_height == block.block_height
	} ( 
		block.timestamp
	);
	
	if (user.registered &gt; current_election_start) {
		log("Not elgible for voting: User registered after election start");
		return false; 
	}
	
	val previous_election_completed = (representative_election, election_block_details, block)@?{
		representative_election == election_block_details.representative_election,
		representative_election.completed == true,
		block.block_height == election_block_details.finished_height
	} ( 
		block.timestamp,
		@omit @sort_desc representative_election.timestamp
	) limit 1;
	
	if (previous_election_completed != null) {
		log("A previous election was held, so verifying correct number of posts");
		val number_of_topics = topic.topic@*{ 
			.author == user,
			.last_modified &gt; previous_election_completed,
			.last_modified &lt; current_election_start
		}( .id ).size();
		
		val number_of_replies = topic.topic_reply@*{
			.author == user,
			.timestamp &gt; previous_election_completed,
			.timestamp &lt; current_election_start
		}( .id ).size();
		
		return number_of_topics + number_of_replies &gt;= 5;
	}
	
	return true;
}

function governing_period_in_blocks(): integer {
	return 75000;
}

function election_duration_in_blocks(): integer {
	return 25000;
}

function get_current_election_id(): integer? {
	return representative_election@?{ .completed == false } ( @omit @sort_desc .timestamp, .id ) limit 1;
}

function get_latest_completed_election_id(): integer? {
	return representative_election@?{ .completed == true } ( .id, @omit @sort_desc .timestamp ) limit 1;
}</string>
                            </entry>
                            <entry key="election/operations.rell">
                                <string>import user;
import util;
import representative;

operation process_election() {
	var something_done = false;
	
	val current_block = op_context.block_height;
	val election_period_in_blocks = election_duration_in_blocks();
	val governing_period_in_blocks = governing_period_in_blocks();
	
	val election_block_details = election_block_details@?{} ( @sort_desc .started_height, .finished_height ) limit 1;
	
	if (election_block_details == null) {
		log("No election held yet, triggering new one");
		create_election_at_height(current_block);
		something_done = true;
	} else if (election_block_details.finished_height &gt;= 0 and election_block_details.finished_height + governing_period_in_blocks &lt; current_block) {
		log("Triggering a new election");
		create_election_at_height(current_block);
		something_done = true;
	} else if (election_block_details.finished_height == -1 
		and election_block_details.started_height + election_period_in_blocks &lt; current_block
	) {
		log("Wrapping up election");
		complete_election();
		something_done = true;
	}
	
	require(something_done, util.app_error(util.error_type.EXPECTED_ERROR, "Nothing done while processing of elections"));
}

function create_election_at_height(height: integer) {
	val election = create representative_election(
			id = height,
			timestamp = op_context.last_block_time, 
			false
		);
		create election_block_details(started_height = height, election);
}

function complete_election() {
	val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
	
    val current_election = representative_election@{ .id == current_election_id };
    update current_election ( completed = true );
    update election_block_details@{ current_election } ( finished_height = op_context.block_height );
    
    val nr_of_participants = temp_votes_counter@*{
    	.representative_election_candidate.representative_election == current_election
    } ( 
    	.representative_election_candidate.user.name
    ).size();
    
    val new_representatives = temp_votes_counter@*{ 
    	.representative_election_candidate.representative_election == current_election
    } (
    	@sort_desc @omit .votes,
    	.representative_election_candidate.user
    ) limit integer((nr_of_participants * 0.1).ceil());

    for (user in new_representatives) {
        create representative.representative(user, current_election);
    }
}

operation vote_for_candidate(voter: name, descriptor_id: byte_array, candidate: name) {
	require(voter != candidate, util.app_error(util.error_type.ILLEGAL_ACTION, "You can't vote for yourself"));
    val user = user.get_and_charge_verified_user(voter, descriptor_id);

	require(is_eligible_to_vote(user), util.app_error(util.error_type.ILLEGAL_ACTION, "Not eligible for voting in the election"));

    val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
    
    clean_up_votes(user, current_election_id);
    
    val vote = create representative_election_vote(
        user,
        representative_election_candidate@{ 
        	user.user@{ .name == candidate }, 
        	.representative_election.id == current_election_id
        }
    );
    
    update temp_votes_counter@ {
    	vote.representative_election_candidate
    } ( votes += 1 );
}

operation sign_up_for_election(name, descriptor_id: byte_array) {
    val user = user.get_and_charge_verified_user(name, descriptor_id);
	val election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));

    val candidate = create representative_election_candidate(
    	representative_election@{ .id == election_id }, 
    	user
    );
    
    create temp_votes_counter(candidate, 0);
}

function clean_up_votes(user.user, id: integer) {
	val old_candidate_votes = representative_election_vote@*{ 
    	user,
    	.representative_election_candidate.representative_election.id == id
    };
	for (old_candidate_vote in old_candidate_votes) {
	    
	    update temp_votes_counter@ {
	    	old_candidate_vote.representative_election_candidate
	    } ( votes -= 1 );
	    
	   	delete old_candidate_vote;
	}
}</string>
                            </entry>
                            <entry key="election/queries.rell">
                                <string>import user;
import util;

query eligible_for_voting(name): boolean {
	val user = user.user@{ .name == name.lower_case() };
	return is_eligible_to_vote(user);
}

query get_election_candidates() {
	val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
	
    return temp_votes_counter@*{
        .representative_election_candidate.representative_election.id == current_election_id
    } ( 
    	@omit @sort_desc .votes,
    	.representative_election_candidate.user.display_name
    );
}

query get_next_election() {
    return representative_election@?{ .completed == false } ( .id, @sort_desc .timestamp ) limit 1;
}

query get_uncompleted_election() {
    return get_current_election_id();
}

query get_user_vote_in_election(name) {
	val current_election_id = require(get_current_election_id(), util.app_error(util.error_type.ILLEGAL_ACTION, "No on-going election"));
	
    return representative_election_vote@?{
        .user == user.user@{ .name == name },
        .representative_election_candidate.representative_election.id == current_election_id
    } ( .representative_election_candidate.user.name ) limit 1;
}

query get_current_representative_period(timestamp) {
    return representative_election @? { .timestamp &lt;= timestamp, .completed == true } ( .id, @sort_desc .timestamp ) limit 1;
}

query blocks_until_next_election() {
	val recent_election_finished = election_block_details@?{} ( 
		@omit @sort_desc .started_height, 
		.finished_height
	) limit 1;
	
	if (recent_election_finished == null) {
		return 0;
	}
	
	require(recent_election_finished != -1, "There is an ongoing election");
	
	val next_election_block = recent_election_finished + governing_period_in_blocks();
	
	var current_block = block@?{} ( @sort_desc .block_height ) limit 1;
	
	if (current_block == null) {
		current_block = 0;
	}
	
	return next_election_block - current_block;
}

query blocks_until_election_wraps_up() {
	val recent_election = election_block_details@{} ( 
		@sort_desc .started_height, 
		.finished_height
	) limit 1;
	
	require(recent_election.finished_height == -1, "There is no ongoing election");
	
	val election_finishing_block = recent_election.started_height + election_duration_in_blocks();
	
	var current_block = block@?{} ( @sort_desc .block_height ) limit 1;
	
	if (current_block == null) {
		current_block = 0;
	}
	
	return election_finishing_block - current_block;
}
</string>
                            </entry>
                            <entry key="follow/index.rell">
                                <string>import user;

entity follow {
    key follower: user.user, follows: user.user;
}
</string>
                            </entry>
                            <entry key="follow/operations.rell">
                                <string>import user;
import util;

operation create_following(follower: text, descriptor_id: byte_array, follows: text) {
    require(follower != follows, util.app_error(util.error_type.ILLEGAL_ACTION, "Follow another user"));
    val user = user.get_and_charge_verified_user(follower, descriptor_id);
    create follow(follower = user, follows = user.user@{ .name == follows.lower_case() });
}

operation remove_following(follower: text, descriptor_id: byte_array, follows: text) {
    require(follower != follows, util.app_error(util.error_type.ILLEGAL_ACTION, "You can't unfollow yourself"));
    val user = user.get_and_charge_verified_user(follower, descriptor_id);
    delete follow@{ .follower == user, .follows == user.user@{ .name == follows.lower_case() } };
}
</string>
                            </entry>
                            <entry key="follow/queries.rell">
                                <string>import user;

query get_user_followers(name) {
    return follow@*{ .follows == user.user @ { .name == name } }( .follower.name );
}

query get_user_follows(name) {
    return follow@*{ .follower == user.user@{ .name == name } } ( .follows.name );
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/auth_basic.rell">
                                <string>// Auth type:

// "S" - single-sig
// "M" - multi-sig

struct single_sig_args {
       flags: set&lt;text&gt;;
       pubkey;
}

struct multi_sig_args {
       flags: set&lt;text&gt;;
       signatures_required: integer;
       pubkeys: list&lt;pubkey&gt;;
}

function check_single_sig_auth(args: byte_array, participants: list&lt;byte_array&gt;, required_flags: list&lt;text&gt;): boolean {
    require(participants.size() == 1);
    val ss_args = single_sig_args.from_bytes(args);
    return
          ss_args.flags.contains_all(required_flags)
            and
          is_signer(participants[0]);
}

function check_multi_sig_auth(args: byte_array, participants: list&lt;byte_array&gt;, required_flags: list&lt;text&gt;): boolean {
   val multi_sign_args = multi_sig_args.from_bytes(args);
   if (not (multi_sign_args.flags.contains_all(required_flags))) return false;
   var num_sign = multi_sign_args.signatures_required;
   for(s in participants) {
      if(is_signer(s)) {
          num_sign -= 1;
          if(num_sign &lt; 1) {return true;}
      }
   }
   return false;
}

function check_auth_args (a_t: text, args: byte_array, participants: list&lt;byte_array&gt;, required_flags: list&lt;text&gt;): boolean {
    return when (a_t) {
        "S" -&gt; check_single_sig_auth(args, participants, required_flags);
        "M" -&gt; check_multi_sig_auth(args, participants, required_flags);
        else -&gt; false;
    };
}



function require_auth (account, descriptor_id: byte_array, required_flags: list&lt;text&gt;) {
   val account_auth_descriptor = account_auth_descriptor @ {
     account,
     .descriptor_id == descriptor_id
   };
	
	require(is_valid(account_auth_descriptor));
	
   	require(
		check_auth_args(
       		account_auth_descriptor.auth_type,
       		account_auth_descriptor.args,
       		auth_descriptor_participant @* { account_auth_descriptor } ( .id ),
       		required_flags
		)
   );
   
   update_auth_descriptor_rule_variables(account_auth_descriptor);
   delete_expired_auth_descriptors(account);
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/auth_descriptor_rule.rell">
                                <string>
enum rule_variable {
	block_height,
	block_time,
	op_count
}

enum rule_operator {
	lt,
	le,
	eq,
	ge,
	gt
}

struct rule_expression {
	variable: text;
	operator: text;
	value: gtv;
}

entity auth_descriptor_rule_variable {
	key account_auth_descriptor, name;
	mutable value: byte_array;
}

function is_valid(auth_descriptor: account_auth_descriptor): boolean {
	// check if rules is null (encoded null is equal to 0xa0020500)
	if (auth_descriptor.rules == x'a0020500') {
		return true;
	}
	
	return is_rule_valid(
		gtv.from_bytes(auth_descriptor.rules), 
		load_variables(auth_descriptor)
	);
}

function is_rule_valid(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(rule);
	val operator = text.from_gtv(parameters[1]);
	
	if (operator == "and") {
		return handle_composed_rule(rule, variables);
	} else {
		return handle_single_rule(rule, variables);
	}
}

function handle_single_rule(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	return evaluate_int_variable_rule(
		rule_expression.from_gtv(rule), 
		variables
	);	
}

 
function handle_composed_rule(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(rule);
	val operator = text.from_gtv(parameters[1]);
	if (operator == "and") {
		return is_rule_valid(parameters[0], variables) and is_rule_valid(parameters[2], variables);
	} else {
		return false;
	}
}



function is_active(account_auth_descriptor): boolean {
	if (account_auth_descriptor.rules == x'a0020500') {
		return true;
	}
	
	return is_rule_active(gtv.from_bytes(account_auth_descriptor.rules), map&lt;text, gtv&gt;());
}


function is_rule_active(r: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(r);
	val operator = text.from_gtv(parameters[1]);
	when (operator) {
		"and" -&gt; {
			return is_rule_active(parameters[0], variables) and is_rule_active(parameters[2], variables);
		}
		else -&gt; {
			return is_simple_rule_active(r, variables);
		}
	}
}

function is_simple_rule_active(rule: gtv, variables: map&lt;text, gtv&gt;): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(rule);
	val variable_name = text.from_gtv(parameters[0]);
	when (rule_variable.value(variable_name)) {
		rule_variable.block_height -&gt; {
			return is_block_height_rule_active(rule);
		}
		rule_variable.block_time -&gt; {
			return is_block_time_rule_active(rule);
		}		
		rule_variable.op_count -&gt; {
			return is_op_count_rule_active(rule);
		}
	}
}

/*
 *  Variables
 */

function evaluate_int_variable_rule(rule: rule_expression, variables: map&lt;text, gtv&gt;): boolean {
	val variable = rule_variable.value(rule.variable);
	val operator = rule_operator.value(rule.operator);
	val current_value = variable_value(variable, variables);
	val defined_value = integer.from_gtv(rule.value);

	when (operator) {
		rule_operator.lt -&gt; {
			return current_value &lt; defined_value;
		}
		rule_operator.le -&gt; {
			return current_value &lt;= defined_value;
		}
		rule_operator.eq -&gt; {
			return current_value == defined_value;
		}
		rule_operator.ge -&gt; {
			return current_value &gt;= defined_value;
		}
		rule_operator.gt -&gt; {
			return current_value &gt; defined_value;
		}
	}
}


/*
 * Called from _add_auth_descriptor function
 */
function setup_auth_descriptor_variables(account_auth_descriptor) {
	
	if (account_auth_descriptor.rules == x'a0020500') {
		return;
	} 
	
	val variables = get_variable_names_set(gtv.from_bytes(account_auth_descriptor.rules));
	
	for (variable in variables) {
		when (variable) {
			rule_variable.op_count.name -&gt; {
				create auth_descriptor_rule_variable(
					account_auth_descriptor,
					name = variable,
					value = op_count_variable_initial_value().to_bytes()
				);
			}
		}
	}
}
 
function update_variables(account_auth_descriptor, variables: map&lt;text, gtv&gt;) {
	for ((name, value) in variables) {
		val variable = auth_descriptor_rule_variable @ { account_auth_descriptor, name };
		val int_value = integer.from_gtv(value);
		
		when (name) {
			rule_variable.op_count.name -&gt; {
				variable.value = (int_value + 1).to_gtv().to_bytes();
			}
		}
	}
}
 
function variable_value(variable: rule_variable, variables: map&lt;text, gtv&gt;): integer {
	when (variable) {
		rule_variable.block_height -&gt; {
			return op_context.block_height;
		}
		rule_variable.block_time -&gt; {
			return op_context.last_block_time;
		}
		rule_variable.op_count -&gt; {
			return integer.from_gtv(variables[rule_variable.op_count.name]);
		}
	}
}

/*
 * Analyze the rules before assigning them to an authenticator descriptor
 */
 function analyze_auth_descriptor_rules(rules: gtv, hop: integer) {
 	require(hop&lt;3, "too many rules");
 	val rules_bytes = rules.to_bytes(); 
 	if (rules_bytes == x'a0020500') {
		return;
	}
	
 	val params = list&lt;gtv&gt;.from_gtv(rules);
 	require(params.size() &lt;=3);
 	
 	val operator = text.from_gtv(params[1]);
 	if(operator == "and") {
 		analyze_auth_descriptor_rules(params[0], hop+1); 
 		analyze_auth_descriptor_rules(params[2], hop+1);
 	} 	
 	
	return;
 }

/*
 * Returns set of variable names used in a rule
 */
function get_variable_names_set(rules: gtv): set&lt;text&gt; {
	val parameters = list&lt;gtv&gt;.from_gtv(rules);
	val operator = text.from_gtv(parameters[1]);
	var vars = set&lt;text&gt;();
	if (operator == "and") {
		vars.add_all(get_variable_names_set(parameters[0]));
		vars.add_all(get_variable_names_set(parameters[2]));
	} else {
		vars.add(text.from_gtv(parameters[0]));
	}
	return vars;
} 

function load_variables(account_auth_descriptor): map&lt;text, gtv&gt; {
	val variables = auth_descriptor_rule_variable @* { account_auth_descriptor };
	
	val variables_map = map&lt;text, gtv&gt;();
	for (variable in variables) {
		variables_map[variable.name] = gtv.from_bytes(variable.value);
	}
	
	return variables_map;
}

function update_auth_descriptor_rule_variables(account_auth_descriptor) {
	val variables = load_variables(account_auth_descriptor);
	update_variables(account_auth_descriptor, variables);
}

/*
 * auth descriptor cleanup
 */

function delete_expired_auth_descriptors(account) {
	val auth_descriptors = account_auth_descriptor @* { account };
	
	for (auth_descriptor in auth_descriptors) {
		if (not (is_active(auth_descriptor) and is_valid(auth_descriptor))) {
			_delete_auth_descriptor(auth_descriptor);
		}
	}
}

/****************************************************************************************
 *                                     block_time                                       *
 ****************************************************************************************/

function is_block_time_rule_active(r: gtv): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(r);
	val operator = rule_operator.value(text.from_gtv(parameters[1]));
	val value = integer.from_gtv(parameters[2]);
	when (operator) {
		rule_operator.gt -&gt; {
			return op_context.last_block_time &gt; value;
		}
		rule_operator.ge,
		rule_operator.eq -&gt; {
			return op_context.last_block_time &gt;= value;
		}
		else -&gt; {
			return true;
		}
	}
}


/****************************************************************************************
 *                                  block_height                                        *
 ****************************************************************************************/

function is_block_height_rule_active(r: gtv): boolean {
	val parameters = list&lt;gtv&gt;.from_gtv(r);
	val operator = rule_operator.value(text.from_gtv(parameters[1]));
	val value = integer.from_gtv(parameters[2]);
	when (operator) {
		rule_operator.gt -&gt; {
			return op_context.block_height &gt; value;
		}
		rule_operator.ge,
		rule_operator.eq -&gt; {
			return op_context.block_height &gt;= value;
		}
		else -&gt; {
			return true;
		}
	}
}


/****************************************************************************************
 *                                     op_count                                         *
 ****************************************************************************************/
 
 function op_count_variable_initial_value(): gtv {
 	return (1).to_gtv();
 }
 
 function is_op_count_rule_active(rule: gtv): boolean {
 	return true;
 }</string>
                            </entry>
                            <entry key="lib/ft3/account/module.rell">
                                <string>@mount('ft3')
module;

import core: ^.core;

struct auth_descriptor {
    auth_type: text;
    participants: list&lt;byte_array&gt;;
    args: list&lt;gtv&gt;;
    rules: gtv;
}

entity account {
    key id: byte_array;
}

entity account_meta {
    meta_key: text;
    value: byte_array;
    index account, meta_key;
    index meta_key, value;
}

entity account_auth_descriptor {
     descriptor_id: byte_array;
     key account, descriptor_id;
     index descriptor_id;
     auth_type: text;
     args: byte_array;
     rules: byte_array;
}

entity auth_descriptor_participant {
    key account_auth_descriptor, id: byte_array;
}


// rate limiter
entity rl_state {
    key account;
    mutable points: integer;
    mutable last_update: timestamp;
    mutable max_points: integer;
    mutable recovery_time: timestamp;
}

function _add_auth_descriptor (account, auth_descriptor) {
     val descriptor_id = auth_descriptor.hash();
     
     analyze_auth_descriptor_rules(auth_descriptor.rules, 0);
     
     val account_auth_descriptor = create account_auth_descriptor (
        account, descriptor_id,
        auth_descriptor.auth_type,
        args = auth_descriptor.args.to_gtv().to_bytes(),
        rules = auth_descriptor.rules.to_gtv().to_bytes()
     );
     
     for (participant in auth_descriptor.participants) {
        require(is_signer(participant));
        create auth_descriptor_participant(account_auth_descriptor, id = participant);
     }
     
     setup_auth_descriptor_variables(account_auth_descriptor);
}

function _delete_auth_descriptor(auth_descriptor: account_auth_descriptor) {
	delete auth_descriptor_rule_variable @* { auth_descriptor };
	delete auth_descriptor_participant @* { auth_descriptor };
	delete auth_descriptor;
}

function _delete_all_auth_descriptors_exclude(account, auth_descriptor_id: byte_array) {
	delete (adrv: auth_descriptor_rule_variable, ad: account_auth_descriptor) @* {
		ad.account == account, ad.descriptor_id != auth_descriptor_id, adrv.account_auth_descriptor == ad		
	};
	
	delete (adp: auth_descriptor_participant, ad: account_auth_descriptor) @* {
        ad.account == account and ad.descriptor_id != auth_descriptor_id and adp.account_auth_descriptor == ad
    };

    delete account_auth_descriptor @* {
       .account == account,
       .descriptor_id != auth_descriptor_id
    };
}

function create_account_with_auth (auth_descriptor): byte_array {
     val id = auth_descriptor.hash();
     val acc = create account (id);
     _add_auth_descriptor(
        acc, auth_descriptor
     );
     val max_points = core.my_blockchain_info.rate_limit_max_points;
     val recovery_time = core.my_blockchain_info.rate_limit_recovery_time;
     val points_at_start = core.my_blockchain_info.rate_limit_points_at_account_creation;
     
	create rl_state(acc, .points = points_at_start, .last_update = op_context.last_block_time, max_points, recovery_time);
    
    return id;
}

function auth_and_log(account_id: byte_array, auth_descriptor_id: byte_array, required_flags: list&lt;text&gt;): account {
	val account = account @ { .id == account_id };
	rate_limit(account);
	require_auth(account, auth_descriptor_id, required_flags);
	return account;
}

query is_auth_descriptor_valid(account_id: byte_array, auth_descriptor_id: byte_array) {
    return is_valid(account_auth_descriptor @ {
        .account.id == account_id,
        .descriptor_id == auth_descriptor_id
    });
}

query get_account_auth_descriptors(id: byte_array) {
    return account_auth_descriptor @* {
        .account.id == id
    } (
        id = .descriptor_id,
        type = .auth_type,
        args = .args
    );
}

query get_account_by_id(id: byte_array) {
    return account @? { id } ( .id );
}

query get_account_by_auth_descriptor(auth_descriptor) {
    return account @? { .id == auth_descriptor.hash() } ( .id );
}

query get_accounts_by_participant_id(id: byte_array) {
    return auth_descriptor_participant @* { id } ( .account_auth_descriptor.account.id );
}

query get_accounts_by_auth_descriptor_id(descriptor_id: byte_array) {
    return account_auth_descriptor @* { descriptor_id } ( .account.id );
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/operations/module.rell">
                                <string>@mount('ft3')
module;

import acc: ^^.account;
import core: ^^.core;


operation delete_auth_descriptor(account_id: byte_array, auth_descriptor_id: byte_array, delete_descriptor_id: byte_array) {
    val flags = if (auth_descriptor_id == delete_descriptor_id) list&lt;text&gt;() else ["A"];

    val account = acc.auth_and_log(account_id, auth_descriptor_id, flags);

    acc._delete_auth_descriptor(acc.account_auth_descriptor @ {
        .account == account,
        .descriptor_id == delete_descriptor_id
    });
}

operation delete_all_auth_descriptors_exclude(account_id: byte_array, auth_descriptor_id: byte_array) {
    val account = acc.auth_and_log(account_id, auth_descriptor_id, ["A"]);

	acc._delete_all_auth_descriptors_exclude(account, auth_descriptor_id);
}

operation add_auth_descriptor (account_id: byte_array, auth_id: byte_array, new_desc: acc.auth_descriptor) {
      val account = acc.auth_and_log(account_id, auth_id, ["A"]);
      acc._add_auth_descriptor(account, new_desc);
}
</string>
                            </entry>
                            <entry key="lib/ft3/account/rate_limit.rell">
                                <string>import ^.core;


function rate_limit (account) {
	if(core.my_blockchain_info.rate_limit_active == false ) return;
    val max_counter = core.my_blockchain_info.rate_limit_max_points;
    val recovery_time = core.my_blockchain_info.rate_limit_recovery_time;
    val stat = rl_state@{account} (.points, .last_update);
    val delta = op_context.last_block_time - stat.last_update;
    var got_points = 0;
    var update_time = stat.last_update;

    if (delta &gt; recovery_time)
    {
        got_points = delta / recovery_time;
        update_time = stat.last_update + got_points * recovery_time;
        if (got_points + stat.points &gt; max_counter) {
            got_points = max_counter - stat.points;
            // if user is at maximum reset his 
            // timer
            update_time = op_context.last_block_time;
        }
    }
    
    require(stat.points + got_points &gt; 0);
    
    update rl_state@{account} (
        .points += got_points - 1,
        .last_update = update_time
    );
}


query get_account_rate_limit_last_update(account_id: byte_array) {
	if(core.my_blockchain_info.rate_limit_active == false ) return (points = 0, last_update = 0);
	val t= rl_state@{.account.id == account_id}
	(
		.points, 
		.last_update
	);
	
	return t;
}

query get_last_timestamp(): integer {
	return (block@{.timestamp&gt;0}(@sort_desc .timestamp) limit 1);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/asset.rell">
                                <string>import acc: ^.account;

entity asset {
    id: byte_array;
    key id;
    name;
    issuing_chain_rid: byte_array;
}

entity balance {
    key acc.account, asset;
    mutable amount: integer = 0;
}

function ensure_balance(acc.account, asset): balance {
    val balance = balance @? {asset, account};
    if (balance != null) {
       return balance;
    }
    else return create balance(account, asset, amount = 0);
}

function register_asset (name, issuing_chain_rid: byte_array): asset {
   val id = (name, issuing_chain_rid).hash();
   return create asset (id, name, issuing_chain_rid);
}

function _get_asset_balances(account_id: byte_array): list&lt;(id:byte_array,name:text,amount:integer,chain_id:byte_array)&gt; {
    return balance @* { .account.id == account_id } (
      id = .asset.id,
      name = .asset.name,
      amount = .amount,
      chain_id = .asset.issuing_chain_rid
    );
}

query get_asset_balances(account_id: byte_array) {
    return _get_asset_balances(account_id);
}

query get_asset_balance(account_id: byte_array, asset_id: byte_array) {
    return balance @? {
        .account.id == account_id,
        .asset.id == asset_id
    } (
        id = .asset.id,
        name = .asset.name,
        amount = .amount,
        chain_id = .asset.issuing_chain_rid
    );
}

query get_asset_by_name(name) {
    return asset @* { name } (
        .id,
        .name,
        .issuing_chain_rid
    );
    
}

query get_asset_by_id(asset_id: byte_array) {
	return asset@{
		.id == asset_id
	}(
		id = .id,
		name = .name,
		issuing_chain_rid = .issuing_chain_rid
		
	);
}

query get_all_assets() {
	return asset@*{}(
		id = .id,
		name = .name,
		issuing_chain_rid = .issuing_chain_rid	
	);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/dev_op.rell">
                                <string>module;

import ft3: ^^.core;
import acc: ^^.account;

object dev_state {
   mutable allow_dev_ops: boolean = true;
}

function require_dev() {
    require(dev_state.allow_dev_ops);
}

function dev_give_points_(account: acc.account, amount: integer) {
	require_dev();
	update acc.rl_state@{account}(.points += amount);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/history.rell">
                                <string>import acc: ^.account;

@log entity payment_history_entry {
    index acc.account, asset;
    delta: integer;

    // helps to locate exact position of payment entry in transaction
    op_index: integer;
    is_input: boolean;
    entry_index: integer;
}

query get_payment_history(account_id: byte_array, after_block: integer) {
    return payment_history_entry @* {
        acc.account @ { account_id },
        .transaction.block.block_height &gt; after_block
    } (
        delta = .delta,
        asset = .asset.name,
        asset_id = .asset.id,
        is_input = .is_input,
        timestamp = .transaction.block.timestamp,
        block_height = .transaction.block.block_height,
        entry_index = .entry_index,
        tx_rid = .transaction.tx_rid,
        tx_data = .transaction.tx_data
    );
}
</string>
                            </entry>
                            <entry key="lib/ft3/core/module.rell">
                                <string>@mount('ft3')
module;

struct module_args {
	my_blockchain_name: text;
	my_blockchain_website: text;
	my_blockchain_description: text;
	rate_limit_active: boolean;
	rate_limit_max_points: integer;
    rate_limit_recovery_time: integer;
    rate_limit_points_at_account_creation: integer;    
}

function scan_args_my_blockchain_info(): module_args {
    return module_args(
        my_blockchain_name = chain_context.args.my_blockchain_name,
        my_blockchain_website = chain_context.args.my_blockchain_website,
        my_blockchain_description = chain_context.args.my_blockchain_description,
        rate_limit_active = chain_context.args.rate_limit_active,
        rate_limit_max_points = chain_context.args.rate_limit_max_points,
        rate_limit_recovery_time = chain_context.args.rate_limit_recovery_time,
        rate_limit_points_at_account_creation = chain_context.args.rate_limit_points_at_account_creation
    );
}</string>
                            </entry>
                            <entry key="lib/ft3/core/my_blockchain_info.rell">
                                <string>
object my_blockchain_info {
    mutable name: text = chain_context.args.my_blockchain_name;
    mutable website: text = chain_context.args.my_blockchain_website;
    mutable description: text = chain_context.args.my_blockchain_description;
    mutable rate_limit_active: boolean = chain_context.args.rate_limit_active;
    mutable rate_limit_max_points: integer = chain_context.args.rate_limit_max_points;
    mutable rate_limit_recovery_time: integer = chain_context.args.rate_limit_recovery_time;
    mutable rate_limit_points_at_account_creation: integer = chain_context.args.rate_limit_points_at_account_creation;
    
    mutable last_update: integer = 0;
}


//operation update_blockchain(name, website: text, description: text) {
//    blockchain.name = name;
//    blockchain.website = website;
//    blockchain.description = description;
//}

query get_blockchain_info() {
    return (
        name = my_blockchain_info.name,
        website = my_blockchain_info.website,
        description = my_blockchain_info.description,
        rate_limit_active = my_blockchain_info.rate_limit_active,
        rate_limit_max_points = my_blockchain_info.rate_limit_max_points,
        rate_limit_recovery_time = my_blockchain_info.rate_limit_recovery_time,
        rate_limit_points_at_account_creation = chain_context.args.rate_limit_points_at_account_creation
    );
}

</string>
                            </entry>
                            <entry key="lib/ft3/core/operations/transfer.rell">
                                <string>@mount('ft3')
module;

import ft3: ^^;


operation transfer (inputs: list&lt;ft3.xfer_input&gt;, outputs: list&lt;ft3.xfer_output&gt;) {
    ft3._transfer(inputs, outputs);
}</string>
                            </entry>
                            <entry key="lib/ft3/core/transfer.rell">
                                <string>import acc: ^.account;

struct xfer_input {
   account_id: byte_array;
   asset_id: byte_array;
   auth_descriptor_id: byte_array;
   amount: integer;
   extra: map&lt;text, gtv&gt;;
}

struct xfer_output {
   account_id: byte_array;
   asset_id: byte_array;
   amount: integer;
   extra: map&lt;text, gtv&gt;;
}

function deduct_balance (acc.account, asset, d_amount: integer) {
    val b = balance @ { account, asset };
    require( b.amount &gt;= d_amount, "Balance is too low");
    update b (amount -= d_amount);
}

function consume_input (i: xfer_input, idx: integer, assets: map&lt;asset, integer&gt;): payment_history_entry {
      val asset = asset @ { .id == i.asset_id };
      val account = acc.auth_and_log(i.account_id, i.auth_descriptor_id, ["T"]);
      require( i.amount &gt; 0, "Amount should be non 0 positive." );

      deduct_balance(account, asset, i.amount);
      assets[asset] = i.amount + if (asset in assets) assets[asset] else 0;
      return create payment_history_entry (
        account,
        asset,
        .delta = i.amount,
        .op_index = 500, //op_context ???
        .is_input = true,
        .entry_index = idx
      );
}

function process_transfer_output (o: xfer_output, idx: integer, available_assets: map&lt;asset, integer&gt;): payment_history_entry {
      if (o.extra.contains("reg_auth_desc")) {
          val auth_desc = acc.auth_descriptor.from_gtv(o.extra["reg_auth_desc"]);
          require(o.account_id
           == acc.create_account_with_auth(auth_desc));
      }

      val target_account = acc.account @ { .id == o.account_id };
      val asset = asset @ { .id == o.asset_id };
      require(o.amount &gt; 0, "You cannot tx output negative numbers");
      require( available_assets[asset] &gt;= o.amount );
      available_assets[asset] -= o.amount;
      require(available_assets[asset] &gt;= 0);
      val balance = ensure_balance(target_account, asset);
      balance.amount += o.amount;

      return create payment_history_entry (
        .account = target_account,
        asset,
        .delta = o.amount,

        .op_index = 500, // something from op_context,
        .is_input = false,
        .entry_index = idx
      );
}

function _transfer (inputs: list&lt;xfer_input&gt;, outputs: list&lt;xfer_output&gt;) {
   val sum_inputs = map&lt;asset, integer&gt;();
   var idx = 0;
   for (i in inputs) {
      consume_input(i, idx, sum_inputs);
      idx += 1;
   }

   idx = 0;
   for (o in outputs) {
      process_transfer_output(o, idx, sum_inputs);
      idx += 1;
   }
}
</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/blockchain.rell">
                                <string>import ft3: ^.core;
import acc: ^.account;


entity asset_origin {
    key ft3.asset;
    origin_chain_rid: byte_array;
}

entity linked_chain {
    key chain_rid: byte_array;
}

function blockchain_account_id (blockchain_rid: byte_array): byte_array {
   return ("B", blockchain_rid).hash();
}

function ensure_blockchain_account (blockchain_rid: byte_array): acc.account {
   val blockchain_account_id = blockchain_account_id(blockchain_rid);
   val acc = acc.account @? { .id == blockchain_account_id };
   return if (acc??)  acc
   else create acc.account (id = blockchain_account_id);
}

function get_blockchain_account (blockchain_rid: byte_array): acc.account {
   return acc.account @ { .id == blockchain_account_id(blockchain_rid) };
}


query get_linked_chains() {
    return linked_chain @* {} ( .chain_rid );
}

query is_linked_with_chain(chain_rid: byte_array) {
    return linked_chain @? { chain_rid } != null;
}
</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/module.rell">
                                <string>@mount('ft3.xc')
module;
</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/structures.rell">
                                <string>struct operation_rec {
   name;
   args: list&lt;gtv&gt;;
}

struct transaction_body_rec {
    blockchain_rid: byte_array;
    operations: list&lt;operation_rec&gt;;
    signers: list&lt;gtv&gt;;
}

struct transaction_rec {
   body: transaction_body_rec;
   signatures: list&lt;gtv&gt;;
}

struct transaction_proof {
     tx: virtual&lt;transaction_rec&gt;;
     // block_header: byte_array;
     // merkle_path: virtual&lt;list&lt;byte_array&gt;&gt;;
     // tx_index: integer;
     block_rid: byte_array;
     block_signers: list&lt;byte_array&gt;;
     signatures: list&lt;byte_array&gt;;     
}

function verify_transaction_proof( p: transaction_proof ) {
   // TODO
}</string>
                            </entry>
                            <entry key="lib/ft3/crosschain/transfer.rell">
                                <string>import ft3: ^.core;

struct xc_target {
    account_id: byte_array;
    extra: map&lt;text, gtv&gt;;
}

function add_to_blockchain_balance (blockchain_rid: byte_array, ft3.asset, amount: integer) {
    require( chain_context.blockchain_rid != blockchain_rid ); // cannot add to own account

    val origin_chain_rid = asset_origin @? { asset } .origin_chain_rid;

    if (exists(origin_chain_rid) and (blockchain_rid == origin_chain_rid)) {
       // do nothing. in future we might track origin
    } else {
         val bc_acc = ensure_blockchain_account(blockchain_rid);
         ft3.ensure_balance(bc_acc, asset).amount += amount;
    }
}


struct init_xfer_args {
          source: ft3.xfer_input;
          target: xc_target;
          hops: list&lt;byte_array&gt;;
}

entity applied_transfers { key tx_rid: byte_array; }


</string>
                            </entry>
                            <entry key="lib/ft3/ft3_basic_dev.rell">
                                <string>module;

namespace ft3 {
	import acc: ^.account;
	import acc_op: ^.account.operations;
	import core: ^.ft3_basic_dev;
	import transfer_op: ^.core.operations.transfer;
//	import ^.crosschain;
//	import ^.crosschain.operations;
	
	import ^.operations.dev_op_account;
	import ^.operations.dev_op_asset;
	import ^.operations.dev_op_balance;
	import ^.operations.dev_op_rate_limit;
}

</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_account.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import acc: ^^.account; 


operation dev_register_account (acc.auth_descriptor) {
    dev_op.require_dev();
    acc.create_account_with_auth( auth_descriptor );
}
</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_asset.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import ft3: ^^.core;

import xft3: ^^.crosschain; 

operation dev_register_asset (name, issuing_chain_rid: byte_array) {
    dev_op.require_dev();
    ft3.register_asset(name, issuing_chain_rid);
}

operation dev_register_xc_asset (name, issuing_chain_rid: byte_array, origin_chain_rid: byte_array) {
    dev_op.require_dev();   
    val asset = ft3.register_asset(name, issuing_chain_rid);
    create xft3.asset_origin (asset, origin_chain_rid);
}
</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_balance.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import ft3: ^^.core;
import acc: ^^.account;


operation dev_give_balance (asset_id: byte_array, account_id: byte_array, amount: integer) {
    dev_op.require_dev();
    require(amount &gt;= 0);
    ft3.ensure_balance( acc.account @ { account_id }, ft3.asset @ { .id == asset_id } ).amount += amount;
}</string>
                            </entry>
                            <entry key="lib/ft3/operations/dev_op_rate_limit.rell">
                                <string>@mount('ft3')
module;

import dev_op: ^^.core.dev_op;
import acc: ^^.account;



/*
 * Can be negative
 */
operation dev_give_points(account_id: byte_array, amount: integer){
	val account = acc.account@{.id == account_id};
	dev_op.dev_give_points_(account, amount);
}

operation dev_free_op(account_id: byte_array) {
	// this operation does not cost points in the rate limit
	val account = acc.account@{.id == account_id};
	dev_op.dev_give_points_(account, 1);
	acc.rate_limit(account);
}</string>
                            </entry>
                            <entry key="main.rell">
                                <string>import lib.ft3.ft3_basic_dev;

// Remove for production
// ---

import user;
import topic;
import notifications;
import channel;
import follow;
import election;
import representative;
import chat;
import config;
</string>
                            </entry>
                            <entry key="notifications/index.rell">
                                <string>import user;

entity notification {
    key id: text, user.user;
    trigger: text;
    content: text;
    mutable read: boolean;
    index timestamp;
}
</string>
                            </entry>
                            <entry key="notifications/operations.rell">
                                <string>import user;
import user.distrust;

operation create_notifications_for_users(name, descriptor_id: byte_array, id: text, trigger: text, content: text, usernames: set&lt;text&gt;) {
    val opr_user = user.get_verified_user(name, descriptor_id);

    for (username in usernames) {
        val toUser = user.user@?{ .name == username.lower_case() };
        if (toUser != null and distrust.user_distrust@?{ .distruster == toUser, .distrusted == opr_user } == null) {
            create notification(
                id = id,
                toUser,
                trigger = trigger,
                content = content,
                false,
                op_context.last_block_time
            );
        }
    }
}

operation remove_notifications_for_users(name, descriptor_id: byte_array, id: text, usernames: set&lt;text&gt;) {
    val user = user.get_verified_user(name, descriptor_id);

    for (username in usernames) {
        val to_user = user.user@?{ .name == username };
        if (to_user != null) {
            delete notification@?{ id, .user == to_user };
        }
    }
}

operation mark_notifications_since_timestamp_read(name, descriptor_id: byte_array, timestamp) {
    val user = user.get_verified_user(name, descriptor_id);
    update notification@*{ .user == user, .timestamp &gt; timestamp } ( read = true );
}</string>
                            </entry>
                            <entry key="notifications/queries.rell">
                                <string>import user;

query count_unread_user_notifications(name) {
    val user = user.user@{ .name == name };
    return notification@*{ .user == user, .read == false } ( .id );
}

query get_user_notifications_prior_to_timestamp(name, timestamp, page_size: integer) {
    val user = user.user@{ .name == name };
    return notification@*{ .user == user, .timestamp &lt; timestamp } (
        .id,
        .trigger,
        .content,
        .read,
        @sort_desc .timestamp
    ) limit page_size;
}
</string>
                            </entry>
                            <entry key="representative/functions.rell">
                                <string>import user;
import election;

function is_username_representative(name): boolean {
	val user = user.user@?{ .name == name};
	
	if (user == null) {
		return false;
	}
	
	val prev_election = election.get_latest_completed_election_id();
	
	if (prev_election == null) {
		return false;
	}
	
	return representative@?{ .user == user, .representative_election.id == prev_election } != null;
}

function is_user_suspended(rep: user.user, suspendee: user.user, timestamp): boolean {
	return user.user_suspension@?{ 
		.user == suspendee, 
		.suspended_by == rep,
		.suspended_until &gt;= timestamp
	} != null;
} </string>
                            </entry>
                            <entry key="representative/index.rell">
                                <string>import election;
import user;

entity representative {
    key user.user, election.representative_election;
}

entity representative_action {
    key id: byte_array;
    index representative;
    index timestamp;
    action: text;
}

entity representative_distrust {
	key distruster: user.user, representative;
}

import representative.report;
</string>
                            </entry>
                            <entry key="representative/operations.rell">
                                <string>import election;
import topic;
import user;
import util;

operation remove_topic(username: text, descriptor_id: byte_array, topic_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);

    val recent_election = election.representative_election@{ .completed == true } ( .id, @sort_desc .timestamp ) limit 1;
    val representative = representative @{ user, .representative_election.id == recent_election.id };

    val the_topic = topic.topic @{ .id == topic_id };
    
    create topic.topic_moderation(representative.user, the_topic);

    create representative_action(
        id = op_context.transaction.tx_rid,
        representative,
        op_context.last_block_time,
        action = "A topic from @" + the_topic.author.display_name + " was removed by @" + user.display_name
    );
}

operation remove_topic_reply(username: text, descriptor_id: byte_array, topic_reply_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);

    val recent_election_id = require(election.get_latest_completed_election_id(), "No election has been held yet");
    val representative = representative @{ user, .representative_election.id == recent_election_id };

    val the_reply = topic.topic_reply @{ .id == topic_reply_id };
    
    create topic.topic_reply_moderation(representative.user, the_reply);

    create representative_action(
        id = op_context.transaction.tx_rid,
        representative,
        op_context.last_block_time,
        action = "Reply from @" + the_reply.author.display_name 
               + " in topic /t/" + the_reply.topic.id + " was removed by @" + user.display_name
    );
}

operation suspend_user(username: text, descriptor_id: byte_array, user_to_be_suspended: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);

    val recent_election_id = require(election.get_latest_completed_election_id(), "No election has been held yet");
    val representative = representative @{ user, .representative_election.id == recent_election_id };

    val suspendee = user.user@{ .name == user_to_be_suspended };
    
    val action_id = "suspend_user:" + user_to_be_suspended;
	
	require(
		not is_user_suspended(user, suspendee, op_context.last_block_time), 
		"User already suspended"
	);
	
    val updated_times_suspended = user.user_suspension@*{
    	.user == suspendee,
    	.suspended_by == user
    }( .user ).size() + 1;
    
    val one_day_millis = 86400000;
    val days_suspended = updated_times_suspended * updated_times_suspended;
    val suspension_time_millis = days_suspended * one_day_millis;
	val suspended_until = op_context.last_block_time + suspension_time_millis;

	create user.user_suspension(user = suspendee, suspended_by = user, suspended_until);

    var daysString = " days ";
    if (days_suspended == 1) {
        daysString = " day ";
    }

    create representative_action(
        id = op_context.transaction.tx_rid,
        representative,
        op_context.last_block_time,
        action = "@" + suspendee.display_name + " was suspended for " + days_suspended + daysString +  "by @" + user.display_name
    );
}

operation distrust_representative(name, descriptor_id: byte_array, distrusted: name) {
	val user = user.get_and_charge_verified_user(name, descriptor_id);
	
	val recent_election_id = require(election.get_latest_completed_election_id(), "No election has been held yet");
	
	require(is_eligible_to_distrust(user, recent_election_id), "User is not eligible to distrust");
	
    val representative = representative @{ 
    	.user.name == distrusted.lower_case(), 
    	.representative_election.id == recent_election_id
    };
    
    val required_votes = election.temp_votes_counter@{
    	.representative_election_candidate.representative_election.id == recent_election_id
    } ( @sort_desc .votes ) limit 1;
    
    val distrusts = representative_distrust@*{ 
    	representative
    }( .distruster ).size();
    
    if (distrusts &gt;= 10 and distrusts &gt; required_votes) {
    	delete representative;
    } else {
    	create representative_distrust(user, representative);
    }
}

function is_eligible_to_distrust(user.user, prev_election_id: integer): boolean {	
	val recent_election_start = election.election_block_details@{
		.representative_election.id == prev_election_id
	} ( .started_height );
	
	if (user.registered &gt; recent_election_start) {
		log("User must have registered before the previous election started");
		return false;
	}
	
	val previous_election_completed = (election: election.representative_election, details: election.election_block_details)@?{
		election.id != prev_election_id,
		election == details.representative_election,
		election.completed == true
	} ( 
		details.finished_height,
		@omit @sort_desc election.timestamp
	) limit 1;
	
	if (previous_election_completed == null) {
		return true;
	}
	
	val number_of_topics = topic.topic@*{ 
		.author == user,
		.last_modified &gt; previous_election_completed,
		.last_modified &lt; recent_election_start
	}( .id ).size();
	
	val number_of_replies = topic.topic_reply@*{
		.author == user,
		.timestamp &gt; previous_election_completed,
		.timestamp &lt; recent_election_start
	}( .id ).size();
	
	return number_of_topics + number_of_replies &gt;= 5;
}</string>
                            </entry>
                            <entry key="representative/queries.rell">
                                <string>import election;
import user;

query get_representatives(): list&lt;name&gt; {
    val election = election.representative_election@?{ .completed == true } ( .id, @sort_desc .timestamp ) limit 1;

    if (election == null) {
        return list&lt;name&gt;();
    }

    return representative@*{
        .representative_election.id == election.id
    } ( .user.name );
}

query get_all_representative_actions(timestamp, page_size: integer) {
    return representative_action@*{
        .timestamp &lt; timestamp
    } (
        .id,
        representative = .representative.user.name,
        @sort_desc .timestamp,
        .action
    ) limit page_size;
}

query get_number_of_times_representative(name) {
    return representative@*{ .user.name == name.lower_case() } ( .representative_election.id ).size();
}

query is_user_suspended_by_me(username: name, user_to_be_suspended: name, timestamp) {
	val user = user.user@{ .name == username.lower_case() };
	val suspendee = user.user@{ .name == user_to_be_suspended.lower_case() };
	return is_user_suspended(user, suspendee, timestamp);
}</string>
                            </entry>
                            <entry key="representative/report/index.rell">
                                <string>import user;

entity representative_report {
    key id: text;
    index timestamp;
    text;
}
</string>
                            </entry>
                            <entry key="representative/report/operations.rell">
                                <string>import election;
import user;
import representative;
import util;

operation create_representative_report(username: text, descriptor_id: byte_array, id: text, text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create representative_report(id = id, op_context.last_block_time, text = text);
}
</string>
                            </entry>
                            <entry key="representative/report/queries.rell">
                                <string>query get_unhandled_representative_reports(timestamp) {
    return representative_report@*{
    	.timestamp &gt; timestamp
    } ( 
    	.id, 
    	@sort_desc .timestamp, 
    	.text
    ) limit 25;
}</string>
                            </entry>
                            <entry key="representative/topic_pin.rell">
                                <string>import election;
import topic;
import user;
import user.distrust;

entity topic_pin {
	key representative;
	mutable topic.topic;
}

operation pin_topic(name, descriptor_id: byte_array, topic_id: text) {
	val user = user.get_and_charge_verified_user(name, descriptor_id);

    val recent_election = election.representative_election@{ .completed == true } ( .id, @sort_desc .timestamp ) limit 1;
    val representative = representative @{ user, .representative_election.id == recent_election.id };
    
    val topic = topic.topic@{ .id == topic_id };
    
    val prev_pin = topic_pin@?{ representative };
    
    if (prev_pin != null) {
    	update prev_pin(topic);
    } else {
    	create topic_pin(representative, topic);
    }
}

query get_pinned_topic(name) {
    val recent_election = election.representative_election@?{ .completed == true } ( .id, @sort_desc .timestamp ) limit 1;
	
	if (recent_election == null) {
		return null;
	}
	
	val distrusted_by_me = distrust.user_distrust@*{ 
		.distruster.name == name.lower_case() 
	} ( .distrusted.name );
	
	val topic_pins = topic_pin@*{
		.representative.representative_election.id == recent_election.id
	} ( 
		topic_id = .topic.id, 
		name = .representative.user.name
	);
	
	val pins_map = map&lt;text, integer&gt;();
	for (pin in topic_pins) {
		if (not distrusted_by_me.contains(pin.name)) {
			var nrOfPins = 1;
			if (pins_map.contains(pin.topic_id)) {
				nrOfPins += pins_map[pin.topic_id];
			}
			pins_map.put(pin.topic_id, nrOfPins);
		}
	}
	
	var highest_topic_id = "";
	var highest = 0;
	
	for (id in pins_map.keys()) {
		val moderated_by = topic.topic_moderation@*{ .topic.id == id } ( .user.name );
		var topic_is_clean = moderated_by.empty();
		
		var distrusted_moderators = set&lt;name&gt;();
		for (moderator in moderated_by) {
			if (distrusted_by_me.contains(moderator)) {
				distrusted_moderators.add(moderator);
			}
		}
		
		if (topic_is_clean or distrusted_moderators.size() == moderated_by.size()) {
			val pins_on_topic = pins_map[id];
			if (pins_on_topic &gt; highest) {
				highest_topic_id = id;
				highest = pins_on_topic;
			}	
		}
	}
	
	return highest_topic_id;
}

query get_representatives_topic_pin(name) {
    val recent_election = election.representative_election@?{ .completed == true } ( .id, @sort_desc .timestamp ) limit 1;
    
    if (recent_election == null)
    	return null;
    
	return topic_pin@?{
		.representative.representative_election.id == recent_election.id,
		.representative.user.name == name.lower_case()
	} ( .topic.id ) limit 1;
}</string>
                            </entry>
                            <entry key="topic/functions.rell">
                                <string>import util;

function find_topic_by_id(id: text): topic {
    return topic@{ .id == id };
}

function require_mutable(post_timestamp: timestamp, op_timestamp: timestamp, action: text) {
	val fiveMinutesInMillis = 300000;
    require(
    	op_timestamp &lt; post_timestamp + fiveMinutesInMillis,
    	util.app_error(util.error_type.TOPIC_IMMUTABLE, action)
    );
}

function get_latest_poster_in_topic(id: text, topic_author: name): text {
	val latest_reply = topic_reply@?{ .topic.id == id} (
		@sort_desc .timestamp,
		.author
	) limit 1;
	
	if (latest_reply != null) {
		return latest_reply.author.display_name;
	} else {
		return topic_author;
	}
}</string>
                            </entry>
                            <entry key="topic/index.rell">
                                <string>import user;

entity topic {
    key id: text;
    index author: user.user;
    timestamp;
    mutable last_modified: timestamp;
    index last_modified;
    title: name;
    mutable message: text;
}

entity topic_moderation {
	key user.user, topic;
}

entity topic_reply {
    key id: text;
    index topic;
    index author: user.user;
    index timestamp;
    is_sub_reply: boolean = false;
    index is_sub_reply;
    mutable message: text;
}

entity topic_reply_moderation {
	key user.user, topic_reply;
}

entity sub_reply {
    key parent_reply: topic_reply, child_reply: topic_reply;
}

struct ext_topic {
	id: text;
	author: text;
	title: text;
	message: text;
	timestamp;
	last_modified: timestamp;
	latest_poster: name;
	moderated_by: list&lt;name&gt;;
}

struct ext_topic_reply {
	id: text;
	topic_id: text;
	author: text;
	message: text;
	is_sub_reply: boolean;
	timestamp;
	moderated_by: list&lt;name&gt;;
}

import topic.rating;
import topic.subscription;
</string>
                            </entry>
                            <entry key="topic/operations.rell">
                                <string>import channel;
import topic.rating;
import user;
import topic.subscription;
import topic.poll;

operation create_topic(id: text, descriptor_id: byte_array, username: text, channel_key: name, channel_name: name, title: name, message: text) {
    val pattern = ".{3,40}";
    require(title.matches(pattern), "Title [" + title + "] is invalid, must match: " + pattern);
    
    val author = user.get_and_charge_verified_user(username, descriptor_id);

    val topic = create topic(
        id = id,
        author,
        timestamp = op_context.last_block_time,
        last_modified = op_context.last_block_time,
        title = title,
        message = message
    );

    create channel.channel(name = channel_key.lower_case(), topic, op_context.last_block_time, display_name = channel_name);
    create rating.tmp_topic_rating (topic, 0);
        
    for (suspension in user.user_suspension@*{ .user == author, .suspended_until &gt; op_context.last_block_time }) {
    	create topic_moderation(suspension.suspended_by, topic);
    }
}

operation modify_topic(id: text, descriptor_id: byte_array, username: text, text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);

    val topic = topic@{ .id == id, .author == author };
    require_mutable(topic.timestamp, op_context.last_block_time, "Modify topic");

    update topic ( message = text );
}

operation delete_topic(id: text, descriptor_id: byte_array, username: text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);

    val topic = topic@{ .id == id, .author == author };
    require_mutable(topic.timestamp, op_context.last_block_time, "Delete topic");
    delete channel.channel@{ topic };
    delete rating.tmp_topic_rating@{ topic };
    delete subscription.subscription@?{ topic };
    
    val opt_poll = poll.poll@?{ topic };
    if (opt_poll != null) {
    	delete poll.poll_option@*{ .poll == opt_poll };
    	delete poll.poll_vote@*{ .poll == opt_poll };
    	delete opt_poll;
    }
    
	delete topic;
}

operation create_reply(topic_id: text, descriptor_id: byte_array, id: text, username: text, message: text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);
    val topic = find_topic_by_id(topic_id);

    val reply = create topic_reply(
        id = id,
        topic,
        author,
        timestamp = op_context.last_block_time,
        message = message
    );
    
    for (suspension in user.user_suspension@*{ .user == author, .suspended_until &gt; op_context.last_block_time }) {
    	create topic_reply_moderation(suspension.suspended_by, reply);
    }

     update topic ( last_modified = op_context.last_block_time);
}

operation modify_reply(id: text, descriptor_id: byte_array, username: text, text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);

    val reply = topic_reply@{ .id == id, .author == author };
    require_mutable(reply.timestamp, op_context.last_block_time, "Modify reply");

    update reply ( message = text );
}

operation delete_reply(id: text, descriptor_id: byte_array, username: text) {
	val author = user.get_and_charge_verified_user(username, descriptor_id);
	val reply = topic_reply@{ id, author };
	require_mutable(reply.timestamp, op_context.last_block_time, "Delete reply");
	
	delete sub_reply@?{ .child_reply == reply };
	delete reply;
}

operation create_sub_reply(topic_id: text, descriptor_id: byte_array, parent_reply_id: text, id: text, username: text, message: text) {
    val author = user.get_and_charge_verified_user(username, descriptor_id);
    val topic = find_topic_by_id(topic_id);

    val topic_reply = create topic_reply(
        id = id,
        topic,
        author,
        timestamp = op_context.last_block_time,
        is_sub_reply = true,
        message = message	
    );
    
    for (suspension in user.user_suspension@*{ .user == author, .suspended_until &gt; op_context.last_block_time }) {
    	create topic_reply_moderation(suspension.suspended_by, topic_reply);
    }

    create sub_reply(
        parent_reply = topic_reply@{ .id == parent_reply_id },
        child_reply = topic_reply
    );

    update topic ( last_modified = op_context.last_block_time);
}</string>
                            </entry>
                            <entry key="topic/poll/index.rell">
                                <string>import topic;
import user;

entity poll {
	key topic.topic;
	text;
}

entity poll_option {
	key poll, text;
	mutable votes: integer;
}

entity poll_vote {
	key poll, user.user;
	poll_option;
}

struct poll_record {
	question: text;
	options: list&lt;option_record&gt;;
}

struct option_record {
	option: text;
	votes: integer;
}</string>
                            </entry>
                            <entry key="topic/poll/operations.rell">
                                <string>import user;
import topic;

operation create_poll(id: text, descriptor_id: byte_array, 
	username: text, question: text, options: list&lt;text&gt;
) {
	val author = user.get_and_charge_verified_user(username, descriptor_id);
	val topic = topic.topic@{ .id == id, author };
	
	val poll = create poll(topic, question);
	
	for (option in options) {
		create poll_option(poll, option, 0);
	}
}

operation vote_for_poll_option(id: text, descriptor_id: byte_array, username: text, option: text) {
	val user = user.get_and_charge_verified_user(username, descriptor_id);
	
	val poll_opt = poll_option@{ .poll.topic.id == id, .text == option };

	create poll_vote(poll_opt.poll, user, poll_opt);
	update poll_opt ( .votes+1 );
}</string>
                            </entry>
                            <entry key="topic/poll/queries.rell">
                                <string>query get_poll(topic_id: text): poll_record? {
	val poll = poll@?{ .topic.id == topic_id };
	
	if (poll == null) {
		return null;
	}
	
	val options = list&lt;option_record&gt;();
	for (opt in poll_option@*{ .poll == poll }) {
		options.add(option_record(opt.text, opt.votes));
	}
	
	return poll_record(poll.text, options);
}

query get_poll_vote(topic_id: text, username: text): text? {
	val vote = poll_vote@?{ 
		.poll.topic.id == topic_id, 
		.user.name == username.lower_case()
	};
	
	if (vote == null) return null;
	return vote.poll_option.text;
}</string>
                            </entry>
                            <entry key="topic/queries.rell">
                                <string>import channel;
import follow;
import topic.rating;
import user;
import representative;

query get_topics_after_timestamp(timestamp, page_size: integer) {
    val topics = topic@*{ .last_modified &gt; timestamp } (
        .id,
        author=.author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_prior_to_timestamp(timestamp, page_size: integer): list&lt;ext_topic&gt; {
    val topics = topic@*{ .last_modified &lt; timestamp }(
        .id,
        author = .author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    ) limit page_size;
        
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
  	   	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topic_replies_prior_to_timestamp(username: name, topic_id: text, timestamp, page_size: integer) {	
    val replies = topic_reply@*{
        topic@{ .id == topic_id },
        .timestamp &lt; timestamp,
        .is_sub_reply == false
    }(
        .id,
        topic_id = .topic.id,
        author= .author.display_name,
        .message,
        .is_sub_reply,
        @sort_desc .timestamp
    ) limit page_size;
    
    val ext_replies = list&lt;ext_topic_reply&gt;();
    for (reply in replies) {
    	val moderated_by = topic_reply_moderation @*{ .topic_reply.id == reply.id } ( .user.name );
    	val ext_reply = ext_topic_reply (
    		id = reply.id,
    		topic_id = reply.topic_id,
    		author = reply.author,
    		message = reply.message,
    		is_sub_reply = reply.is_sub_reply,
    		timestamp = reply.timestamp,
    		moderated_by = moderated_by
    	);
    	ext_replies.add(ext_reply);
    }
    
    return ext_replies;
}

query count_topic_replies(topic_id: text) {
	return topic_reply@*{ .topic.id == topic_id }( .id ).size();
}

query get_topic_replies_after_timestamp(username: name, topic_id: text, timestamp, page_size: integer) {	
	val replies = topic_reply@*{
        topic@{ .id == topic_id },
        .timestamp &gt; timestamp,
        .is_sub_reply == false
    }(
        .id,
        topic_id = .topic.id,
        author= .author.display_name,
        .message,
        .is_sub_reply,
        @sort_desc .timestamp
    ) limit page_size;
			
    val ext_replies = list&lt;ext_topic_reply&gt;();
    for (reply in replies) {
    	val moderated_by = topic_reply_moderation @*{ .topic_reply.id == reply.id } ( .user.name );
    	val ext_reply = ext_topic_reply (
    		id = reply.id,
    		topic_id = reply.topic_id,
    		author = reply.author,
    		message = reply.message,
    		is_sub_reply = reply.is_sub_reply,
    		timestamp = reply.timestamp,
    		moderated_by = moderated_by
    	);
    	ext_replies.add(ext_reply);
    }
    
    return ext_replies;
}

query get_topic_replies_by_user_prior_to_timestamp(name, timestamp, page_size: integer) {
    val replies = topic_reply@*{ .author.name == name, .timestamp &lt; timestamp } (
        .id,
        topic_id = .topic.id,
        author=.author.display_name,
        .message,
        .is_sub_reply,
        @sort_desc .timestamp
    ) limit page_size;
    
    val ext_replies = list&lt;ext_topic_reply&gt;();
    for (reply in replies) {
    	val moderated_by = topic_reply_moderation @*{ .topic_reply.id == reply.id } ( .user.name );
    	val ext_reply = ext_topic_reply (
    		id = reply.id,
    		topic_id = reply.topic_id,
    		author = reply.author,
    		message = reply.message,
    		is_sub_reply = reply.is_sub_reply,
    		timestamp = reply.timestamp,
    		moderated_by = moderated_by
    	);
    	ext_replies.add(ext_reply);
    }
    
    return ext_replies;
}

query count_topics_by_user(name): integer {
    return topic@*{ .author.name == name }( .id ).size();
}

query count_replies_by_user(name): integer {
    return topic_reply@*{ .author.name == name }( .id ).size();
}

query get_sub_replies(username: name, parent_reply_id: text) {	
    val replies = sub_reply@*{ .parent_reply.id == parent_reply_id } (
        id = .child_reply.id,
        topic_id = .child_reply.topic.id,
        author = .child_reply.author.display_name,
        message = .child_reply.message,
        is_sub_reply = .child_reply.is_sub_reply,
        @sort timestamp= .child_reply.timestamp
    );
   
   val ext_replies = list&lt;ext_topic_reply&gt;();
    for (reply in replies) {
    	val moderated_by = topic_reply_moderation @*{ .topic_reply.id == reply.id } ( .user.name );
    	val ext_reply = ext_topic_reply (
    		id = reply.id,
    		topic_id = reply.topic_id,
    		author = reply.author,
    		message = reply.message,
    		is_sub_reply = reply.is_sub_reply,
    		timestamp = reply.timestamp,
    		moderated_by = moderated_by
    	);
    	ext_replies.add(ext_reply);
    }
    
    return ext_replies;
}

query get_topics_by_user_id_prior_to_timestamp(name, timestamp, page_size: integer) {
    val topics = topic@*{
        user.user@{ .name == name },
        .last_modified &lt; timestamp
    }(
        .id,
        author= .author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_from_follows_after_timestamp(name, timestamp, page_size: integer) {
    val topics = (topic, follow.follow)@*{
            follow.follower.name == name.lower_case(),
            follow.follows == topic.author,
            topic.last_modified &gt; timestamp
    }(
        topic.id,
        author=topic.author.display_name,
        topic.title,
        topic.message,
        @sort_desc topic.last_modified,
        topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_from_follows_prior_to_timestamp(name, timestamp, page_size: integer) {
    val topics = (topic, follow.follow) @* {
        follow.follower.name == name.lower_case(),
        follow.follows == topic.author,
        topic.last_modified &lt; timestamp
    }(
        topic.id,
        author = topic.author.display_name,
        topic.title,
        topic.message,
        @sort_desc topic.last_modified,
        topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topic_by_id(username: name, id: text) {
    val topic = topic@{ .id == id }(
        .id,
        author = .author.display_name,
        .title,
        .message,
        @sort_desc .last_modified,
        .timestamp
    );
    
    val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
	return ext_topic (
		id = topic.id,
		author = topic.author,
		title = topic.title,
		message = topic.message,
		timestamp = topic.timestamp,
		last_modified = topic.last_modified,
		latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
		moderated_by = moderated_by
	);
}

query get_all_topics_by_stars_since_timestamp(timestamp, page_size: integer) {
    val topics = rating.tmp_topic_rating@*{
        .topic.last_modified &gt; timestamp
    } (
        @sort_desc .stars,
        id = .topic.id,
        author=.topic.author.display_name,
        title=.topic.title,
        message=.topic.message,
        last_modified=.topic.last_modified,
        timestamp=.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_by_follows_and_stars_since_timestamp(name, timestamp, page_size: integer) {
    val topics = (rating.tmp_topic_rating, follow.follow) @*{
            follow.follower.name == name,
            tmp_topic_rating.topic.author == follow.follows,
            tmp_topic_rating.topic.last_modified &gt; timestamp
        } (
        @sort_desc tmp_topic_rating.stars,
        id = tmp_topic_rating.topic.id,
        author = tmp_topic_rating.topic.author.display_name,
        title = tmp_topic_rating.topic.title,
        message = tmp_topic_rating.topic.message,
        last_modified = tmp_topic_rating.topic.last_modified,
        timestamp = tmp_topic_rating.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_by_channel_after_timestamp_sorted_by_popularity(name, timestamp, page_size: integer) {
    val topics = (rating.tmp_topic_rating, channel.channel)@*{
        name == channel.name,
        tmp_topic_rating.topic == channel.topic,
        tmp_topic_rating.topic.last_modified &gt; timestamp
    } (
        @sort_desc .stars,
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        last_modified = channel.topic.last_modified,
        timestamp = channel.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}

query get_topics_by_followed_channels_after_timestamp_sorted_by_popularity(name, timestamp, page_size: integer) {
    val topics = (rating.tmp_topic_rating, channel.channel_following, channel.channel)@*{
        channel_following.user == user.user@{ name },
        channel_following.name == channel.name,
        tmp_topic_rating.topic == channel.topic,
        tmp_topic_rating.topic.last_modified &gt; timestamp
    } (
        @sort_desc .stars,
        id = channel.topic.id,
        author = channel.topic.author.display_name,
        title = channel.topic.title,
        message = channel.topic.message,
        last_modified = channel.topic.last_modified,
        timestamp = channel.topic.timestamp
    ) limit page_size;
    
    val ext_topics = list&lt;ext_topic&gt;();
    for (topic in topics) {
    	val moderated_by = topic_moderation@*{ .topic.id == topic.id } ( .user.name );
    	val ext_topic = ext_topic (
			id = topic.id,
			author = topic.author,
			title = topic.title,
			message = topic.message,
			timestamp = topic.timestamp,
			last_modified = topic.last_modified,
			latest_poster = get_latest_poster_in_topic(topic.id, topic.author),
			moderated_by = moderated_by
		);
    	ext_topics.add(ext_topic);
    }
    
    return ext_topics;
}</string>
                            </entry>
                            <entry key="topic/rating/index.rell">
                                <string>import user;
import topic;

entity topic_star_rating {
    key topic.topic, user.user;
}

// To be deleted when GROUP BY and COUNT is supported, then will use topic_star_rating instead
entity tmp_topic_rating {
    key topic.topic;
    mutable stars: integer;
    index stars;
}

entity reply_star_rating {
    key topic.topic_reply, user.user;
}
</string>
                            </entry>
                            <entry key="topic/rating/operations.rell">
                                <string>import user;
import topic;

operation give_topic_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create topic_star_rating(topic.topic@{ .id == id }, user);

    val topicRating = tmp_topic_rating@{ topic.topic@{ .id == id }};
    update topicRating ( stars = topicRating.stars + 1 );
}

operation remove_topic_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    delete topic_star_rating@{ topic.topic@{ .id == id }, user };

    val topicRating = tmp_topic_rating@{ topic.topic@{ .id == id }};
    update topicRating ( stars = topicRating.stars - 1 );
}

operation give_reply_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create reply_star_rating(topic.topic_reply@{ .id == id }, user);
}

operation remove_reply_star_rating(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    delete reply_star_rating@{ topic.topic_reply@{ .id == id }, user };
}</string>
                            </entry>
                            <entry key="topic/rating/queries.rell">
                                <string>import topic;

query get_star_rating_for_topic(id: text) {
    return topic_star_rating@*{ topic.topic@{ .id == id }} ( .user.name );
}

query get_star_rating_for_reply(id: text) {
    return reply_star_rating@*{ topic.topic_reply@{ .id == id }} ( .user.name );
}

query count_user_topic_star_rating(name): integer {
    return topic_star_rating@*{ .topic.author.name == name } ( .topic, .user ).size();
}

query count_user_reply_star_rating(name): integer {
    return reply_star_rating@*{ .topic_reply.author.name == name } ( .topic_reply, .user ).size();
}</string>
                            </entry>
                            <entry key="topic/subscription/index.rell">
                                <string>import user;
import topic;

entity subscription {
    key topic.topic, user.user;
}
</string>
                            </entry>
                            <entry key="topic/subscription/operations.rell">
                                <string>import user;
import topic;

operation subscribe_to_topic(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    create subscription(topic.topic@{ .id == id }, user);
}

operation unsubscribe_from_topic(username: text, descriptor_id: byte_array, id: text, unique_id: text) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);
    delete subscription@{ topic.topic@{ .id == id }, user };
}</string>
                            </entry>
                            <entry key="topic/subscription/queries.rell">
                                <string>import topic;

query get_subscribers_for_topic(id: text) {
    return subscription@*{ topic.topic@{ .id == id }} ( .user.name );
}</string>
                            </entry>
                            <entry key="user/distrust/index.rell">
                                <string>import user;

entity user_distrust {
    key distruster: user.user, distrusted: user.user;
}</string>
                            </entry>
                            <entry key="user/distrust/operations.rell">
                                <string>import user;

operation toggle_distrust(username: name, descriptor_id: byte_array, name, muted: boolean) {
    val user = user.get_and_charge_verified_user(username, descriptor_id);

    if (muted) {
        create user_distrust(distruster = user, distrusted = user.user@{ .name == name });
    } else {
        delete user_distrust@{ .distruster == user, .distrusted == user.user@{ .name == name }};
    }
}
</string>
                            </entry>
                            <entry key="user/distrust/queries.rell">
                                <string>query get_distrusted_users(name) {
    return user_distrust@*{ .distruster.name == name.lower_case() } ( .distrusted.name );
}

query times_user_was_distrusted(name): integer {
	return user_distrust@*{ .distrusted.name == name } ( .distruster ).size();
}

query times_user_distrusted_someone(name): integer {
	return user_distrust@*{ .distruster.name == name } ( .distrusted ).size();
}</string>
                            </entry>
                            <entry key="user/functions.rell">
                                <string>import ft3_acc: lib.ft3.account;
import util;

function get_verified_user(name, descriptor_id: byte_array): user {
    val user = user@{ .name == name.lower_case() };
    ft3_acc.require_auth(user.account, descriptor_id, list&lt;text&gt;());
    return user;
}

function get_and_charge_verified_user(name, descriptor_id: byte_array): user {
	val user = get_verified_user(name, descriptor_id);
	ft3_acc.rate_limit(user.account);
	return user;
}</string>
                            </entry>
                            <entry key="user/index.rell">
                                <string>import ft3_acc: lib.ft3.account;

entity user {
    key name;
    index ft3_acc.account;
    display_name: name;
    registered: integer = 0;
}

entity user_suspension {
	index user;
	index suspended_by: user;
	index suspended_until: timestamp;
}

import user.settings;
import user.distrust;
</string>
                            </entry>
                            <entry key="user/operations.rell">
                                <string>import ft3_acc: lib.ft3.account;

import user.settings;

operation register_user(name, account_id: byte_array) {
	val pattern = "[a-zA-Z0-9]{3,16}";
	require(name.matches(pattern), "Not a valid username, must match: " + pattern);
	
    val account = ft3_acc.account @ { account_id };
    val user = create user(name = name.lower_case(), display_name = name, account, op_context.block_height);
    
    create settings.user_settings(user, avatar = "" , description = "");
}
</string>
                            </entry>
                            <entry key="user/queries.rell">
                                <string>import ft3_acc: lib.ft3.account;

query get_user(name) {
    return user@?{ .name == name.lower_case() } ( name = .display_name );
}

query get_account_id(name) {
    return user@?{ .name == name.lower_case() } ( .account.id );
}

query get_registered_at(name) {
	return user@{ .name == name.lower_case() } ( .registered );
}

query username_by_account_id(id: byte_array): name? {
	val account = ft3_acc.account@? { id };
	if (account != null) {
		return user@?{ .account == account } ( .display_name );
	}
	
	return null;
}</string>
                            </entry>
                            <entry key="user/settings/index.rell">
                                <string>import user;

entity user_settings {
    key user.user;
    mutable avatar: text;
    mutable description: text;
    mutable socials: json = json("{}");
}
</string>
                            </entry>
                            <entry key="user/settings/operations.rell">
                                <string>import user;

operation create_user_settings(name, descriptor_id: byte_array, avatar: text, description: text, socials: json) {
    val user = user.get_and_charge_verified_user(name, descriptor_id);
    create user_settings(user, avatar = avatar, description = description, socials);
}

operation update_user_settings(name, descriptor_id: byte_array, avatar: text, description: text, socials: json) {
    val user = user.get_and_charge_verified_user(name, descriptor_id);
    update user_settings@{ .user == user }( avatar = avatar, description = description, socials);
}
</string>
                            </entry>
                            <entry key="user/settings/queries.rell">
                                <string>import user;

query get_user_settings(name) {
    return user_settings@?{ user.user@{ .name == name }} ( .avatar, .description, .socials );
}
</string>
                            </entry>
                            <entry key="util/log.rell">
                                <string>enum error_type {
	USER_UNAUTHORIZED,
	USER_SUSPENDED,
	TOPIC_IMMUTABLE,
	REPRESENTATIVE_ALREADY_SUSPENDED,
	ILLEGAL_ACTION,
	EXPECTED_ERROR
}

function app_error(error_type, action: text): text {
	val msg = when(error_type) {
		USER_UNAUTHORIZED -&gt; message_with_code("CERR_10", "Requester was unauthorized", action);
		USER_SUSPENDED -&gt; message_with_code("CERR_11", "Requester was suspended", action);
		TOPIC_IMMUTABLE -&gt; message_with_code("CERR_20", "Topic is no longer mutable", action);
		REPRESENTATIVE_ALREADY_SUSPENDED -&gt; message_with_code("CERR_30", "User was already suspended", action);
		ILLEGAL_ACTION -&gt; message_with_code("CERR_40", "The attempted action was illegal", action);
		EXPECTED_ERROR -&gt; message_with_code("CERR_50", "Expected error", action);
	};
	
	log(msg);
	return msg;
}

function message_with_code(code: text, message: text, action: text): text {
	return '{"code":"' + code + '","message":"' + message + '","action":"' + action + '"}';
}</string>
                            </entry>
                        </dict>
                    </entry>
                </dict>
            </entry>
        </dict>
    </entry>
    <entry key="signers">
        <array>
            <bytea>0350FE40766BC0CE8D08B3F5B810E49A8352FDD458606BD5FAFE5ACDCDC8FF3F57</bytea>
        </array>
    </entry>
</dict>

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.