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
//!
//! # INTERLOCK NETWORK MVP SMART CONTRACT
//!  - ### PSP22 TOKEN
//!  - ### REWARDS
//!
//! This is a standard ERC20-style token contract
//! with provisions for rewarding interlockers for
//! browsing the internet with the Interlock browser extension,
//! and eventually security staking and bounty hunting.
//!
//! #### To ensure build with cargo-contract version 2.0.0, run:
//!
//! cargo install cargo-contract --force --version 2.0.0
//!
//! #### To build, run:
//!
//! cargo +nightly-2023-02-07 contract build
//!
//! #### To build docs, run:
//!
//! cargo +nightly doc --no-deps --document-private-items --open
//!
//! #### To reroute docs in Github, run:
//!
//! echo "<meta http-equiv=\"refresh\" content=\"0; url=ilockmvp\">" >
//! target/doc/index.html;
//! cp -r target/doc ./docs
//!

#![doc(
    html_logo_url = "https://assets-global.website-files.com/64d9930f57641d176ab09b78/64dde3b1459a01ddf7b4a529_interlock-logo-large.webp",
    html_favicon_url = "https://assets-global.website-files.com/64d9930f57641d176ab09b78/64da50c8875e833f16060147_Favicon.png",
)]

#![allow(non_snake_case)]
#![cfg_attr(not(feature = "std"), no_std)]
#![feature(min_specialization)]


pub use self::ilockmvp::{
    ILOCKmvp,
    ILOCKmvpRef,
};

#[openbrush::contract]
pub mod ilockmvp {

    use ink::{
        codegen::{EmitEvent, Env},
        reflect::ContractEventBase,
    };
    use ink::prelude::{
        vec::Vec,
        format,
        string::{String, ToString},
    };
    use ink::storage::Mapping;
    use openbrush::{
        contracts::{
            psp22::{
                extensions::metadata::*,
                Internal,
            },
            ownable::*,
            pausable::*,
        },
        traits::Storage,
    };

////////////////////////////////////////////////////////////////////////////
//// constants /////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

    /// - Magic numbers.
    pub const ID_LENGTH: usize = 32;                                // 32B account id
    pub const POOL_COUNT: usize = 13;                               // number of token pools
    pub const ONE_MONTH: Timestamp = 2_592_000_000;                 // milliseconds in 30 days
    pub const MULTISIG_TIME: Timestamp = 86400_000;                 // milliseconds in 30 days
    pub const MIN_SHARE: u128 = 1_000_000_000;
    pub const TIME_LIMIT_MIN: Timestamp = 600_000;                  // 10 minutes
    pub const THRESHOLD_MIN: u16 = 2;                               // two signers

    /// - Token data.
    pub const TOKEN_CAP: u128 = 1_000_000_000;                      // 10^9
    pub const DECIMALS_POWER10: u128 = 1_000_000_000_000_000_000;   // 10^18
    pub const SUPPLY_CAP: u128 = TOKEN_CAP * DECIMALS_POWER10;      // 10^27
    pub const TOKEN_NAME: &str = "Interlock Network";
    pub const TOKEN_DECIMALS: u8 = 18;
    pub const TOKEN_SYMBOL: &str = "ILOCK";
    pub const INITIAL_REWARDS: u128 = 150_000_000 * DECIMALS_POWER10;

    /// - Multisig functions.
    pub const TRANSFER_OWNERSHIP: u8    = 0;
    pub const UNPAUSE: u8               = 1;
    pub const CREATE_PORT: u8           = 2;
    pub const ADD_SIGNATORY: u8         = 3;
    pub const REMOVE_SIGNATORY: u8      = 4;
    pub const CHANGE_TIMELIMIT: u8      = 5;
    pub const CHANGE_THRESHOLD: u8      = 6;
    pub const UPDATE_CONTRACT: u8       = 7;

////////////////////////////////////////////////////////////////////////////
//// structured data ///////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

    /// This is a type wrapper to implement Default method
    /// on AccountId type. Ink 4 stable eliminated AccountId Default
    /// (which was zero address, that has known private key)
    /// ...we only really need this because Openbrush contract
    ///    relies on deriving Default for contract storage, and
    ///    our AccesData struct contains AccountId.
    #[derive(scale::Encode, scale::Decode, Copy, Clone, Debug, PartialEq)]
    #[cfg_attr(
        feature = "std",
        derive(
            Eq,
            scale_info::TypeInfo,
            ink::storage::traits::StorageLayout,
        )
    )]
    pub struct AccountID {
        address: AccountId,
    }
    impl Default for AccountID {
        fn default() -> AccountID {
            AccountID {
                address: AccountId::from([1_u8;32]),
            }
        }
    }

    /// - This is upgradable storage for the token rewarding feature of this
    /// PSP22 contract.
    pub const REWARD_KEY: u32 = openbrush::storage_unique_key!(RewardData);
    #[derive(Default, Debug)]
    #[openbrush::upgradeable_storage(REWARD_KEY)]
    pub struct RewardData {

        // ABSOLUTELY DO NOT CHANGE THE ORDER OF THESE VARIABLES
        // OR TYPES IF UPGRADING THIS CONTRACT!!!

        /// - How much ILOCK have we rewarded each Interlocker?
        interlocker: Mapping<AccountId, Balance>,

        /// - In total, how much ILOCK have we rewarded to Interlockers?
        total: Balance,

        /// - Reward parameters
        rewardmax: Balance,

        /// - Expand storage related to the pool accounting functionality.
        pub _reserved: Option<()>,
    }

    /// - This is upgradable storage for the application connection feature of this
    /// PSP22 contract (ie, the application/socket/port contract connectivity formalism).
    pub const APP_KEY: u32 = openbrush::storage_unique_key!(ApplicationData);
    #[derive(Default, Debug)]
    #[openbrush::upgradeable_storage(APP_KEY)]
    pub struct AppData {

        // ABSOLUTELY DO NOT CHANGE THE ORDER OF THESE VARIABLES
        // OR TYPES IF UPGRADING THIS CONTRACT!!!

        /// - Contains information specifying a particular _type_ of connecting
        /// external application contract via the application/socket abstraction.
        /// - When an application contract creates a connecting socket with this token
        /// contract with a particular port, it adheres to the logic and protocol
        /// specified by the port type.
        /// - For example, PORT 0 in this contract only accepts connections from universal
        /// access NFT contract owned by Interlock, and for every socket call from a UANFT contract 
        /// application, tokens in the amount of the set NFT price are transferred from the calling minter
        /// to this ILOCK contract's owner account. On the application side, once the ILOCK
        /// tokens are successfully transferred via the port protocol, a UANFT is minted to
        /// the caller.
        /// - For example, PORT 1 in this contract is the same as PORT 0, but UANFT application
        /// contracts are owned by different operators, and on each socket call, the protocol
        /// includes an additional tax in ILOCK, which Interlock Network collects.
        /// - The mapping is from port number, to port details and specs.
        /// - Only this contract's owner has the authority to create or edit a port.
        /// - See detailed struct below.
        ///
        /// ports:         port number -> port(app contract hash, metadata, port owner)
        ///
        pub ports: Mapping<u16, Port>,

        /// - Contains information specifying a particular _instance_ of an application
        /// (as defined by port application hash) contract's connection to this PSP22
        /// contract.
        /// - Similar to the standard TCP/IP address:port format, the port specifies the
        /// protocol, and the address specifies the operator of that particular instance
        /// of the application contract connecting to this PSP22 contract.
        /// - In the example of PORT 1, the address of a socket connection is the address
        /// that receives the ILOCK token transfer, ultimately in exchange for the UANFT
        /// mint back on the application side.
        /// - The mapping is from application address, to socket operator address and port number.
        /// - One socket may serve multiple applications (ie, the same operator address:port
        /// number pair) which is a slight deviation from the socket formality in TCP/IP.
        /// - Any agent with a verified application contract may connect to this PSP22 contract
        /// without permission from this contract's owner.
        /// - See detailed struct below.
        ///
        /// sockets:         application contract address -> socket(app operator address : port)
        ///
        pub sockets: Mapping<AccountId, Socket>,

        /// - Expand storage related to the application/socket/port functionality.
        pub _reserved: Option<()>,
    }
    /// - Information pertaining to port definition in application/socket/port contract
    /// connectivity formalism.
    #[derive(scale::Encode, scale::Decode, Clone)]
    #[cfg_attr(
    feature = "std",
    derive(
        Debug,
        PartialEq,
        Eq,
        scale_info::TypeInfo,
        ink::storage::traits::StorageLayout
        )
    )]
    pub struct Port {

        // ABSOLUTELY DO NOT CHANGE THE ORDER OF THESE VARIABLES
        // OR TYPES IF UPGRADING THIS CONTRACT!!!

        /// - What is the codehash of the application smart contract associated with
        /// this port?
        /// - This codehash is the application template that numerous individual application 
        /// contracts may be instantiated and connected to this PSP22 contract via socket
        /// without signed permission from this ILOCK contract's owner.
        /// - This codehash is essential to making sure that only safe and approved application
        /// contracts are able to connect to this token contract and manipulate its owneronly
        /// functionalities (as defined per respective port protocol).
        pub application: Hash,

        /// - How much does Interlock tax transaction taking place within a port protocol's
        /// socket call?
        pub tax: Balance,

        /// - For withdrawing rewards from ILOCK rewards pool, what is the max this particular
        /// port owner's application type can withdraw from rewards pool?
        pub cap: Balance,

        /// - If locked, only Interlock token contract owner can create a socket connection with
        /// this token contract using the appropriate application codehash.
        pub locked: bool,

        /// - How much ILOCK has this port been rewarded or issued throughout the course of
        /// its operation (in case where protocol rewards or issues ILOCK, that is)?
        pub paid: Balance,

        /// - How much has Interlock collected from this port in taxes or other collections?
        pub collected: Balance,

        /// - Who is the overall owner of this port?
        /// - Socket operators are not necessarily owners of the port.
        /// - For example, a restaurant franchise has one owner, whereas the franchise may have
        /// numberous restaurant locations, each with it's own operator, each operator/franchise
        /// pair forming a separate socket connection.
        pub owner: AccountId,
    }
    /// - Ink 4 has no AccountId Default impl thus struct Default cannot be derived
    /// due to `owner` field.
    /// - Default derivation is required by openbrush contract implementation of
    /// contract storage.
    impl Default for Port {
        fn default() -> Port {
            Port {
                application: Default::default(),
                tax: 0,
                cap: 0,
                locked: true,
                paid: 0,
                collected: 0,
                owner: AccountId::from([1_u8; 32]),
            }
        }
    }
    /// - Information pertaining to socket definition in application/socket/port contract
    /// connectivity formalism.
    #[derive(scale::Encode, scale::Decode, Clone, Copy)]
    #[cfg_attr(
    feature = "std",
    derive(
        Debug,
        PartialEq,
        Eq,
        scale_info::TypeInfo,
        ink::storage::traits::StorageLayout
        )
    )]
    pub struct Socket {

        // ABSOLUTELY DO NOT CHANGE THE ORDER OF THESE VARIABLES
        // OR TYPES IF UPGRADING THIS CONTRACT!!!

        /// - Who operates (owns usually) a specific instance of a connecting application
        /// contract?
        /// - Using the restaurant franchise metaphor again, the operator may have several
        /// different instances of the port's application contract.
        /// - Each instance of the application contract has its own address, but each restaurant
        /// has the same operator.
        /// - The socket (operator:franchise or operator:port#) is like the single business franchise
        /// agreement between the restaurant operator and the franchise owner.
        /// - There is only one agreement between the franchise and the restaurant operator,
        /// regardless of how many restaurants the operator has.
        pub operator: AccountId,

        /// - What port is this operator connected to?
        /// - Using the restaurant franchise metaphor again, the port is like the franchise
        /// itself.
        /// - The port number is what identifies a particular franchise and its protocols,
        /// procedures, metadata, and ultimately business model and standards for any
        /// franchisees.
        pub portnumber: u16,
    }
    /// - Ink 4 has no AccountId Default impl thus struct Default cannot be derived
    /// due to `operator` field.
    impl Default for Socket {
        fn default() -> Socket {
            Socket {
                operator: AccountId::from([1_u8;32]),
                portnumber: 65535,
            }
        }
    }

    /// - This is upgradable storage for the multisig feature of this
    /// PSP22 contract (ie, the application/socket/port contract connectivity formalism).
    pub const MULTISIG_KEY: u32 = openbrush::storage_unique_key!(MultisigData);
    #[derive(Default, Debug)]
    #[openbrush::upgradeable_storage(MULTISIG_KEY)]
    pub struct MultisigData {

        // ABSOLUTELY DO NOT CHANGE THE ORDER OF THESE VARIABLES
        // OR TYPES IF UPGRADING THIS CONTRACT!!!

        /// - Stanging transaction
        pub tx: Transaction,

        /// - Vector of signatories.
        pub signatories: Vec<AccountID>,
        
        /// - Multisig threshold..
        pub threshold: u16,

        /// - Multisig time limit.
        pub timelimit: Timestamp,

        /// - Expand storage related to the multisig functionality.
        pub _reserved: Option<()>,
    }
    /// - TransactionData struct contains all pertinent information for multisigtx transaction
    #[derive(scale::Encode, scale::Decode, Clone, Default, Debug)]
    #[cfg_attr(
    feature = "std",
    derive(
        PartialEq,
        Eq,
        scale_info::TypeInfo,
        ink::storage::traits::StorageLayout,
        )
    )]
    pub struct Transaction {

        // ABSOLUTELY DO NOT CHANGE THE ORDER OF THESE VARIABLES
        // OR TYPES IF UPGRADING THIS CONTRACT!!!

        /// - Which signatory ordered the multisigtx tx?
        pub orderer: AccountID,

        /// - What signatures have been collected?
        pub signatures: Vec<Signature>,

        /// - Which multisigtx function is being called?
        pub function: u8,

        /// - What is the timestamp on current transaction?
        pub time: Timestamp,

        /// - Was transaction completed?
        pub complete: bool,
    }
    /// - TransactionData struct contains all pertinent information for multisigtx transaction
    #[derive(scale::Encode, scale::Decode, Clone, Copy, Default, Debug)]
    #[cfg_attr(
    feature = "std",
    derive(
        PartialEq,
        Eq,
        scale_info::TypeInfo,
        ink::storage::traits::StorageLayout,
        )
    )]
    pub struct Signature {

        // ABSOLUTELY DO NOT CHANGE THE ORDER OF THESE VARIABLES
        // OR TYPES IF UPGRADING THIS CONTRACT!!!

        /// - Who signed this signature?
        pub signer: AccountID,

        /// - What is the timestamp on current transaction?
        pub time: Timestamp,
    }



    /// - ILOCKmvp struct contains overall storage data for contract
    #[ink(storage)]
    #[derive(Default, Storage)]
    pub struct ILOCKmvp {

        // ABSOLUTELY DO NOT CHANGE THE ORDER OF THESE VARIABLES
        // OR TYPES IF UPGRADING THIS CONTRACT!!!

        /// - Openbrush PSP22.
        #[storage_field]
        pub psp22: psp22::Data,

        /// - Openbrush ownership extension.
        #[storage_field]
        pub ownable: ownable::Data,

        /// - Openbrush metadata extension.
        #[storage_field]
        pub metadata: metadata::Data,

        /// - Openbrush pausable extensios.
        #[storage_field]
		pub pausable: pausable::Data,

        /// - ILOCK Rewards info.
        #[storage_field]
        pub reward: RewardData,

        /// - ILOCK connecting application contract info.
        #[storage_field]
        pub app: AppData,

        /// - ILOCK multisig contract info.
        #[storage_field]
        pub multisig: MultisigData,

        /// - ILOCK token pool balances.
        pub rewards: Balance,
        pub circulating: Balance,
        pub proceeds: Balance,
    }

////////////////////////////////////////////////////////////////////////////
//// events and errors /////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

    /// - Specify transfer event.
    #[ink(event)]
    pub struct Transfer {
        #[ink(topic)]
        pub from: Option<AccountId>,
        #[ink(topic)]
        pub to: Option<AccountId>,
        pub amount: Balance,
    }

    /// - Specify approval event.
    #[ink(event)]
    pub struct Approval {
        #[ink(topic)]
        pub owner: Option<AccountId>,
        #[ink(topic)]
        pub spender: Option<AccountId>,
        pub amount: Balance,
    }

    /// - Specify reward event.
    #[ink(event)]
    pub struct Reward {
        #[ink(topic)]
        pub to: Option<AccountId>,
        pub amount: Balance,
    }

    /// - Other contract error types.
    #[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)]
    #[cfg_attr(
        feature = "std",
        derive(scale_info::TypeInfo)
    )]
    pub enum OtherError {
        /// - Returned if caller is not contract owner.
        CallerNotOwner,
        /// - Returned if stakeholder share is entirely paid out.
        StakeholderSharePaid,
        /// - Returned if the stakeholder doesn't exist.
        StakeholderNotFound,
        /// - Returned if stakeholder has not yet passed cliff.
        CliffNotPassed,
        /// - Returned if it is too soon to payout for month.
        PayoutTooEarly,
        /// - Returned if reward is too large.
        PaymentTooLarge,
        /// - Returned if socket does not exist.
        NoSocket,
        /// - Returned if port does not exist.
        NoPort,
        /// - Returned if not contract.
        NotContract,
        /// - Returned if only owner can add socket.
        PortLocked,
        /// - Returned if port cap is surpassed.
        PortCapSurpassed,
        /// - Returned if reward recipient is a contract.
        CannotRewardContract,
        /// - Returned if socket contract does not match registered hash.
        UnsafeContract,
        /// - Returned if application contract caller is not its operator.
        CallerNotOperator,
        /// - Returned if transfer caller is the owner.
        CallerIsOwner,
        /// - Returned if checked add overflows.
        Overflow,
        /// - Returned if checked sub underflows.
        Underflow,
        /// - Returned if checked divide errors out.
        DivError,
        /// - Returned if share is not greater than zero.
        ShareTooSmall,
        /// - Returned if pool number provided is invalid.
        InvalidPool,
        /// - Returned if port number provided is invalid.
        InvalidPort,
        /// - Returned if Stakeholder already registered with pool and no overwrite force.
        AlreadyRegistered,
        /// - Returned if Stakeholder has no stake in pool.
        NoPool,
        /// - Returned if no stake exists.
        NoStake,
        /// - Returned if zero address.
        IsZeroAddress,
        /// - Returned if pool argument is out of bounds.
        PoolOutOfBounds,
        /// - Returned if checked div by zero.
        DivideByZero,
        /// - Returned if port exists and no overwrite flag.
        PortExists,
        /// - Returned if port cap is larger than rewards pool.
        CapTooLarge,
        /// - Returned if multisigtx transaction does not exist for called function.
        NoTransaction,
        /// - Returned if multisigtx transaction was already completed.
        TransactionAlreadyCompleted,
        /// - Returned if multisigtx transaction was already and not being force reordered.
        TransactionAlreadyOrdered,
        /// - Returned if address does not have enough balance for port 1 self mint..
        InsufficientIlockBalance,
        /// - Returned multisigtx transactionalready ordered by signatory.
        AlreadyOrdered,
        /// - Returned if specified multisigtx function is invalid.
        InvalidFunction,
        /// - Returned if caller is not signatory.
        CallerNotSignatory,
        /// - Returned if caller is ordering a second transaction in a row.
        CannotReorder,
        /// - Returned if function spacified by signer does not match order.
        WrongFunction,
        /// - Returned if multisigtx is too old.
        TransactionStale,
        /// - Returned if there are not enough signatures to call function.
        NotEnoughSignatures,
        /// - Returned if signer already signed.
        AlreadySigned,
        /// - Returned if signatory to add is already in vector.
        AlreadySignatory,
        /// - Returned if new timelimit is under time minimum.
        UnderTimeMin,
        /// - Returned if new threshold is under threshold minimum..
        UnderThresholdMin,
        /// - Returned if too few signatories.
        TooFewSignatories,
        /// - Returned if signatory not present.
        NoSignatory,
        /// - Returned if contract constructor (owner) is listed as signatory.
        CallerIsSignatory,
        /// - Returned if contract constructor signatory arguments are identical.
        SignatoriesAreTheSame,
        /// - Returned if multisig transaction has already been called.
        TransactionAlreadyCalled,
        /// - Custom contract error.
        Custom(String),
    }

    /// - Convert from OtherError into PSP22Error.
    impl Into<PSP22Error> for OtherError {
        fn into(self) -> PSP22Error {
            PSP22Error::Custom(format!("{:?}", self).into_bytes())
        }
    }

    /// - Convert from PSP22Error into OtherError.
    impl Into<OtherError> for PSP22Error {
        fn into(self) -> OtherError {
            OtherError::Custom(format!("{:?}", self))
        }
    }

    /// - For ILOCKmvpRef used in PSP34 or application contracts.
    impl From<OwnableError> for OtherError {
        fn from(error: OwnableError) -> Self {
            OtherError::Custom(format!("{:?}", error))
        }
    }

    /// - For Pausable functions that are only_owner.
    impl From<PausableError> for OtherError {
        fn from(error: PausableError) -> Self {
            OtherError::Custom(format!("{:?}", error))
        }
    }

    /// - Convenience Result Type.
    pub type PSP22Result<T> = core::result::Result<T, PSP22Error>;

    /// - Convenience Result Type
    pub type OtherResult<T> = core::result::Result<T, OtherError>;

    /// - Needed for Openbrush internal event emission implementations.
    pub type Event = <ILOCKmvp as ContractEventBase>::Type;

////////////////////////////////////////////////////////////////////////////
/////// reimplement some functions /////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

    impl PSP22 for ILOCKmvp {
        
        /// - Override default total_supply getter.
        /// - Total supply reflects token in circulation.
        #[ink(message)]
        fn total_supply(&self) -> Balance {

            // revert, testing set code hash
            self.circulating
        }

        /// - Override default transfer doer.
        /// - Transfer from owner increases total circulating supply.
        /// - Transfer to owner decreases total circulating supply.
        #[ink(message)]
        #[openbrush::modifiers(when_not_paused)]
        fn transfer(
            &mut self,
            to: AccountId,
            value: Balance,
            data: Vec<u8>,
        ) -> PSP22Result<()> {

            let from = self.env().caller();

            // if sender is owner, deny
            if from == self.ownable.owner {
               return Err(OtherError::CallerIsOwner.into()); 
            }

            let _ = self._transfer_from_to(from, to, value, data)?;

            // if recipient is owner, then tokens are being returned or added to rewards pool
            if to == self.ownable.owner {

                match self.rewards.checked_add(value) {
                    Some(sum) => self.rewards = sum,
                    None => return Err(OtherError::Overflow.into()),
                };
                match self.circulating.checked_sub(value) {
                    Some(difference) => self.circulating = difference,
                    None => return Err(OtherError::Underflow.into()),
                };
            }

            Ok(())
        }

        /// - Override default transfer_from_to doer.
        /// - Transfer from owner increases total supply.
        #[ink(message)]
        #[openbrush::modifiers(when_not_paused)]
        fn transfer_from(
            &mut self,
            from: AccountId,
            to: AccountId,
            value: Balance,
            data: Vec<u8>,
        ) -> PSP22Result<()> {

            let caller = self.env().caller();
            let allowance = self._allowance(&from, &caller);

            if allowance < value {
                return Err(PSP22Error::InsufficientAllowance)
            }

            // if sender is owner, and from is owner (owner cannot distribute tokens using
            // transfer/transfer_from()
            if from == self.ownable.owner && caller == self.ownable.owner {
               return Err(OtherError::CallerIsOwner.into());
            }

            let _ = self._approve_from_to(from, caller, allowance - value)?;
            let _ = self._transfer_from_to(from, to, value, data)?;

            // if sender is owner, then tokens are entering circulation
            if from == self.ownable.owner {

                match self.circulating.checked_add(value) {
                    Some(sum) => self.circulating = sum,
                    None => return Err(OtherError::Overflow.into()),
                };
            }

            // if recipient is owner, then tokens are being returned or added to rewards pool
            if to == self.ownable.owner {

                match self.rewards.checked_add(value) {
                    Some(sum) => self.rewards = sum,
                    None => return Err(OtherError::Overflow.into()),
                };
                match self.circulating.checked_sub(value) {
                    Some(difference) => self.circulating = difference,
                    None => return Err(OtherError::Underflow.into()),
                };
            }

            Ok(())
        }

        /// - Wrap default approve doer to enforce pausable macro.
        #[ink(message)]
        #[openbrush::modifiers(when_not_paused)]
        fn approve(
            &mut self,
            spender: AccountId,
            value: Balance
        ) -> Result<(), PSP22Error> {

            let owner = self.env().caller();

            self._approve_from_to(owner, spender, value)
        }

        /// - Wrap default increase allowance doer to enforce pausable macro.
        #[ink(message)]
        #[openbrush::modifiers(when_not_paused)]
        fn increase_allowance(
            &mut self,
            spender: AccountId,
            delta_value: Balance
        ) -> Result<(), PSP22Error> {

            let owner = self.env().caller();
            let allowance = self._allowance(&owner, &spender);

            self._approve_from_to(owner, spender, allowance + delta_value)
        }

        /// - Wrap default decrease allowance doer to enforce pausable macro.
        #[ink(message)]
        #[openbrush::modifiers(when_not_paused)]
        fn decrease_allowance(
            &mut self,
            spender: AccountId,
            delta_value: Balance
        ) -> Result<(), PSP22Error> {

            let owner = self.env().caller();
            let allowance = self._allowance(&owner, &spender);

            if allowance < delta_value {
                return Err(PSP22Error::InsufficientAllowance)
            }

            self._approve_from_to(owner, spender, allowance - delta_value)
        }
    }

    impl PSP22Metadata for ILOCKmvp {}

    impl Pausable for ILOCKmvp {}

    impl Ownable for ILOCKmvp {
        
        /// - Nobody can transfer ownership..does nothing.
        /// - Transfer ownership implemented before update_contract() with multisigtx
        #[ink(message)]
        fn transfer_ownership(&mut self, _newowner: AccountId) -> Result<(), OwnableError> {

            // do nothing
            Ok(())
        }

        /// - Nobody can renounce ownership..does nothing.
        #[ink(message)]
        fn renounce_ownership(&mut self) -> Result<(), OwnableError> {

            // do nothing
            Ok(()) 
        }
    }

    impl Internal for ILOCKmvp {

        /// - Impliment Transfer emit event because Openbrush doesn't.
        fn _emit_transfer_event(
            &self,
            _from: Option<AccountId>,
            _to: Option<AccountId>,
            _amount: Balance,
        ) {
            ILOCKmvp::emit_event(
                self.env(),
                Event::Transfer(Transfer {
                    from: _from,
                    to: _to,
                    amount: _amount,
                }),
            );
        }

        /// - Impliment Approval emit event because Openbrush doesn't.
        fn _emit_approval_event(
            &self,
            _owner: AccountId,
            _spender: AccountId,
            _amount: Balance
        ) {
            ILOCKmvp::emit_event(
                self.env(),
                Event::Approval(Approval {
                    owner: Some(_owner),
                    spender: Some(_spender),
                    amount: _amount,
                }),
            );
        }
    }

    /// - This is for linking openbrush PSP34 or application contract.
    /// - This is necessary because a struct in PSP34 needs derive(Default)
    /// and the contract Ref has no derivable Default implementation.
    impl Default for ILOCKmvpRef {
        fn default() -> ILOCKmvpRef {
            ink::env::call::FromAccountId::from_account_id(AccountId::from([1_u8; 32]))
        }
    }

////////////////////////////////////////////////////////////////////////////
/////// implement token contract ///////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

    impl ILOCKmvp {

        /// - Function for internal _emit_event implementations.
        pub fn emit_event<EE: EmitEvent<Self>>(emitter: EE, event: Event) {
            emitter.emit_event(event);
        }

        /// - Constructor to initialize contract.
        #[ink(constructor)]
        pub fn new_token(
            timelimit: Timestamp,
            rewardmax: Balance,
            signatory_2: AccountId,
            signatory_3: AccountId,
        ) -> OtherResult<Self> {

            // create contract
            let mut contract = Self::default();
                
            // define owner as caller
            let caller = contract.env().caller();

            // PANICS NECESSARY FOR PASSING ERRORS PRE CONSTRUCTION (ie via dryrun)

            // owner cannot be double listed as signatory
            if caller == signatory_2 || caller == signatory_3 {

                panic!("CallerIsSignatory");
            }

            // cannot construct with both signantories the same
            if signatory_2 == signatory_3 {

                panic!("SignatoriesAreTheSame");
            }

            if timelimit < TIME_LIMIT_MIN {

                panic!("UnderTimeMin");
            }

            // define first three signatory
            let firstsignatory: AccountID = AccountID { address: caller };
            let secondsignatory: AccountID = AccountID { address: signatory_2 };
            let thirdsignatory: AccountID = AccountID { address: signatory_3 };

            // push first two signatories
            contract.multisig.signatories.push(firstsignatory);
            contract.multisig.signatories.push(secondsignatory);
            contract.multisig.signatories.push(thirdsignatory);

            // multisig defaults
            contract.multisig.timelimit = timelimit;
            contract.multisig.threshold = 2;

            // set initial data
            contract.reward.total = 0;

            contract.metadata.name = Some(TOKEN_NAME.to_string().into_bytes());
            contract.metadata.symbol = Some(TOKEN_SYMBOL.to_string().into_bytes());
            contract.metadata.decimals = TOKEN_DECIMALS;

            // mint with openbrush:
            contract._mint_to(caller, INITIAL_REWARDS)
                    .expect("Failed to mint the initial supply");
            contract._init_with_owner(caller);
            
            contract.rewards = INITIAL_REWARDS;
            contract.circulating = 0;
            contract.proceeds = 0;

            contract.reward.rewardmax = rewardmax;

            Ok(contract)
        }

////////////////////////////////////////////////////////////////////////////
/////// multisigtx /////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
//
// Workflow:
//
// 1) signatory orders multisig transaction via order_multisigtx()
//      ...this signatory's order is considered the first signature
// 2) other signatories sign multisig transaction via sign_multisigtx()
// 3) any signatory may check the number of signatures
// 4) when signature count threshold is met, then any signatory may call specified function
//
// - all signatories must agree on the function they are signing for (ie, the multisigtx ordered)
// - to prevent case where corrupted signatory exists, no signatory may order a multisigtx
//   consecutively. This is to prevent corrupted signatory from jamming up the multisig process
//

        /// - Helper function for checking signature count
        pub fn check_multisig(
            &mut self,
            function: String,
        ) -> OtherResult<()> {

            let caller: AccountID = AccountID { address: self.env().caller() };
            let thistime: Timestamp = self.env().block_timestamp();

            // make sure caller is designated multisigtx account
            if !self.multisig.signatories.contains(&caller) {

                return Err(OtherError::CallerNotSignatory);
            }

            // if enough signatures had not been supplied, revert
            if self.multisig.tx.signatures.len() < self.multisig.threshold as usize {

                return Err(OtherError::NotEnoughSignatures);
            }

            // if multisigtx is too old, then signature does not matter
            if thistime - self.multisig.tx.time >= self.multisig.timelimit {

                return Err(OtherError::TransactionStale);
            }

            // get function index
            let function: u8 = match function.as_str() {
                "TRANSFER_OWNERSHIP"    => TRANSFER_OWNERSHIP,
                "UNPAUSE"               => UNPAUSE,
                "CREATE_PORT"           => CREATE_PORT,
                "ADD_SIGNATORY"         => ADD_SIGNATORY,
                "REMOVE_SIGNATORY"      => REMOVE_SIGNATORY,
                "CHANGE_THRESHOLD"      => CHANGE_THRESHOLD,
                "CHANGE_TIMELIMIT"      => CHANGE_TIMELIMIT,
                "UPDATE_CONTRACT"       => UPDATE_CONTRACT,
                _ => return Err(OtherError::InvalidFunction),
            };

            // signer must know they are signing for the right function
            if function != self.multisig.tx.function {

                return Err(OtherError::WrongFunction);
            }

            // transaction must not have already been completed
            if self.multisig.tx.complete {

                return Err(OtherError::TransactionAlreadyCalled);
            }

            // making it this far means that function is ready to call
            // ...if called function fails, then tx will need to be reordered
            self.multisig.tx.complete = true;

            Ok(())
        }

        /// - Function to order multisigtx transaction.
        #[ink(message)]
        pub fn order_multisigtx(
            &mut self,
            function: String,
        ) -> OtherResult<()> {

            let caller: AccountID = AccountID { address: self.env().caller() };
            let thistime: Timestamp = self.env().block_timestamp();

            // make sure caller is designated multisigtx account
            if !self.multisig.signatories.contains(&caller) {

                return Err(OtherError::CallerNotSignatory);
            }

            // if the signing period has already begun, orderer
            if thistime - self.multisig.tx.time < self.multisig.timelimit &&
                !self.multisig.tx.complete {

                return Err(OtherError::TransactionAlreadyOrdered);
            }

            // this is important to prevent corrupted key from 'freezing out'
            // other signatories' ability to order transaction
            if caller == self.multisig.tx.orderer {

                return Err(OtherError::CannotReorder);
            }

            // get function index
            let function: u8 = match function.as_str() {
                "TRANSFER_OWNERSHIP"    => TRANSFER_OWNERSHIP,
                "UNPAUSE"               => UNPAUSE,
                "CREATE_PORT"           => CREATE_PORT,
                "ADD_SIGNATORY"         => ADD_SIGNATORY,
                "REMOVE_SIGNATORY"      => REMOVE_SIGNATORY,
                "CHANGE_THRESHOLD"      => CHANGE_THRESHOLD,
                "CHANGE_TIMELIMIT"      => CHANGE_TIMELIMIT,
                "UPDATE_CONTRACT"       => UPDATE_CONTRACT,
                _ => return Err(OtherError::InvalidFunction),
            };

            // set transaction function
            self.multisig.tx.function = function;

            // set transaction order time
            self.multisig.tx.time = thistime;

            // construct signature
            let signature: Signature = Signature {
                signer: caller,
                time: thistime,
            };

            // add first signature to multisigtx transaction order
            self.multisig.tx.signatures = Vec::new();
            self.multisig.tx.signatures.push(signature);

            // record orderer
            self.multisig.tx.orderer = caller;

            // reset completion flag
            self.multisig.tx.complete = false;

            Ok(())
        }

        /// - A multisigtx signer calls this to sign.
        #[ink(message)]
        pub fn sign_multisigtx(
            &mut self,
            function: String,
        ) -> OtherResult<()> {

            let caller: AccountID = AccountID { address: self.env().caller() };
            let thistime: Timestamp = self.env().block_timestamp();

            // make sure caller is designated multisigtx account
            if !self.multisig.signatories.contains(&caller) {

                return Err(OtherError::CallerNotSignatory);
            }

            // get function index
            let function: u8 = match function.as_str() {
                "TRANSFER_OWNERSHIP"    => TRANSFER_OWNERSHIP,
                "UNPAUSE"               => UNPAUSE,
                "CREATE_PORT"           => CREATE_PORT,
                "ADD_SIGNATORY"         => ADD_SIGNATORY,
                "REMOVE_SIGNATORY"      => REMOVE_SIGNATORY,
                "CHANGE_THRESHOLD"      => CHANGE_THRESHOLD,
                "CHANGE_TIMELIMIT"      => CHANGE_TIMELIMIT,
                "UPDATE_CONTRACT"       => UPDATE_CONTRACT,
                _ => return Err(OtherError::InvalidFunction),
            };


            // signer must know they are signing for the right function
            if function != self.multisig.tx.function {

                return Err(OtherError::WrongFunction);
            }

            // if multisigtx is too old, then signature does not matter
            if thistime - self.multisig.tx.time >= self.multisig.timelimit {

                return Err(OtherError::TransactionStale);
            }

            // make sure signatory has not already signed for the transaction
            if self.multisig.tx.signatures.iter().any(|sig| sig.signer == caller) {

                return Err(OtherError::AlreadySigned);
            }

            // construct signature
            let signature: Signature = Signature {
                signer: caller,
                time: thistime,
            };

            self.multisig.tx.signatures.push(signature);

            Ok(())
        }

        /// - This adds a signatory from the list of permitted signatories.
        #[ink(message)]
        pub fn add_signatory(
            &mut self,
            signatory:AccountId,
            function: String,
        ) -> OtherResult<()> {
    
            // verify multisig good
            let _ = self.check_multisig(function)?;

            // make sure signatory is not zero address
            if signatory == AccountId::from([0_u8; 32]) {
                return Err(OtherError::IsZeroAddress)
            }

            let signatory: AccountID = AccountID { address: signatory };

            // make sure caller is designated multisigtx account
            if self.multisig.signatories.contains(&signatory) {

                return Err(OtherError::AlreadySignatory);
            }

            self.multisig.signatories.push(signatory);

            Ok(())
        }

        /// - This removes a signatory from the list of permitted signatories.
        #[ink(message)]
        pub fn remove_signatory(
            &mut self,
            signatory: AccountId,
            function: String,
        ) -> OtherResult<()> {

            // check multisig tx
            let _ = self.check_multisig(function)?;

            // make sure signatory is not zero address
            if signatory == AccountId::from([0_u8; 32]) {
                return Err(OtherError::IsZeroAddress)
            }
    
            let signatory: AccountID = AccountID { address: signatory };

            // make sure signatory is designated multisigtx account
            if !self.multisig.signatories.contains(&signatory) {

                return Err(OtherError::NoSignatory);
            }

            // contract must maintain THRESHOLD + 1 signatories at all times
            let neededsignatories: u16 = match self.multisig.threshold.checked_add(1) {
                Some(sum) => sum,
                None => return Err(OtherError::Overflow),
            };

            // make sure there are enough signatories for new threshold
            if self.multisig.signatories.len() <= neededsignatories.into() {

                return Err(OtherError::TooFewSignatories);
            }

            self.multisig.signatories.retain(|&account| account != signatory);

            Ok(())
        }

        /// - This changes signer threshold for approving multisigtx.
        #[ink(message)]
        pub fn change_threshold(
            &mut self,
            threshold: u16,
            function: String,
        ) -> OtherResult<()> {
    
            // check multisig tx
            let _ = self.check_multisig(function)?;

            // make sure new threshold is greater then minimum
            if threshold < THRESHOLD_MIN {

                return Err(OtherError::UnderThresholdMin);
            }

            // contract must maintain THRESHOLD + 1 signatories at all times
            let neededsignatories: u16 = match threshold.checked_add(1) {
                Some(sum) => sum,
                None => return Err(OtherError::Overflow),
            };

            // make sure there are enough signatories for new threshold
            if self.multisig.signatories.len() < neededsignatories.into() {

                return Err(OtherError::TooFewSignatories);
            }

            self.multisig.threshold = threshold;

            Ok(())
        }

        /// - This modifies timelimit for a multisig transaction.
        #[ink(message)]
        pub fn change_multisigtxtimelimit(
            &mut self,
            timelimit: Timestamp,
            function: String,
        ) -> OtherResult<()> {
    
            // check multisig tx
            let _ = self.check_multisig(function)?;

            // make sure limit is respected
            if timelimit < TIME_LIMIT_MIN {

                return Err(OtherError::UnderTimeMin);
            }

            self.multisig.timelimit = timelimit;

            Ok(())
        }

        /// - This gets the current signature threshold for multisigtx.
        #[ink(message)]
        pub fn threshold(
            &self,
        ) -> u16 {

            self.multisig.threshold
        }

        /// - This gets the current timelimit for signatories to sign multisigtx.
        #[ink(message)]
        pub fn multisigtimelimit(
            &self,
        ) -> Timestamp {

            self.multisig.timelimit
        }

        /// - This gets a list of current accounts permitted to sign multisigtx.
        #[ink(message)]
        pub fn signatories(
            &mut self,
        ) -> OtherResult<Vec<AccountID>> {

            let caller: AccountID = AccountID { address: self.env().caller() };

            // make sure caller is designated multisigtx account
            if !self.multisig.signatories.contains(&caller) {

                return Err(OtherError::CallerNotSignatory);
            }
            
            Ok(self.multisig.signatories.iter().map(|sig| *sig ).collect())
        }

        /// - This gets number of signatories permitted to sign multisigtx.
        #[ink(message)]
        pub fn signatory_count(
            &self,
        ) -> u8 {

            self.multisig.signatories.len() as u8
        }

        /// - This gets current number of signatures for multisigtx.
        #[ink(message)]
        pub fn signature_count(
            &self,
        ) -> u8 {

            self.multisig.tx.signatures.len() as u8
        }

        /// - This gets a list of all signers so far on a multisigtx.
        #[ink(message)]
        pub fn check_signatures(
            &mut self,
        ) -> OtherResult<Vec<Signature>> {

            let thistime: Timestamp = self.env().block_timestamp();
            let caller: AccountID = AccountID { address: self.env().caller() };

            // make sure caller is designated multisigtx account
            if !self.multisig.signatories.contains(&caller) {

                return Err(OtherError::CallerNotSignatory);
            }

            // if multisigtx is too old, then it doesn't matter who signed
            if thistime - self.multisig.tx.time > self.multisig.timelimit {

                return Err(OtherError::TransactionStale);
            }

            Ok(self.multisig.tx.signatures.iter().map(|sig| *sig ).collect())
        }


////////////////////////////////////////////////////////////////////////////
/////// pausability ////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

        /// - Function pauses contract.
        /// - Any signatory may call.
        #[ink(message)]
        pub fn pause(
            &mut self,
        ) -> OtherResult<()> {

            let caller: AccountID = AccountID { address: self.env().caller() };

            // make sure caller is designated multisigtx account
            if !self.multisig.signatories.contains(&caller) {

                return Err(OtherError::CallerNotSignatory);
            }

            self._pause()
        }

        /// - Function unpauses contract.
        #[ink(message)]
        pub fn unpause(
            &mut self,
            function: String,
        ) -> OtherResult<()> {
    
            // check multisig tx
            let _ = self.check_multisig(function)?;

            self._unpause()
        }

////////////////////////////////////////////////////////////////////////////
//// rewarding  ////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

        /// - Reward the interlocker for browsing, etc.
        /// - This is a manual rewarding function, to override the socket formalism.
        #[ink(message)]
        #[openbrush::modifiers(only_owner)]
        #[openbrush::modifiers(when_not_paused)]
        pub fn reward_interlocker(
            &mut self,
            reward: Balance,
            interlocker: AccountId
        ) -> OtherResult<Balance> {

            // make sure interlocker is not zero address
            if interlocker == AccountId::from([0_u8; 32]) {
                return Err(OtherError::IsZeroAddress)
            }

            // make sure reward not too large
            if self.reward.rewardmax <= reward {
                return Err(OtherError::PaymentTooLarge)
            }

            // make sure rewardee is not contract
            if self.env().is_contract(&interlocker) {
                return Err(OtherError::CannotRewardContract)
            }

            // update rewards pool balance
            // (contract calls transfer, not owner, thus we must update here)
            match self.rewards.checked_sub(reward) {
                Some(difference) => self.rewards = difference,
                None => return Err(OtherError::PaymentTooLarge),
            };

            // increment reward to operator's account
            let mut interlockerbalance: Balance = self.psp22.balance_of(interlocker);
            match interlockerbalance.checked_add(reward) {
                Some(sum) => interlockerbalance = sum,
                None => return Err(OtherError::Overflow),
            };
            self.psp22.balances.insert(&interlocker, &interlockerbalance);

            // update total amount rewarded to interlocker
            match self.reward.total.checked_add(reward) {
                Some(sum) => self.reward.total = sum,
                None => return Err(OtherError::PaymentTooLarge),
            };

            // increment total supply
            match self.circulating.checked_add(reward) {
                Some(sum) => self.circulating = sum,
                None => return Err(OtherError::Overflow),
            };

            // deduct tokens from owners account
            let mut ownerbalance: Balance = self.psp22.balance_of(self.env().caller());
            match ownerbalance.checked_sub(reward) {
                Some(difference) => ownerbalance = difference,
                None => return Err(OtherError::Underflow),
            };
            self.psp22.balances.insert(&self.env().caller(), &ownerbalance);

            // compute and update new total awarded to interlocker
            let rewardedinterlockertotal: Balance = match self.reward.interlocker.get(interlocker) {
                Some(total) => total,
                None => 0,
            };
            let newrewardedtotal: Balance = match rewardedinterlockertotal.checked_add(reward) {
                Some(sum) => sum,
                None => return Err(OtherError::PaymentTooLarge),
            };
            self.reward.interlocker.insert(interlocker, &newrewardedtotal);

            // emit Reward event
            self.env().emit_event(Reward {
                to: Some(interlocker),
                amount: reward,
            });

            // this returns interlocker total reward amount for extension display purposes
            Ok(newrewardedtotal)
        }

        /// - Get amount rewarded to interlocker to date.
        #[ink(message)]
        pub fn rewarded_interlocker_total(
            &self,
            interlocker: AccountId
        ) -> OtherResult<Balance> {

            // make sure interlocker is not zero address
            if interlocker == AccountId::from([0_u8; 32]) {
                return Err(OtherError::IsZeroAddress)
            }

            let total_rewarded: Balance = match self.reward.interlocker.get(interlocker) {
                Some(total) => total,
                None => 0,
            };

            Ok(total_rewarded)
        }

        /// - Get total amount rewarded to date.
        #[ink(message)]
        pub fn rewarded_total(
            &self
        ) -> Balance {

            self.reward.total
        }

////////////////////////////////////////////////////////////////////////////
//// portability and extensibility  ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

        #[ink(message)]
        pub fn transfer_ownership(
            &mut self,
            newowner: AccountId,
            function: String,
        ) -> Result<(), OtherError> {
    
            // check multisig tx
            let _ = self.check_multisig(function)?;

            // make sure interlocker is not zero address
            if newowner == AccountId::from([0_u8; 32]) {

                return Err(OtherError::IsZeroAddress);
            }

            let oldowner = self.ownable.owner;

            let oldbalance: Balance = self.balance_of(oldowner);

            // transfer all remaining owner tokens (pools) to new owner
            let mut newbalance: Balance = self.psp22.balance_of(newowner);
            match newbalance.checked_add(oldbalance) {
                Some(sum) => newbalance = sum,
                None => (), // case not possible
            };
            self.psp22.balances.insert(&newowner, &newbalance);

            // deduct tokens from owners account
            self.psp22.balances.insert(&oldowner, &0);

            self.ownable.owner = newowner;

            // make new owner signatory if not already so
            let newsignatory: AccountID = AccountID { address: newowner };
            if !self.multisig.signatories.contains(&newsignatory) {
             
                self.multisig.signatories.push(newsignatory);
            }

            Ok(())
        }

        /// - Modifies the code which is used to execute calls to this contract address.
        /// - This upgrades the token contract logic while using old state.
        #[ink(message)]
        pub fn update_contract(
            &mut self,
            code_hash: [u8; 32],
            function: String, 
        ) -> OtherResult<()> {
    
            // check multisig tx
            let _ = self.check_multisig(function)?;

            // takes code hash of updates contract and modifies preexisting logic to match
            ink::env::set_code_hash(&code_hash).unwrap_or_else(|err| {
                panic!(
                    "Failed to `set_code_hash` to {:?} due to {:?}",
                    code_hash, err
                )
            });

            Ok(())
        }

        /// - Create a new port that application contract can register with.
        /// - Each port tracks amount rewarded, tax collected, if it is locked or not, owner.
        /// - A locked port may only be registered by the Interlock Network foundation.
        #[ink(message)]
        pub fn create_port(
            &mut self,
            codehash: Hash,
            tax: Balance,
            cap: Balance,
            locked: bool,
            number: u16,
            owner: AccountId,
            overwrite: bool,
            function: String,
        ) -> OtherResult<()> {
    
            // check multisig tx
            let _ = self.check_multisig(function)?;

            // guard to check if port exists and if intention is to overwrite
            // * note: bool value is false by default
            let _ = match self.app.ports.get(number) {
                Some(_port) => {
                    if !overwrite {
                        return Err(OtherError::PortExists);
                    }
                },
                None => (),
            };

            // guard to make sure cap is not greater than rewards on hand
            if cap > self.rewards {
                return Err(OtherError::CapTooLarge);
            }

            // make sure owner is not zero address
            if owner == AccountId::from([0_u8; 32]) {
                return Err(OtherError::IsZeroAddress)
            }

            let port = Port {
                application: codehash,     // <--! a port defines an external staking/reward contract plus any
                tax: tax,                  //      custom logic preceding the tax_and_reward() function
                cap: cap,
                locked: locked,
                paid: 0,
                collected: 0,
                owner: owner,
            };
            self.app.ports.insert(number, &port);

            Ok(())
        }

        /// - Rewards/staking/application contracts register with this token contract here.
        /// - Contract must first register with token contract as port to allow connection via
        /// socket (ie, a port must first exist before a socket may form)..
        #[ink(message)]
        #[openbrush::modifiers(when_not_paused)]
        pub fn create_socket(
            &mut self,
            operator: AccountId,
            portnumber: u16,
        ) -> OtherResult<()> {

            // get application contract address
            let application: AccountId = self.env().caller();

            // make sure operator is not zero address
            if operator == AccountId::from([0_u8; 32]) {
                return Err(OtherError::IsZeroAddress)
            }

            // make sure caller is a contract, return if not
            if !self.env().is_contract(&application) {
                return Err(OtherError::NotContract);
            };

            // get hash of calling application contract
            let callinghash: Hash = match self.env().code_hash(&application) {
                Ok(hash) => hash,
                Err(_) => return Err(OtherError::NotContract),
            };

            // get port specified by calling application contract
            let port: Port = match self.app.ports.get(portnumber) {
                Some(port) => port,
                None => return Err(OtherError::NoPort),
            };

            // make sure port is unlocked, or caller is token contract owner (interlock)
            //   . this makes it so that people can't build their own client application
            //     to 'hijack' an approved and registered rewards contract.
            //   . if port is locked then only interlock can create new socket with port
            //   . socket creation is only called by an external application contract that
            //     the port represents
            if port.locked && (self.ownable.owner != operator) {
                return Err(OtherError::PortLocked);
            }
            
            // compare calling contract hash to registered port hash
            // to make sure application contract is safe (ie, approved and audited by interlock)
            if callinghash == port.application {
                
                // if safe, contract is allowed to create socket (socket == operatoraddress:portnumber)
                let socket = Socket { operator: operator, portnumber: portnumber };

                // socket is registered with token contract thus the calling
                // contract that created the socket may start calling socket to receive rewards
                self.app.sockets.insert(application, &socket);
            
                // setup socket according to port type
                match portnumber {

                    // Interlock-owned UANFTs
                    0 => { /* do nothing */ },

                    // non-Interlock-owned UANFTs
                    1 => { /* do nothing */ },

                    // Interlock gray area staking applications
                    2 => {

                        // this is primarily to serve as a socket setup example
                        // ... for this particular case, port two is probably *locked*
                        //
                        // give socket allowance up to port cap
                        //   . connecting contracts will not be able to reward
                        //     more than cap specified by interlock (this may be a stipend, for example)
                        //   . rewards fail to transfer if the amount paid plus the reward exceeds cap
                        self.psp22.allowances.insert(
                            &(&self.ownable.owner, &application),
                            &port.cap
                        );

                        self._emit_approval_event(self.ownable.owner, application, port.cap);
                    },
                    _ => return Err(OtherError::InvalidPort),

                };

                return Ok(()) 
            }

            // returns error if calling staking application contract is not a known
            // safe contract registered by interlock as a 'port application' 
            Err(OtherError::UnsafeContract)
        }

        /// - Check for socket and apply custom logic after being called from application contract.
        /// - Application contract calls its socket to trigger internal logic defined by port.
        /// - Default parameters are address and amount or value.
        /// - Additional parameters may be encoded as _data: Vec<u8>.
        #[ink(message)]
        #[openbrush::modifiers(when_not_paused)]
        pub fn call_socket(
            &mut self,
            address: AccountId,
            amount: Balance,
            _data: Vec<u8>,
        ) -> OtherResult<()> {

            // get application contract's address
            let application: AccountId = self.env().caller();

            // make sure address is not zero address
            if address == AccountId::from([0_u8; 32]) {
                return Err(OtherError::IsZeroAddress)
            }

            // make sure caller is contract; only application contracts may call socket
            if !self.env().is_contract(&application) {
                return Err(OtherError::NotContract);
            }

            // get socket, to get port assiciated with socket
            let socket: Socket = match self.app.sockets.get(application) {
                Some(socket) => socket,
                None => return Err(OtherError::NoSocket),
            };

            // get port info
            let mut port: Port = match self.app.ports.get(socket.portnumber) {
                Some(port) => port,
                None => return Err(OtherError::NoPort),
            };

            // apply custom logic for given port
            match socket.portnumber {

                // NOTE: injecting custom logic into port requires Interlock Token
                //       contract codehash update after internal port contract audit
                
                // PORT 0 == Interlock-owned UANFTs
                //
                // This socket call is a UANFT self-mint operation with ILOCK proceeds returning to
                // rewards pool
                0 => { 

                    // verify address has enough tokens for uanft self mint
                    if self.balance_of(address) < amount {

                        return Err(OtherError::InsufficientIlockBalance);
                    }

                    // deduct cost of uanft from minter's account
                    let mut minterbalance: Balance = self.psp22.balance_of(address);
                    match minterbalance.checked_sub(amount) {
                        Some(difference) => minterbalance = difference,
                        None => return Err(OtherError::Underflow),
                    };
                    self.psp22.balances.insert(&address, &minterbalance);
                
                    // update pools
                    match self.rewards.checked_add(amount) {
                        Some(sum) => self.rewards = sum,
                        None => return Err(OtherError::Overflow),
                    };
                    match self.circulating.checked_sub(amount) {
                        Some(difference) => self.circulating = difference,
                        None => return Err(OtherError::Underflow),
                    };

                    // update port
                    match port.paid.checked_add(amount) {
                        Some(sum) => port.paid = sum,
                        None => return Err(OtherError::Overflow),
                    };
                    self.app.ports.insert(socket.portnumber, &port);
                },

                // PORT 1 == Non-Interlock-owned UANFTs
                //
                // This socket call is for a UANFT self-mint operation that is taxed by Interlock
                // but mint ILOCK proceeds go to socket operator instead of Interlock
                1 => {

                    // verify address has enough tokens for uanft self mint
                    if self.balance_of(address) < amount {

                        return Err(OtherError::InsufficientIlockBalance);
                    }

                    // deduct cost of uanft from minter's account
                    let mut minterbalance: Balance = self.psp22.balance_of(address);
                    match minterbalance.checked_sub(amount) {
                        Some(difference) => minterbalance = difference,
                        None => return Err(OtherError::Underflow),
                    };
                    self.psp22.balances.insert(&address, &minterbalance);

                    let adjustedamount: Balance = self.tax_port_transfer(socket, port, amount)?;

                    // increment cost of uanft to operator's account
                    let mut operatorbalance: Balance = self.psp22.balance_of(socket.operator);
                    match operatorbalance.checked_add(adjustedamount) {
                        Some(sum) => operatorbalance = sum,
                        None => return Err(OtherError::Overflow),
                    };
                    self.psp22.balances.insert(&socket.operator, &operatorbalance);
                    
                    // emit Transfer event, uanft transfer
                    self.env().emit_event(Transfer {
                        from: Some(address),
                        to: Some(socket.operator),
                        amount: adjustedamount,
                    });

                },

                // PORT 2 == reserved for Interlock gray-area staking applications
                //
                // reserved Interlock ports
                2 => { /* gray area staking rewards logic here */ },

                // .
                // .
                // .
                //

                // ... custom logic example:
                65535 => {

                    // < inject custom logic here BEFORE tax_and_reward >
                    // <    (ie, do stuff with port and socket data)    >
                },
                _ => return Err(OtherError::InvalidPort),
            };

            Ok(())
        }

        /// - Tax and reward transfer between socket calling address and socket operator.
        pub fn tax_port_transfer(
            &mut self,
            socket: Socket,
            mut port: Port,
            amount: Balance,
        ) -> OtherResult<Balance> {

            // compute tax - tax number is in centipercent, 0.01% ==> 100% = 1 & 1% = 100 & 0.01% = 10_000
            //
            // a tax of 0.01% is amount/10_000
            let tax: Balance = match amount.checked_div(port.tax as Balance) {
                Some(quotient) => quotient,
                None => return Err(OtherError::DivError),
            };

            // update proceeds pool and total circulation
            match self.proceeds.checked_add(tax) {
                Some(sum) => self.proceeds = sum,
                None => return Err(OtherError::Overflow),
            };
            match self.circulating.checked_sub(tax) {
                Some(difference) => self.circulating = difference,
                None => return Err(OtherError::Underflow),
            };

            // increment ILOCK contract owner's account balance
            let mut ownerbalance: Balance = self.psp22.balance_of(self.ownable.owner);
            match ownerbalance.checked_add(tax) {
                Some(sum) => ownerbalance = sum,
                None => return Err(OtherError::Overflow),
            };
            self.psp22.balances.insert(&self.ownable.owner, &ownerbalance);

            // update port (paid and collected) 
            match port.collected.checked_add(tax) {
                Some(sum) => port.collected = sum,
                None => return Err(OtherError::Overflow),
            };
            let adjustedamount: Balance = match amount.checked_sub(tax) {
                Some(difference) => difference,
                None => return Err(OtherError::Underflow),
            };
            match port.paid.checked_add(adjustedamount) {
                Some(sum) => port.paid = sum,
                None => return Err(OtherError::Overflow),
            };
            self.app.ports.insert(socket.portnumber, &port);
                    
            // emit Transfer event, operator to ILOCK proceeds pool
            self.env().emit_event(Transfer {
                from: Some(socket.operator), // we do not tax port owner,
                to: Some(self.ownable.owner),// rather we tax xfer itself in this case
                amount: tax,
            });

            // return adjusted amount
            Ok(amount - tax)
        }

        /// - Get socket info.
        #[ink(message)]
        pub fn socket(
            &self,
            application: AccountId,
        ) -> Socket {
            
            match self.app.sockets.get(application) {
                Some(socket) => socket,
                None => Default::default(),
            }
        }

        /// - Get port info.
        #[ink(message)]
        pub fn port(
            &self,
            portnumber: u16,
        ) -> Port {
            
            match self.app.ports.get(portnumber) {
                Some(port) => port,
                None => Default::default(),
            }
        }        

    } // END OF ILOCKmvp IMPL BLOCK
 }

#[cfg(all(test, feature = "e2e-tests"))]
pub mod tests_e2e;

#[cfg(test)]
pub mod tests_unit;

// TEST TODO
// in order of appearance
//
// [x] happyunit_total_supply                <-- checked within new_token()
// [x] happye2e_transfer             \
// [] sade2e_transfer                |
// [x] happye2e_transfer_from        |---- we test these because we change the default openbrush
// [] sade2e_transfer_from           /     implementations ... per agreement with Kudelski, we will
//                                         be assuming that openbrush is safe ... we may wish to perform
//                                         additional tests once audit is underway or/ in general future
// [x] happyunit_new_token (no sad, returns only Self)
// [!] happyunit_check_time                  <-- not possible to advance block, TEST ON TESTNET
// [!] sadunit_check_time                    <-- not possible to advance block, TEST ON TESTNET
// [!] happyunit_remaining_time              <-- not possible to advance block, TEST ON TESTNET
// [x] happyunit_stakeholder_data            <-- checked within distriut_tokens()
// [x] happye2e_distribute_tokens            <-- this is to check that the vesting schedule works...
// [x] happye2e_payout_tokens                 ...month passage is artificial here, without
// [] sade2e_payout_tokens                    advancing blocks.
// [x] happyunit_pool_data
// [x] happye2e_reward_interlocker
// [x] happyunit_rewarded_interlocker_total  <-- checked within reward_interlocker()
// [x] happyunit_rewarded_total              <-- checked within reward_interlocker()
// [x] happyunit_months_passed               <-- checked within new_token()
// [x] happyunit_cap                         <-- checked within new_token()
// [!] happyunit_update_contract             <-- TEST ON TESTNET
// [] sadunit_update_contract
// [x] happyunit_create_port
//      [x] happyunit_port                   <-- checked within create_port()
// [x] ** happye2e_create_socket     \
// [x] ** sade2e_create_socket       |----- these must be performed from generic port
// [x] ** happye2e_call_socket       |      or from the uanft contract's self minting message
// [x] ** sade2e_call_socket         /
// [x] happyunit_tax_port_transfer
// [] sadunit_tax_port_transfer
// [x] happyunit_check_time
//