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
/* This file is part of DarkFi (https://dark.fi)
 *
 * Copyright (C) 2020-2024 Dyne.org foundation
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

use std::{collections::HashMap, fmt};

use lazy_static::lazy_static;
use num_bigint::BigUint;
use rand::rngs::OsRng;
use rusqlite::types::Value;

use darkfi::{
    tx::{ContractCallLeaf, Transaction, TransactionBuilder},
    util::parse::{decode_base10, encode_base10},
    zk::{empty_witnesses, halo2::Field, ProvingKey, ZkCircuit},
    zkas::ZkBinary,
    Error, Result,
};
use darkfi_dao_contract::{
    blockwindow,
    client::{
        make_mint_call, DaoAuthMoneyTransferCall, DaoExecCall, DaoProposeCall,
        DaoProposeStakeInput, DaoVoteCall, DaoVoteInput,
    },
    model::{
        Dao, DaoAuthCall, DaoBulla, DaoExecParams, DaoMintParams, DaoProposal, DaoProposalBulla,
        DaoProposeParams, DaoVoteParams,
    },
    DaoFunction, DAO_CONTRACT_ZKAS_DAO_AUTH_MONEY_TRANSFER_ENC_COIN_NS,
    DAO_CONTRACT_ZKAS_DAO_AUTH_MONEY_TRANSFER_NS, DAO_CONTRACT_ZKAS_DAO_EXEC_NS,
    DAO_CONTRACT_ZKAS_DAO_MINT_NS, DAO_CONTRACT_ZKAS_DAO_PROPOSE_INPUT_NS,
    DAO_CONTRACT_ZKAS_DAO_PROPOSE_MAIN_NS, DAO_CONTRACT_ZKAS_DAO_VOTE_INPUT_NS,
    DAO_CONTRACT_ZKAS_DAO_VOTE_MAIN_NS,
};
use darkfi_money_contract::{
    client::transfer_v1::{select_coins, TransferCallBuilder, TransferCallInput},
    model::{CoinAttributes, Nullifier, TokenId},
    MoneyFunction, MONEY_CONTRACT_ZKAS_BURN_NS_V1, MONEY_CONTRACT_ZKAS_FEE_NS_V1,
    MONEY_CONTRACT_ZKAS_MINT_NS_V1,
};
use darkfi_sdk::{
    bridgetree,
    crypto::{
        poseidon_hash,
        smt::{MemoryStorageFp, PoseidonFp, SmtMemoryFp, EMPTY_NODES_FP},
        util::{fp_mod_fv, fp_to_u64},
        BaseBlind, Blind, FuncId, FuncRef, Keypair, MerkleNode, MerkleTree, PublicKey, ScalarBlind,
        SecretKey, DAO_CONTRACT_ID, MONEY_CONTRACT_ID,
    },
    dark_tree::DarkTree,
    pasta::pallas,
    tx::TransactionHash,
    ContractCall,
};
use darkfi_serial::{
    async_trait, deserialize_async, serialize_async, AsyncEncodable, SerialDecodable,
    SerialEncodable,
};

use crate::{
    convert_named_params,
    error::{WalletDbError, WalletDbResult},
    money::{BALANCE_BASE10_DECIMALS, MONEY_SMT_COL_KEY, MONEY_SMT_COL_VALUE, MONEY_SMT_TABLE},
    walletdb::{WalletSmt, WalletStorage},
    Drk,
};

// Wallet SQL table constant names. These have to represent the `wallet.sql`
// SQL schema. Table names are prefixed with the contract ID to avoid collisions.
lazy_static! {
    pub static ref DAO_DAOS_TABLE: String = format!("{}_dao_daos", DAO_CONTRACT_ID.to_string());
    pub static ref DAO_TREES_TABLE: String = format!("{}_dao_trees", DAO_CONTRACT_ID.to_string());
    pub static ref DAO_COINS_TABLE: String = format!("{}_dao_coins", DAO_CONTRACT_ID.to_string());
    pub static ref DAO_PROPOSALS_TABLE: String =
        format!("{}_dao_proposals", DAO_CONTRACT_ID.to_string());
    pub static ref DAO_VOTES_TABLE: String = format!("{}_dao_votes", DAO_CONTRACT_ID.to_string());
}

// DAO_DAOS_TABLE
pub const DAO_DAOS_COL_BULLA: &str = "bulla";
pub const DAO_DAOS_COL_NAME: &str = "name";
pub const DAO_DAOS_COL_PARAMS: &str = "params";
pub const DAO_DAOS_COL_LEAF_POSITION: &str = "leaf_position";
pub const DAO_DAOS_COL_TX_HASH: &str = "tx_hash";
pub const DAO_DAOS_COL_CALL_INDEX: &str = "call_index";

// DAO_TREES_TABLE
pub const DAO_TREES_COL_DAOS_TREE: &str = "daos_tree";
pub const DAO_TREES_COL_PROPOSALS_TREE: &str = "proposals_tree";

// DAO_PROPOSALS_TABLE
pub const DAO_PROPOSALS_COL_BULLA: &str = "bulla";
pub const DAO_PROPOSALS_COL_DAO_BULLA: &str = "dao_bulla";
pub const DAO_PROPOSALS_COL_PROPOSAL: &str = "proposal";
pub const DAO_PROPOSALS_COL_DATA: &str = "data";
pub const DAO_PROPOSALS_COL_LEAF_POSITION: &str = "leaf_position";
pub const DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE: &str = "money_snapshot_tree";
pub const DAO_PROPOSALS_COL_NULLIFIERS_SMT_SNAPSHOT: &str = "nullifiers_smt_snapshot";
pub const DAO_PROPOSALS_COL_TX_HASH: &str = "tx_hash";
pub const DAO_PROPOSALS_COL_CALL_INDEX: &str = "call_index";
pub const DAO_PROPOSALS_COL_EXEC_TX_HASH: &str = "exec_tx_hash";

// DAO_VOTES_TABLE
pub const DAO_VOTES_COL_PROPOSAL_BULLA: &str = "proposal_bulla";
pub const DAO_VOTES_COL_VOTE_OPTION: &str = "vote_option";
pub const DAO_VOTES_COL_YES_VOTE_BLIND: &str = "yes_vote_blind";
pub const DAO_VOTES_COL_ALL_VOTE_VALUE: &str = "all_vote_value";
pub const DAO_VOTES_COL_ALL_VOTE_BLIND: &str = "all_vote_blind";
pub const DAO_VOTES_COL_TX_HASH: &str = "tx_hash";
pub const DAO_VOTES_COL_CALL_INDEX: &str = "call_index";
pub const DAO_VOTES_COL_NULLIFIERS: &str = "nullifiers";

#[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
/// Parameters representing a DAO to be initialized
pub struct DaoParams {
    /// The on chain representation of the DAO
    pub dao: Dao,
    /// Secret key for the DAO
    pub secret_key: SecretKey,
}

impl DaoParams {
    pub fn new(
        proposer_limit: u64,
        quorum: u64,
        approval_ratio_base: u64,
        approval_ratio_quot: u64,
        gov_token_id: TokenId,
        secret_key: SecretKey,
        bulla_blind: BaseBlind,
    ) -> Self {
        let dao = Dao {
            proposer_limit,
            quorum,
            approval_ratio_base,
            approval_ratio_quot,
            gov_token_id,
            public_key: PublicKey::from_secret(secret_key),
            bulla_blind,
        };
        Self { dao, secret_key }
    }
}

impl fmt::Display for DaoParams {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let s = format!(
            "{}\n{}\n{}: {} ({})\n{}: {} ({})\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {:?}",
            "DAO Parameters",
            "==============",
            "Proposer limit",
            encode_base10(self.dao.proposer_limit, BALANCE_BASE10_DECIMALS),
            self.dao.proposer_limit,
            "Quorum",
            encode_base10(self.dao.quorum, BALANCE_BASE10_DECIMALS),
            self.dao.quorum,
            "Approval ratio",
            self.dao.approval_ratio_quot as f64 / self.dao.approval_ratio_base as f64,
            "Governance Token ID",
            self.dao.gov_token_id,
            "Public key",
            self.dao.public_key,
            "Secret key",
            self.secret_key,
            "Bulla blind",
            self.dao.bulla_blind,
        );

        write!(f, "{}", s)
    }
}

#[derive(Debug, Clone)]
/// Structure representing a `DAO_DAOS_TABLE` record.
pub struct DaoRecord {
    /// Name identifier for the DAO
    pub name: String,
    /// DAO parameters
    pub params: DaoParams,
    /// Leaf position of the DAO in the Merkle tree of DAOs
    pub leaf_position: Option<bridgetree::Position>,
    /// The transaction hash where the DAO was deployed
    pub tx_hash: Option<TransactionHash>,
    /// The call index in the transaction where the DAO was deployed
    pub call_index: Option<u8>,
}

impl DaoRecord {
    pub fn new(
        name: String,
        params: DaoParams,
        leaf_position: Option<bridgetree::Position>,
        tx_hash: Option<TransactionHash>,
        call_index: Option<u8>,
    ) -> Self {
        Self { name, params, leaf_position, tx_hash, call_index }
    }

    pub fn bulla(&self) -> DaoBulla {
        self.params.dao.to_bulla()
    }

    pub fn keypair(&self) -> Keypair {
        let public = PublicKey::from_secret(self.params.secret_key);
        Keypair { public, secret: self.params.secret_key }
    }
}

impl fmt::Display for DaoRecord {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let leaf_position = match self.leaf_position {
            Some(p) => format!("{p:?}"),
            None => "None".to_string(),
        };
        let tx_hash = match self.tx_hash {
            Some(t) => format!("{t}"),
            None => "None".to_string(),
        };
        let call_index = match self.call_index {
            Some(c) => format!("{c}"),
            None => "None".to_string(),
        };
        let s = format!(
            "{}\n{}\n{}: {}\n{}: {}\n{}: {} ({})\n{}: {} ({})\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}",
            "DAO Parameters",
            "==============",
            "Name",
            self.name,
            "Bulla",
            self.bulla(),
            "Proposer limit",
            encode_base10(self.params.dao.proposer_limit, BALANCE_BASE10_DECIMALS),
            self.params.dao.proposer_limit,
            "Quorum",
            encode_base10(self.params.dao.quorum, BALANCE_BASE10_DECIMALS),
            self.params.dao.quorum,
            "Approval ratio",
            self.params.dao.approval_ratio_quot as f64 / self.params.dao.approval_ratio_base as f64,
            "Governance Token ID",
            self.params.dao.gov_token_id,
            "Public key",
            self.params.dao.public_key,
            "Secret key",
            self.params.secret_key,
            "Bulla blind",
            self.params.dao.bulla_blind,
            "Leaf position",
            leaf_position,
            "Transaction hash",
            tx_hash,
            "Call index",
            call_index,
        );

        write!(f, "{}", s)
    }
}

#[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
/// Structure representing a `DAO_PROPOSALS_TABLE` record.
pub struct ProposalRecord {
    /// The on chain representation of the proposal
    pub proposal: DaoProposal,
    /// Plaintext proposal call data the members share between them
    pub data: Option<Vec<u8>>,
    /// Leaf position of the proposal in the Merkle tree of proposals
    pub leaf_position: Option<bridgetree::Position>,
    /// Money merkle tree snapshot for reproducing the snapshot Merkle root
    pub money_snapshot_tree: Option<MerkleTree>,
    /// Money nullifiers SMT snapshot for reproducing the snapshot Merkle root
    pub nullifiers_smt_snapshot: Option<HashMap<BigUint, pallas::Base>>,
    /// The transaction hash where the proposal was deployed
    pub tx_hash: Option<TransactionHash>,
    /// The call index in the transaction where the proposal was deployed
    pub call_index: Option<u8>,
    /// The transaction hash where the proposal was executed
    pub exec_tx_hash: Option<TransactionHash>,
}

impl ProposalRecord {
    pub fn bulla(&self) -> DaoProposalBulla {
        self.proposal.to_bulla()
    }
}

impl fmt::Display for ProposalRecord {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let leaf_position = match self.leaf_position {
            Some(p) => format!("{p:?}"),
            None => "None".to_string(),
        };
        let tx_hash = match self.tx_hash {
            Some(t) => format!("{t}"),
            None => "None".to_string(),
        };
        let call_index = match self.call_index {
            Some(c) => format!("{c}"),
            None => "None".to_string(),
        };

        let s = format!(
            "{}\n{}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {} ({})",
            "Proposal parameters",
            "===================",
            "Bulla",
            self.bulla(),
            "DAO Bulla",
            self.proposal.dao_bulla,
            "Proposal leaf position",
            leaf_position,
            "Proposal transaction hash",
            tx_hash,
            "Proposal call index",
            call_index,
            "Creation block window",
            self.proposal.creation_blockwindow,
            "Duration",
            self.proposal.duration_blockwindows,
            "Block windows"
        );

        write!(f, "{}", s)
    }
}

#[derive(Debug, Clone)]
/// Structure representing a `DAO_VOTES_TABLE` record.
pub struct VoteRecord {
    /// Numeric identifier for the vote
    pub id: u64,
    /// Bulla identifier of the proposal this vote is for
    pub proposal: DaoProposalBulla,
    /// The vote
    pub vote_option: bool,
    /// Blinding factor for the yes vote
    pub yes_vote_blind: ScalarBlind,
    /// Value of all votes
    pub all_vote_value: u64,
    /// Blinding facfor of all votes
    pub all_vote_blind: ScalarBlind,
    /// Transaction hash where this vote was casted
    pub tx_hash: TransactionHash,
    /// Call index in the transaction where this vote was casted
    pub call_index: u8,
    /// Vote input nullifiers
    pub nullifiers: Vec<Nullifier>,
}

impl Drk {
    /// Initialize wallet with tables for the DAO contract.
    pub async fn initialize_dao(&self) -> WalletDbResult<()> {
        // Initialize DAO wallet schema
        let wallet_schema = include_str!("../dao.sql");
        self.wallet.exec_batch_sql(wallet_schema)?;

        // Check if we have to initialize the Merkle trees.
        // We check if one exists, but we actually create two. This should be written
        // a bit better and safer.
        // For now, on success, we don't care what's returned, but in the future
        // we should actually check it.
        if self.wallet.query_single(&DAO_TREES_TABLE, &[DAO_TREES_COL_DAOS_TREE], &[]).is_err() {
            println!("Initializing DAO Merkle trees");
            let tree = MerkleTree::new(1);
            self.put_dao_trees(&tree, &tree).await?;
            println!("Successfully initialized Merkle trees for the DAO contract");
        }

        Ok(())
    }

    /// Replace the DAO Merkle trees in the wallet.
    pub async fn put_dao_trees(
        &self,
        daos_tree: &MerkleTree,
        proposals_tree: &MerkleTree,
    ) -> WalletDbResult<()> {
        // First we remove old records
        let query = format!("DELETE FROM {};", *DAO_TREES_TABLE);
        self.wallet.exec_sql(&query, &[])?;

        // then we insert the new one
        let query = format!(
            "INSERT INTO {} ({}, {}) VALUES (?1, ?2);",
            *DAO_TREES_TABLE, DAO_TREES_COL_DAOS_TREE, DAO_TREES_COL_PROPOSALS_TREE,
        );
        self.wallet.exec_sql(
            &query,
            rusqlite::params![
                serialize_async(daos_tree).await,
                serialize_async(proposals_tree).await
            ],
        )
    }

    /// Fetch DAO Merkle trees from the wallet.
    pub async fn get_dao_trees(&self) -> Result<(MerkleTree, MerkleTree)> {
        let row = match self.wallet.query_single(&DAO_TREES_TABLE, &[], &[]) {
            Ok(r) => r,
            Err(e) => {
                return Err(Error::RusqliteError(format!(
                    "[get_dao_trees] Trees retrieval failed: {e:?}"
                )))
            }
        };

        let Value::Blob(ref daos_tree_bytes) = row[0] else {
            return Err(Error::ParseFailed("[get_dao_trees] DAO tree bytes parsing failed"))
        };
        let daos_tree = deserialize_async(daos_tree_bytes).await?;

        let Value::Blob(ref proposals_tree_bytes) = row[1] else {
            return Err(Error::ParseFailed("[get_dao_trees] Proposals tree bytes parsing failed"))
        };
        let proposals_tree = deserialize_async(proposals_tree_bytes).await?;

        Ok((daos_tree, proposals_tree))
    }

    /// Fetch all DAO secret keys from the wallet.
    pub async fn get_dao_secrets(&self) -> Result<Vec<SecretKey>> {
        let daos = self.get_daos().await?;
        let mut ret = Vec::with_capacity(daos.len());
        for dao in daos {
            ret.push(dao.params.secret_key);
        }

        Ok(ret)
    }

    /// Auxiliary function to parse a `DAO_DAOS_TABLE` record.
    async fn parse_dao_record(&self, row: &[Value]) -> Result<DaoRecord> {
        let Value::Text(ref name) = row[1] else {
            return Err(Error::ParseFailed("[parse_dao_record] Name parsing failed"))
        };
        let name = name.clone();

        let Value::Blob(ref params_bytes) = row[2] else {
            return Err(Error::ParseFailed("[parse_dao_record] Params bytes parsing failed"))
        };
        let params = deserialize_async(params_bytes).await?;

        let leaf_position = match row[3] {
            Value::Blob(ref leaf_position_bytes) => {
                Some(deserialize_async(leaf_position_bytes).await?)
            }
            Value::Null => None,
            _ => {
                return Err(Error::ParseFailed(
                    "[parse_dao_record] Leaf position bytes parsing failed",
                ))
            }
        };

        let tx_hash = match row[4] {
            Value::Blob(ref tx_hash_bytes) => Some(deserialize_async(tx_hash_bytes).await?),
            Value::Null => None,
            _ => {
                return Err(Error::ParseFailed(
                    "[parse_dao_record] Transaction hash bytes parsing failed",
                ))
            }
        };

        let call_index = match row[5] {
            Value::Integer(call_index) => {
                let Ok(call_index) = u8::try_from(call_index) else {
                    return Err(Error::ParseFailed("[parse_dao_record] Call index parsing failed"))
                };
                Some(call_index)
            }
            Value::Null => None,
            _ => return Err(Error::ParseFailed("[parse_dao_record] Call index parsing failed")),
        };

        let dao = DaoRecord::new(name, params, leaf_position, tx_hash, call_index);

        Ok(dao)
    }

    /// Fetch all known DAOs from the wallet.
    pub async fn get_daos(&self) -> Result<Vec<DaoRecord>> {
        let rows = match self.wallet.query_multiple(&DAO_DAOS_TABLE, &[], &[]) {
            Ok(r) => r,
            Err(e) => {
                return Err(Error::RusqliteError(format!("[get_daos] DAOs retrieval failed: {e:?}")))
            }
        };

        let mut daos = Vec::with_capacity(rows.len());
        for row in rows {
            daos.push(self.parse_dao_record(&row).await?);
        }

        Ok(daos)
    }

    /// Auxiliary function to parse a proposal record row.
    async fn parse_dao_proposal(&self, row: &[Value]) -> Result<ProposalRecord> {
        let Value::Blob(ref proposal_bytes) = row[2] else {
            return Err(Error::ParseFailed(
                "[get_dao_proposals] Proposal bytes bytes parsing failed",
            ))
        };
        let proposal = deserialize_async(proposal_bytes).await?;

        let data = match row[3] {
            Value::Blob(ref data_bytes) => Some(data_bytes.clone()),
            Value::Null => None,
            _ => return Err(Error::ParseFailed("[get_dao_proposals] Data bytes parsing failed")),
        };

        let leaf_position = match row[4] {
            Value::Blob(ref leaf_position_bytes) => {
                Some(deserialize_async(leaf_position_bytes).await?)
            }
            Value::Null => None,
            _ => {
                return Err(Error::ParseFailed(
                    "[get_dao_proposals] Leaf position bytes parsing failed",
                ))
            }
        };

        let money_snapshot_tree = match row[5] {
            Value::Blob(ref money_snapshot_tree_bytes) => {
                Some(deserialize_async(money_snapshot_tree_bytes).await?)
            }
            Value::Null => None,
            _ => {
                return Err(Error::ParseFailed(
                    "[get_dao_proposals] Money snapshot tree bytes parsing failed",
                ))
            }
        };

        let nullifiers_smt_snapshot = match row[6] {
            Value::Blob(ref nullifiers_smt_snapshot_bytes) => {
                Some(deserialize_async(nullifiers_smt_snapshot_bytes).await?)
            }
            Value::Null => None,
            _ => {
                return Err(Error::ParseFailed(
                    "[get_dao_proposals] Nullifiers SMT snapshot bytes parsing failed",
                ))
            }
        };

        let tx_hash = match row[7] {
            Value::Blob(ref tx_hash_bytes) => Some(deserialize_async(tx_hash_bytes).await?),
            Value::Null => None,
            _ => {
                return Err(Error::ParseFailed(
                    "[get_dao_proposals] Transaction hash bytes parsing failed",
                ))
            }
        };

        let call_index = match row[8] {
            Value::Integer(call_index) => {
                let Ok(call_index) = u8::try_from(call_index) else {
                    return Err(Error::ParseFailed("[get_dao_proposals] Call index parsing failed"))
                };
                Some(call_index)
            }
            Value::Null => None,
            _ => return Err(Error::ParseFailed("[get_dao_proposals] Call index parsing failed")),
        };

        let exec_tx_hash = match row[9] {
            Value::Blob(ref exec_tx_hash_bytes) => {
                Some(deserialize_async(exec_tx_hash_bytes).await?)
            }
            Value::Null => None,
            _ => {
                return Err(Error::ParseFailed(
                    "[get_dao_proposals] Execution transaction hash bytes parsing failed",
                ))
            }
        };

        Ok(ProposalRecord {
            proposal,
            data,
            leaf_position,
            money_snapshot_tree,
            nullifiers_smt_snapshot,
            tx_hash,
            call_index,
            exec_tx_hash,
        })
    }

    /// Fetch all known DAO proposals from the wallet given a DAO name.
    pub async fn get_dao_proposals(&self, name: &str) -> Result<Vec<ProposalRecord>> {
        let Ok(dao) = self.get_dao_by_name(name).await else {
            return Err(Error::RusqliteError(format!(
                "[get_dao_proposals] DAO with name {name} not found in wallet"
            )))
        };

        let rows = match self.wallet.query_multiple(
            &DAO_PROPOSALS_TABLE,
            &[],
            convert_named_params! {(DAO_PROPOSALS_COL_DAO_BULLA, serialize_async(&dao.bulla()).await)},
        ) {
            Ok(r) => r,
            Err(e) => {
                return Err(Error::RusqliteError(format!(
                    "[get_dao_proposals] Proposals retrieval failed: {e:?}"
                )))
            }
        };

        let mut proposals = Vec::with_capacity(rows.len());
        for row in rows {
            let proposal = self.parse_dao_proposal(&row).await?;
            proposals.push(proposal);
        }

        Ok(proposals)
    }

    // Auxiliary function to apply `DaoFunction::Mint` call data to the wallet.
    async fn apply_dao_mint_data(
        &self,
        new_bulla: DaoBulla,
        tx_hash: TransactionHash,
        call_index: u8,
    ) -> Result<()> {
        let daos = self.get_daos().await?;
        let (mut daos_tree, proposals_tree) = self.get_dao_trees().await?;
        daos_tree.append(MerkleNode::from(new_bulla.inner()));
        for dao in &daos {
            if dao.bulla() == new_bulla {
                println!(
                    "[apply_dao_mint_data] Found minted DAO {}, noting down for wallet update",
                    new_bulla
                );

                // We have this DAO imported in our wallet. Add the metadata:
                let mut dao_to_confirm = dao.clone();
                dao_to_confirm.leaf_position = daos_tree.mark();
                dao_to_confirm.tx_hash = Some(tx_hash);
                dao_to_confirm.call_index = Some(call_index);

                // Update wallet data
                if let Err(e) = self.put_dao_trees(&daos_tree, &proposals_tree).await {
                    return Err(Error::RusqliteError(format!(
                        "[apply_dao_mint_data] Put DAO tree failed: {e:?}"
                    )))
                }
                if let Err(e) = self.confirm_dao(&dao_to_confirm).await {
                    return Err(Error::RusqliteError(format!(
                        "[apply_dao_mint_data] Confirm DAO failed: {e:?}"
                    )))
                }

                break
            }
        }

        Ok(())
    }

    // Auxiliary function to apply `DaoFunction::Propose` call data to the wallet.
    async fn apply_dao_propose_data(
        &self,
        params: DaoProposeParams,
        tx_hash: TransactionHash,
        call_index: u8,
    ) -> Result<()> {
        let daos = self.get_daos().await?;
        let (daos_tree, mut proposals_tree) = self.get_dao_trees().await?;
        proposals_tree.append(MerkleNode::from(params.proposal_bulla.inner()));

        // If we're able to decrypt this note, that's the way to link it
        // to a specific DAO.
        for dao in &daos {
            if let Ok(note) = params.note.decrypt::<DaoProposal>(&dao.params.secret_key) {
                // We managed to decrypt it. Let's place this in a proper ProposalRecord object
                println!("[apply_dao_propose_data] Managed to decrypt DAO proposal note");

                // We need to clone the trees here for reproducing the snapshot Merkle roots
                let money_tree = self.get_money_tree().await?;
                let nullifiers_smt = self.get_nullifiers_smt().await?;

                // Check if we already got the record
                let our_proposal =
                    match self.get_dao_proposal_by_bulla(&params.proposal_bulla).await {
                        Ok(p) => {
                            let mut our_proposal = p;
                            our_proposal.leaf_position = proposals_tree.mark();
                            our_proposal.money_snapshot_tree = Some(money_tree);
                            our_proposal.nullifiers_smt_snapshot = Some(nullifiers_smt);
                            our_proposal.tx_hash = Some(tx_hash);
                            our_proposal.call_index = Some(call_index);
                            our_proposal
                        }
                        Err(_) => ProposalRecord {
                            proposal: note,
                            data: None,
                            leaf_position: proposals_tree.mark(),
                            money_snapshot_tree: Some(money_tree),
                            nullifiers_smt_snapshot: Some(nullifiers_smt),
                            tx_hash: Some(tx_hash),
                            call_index: Some(call_index),
                            exec_tx_hash: None,
                        },
                    };

                if let Err(e) = self.put_dao_trees(&daos_tree, &proposals_tree).await {
                    return Err(Error::RusqliteError(format!(
                        "[apply_dao_propose_data] Put DAO tree failed: {e:?}"
                    )))
                }
                if let Err(e) = self.put_dao_proposal(&our_proposal).await {
                    return Err(Error::RusqliteError(format!(
                        "[apply_dao_propose_data] Put DAO proposals failed: {e:?}"
                    )))
                }

                break
            }
        }

        Ok(())
    }

    // Auxiliary function to apply `DaoFunction::Vote` call data to the wallet.
    async fn apply_dao_vote_data(
        &self,
        params: DaoVoteParams,
        tx_hash: TransactionHash,
        call_index: u8,
    ) -> Result<()> {
        // Check if we got the corresponding proposal
        let Ok(proposal) = self.get_dao_proposal_by_bulla(&params.proposal_bulla).await else {
            return Ok(())
        };

        // Grab the proposal DAO
        let dao = match self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
            Ok(d) => d,
            Err(e) => {
                return Err(Error::RusqliteError(format!(
                    "[apply_dao_vote_data] Couldn't find proposal {} DAO {}: {e}",
                    proposal.bulla(),
                    proposal.proposal.dao_bulla,
                )))
            }
        };

        // Decrypt the vote note
        let note = match params.note.decrypt_unsafe(&dao.params.secret_key) {
            Ok(n) => n,
            Err(e) => {
                return Err(Error::RusqliteError(format!(
                    "[apply_dao_vote_data] Couldn't decrypt proposal {} vote with DAO {} keys: {e}",
                    proposal.bulla(),
                    proposal.proposal.dao_bulla,
                )))
            }
        };

        // Create the DAO vote record
        let vote_option = fp_to_u64(note[0]).unwrap();
        if vote_option > 1 {
            return Err(Error::RusqliteError(format!(
                "[apply_dao_vote_data] Malformed vote for proposal {}: {vote_option}",
                proposal.bulla(),
            )))
        }
        let vote_option = vote_option != 0;
        let yes_vote_blind = Blind(fp_mod_fv(note[1]));
        let all_vote_value = fp_to_u64(note[2]).unwrap();
        let all_vote_blind = Blind(fp_mod_fv(note[3]));

        let v = VoteRecord {
            id: 0, // This will be set by SQLite AUTOINCREMENT
            proposal: params.proposal_bulla,
            vote_option,
            yes_vote_blind,
            all_vote_value,
            all_vote_blind,
            tx_hash,
            call_index,
            nullifiers: params.inputs.iter().map(|i| i.vote_nullifier).collect(),
        };

        if let Err(e) = self.put_dao_vote(&v).await {
            return Err(Error::RusqliteError(format!(
                "[apply_dao_vote_data] Put DAO votes failed: {e:?}"
            )))
        }

        Ok(())
    }

    // Auxiliary function to apply `DaoFunction::Exec` call data to the wallet.
    async fn apply_dao_exec_data(
        &self,
        params: DaoExecParams,
        tx_hash: TransactionHash,
    ) -> Result<()> {
        // Check if we got the corresponding proposal
        let Ok(mut proposal) = self.get_dao_proposal_by_bulla(&params.proposal_bulla).await else {
            return Ok(())
        };

        // Update its exec transaction hash
        proposal.exec_tx_hash = Some(tx_hash);
        if let Err(e) = self.put_dao_proposal(&proposal).await {
            return Err(Error::RusqliteError(format!(
                "[apply_dao_exec_data] Put DAO proposal failed: {e:?}"
            )))
        }

        Ok(())
    }

    /// Append data related to DAO contract transactions into the wallet database.
    pub async fn apply_tx_dao_data(
        &self,
        data: &[u8],
        tx_hash: TransactionHash,
        call_idx: u8,
    ) -> Result<()> {
        // Run through the transaction call data and see what we got:
        match DaoFunction::try_from(data[0])? {
            DaoFunction::Mint => {
                println!("[apply_tx_dao_data] Found Dao::Mint call");
                let params: DaoMintParams = deserialize_async(&data[1..]).await?;
                self.apply_dao_mint_data(params.dao_bulla, tx_hash, call_idx).await
            }
            DaoFunction::Propose => {
                println!("[apply_tx_dao_data] Found Dao::Propose call");
                let params: DaoProposeParams = deserialize_async(&data[1..]).await?;
                self.apply_dao_propose_data(params, tx_hash, call_idx).await
            }
            DaoFunction::Vote => {
                println!("[apply_tx_dao_data] Found Dao::Vote call");
                let params: DaoVoteParams = deserialize_async(&data[1..]).await?;
                self.apply_dao_vote_data(params, tx_hash, call_idx).await
            }
            DaoFunction::Exec => {
                println!("[apply_tx_dao_data] Found Dao::Exec call");
                let params: DaoExecParams = deserialize_async(&data[1..]).await?;
                self.apply_dao_exec_data(params, tx_hash).await
            }
            DaoFunction::AuthMoneyTransfer => {
                println!("[apply_tx_dao_data] Found Dao::AuthMoneyTransfer call");
                // Does nothing, just verifies the other calls are correct
                Ok(())
            }
        }
    }

    /// Confirm already imported DAO metadata into the wallet.
    /// Here we just write the leaf position, tx hash, and call index.
    /// Panics if the fields are None.
    pub async fn confirm_dao(&self, dao: &DaoRecord) -> WalletDbResult<()> {
        let query = format!(
            "UPDATE {} SET {} = ?1, {} = ?2, {} = ?3 WHERE {} = ?4;",
            *DAO_DAOS_TABLE,
            DAO_DAOS_COL_LEAF_POSITION,
            DAO_DAOS_COL_TX_HASH,
            DAO_DAOS_COL_CALL_INDEX,
            DAO_DAOS_COL_BULLA
        );
        self.wallet.exec_sql(
            &query,
            rusqlite::params![
                serialize_async(&dao.leaf_position.unwrap()).await,
                serialize_async(&dao.tx_hash.unwrap()).await,
                dao.call_index.unwrap(),
                serialize_async(&dao.bulla()).await,
            ],
        )
    }

    /// Unconfirm imported DAOs by removing the leaf position, tx hash, and call index.
    pub async fn unconfirm_daos(&self, daos: &[DaoRecord]) -> WalletDbResult<()> {
        for dao in daos {
            let query = format!(
                "UPDATE {} SET {} = ?1, {} = ?2, {} = ?3 WHERE {} = ?4;",
                *DAO_DAOS_TABLE,
                DAO_DAOS_COL_LEAF_POSITION,
                DAO_DAOS_COL_TX_HASH,
                DAO_DAOS_COL_CALL_INDEX,
                DAO_DAOS_COL_BULLA
            );
            self.wallet.exec_sql(
                &query,
                rusqlite::params![
                    None::<Vec<u8>>,
                    None::<Vec<u8>>,
                    None::<u64>,
                    serialize_async(&dao.bulla()).await
                ],
            )?;
        }

        Ok(())
    }

    /// Import given DAO proposal into the wallet.
    pub async fn put_dao_proposal(&self, proposal: &ProposalRecord) -> Result<()> {
        if let Err(e) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
            return Err(Error::RusqliteError(format!(
                "[put_dao_proposal] Couldn't find proposal {} DAO {}: {e}",
                proposal.bulla(),
                proposal.proposal.dao_bulla
            )))
        }

        let query = format!(
            "INSERT OR REPLACE INTO {} ({}, {}, {}, {}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10);",
            *DAO_PROPOSALS_TABLE,
            DAO_PROPOSALS_COL_BULLA,
            DAO_PROPOSALS_COL_DAO_BULLA,
            DAO_PROPOSALS_COL_PROPOSAL,
            DAO_PROPOSALS_COL_DATA,
            DAO_PROPOSALS_COL_LEAF_POSITION,
            DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE,
            DAO_PROPOSALS_COL_NULLIFIERS_SMT_SNAPSHOT,
            DAO_PROPOSALS_COL_TX_HASH,
            DAO_PROPOSALS_COL_CALL_INDEX,
            DAO_PROPOSALS_COL_EXEC_TX_HASH,
        );

        let data = match &proposal.data {
            Some(data) => Some(data),
            None => None,
        };

        let leaf_position = match &proposal.leaf_position {
            Some(leaf_position) => Some(serialize_async(leaf_position).await),
            None => None,
        };

        let money_snapshot_tree = match &proposal.money_snapshot_tree {
            Some(money_snapshot_tree) => Some(serialize_async(money_snapshot_tree).await),
            None => None,
        };

        let nullifiers_smt_snapshot = match &proposal.nullifiers_smt_snapshot {
            Some(nullifiers_smt_snapshot) => Some(serialize_async(nullifiers_smt_snapshot).await),
            None => None,
        };

        let tx_hash = match &proposal.tx_hash {
            Some(tx_hash) => Some(serialize_async(tx_hash).await),
            None => None,
        };

        let exec_tx_hash = match &proposal.exec_tx_hash {
            Some(exec_tx_hash) => Some(serialize_async(exec_tx_hash).await),
            None => None,
        };

        if let Err(e) = self.wallet.exec_sql(
            &query,
            rusqlite::params![
                serialize_async(&proposal.bulla()).await,
                serialize_async(&proposal.proposal.dao_bulla).await,
                serialize_async(&proposal.proposal).await,
                data,
                leaf_position,
                money_snapshot_tree,
                nullifiers_smt_snapshot,
                tx_hash,
                proposal.call_index,
                exec_tx_hash,
            ],
        ) {
            return Err(Error::RusqliteError(format!(
                "[put_dao_proposal] Proposal insert failed: {e:?}"
            )))
        };

        Ok(())
    }

    /// Unconfirm imported DAO proposals by removing the leaf position, tx hash, and call index.
    pub async fn unconfirm_proposals(&self, proposals: &[ProposalRecord]) -> WalletDbResult<()> {
        for proposal in proposals {
            let query = format!(
                "UPDATE {} SET {} = ?1, {} = ?2, {} = ?3, {} = ?4, {} = ?5, {} = ?6 WHERE {} = ?7;",
                *DAO_PROPOSALS_TABLE,
                DAO_PROPOSALS_COL_LEAF_POSITION,
                DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE,
                DAO_PROPOSALS_COL_NULLIFIERS_SMT_SNAPSHOT,
                DAO_PROPOSALS_COL_TX_HASH,
                DAO_PROPOSALS_COL_CALL_INDEX,
                DAO_PROPOSALS_COL_EXEC_TX_HASH,
                DAO_PROPOSALS_COL_BULLA
            );
            self.wallet.exec_sql(
                &query,
                rusqlite::params![
                    None::<Vec<u8>>,
                    None::<Vec<u8>>,
                    None::<Vec<u8>>,
                    None::<Vec<u8>>,
                    None::<u64>,
                    None::<Vec<u8>>,
                    serialize_async(&proposal.bulla()).await
                ],
            )?;
        }

        Ok(())
    }

    /// Import given DAO votes into the wallet.
    pub async fn put_dao_vote(&self, vote: &VoteRecord) -> WalletDbResult<()> {
        eprintln!("Importing DAO vote into wallet");

        let query = format!(
            "INSERT INTO {} ({}, {}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8);",
            *DAO_VOTES_TABLE,
            DAO_VOTES_COL_PROPOSAL_BULLA,
            DAO_VOTES_COL_VOTE_OPTION,
            DAO_VOTES_COL_YES_VOTE_BLIND,
            DAO_VOTES_COL_ALL_VOTE_VALUE,
            DAO_VOTES_COL_ALL_VOTE_BLIND,
            DAO_VOTES_COL_TX_HASH,
            DAO_VOTES_COL_CALL_INDEX,
            DAO_VOTES_COL_NULLIFIERS,
        );

        self.wallet.exec_sql(
            &query,
            rusqlite::params![
                serialize_async(&vote.proposal).await,
                vote.vote_option as u64,
                serialize_async(&vote.yes_vote_blind).await,
                serialize_async(&vote.all_vote_value).await,
                serialize_async(&vote.all_vote_blind).await,
                serialize_async(&vote.tx_hash).await,
                vote.call_index,
                serialize_async(&vote.nullifiers).await,
            ],
        )?;

        println!("DAO vote added to wallet");

        Ok(())
    }

    /// Reset the DAO Merkle trees in the wallet.
    pub async fn reset_dao_trees(&self) -> WalletDbResult<()> {
        println!("Resetting DAO Merkle trees");
        let tree = MerkleTree::new(1);
        self.put_dao_trees(&tree, &tree).await?;
        println!("Successfully reset DAO Merkle trees");

        Ok(())
    }

    /// Reset confirmed DAOs in the wallet.
    pub async fn reset_daos(&self) -> WalletDbResult<()> {
        println!("Resetting DAO confirmations");
        let daos = match self.get_daos().await {
            Ok(d) => d,
            Err(e) => {
                println!("[reset_daos] DAOs retrieval failed: {e:?}");
                return Err(WalletDbError::GenericError);
            }
        };
        self.unconfirm_daos(&daos).await?;
        println!("Successfully unconfirmed DAOs");

        Ok(())
    }

    /// Reset all DAO proposals in the wallet.
    pub async fn reset_dao_proposals(&self) -> WalletDbResult<()> {
        println!("Resetting DAO proposals confirmations");
        let proposals = match self.get_proposals().await {
            Ok(p) => p,
            Err(e) => {
                println!("[reset_dao_proposals] DAO proposals retrieval failed: {e:?}");
                return Err(WalletDbError::GenericError);
            }
        };
        self.unconfirm_proposals(&proposals).await?;
        println!("Successfully unconfirmed DAO proposals");

        Ok(())
    }

    /// Reset all DAO votes in the wallet.
    pub fn reset_dao_votes(&self) -> WalletDbResult<()> {
        println!("Resetting DAO votes");
        let query = format!("DELETE FROM {};", *DAO_VOTES_TABLE);
        self.wallet.exec_sql(&query, &[])
    }

    /// Import given DAO params into the wallet with a given name.
    pub async fn import_dao(&self, name: &str, params: DaoParams) -> Result<()> {
        // First let's check if we've imported this DAO with the given name before.
        if self.get_dao_by_name(name).await.is_ok() {
            return Err(Error::RusqliteError(
                "[import_dao] This DAO has already been imported".to_string(),
            ))
        }

        println!("Importing \"{name}\" DAO into the wallet");

        let query = format!(
            "INSERT INTO {} ({}, {}, {}) VALUES (?1, ?2, ?3);",
            *DAO_DAOS_TABLE, DAO_DAOS_COL_BULLA, DAO_DAOS_COL_NAME, DAO_DAOS_COL_PARAMS,
        );
        if let Err(e) = self.wallet.exec_sql(
            &query,
            rusqlite::params![
                serialize_async(&params.dao.to_bulla()).await,
                name,
                serialize_async(&params).await,
            ],
        ) {
            return Err(Error::RusqliteError(format!("[import_dao] DAO insert failed: {e:?}")))
        };

        Ok(())
    }

    /// Fetch a DAO given its bulla.
    pub async fn get_dao_by_bulla(&self, bulla: &DaoBulla) -> Result<DaoRecord> {
        let row = match self.wallet.query_single(
            &DAO_DAOS_TABLE,
            &[],
            convert_named_params! {(DAO_DAOS_COL_BULLA, serialize_async(bulla).await)},
        ) {
            Ok(r) => r,
            Err(e) => {
                return Err(Error::RusqliteError(format!(
                    "[get_dao_by_bulla] DAO retrieval failed: {e:?}"
                )))
            }
        };

        self.parse_dao_record(&row).await
    }

    /// Fetch a DAO given its name.
    pub async fn get_dao_by_name(&self, name: &str) -> Result<DaoRecord> {
        let row = match self.wallet.query_single(
            &DAO_DAOS_TABLE,
            &[],
            convert_named_params! {(DAO_DAOS_COL_NAME, name)},
        ) {
            Ok(r) => r,
            Err(e) => {
                return Err(Error::RusqliteError(format!(
                    "[get_dao_by_name] DAO retrieval failed: {e:?}"
                )))
            }
        };

        self.parse_dao_record(&row).await
    }

    /// List DAO(s) imported in the wallet. If a name is given, just print the
    /// metadata for that specific one, if found.
    pub async fn dao_list(&self, name: &Option<String>) -> Result<()> {
        if let Some(name) = name {
            let dao = self.get_dao_by_name(name).await?;
            println!("{dao}");
            return Ok(());
        }

        let daos = self.get_daos().await?;
        for (i, dao) in daos.iter().enumerate() {
            println!("{i}. {}", dao.name);
        }

        Ok(())
    }

    /// Fetch known unspent balances from the wallet for the given DAO name.
    pub async fn dao_balance(&self, name: &str) -> Result<HashMap<String, u64>> {
        let dao = self.get_dao_by_name(name).await?;

        let dao_spend_hook =
            FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
                .to_func_id();

        let mut coins = self.get_coins(false).await?;
        coins.retain(|x| x.0.note.spend_hook == dao_spend_hook);
        coins.retain(|x| x.0.note.user_data == dao.bulla().inner());

        // Fill this map with balances
        let mut balmap: HashMap<String, u64> = HashMap::new();

        for coin in coins {
            let mut value = coin.0.note.value;

            if let Some(prev) = balmap.get(&coin.0.note.token_id.to_string()) {
                value += prev;
            }

            balmap.insert(coin.0.note.token_id.to_string(), value);
        }

        Ok(balmap)
    }

    /// Fetch all known DAO proposalss from the wallet.
    pub async fn get_proposals(&self) -> Result<Vec<ProposalRecord>> {
        let rows = match self.wallet.query_multiple(&DAO_PROPOSALS_TABLE, &[], &[]) {
            Ok(r) => r,
            Err(e) => {
                return Err(Error::RusqliteError(format!(
                    "[get_proposals] DAO proposalss retrieval failed: {e:?}"
                )))
            }
        };

        let mut daos = Vec::with_capacity(rows.len());
        for row in rows {
            daos.push(self.parse_dao_proposal(&row).await?);
        }

        Ok(daos)
    }

    /// Fetch a DAO proposal by its bulla.
    pub async fn get_dao_proposal_by_bulla(
        &self,
        bulla: &DaoProposalBulla,
    ) -> Result<ProposalRecord> {
        // Grab the proposal record
        let row = match self.wallet.query_single(
            &DAO_PROPOSALS_TABLE,
            &[],
            convert_named_params! {(DAO_PROPOSALS_COL_BULLA, serialize_async(bulla).await)},
        ) {
            Ok(r) => r,
            Err(e) => {
                return Err(Error::RusqliteError(format!(
                    "[get_dao_proposal_by_bulla] DAO proposal retrieval failed: {e:?}"
                )))
            }
        };

        // Parse rest of the record
        self.parse_dao_proposal(&row).await
    }

    // Fetch all known DAO proposal votes from the wallet given a proposal ID.
    pub async fn get_dao_proposal_votes(
        &self,
        proposal: &DaoProposalBulla,
    ) -> Result<Vec<VoteRecord>> {
        let rows = match self.wallet.query_multiple(
            &DAO_VOTES_TABLE,
            &[],
            convert_named_params! {(DAO_VOTES_COL_PROPOSAL_BULLA, serialize_async(proposal).await)},
        ) {
            Ok(r) => r,
            Err(e) => {
                return Err(Error::RusqliteError(format!(
                    "[get_dao_proposal_votes] Votes retrieval failed: {e:?}"
                )))
            }
        };

        let mut votes = Vec::with_capacity(rows.len());
        for row in rows {
            let Value::Integer(id) = row[0] else {
                return Err(Error::ParseFailed("[get_dao_proposal_votes] ID parsing failed"))
            };
            let Ok(id) = u64::try_from(id) else {
                return Err(Error::ParseFailed("[get_dao_proposal_votes] ID parsing failed"))
            };

            let Value::Blob(ref proposal_bytes) = row[1] else {
                return Err(Error::ParseFailed(
                    "[get_dao_proposal_votes] Proposal bytes bytes parsing failed",
                ))
            };
            let proposal = deserialize_async(proposal_bytes).await?;

            let Value::Integer(vote_option) = row[2] else {
                return Err(Error::ParseFailed(
                    "[get_dao_proposal_votes] Vote option parsing failed",
                ))
            };
            let Ok(vote_option) = u32::try_from(vote_option) else {
                return Err(Error::ParseFailed(
                    "[get_dao_proposal_votes] Vote option parsing failed",
                ))
            };
            let vote_option = vote_option != 0;

            let Value::Blob(ref yes_vote_blind_bytes) = row[3] else {
                return Err(Error::ParseFailed(
                    "[get_dao_proposal_votes] Yes vote blind bytes parsing failed",
                ))
            };
            let yes_vote_blind = deserialize_async(yes_vote_blind_bytes).await?;

            let Value::Blob(ref all_vote_value_bytes) = row[4] else {
                return Err(Error::ParseFailed(
                    "[get_dao_proposal_votes] All vote value bytes parsing failed",
                ))
            };
            let all_vote_value = deserialize_async(all_vote_value_bytes).await?;

            let Value::Blob(ref all_vote_blind_bytes) = row[5] else {
                return Err(Error::ParseFailed(
                    "[get_dao_proposal_votes] All vote blind bytes parsing failed",
                ))
            };
            let all_vote_blind = deserialize_async(all_vote_blind_bytes).await?;

            let Value::Blob(ref tx_hash_bytes) = row[6] else {
                return Err(Error::ParseFailed(
                    "[get_dao_proposal_votes] Transaction hash bytes parsing failed",
                ))
            };
            let tx_hash = deserialize_async(tx_hash_bytes).await?;

            let Value::Integer(call_index) = row[7] else {
                return Err(Error::ParseFailed("[get_dao_proposal_votes] Call index parsing failed"))
            };
            let Ok(call_index) = u8::try_from(call_index) else {
                return Err(Error::ParseFailed("[get_dao_proposal_votes] Call index parsing failed"))
            };

            let Value::Blob(ref nullifiers_bytes) = row[8] else {
                return Err(Error::ParseFailed(
                    "[get_dao_proposal_votes] Nullifiers bytes parsing failed",
                ))
            };
            let nullifiers = deserialize_async(nullifiers_bytes).await?;

            let vote = VoteRecord {
                id,
                proposal,
                vote_option,
                yes_vote_blind,
                all_vote_value,
                all_vote_blind,
                tx_hash,
                call_index,
                nullifiers,
            };

            votes.push(vote);
        }

        Ok(votes)
    }

    /// Mint a DAO on-chain.
    pub async fn dao_mint(&self, name: &str) -> Result<Transaction> {
        // Retrieve the dao record
        let dao = self.get_dao_by_name(name).await?;

        // Check its not already minted
        if dao.tx_hash.is_some() {
            return Err(Error::Custom(
                "[dao_mint] This DAO seems to have already been minted on-chain".to_string(),
            ))
        }

        // Now we need to do a lookup for the zkas proof bincodes, and create
        // the circuit objects and proving keys so we can build the transaction.
        // We also do this through the RPC. First we grab the fee call from money.
        let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;

        let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
        else {
            return Err(Error::Custom("Fee circuit not found".to_string()))
        };

        let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;

        let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);

        // Creating Fee circuit proving key
        let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);

        // Now we grab the DAO mint
        let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;

        let Some(dao_mint_zkbin) = zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_MINT_NS)
        else {
            return Err(Error::RusqliteError("[dao_mint] DAO Mint circuit not found".to_string()))
        };

        let dao_mint_zkbin = ZkBinary::decode(&dao_mint_zkbin.1)?;

        let dao_mint_circuit = ZkCircuit::new(empty_witnesses(&dao_mint_zkbin)?, &dao_mint_zkbin);

        // Creating DAO Mint circuit proving key
        let dao_mint_pk = ProvingKey::build(dao_mint_zkbin.k, &dao_mint_circuit);

        // Create the DAO mint call
        let (params, proofs) =
            make_mint_call(&dao.params.dao, &dao.params.secret_key, &dao_mint_zkbin, &dao_mint_pk)?;
        let mut data = vec![DaoFunction::Mint as u8];
        params.encode_async(&mut data).await?;
        let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };

        // Create the TransactionBuilder containing above call
        let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;

        // We first have to execute the fee-less tx to gather its used gas, and then we feed
        // it into the fee-creating function.
        let mut tx = tx_builder.build()?;
        let sigs = tx.create_sigs(&[dao.params.secret_key])?;
        tx.signatures.push(sigs);

        let tree = self.get_money_tree().await?;
        let (fee_call, fee_proofs, fee_secrets) =
            self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;

        // Append the fee call to the transaction
        tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;

        // Now build the actual transaction and sign it with all necessary keys.
        let mut tx = tx_builder.build()?;
        let sigs = tx.create_sigs(&[dao.params.secret_key])?;
        tx.signatures.push(sigs);
        let sigs = tx.create_sigs(&fee_secrets)?;
        tx.signatures.push(sigs);

        Ok(tx)
    }

    /// Create a DAO transfer proposal.
    #[allow(clippy::too_many_arguments)]
    pub async fn dao_propose_transfer(
        &self,
        name: &str,
        duration_blockwindows: u64,
        amount: &str,
        token_id: TokenId,
        recipient: PublicKey,
        spend_hook: Option<FuncId>,
        user_data: Option<pallas::Base>,
    ) -> Result<ProposalRecord> {
        // Fetch DAO and check its deployed
        let dao = self.get_dao_by_name(name).await?;
        if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
            return Err(Error::Custom(
                "[dao_propose_transfer] DAO seems to not have been deployed yet".to_string(),
            ))
        }

        // Fetch DAO unspent OwnCoins to see what its balance is
        let dao_spend_hook =
            FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
                .to_func_id();
        let dao_bulla = dao.bulla();
        let dao_owncoins =
            self.get_contract_token_coins(&token_id, &dao_spend_hook, &dao_bulla.inner()).await?;
        if dao_owncoins.is_empty() {
            return Err(Error::Custom(format!(
                "[dao_propose_transfer] Did not find any {token_id} unspent coins owned by this DAO"
            )))
        }

        // Check DAO balance is sufficient
        let amount = decode_base10(amount, BALANCE_BASE10_DECIMALS, false)?;
        if dao_owncoins.iter().map(|x| x.note.value).sum::<u64>() < amount {
            return Err(Error::Custom(format!(
                "[dao_propose_transfer] Not enough DAO balance for token ID: {token_id}",
            )))
        }

        // Generate proposal coin attributes
        let proposal_coinattrs = CoinAttributes {
            public_key: recipient,
            value: amount,
            token_id,
            spend_hook: spend_hook.unwrap_or(FuncId::none()),
            user_data: user_data.unwrap_or(pallas::Base::ZERO),
            blind: Blind::random(&mut OsRng),
        };

        // Convert coin_params to actual coins
        let proposal_coins = vec![proposal_coinattrs.to_coin()];
        let mut proposal_data = vec![];
        proposal_coins.encode_async(&mut proposal_data).await?;

        // Create Auth calls
        let auth_calls = vec![
            DaoAuthCall {
                contract_id: *DAO_CONTRACT_ID,
                function_code: DaoFunction::AuthMoneyTransfer as u8,
                auth_data: proposal_data,
            },
            DaoAuthCall {
                contract_id: *MONEY_CONTRACT_ID,
                function_code: MoneyFunction::TransferV1 as u8,
                auth_data: vec![],
            },
        ];

        // Retrieve next block height and current block time target,
        // to compute their window.
        let next_block_height = self.get_next_block_height().await?;
        let block_target = self.get_block_target().await?;
        let creation_blockwindow = blockwindow(next_block_height, block_target);

        // Create the actual proposal
        let proposal = DaoProposal {
            auth_calls,
            creation_blockwindow,
            duration_blockwindows,
            user_data: user_data.unwrap_or(pallas::Base::ZERO),
            dao_bulla,
            blind: Blind::random(&mut OsRng),
        };

        let proposal_record = ProposalRecord {
            proposal,
            data: Some(serialize_async(&proposal_coinattrs).await),
            leaf_position: None,
            money_snapshot_tree: None,
            nullifiers_smt_snapshot: None,
            tx_hash: None,
            call_index: None,
            exec_tx_hash: None,
        };

        if let Err(e) = self.put_dao_proposal(&proposal_record).await {
            return Err(Error::RusqliteError(format!(
                "[dao_propose_transfer] Put DAO proposal failed: {e:?}"
            )))
        }

        Ok(proposal_record)
    }

    /// Create a DAO transfer proposal transaction.
    pub async fn dao_transfer_proposal_tx(&self, proposal: &ProposalRecord) -> Result<Transaction> {
        // Check we know the plaintext data
        if proposal.data.is_none() {
            return Err(Error::Custom(
                "[dao_transfer_proposal_tx] Proposal plainext data is empty".to_string(),
            ))
        }
        let proposal_coinattrs: CoinAttributes =
            deserialize_async(proposal.data.as_ref().unwrap()).await?;

        // Fetch DAO and check its deployed
        let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
            return Err(Error::Custom(format!(
                "[dao_transfer_proposal_tx] DAO {} was not found",
                proposal.proposal.dao_bulla
            )))
        };
        if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
            return Err(Error::Custom(
                "[dao_transfer_proposal_tx] DAO seems to not have been deployed yet".to_string(),
            ))
        }

        // Fetch DAO unspent OwnCoins to see what its balance is for the coin
        let dao_spend_hook =
            FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
                .to_func_id();
        let dao_owncoins = self
            .get_contract_token_coins(
                &proposal_coinattrs.token_id,
                &dao_spend_hook,
                &proposal.proposal.dao_bulla.inner(),
            )
            .await?;
        if dao_owncoins.is_empty() {
            return Err(Error::Custom(format!(
                "[dao_transfer_proposal_tx] Did not find any {} unspent coins owned by this DAO",
                proposal_coinattrs.token_id,
            )))
        }

        // Check DAO balance is sufficient
        if dao_owncoins.iter().map(|x| x.note.value).sum::<u64>() < proposal_coinattrs.value {
            return Err(Error::Custom(format!(
                "[dao_transfer_proposal_tx] Not enough DAO balance for token ID: {}",
                proposal_coinattrs.token_id,
            )))
        }

        // Fetch our own governance OwnCoins to see what our balance is
        let gov_owncoins = self.get_token_coins(&dao.params.dao.gov_token_id).await?;
        if gov_owncoins.is_empty() {
            return Err(Error::Custom(format!(
                "[dao_transfer_proposal_tx] Did not find any governance {} coins in wallet",
                dao.params.dao.gov_token_id
            )))
        }

        // Find which governance coins we can use
        let mut total_value = 0;
        let mut gov_owncoins_to_use = vec![];
        for gov_owncoin in gov_owncoins {
            if total_value >= dao.params.dao.proposer_limit {
                break
            }

            total_value += gov_owncoin.note.value;
            gov_owncoins_to_use.push(gov_owncoin);
        }

        // Check our governance coins balance is sufficient
        if total_value < dao.params.dao.proposer_limit {
            return Err(Error::Custom(format!(
                "[dao_transfer_proposal_tx] Not enough gov token {} balance to propose",
                dao.params.dao.gov_token_id
            )))
        }

        // Now we need to do a lookup for the zkas proof bincodes, and create
        // the circuit objects and proving keys so we can build the transaction.
        // We also do this through the RPC. First we grab the fee call from money.
        let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;

        let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
        else {
            return Err(Error::Custom(
                "[dao_transfer_proposal_tx] Fee circuit not found".to_string(),
            ))
        };

        let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;

        let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);

        // Creating Fee circuit proving key
        let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);

        // Now we grab the DAO bins
        let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;

        let Some(propose_burn_zkbin) =
            zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_PROPOSE_INPUT_NS)
        else {
            return Err(Error::Custom(
                "[dao_transfer_proposal_tx] Propose Burn circuit not found".to_string(),
            ))
        };

        let Some(propose_main_zkbin) =
            zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_PROPOSE_MAIN_NS)
        else {
            return Err(Error::Custom(
                "[dao_transfer_proposal_tx] Propose Main circuit not found".to_string(),
            ))
        };

        let propose_burn_zkbin = ZkBinary::decode(&propose_burn_zkbin.1)?;
        let propose_main_zkbin = ZkBinary::decode(&propose_main_zkbin.1)?;

        let propose_burn_circuit =
            ZkCircuit::new(empty_witnesses(&propose_burn_zkbin)?, &propose_burn_zkbin);
        let propose_main_circuit =
            ZkCircuit::new(empty_witnesses(&propose_main_zkbin)?, &propose_main_zkbin);

        // Creating DAO ProposeBurn and ProposeMain circuits proving keys
        let propose_burn_pk = ProvingKey::build(propose_burn_zkbin.k, &propose_burn_circuit);
        let propose_main_pk = ProvingKey::build(propose_main_zkbin.k, &propose_main_circuit);

        // Fetch our money Merkle tree
        let money_merkle_tree = self.get_money_tree().await?;

        // Now we can create the proposal transaction parameters.
        // We first generate the `DaoProposeStakeInput` inputs,
        // using our governance OwnCoins.
        let mut inputs = Vec::with_capacity(gov_owncoins_to_use.len());
        for gov_owncoin in gov_owncoins_to_use {
            let input = DaoProposeStakeInput {
                secret: gov_owncoin.secret,
                note: gov_owncoin.note.clone(),
                leaf_position: gov_owncoin.leaf_position,
                merkle_path: money_merkle_tree.witness(gov_owncoin.leaf_position, 0).unwrap(),
            };
            inputs.push(input);
        }

        // Now create the parameters for the proposal tx
        let signature_secret = SecretKey::random(&mut OsRng);

        // Fetch the daos Merkle tree to compute the DAO Merkle path and root
        let (daos_tree, _) = self.get_dao_trees().await?;
        let (dao_merkle_path, dao_merkle_root) = {
            let root = daos_tree.root(0).unwrap();
            let leaf_pos = dao.leaf_position.unwrap();
            let dao_merkle_path = daos_tree.witness(leaf_pos, 0).unwrap();
            (dao_merkle_path, root)
        };

        // Generate the Money nullifiers Sparse Merkle Tree
        let store = WalletStorage::new(
            &self.wallet,
            &MONEY_SMT_TABLE,
            MONEY_SMT_COL_KEY,
            MONEY_SMT_COL_VALUE,
        );
        let money_null_smt = WalletSmt::new(store, PoseidonFp::new(), &EMPTY_NODES_FP);

        // Create the proposal call
        let call = DaoProposeCall {
            money_null_smt: &money_null_smt,
            inputs,
            proposal: proposal.proposal.clone(),
            dao: dao.params.dao,
            dao_leaf_position: dao.leaf_position.unwrap(),
            dao_merkle_path,
            dao_merkle_root,
            signature_secret,
        };

        let (params, proofs) = call.make(
            &propose_burn_zkbin,
            &propose_burn_pk,
            &propose_main_zkbin,
            &propose_main_pk,
        )?;

        // Encode the call
        let mut data = vec![DaoFunction::Propose as u8];
        params.encode_async(&mut data).await?;
        let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };

        // Create the TransactionBuilder containing above call
        let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;

        // We first have to execute the fee-less tx to gather its used gas, and then we feed
        // it into the fee-creating function.
        let mut tx = tx_builder.build()?;
        let sigs = tx.create_sigs(&[signature_secret])?;
        tx.signatures = vec![sigs];

        let tree = self.get_money_tree().await?;
        let (fee_call, fee_proofs, fee_secrets) =
            self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;

        // Append the fee call to the transaction
        tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;

        // Now build the actual transaction and sign it with all necessary keys.
        let mut tx = tx_builder.build()?;
        let sigs = tx.create_sigs(&[signature_secret])?;
        tx.signatures.push(sigs);
        let sigs = tx.create_sigs(&fee_secrets)?;
        tx.signatures.push(sigs);

        Ok(tx)
    }

    /// Vote on a DAO proposal
    pub async fn dao_vote(
        &self,
        proposal_bulla: &DaoProposalBulla,
        vote_option: bool,
        weight: Option<u64>,
    ) -> Result<Transaction> {
        // Feth the proposal and check its deployed
        let Ok(proposal) = self.get_dao_proposal_by_bulla(proposal_bulla).await else {
            return Err(Error::Custom(format!("[dao_vote] Proposal {proposal_bulla} was not found")))
        };
        if proposal.leaf_position.is_none() ||
            proposal.money_snapshot_tree.is_none() ||
            proposal.nullifiers_smt_snapshot.is_none() ||
            proposal.tx_hash.is_none() ||
            proposal.call_index.is_none()
        {
            return Err(Error::Custom(
                "[dao_vote] Proposal seems to not have been deployed yet".to_string(),
            ))
        }

        // Check proposal is not executed
        if let Some(exec_tx_hash) = proposal.exec_tx_hash {
            return Err(Error::Custom(format!(
                "[dao_vote] Proposal was executed on transaction: {exec_tx_hash}"
            )))
        }

        // Check we know the plaintext data
        if proposal.data.is_none() {
            return Err(Error::Custom("[dao_vote] Proposal plainext data is empty".to_string()))
        }

        // Fetch DAO and check its deployed
        let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
            return Err(Error::Custom(format!(
                "[dao_vote] DAO {} was not found",
                proposal.proposal.dao_bulla
            )))
        };
        if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
            return Err(Error::Custom(
                "[dao_vote] DAO seems to not have been deployed yet".to_string(),
            ))
        }

        // Fetch all the proposal votes to check for duplicate nullifiers
        let votes = self.get_dao_proposal_votes(proposal_bulla).await?;
        let mut votes_nullifiers = vec![];
        for vote in votes {
            for nullifier in vote.nullifiers {
                if !votes_nullifiers.contains(&nullifier) {
                    votes_nullifiers.push(nullifier);
                }
            }
        }

        // Fetch our own governance OwnCoins to see what our balance is
        let gov_owncoins = self.get_token_coins(&dao.params.dao.gov_token_id).await?;
        if gov_owncoins.is_empty() {
            return Err(Error::Custom(format!(
                "[dao_vote] Did not find any governance {} coins in wallet",
                dao.params.dao.gov_token_id
            )))
        }

        // Find which governance coins we can use
        let gov_owncoins_to_use = match weight {
            Some(_weight) => {
                // TODO: Build a proper coin selection algorithm so that we can use a
                // coins combination that matches the requested weight
                return Err(Error::Custom(
                    "[dao_vote] Fractional vote weight not supported yet".to_string(),
                ))
            }
            // If no weight was specified, use them all
            None => gov_owncoins,
        };

        // Now we need to do a lookup for the zkas proof bincodes, and create
        // the circuit objects and proving keys so we can build the transaction.
        // We also do this through the RPC. First we grab the fee call from money.
        let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;

        let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
        else {
            return Err(Error::Custom("[dao_vote] Fee circuit not found".to_string()))
        };

        let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;

        let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);

        // Creating Fee circuit proving key
        let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);

        // Now we grab the DAO bins
        let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;

        let Some(dao_vote_burn_zkbin) =
            zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_VOTE_INPUT_NS)
        else {
            return Err(Error::Custom("[dao_vote] DAO Vote Burn circuit not found".to_string()))
        };

        let Some(dao_vote_main_zkbin) =
            zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_VOTE_MAIN_NS)
        else {
            return Err(Error::Custom("[dao_vote] DAO Vote Main circuit not found".to_string()))
        };

        let dao_vote_burn_zkbin = ZkBinary::decode(&dao_vote_burn_zkbin.1)?;
        let dao_vote_main_zkbin = ZkBinary::decode(&dao_vote_main_zkbin.1)?;

        let dao_vote_burn_circuit =
            ZkCircuit::new(empty_witnesses(&dao_vote_burn_zkbin)?, &dao_vote_burn_zkbin);
        let dao_vote_main_circuit =
            ZkCircuit::new(empty_witnesses(&dao_vote_main_zkbin)?, &dao_vote_main_zkbin);

        // Creating DAO VoteBurn and VoteMain circuits proving keys
        let dao_vote_burn_pk = ProvingKey::build(dao_vote_burn_zkbin.k, &dao_vote_burn_circuit);
        let dao_vote_main_pk = ProvingKey::build(dao_vote_main_zkbin.k, &dao_vote_main_circuit);

        // Now create the parameters for the vote tx
        let signature_secret = SecretKey::random(&mut OsRng);
        let mut inputs = Vec::with_capacity(gov_owncoins_to_use.len());
        for gov_owncoin in gov_owncoins_to_use {
            let nullifier = poseidon_hash([gov_owncoin.secret.inner(), gov_owncoin.coin.inner()]);
            let vote_nullifier =
                poseidon_hash([nullifier, gov_owncoin.secret.inner(), proposal_bulla.inner()]);
            if votes_nullifiers.contains(&vote_nullifier.into()) {
                return Err(Error::Custom("[dao_vote] Duplicate input nullifier found".to_string()))
            };

            let input = DaoVoteInput {
                secret: gov_owncoin.secret,
                note: gov_owncoin.note.clone(),
                leaf_position: gov_owncoin.leaf_position,
                merkle_path: proposal
                    .money_snapshot_tree
                    .as_ref()
                    .unwrap()
                    .witness(gov_owncoin.leaf_position, 0)
                    .unwrap(),
                signature_secret,
            };
            inputs.push(input);
        }

        // Retrieve next block height and current block time target,
        // to compute their window.
        let next_block_height = self.get_next_block_height().await?;
        let block_target = self.get_block_target().await?;
        let current_blockwindow = blockwindow(next_block_height, block_target);

        // Generate the Money nullifiers Sparse Merkle Tree
        let store = MemoryStorageFp { tree: proposal.nullifiers_smt_snapshot.unwrap() };
        let money_null_smt = SmtMemoryFp::new(store, PoseidonFp::new(), &EMPTY_NODES_FP);

        // Create the vote call
        let call = DaoVoteCall {
            money_null_smt: &money_null_smt,
            inputs,
            vote_option,
            proposal: proposal.proposal.clone(),
            dao: dao.params.dao.clone(),
            dao_keypair: dao.keypair(),
            current_blockwindow,
        };

        let (params, proofs) = call.make(
            &dao_vote_burn_zkbin,
            &dao_vote_burn_pk,
            &dao_vote_main_zkbin,
            &dao_vote_main_pk,
        )?;

        // Encode the call
        let mut data = vec![DaoFunction::Vote as u8];
        params.encode_async(&mut data).await?;
        let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };

        // Create the TransactionBuilder containing above call
        let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;

        // We first have to execute the fee-less tx to gather its used gas, and then we feed
        // it into the fee-creating function.
        let mut tx = tx_builder.build()?;
        let sigs = tx.create_sigs(&[signature_secret])?;
        tx.signatures = vec![sigs];

        let tree = self.get_money_tree().await?;
        let (fee_call, fee_proofs, fee_secrets) =
            self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;

        // Append the fee call to the transaction
        tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;

        // Now build the actual transaction and sign it with all necessary keys.
        let mut tx = tx_builder.build()?;
        let sigs = tx.create_sigs(&[signature_secret])?;
        tx.signatures.push(sigs);
        let sigs = tx.create_sigs(&fee_secrets)?;
        tx.signatures.push(sigs);

        Ok(tx)
    }

    /// Execute a DAO transfer proposal.
    pub async fn dao_exec_transfer(&self, proposal: &ProposalRecord) -> Result<Transaction> {
        if proposal.leaf_position.is_none() ||
            proposal.money_snapshot_tree.is_none() ||
            proposal.nullifiers_smt_snapshot.is_none() ||
            proposal.tx_hash.is_none() ||
            proposal.call_index.is_none()
        {
            return Err(Error::Custom(
                "[dao_exec_transfer] Proposal seems to not have been deployed yet".to_string(),
            ))
        }

        // Check proposal is not executed
        if let Some(exec_tx_hash) = proposal.exec_tx_hash {
            return Err(Error::Custom(format!(
                "[dao_exec_transfer] Proposal was executed on transaction: {exec_tx_hash}"
            )))
        }

        // Check we know the plaintext data and they are valid
        if proposal.data.is_none() {
            return Err(Error::Custom(
                "[dao_exec_transfer] Proposal plainext data is empty".to_string(),
            ))
        }
        let proposal_coinattrs: CoinAttributes =
            deserialize_async(proposal.data.as_ref().unwrap()).await?;

        // Fetch DAO and check its deployed
        let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
            return Err(Error::Custom(format!(
                "[dao_exec_transfer] DAO {} was not found",
                proposal.proposal.dao_bulla
            )))
        };
        if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
            return Err(Error::Custom(
                "[dao_exec_transfer] DAO seems to not have been deployed yet".to_string(),
            ))
        }

        // Check proposal is approved
        let votes = self.get_dao_proposal_votes(&proposal.bulla()).await?;
        let mut yes_vote_value = 0;
        let mut yes_vote_blind = Blind::ZERO;
        let mut all_vote_value = 0;
        let mut all_vote_blind = Blind::ZERO;
        for vote in votes {
            if vote.vote_option {
                yes_vote_value += vote.all_vote_value;
            };
            yes_vote_blind += vote.yes_vote_blind;
            all_vote_value += vote.all_vote_value;
            all_vote_blind += vote.all_vote_blind;
        }
        let approval_ratio = (yes_vote_value as f64 * 100.0) / all_vote_value as f64;
        if all_vote_value < dao.params.dao.quorum ||
            approval_ratio <
                (dao.params.dao.approval_ratio_quot / dao.params.dao.approval_ratio_base)
                    as f64
        {
            return Err(Error::Custom(
                "[dao_exec_transfer] Proposal is not approved yet".to_string(),
            ))
        };

        // Fetch DAO unspent OwnCoins to see what its balance is for the coin
        let dao_spend_hook =
            FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
                .to_func_id();
        let dao_owncoins = self
            .get_contract_token_coins(
                &proposal_coinattrs.token_id,
                &dao_spend_hook,
                &proposal.proposal.dao_bulla.inner(),
            )
            .await?;
        if dao_owncoins.is_empty() {
            return Err(Error::Custom(format!(
                "[dao_exec_transfer] Did not find any {} unspent coins owned by this DAO",
                proposal_coinattrs.token_id,
            )))
        }

        // Check DAO balance is sufficient
        if dao_owncoins.iter().map(|x| x.note.value).sum::<u64>() < proposal_coinattrs.value {
            return Err(Error::Custom(format!(
                "[dao_exec_transfer] Not enough DAO balance for token ID: {}",
                proposal_coinattrs.token_id,
            )))
        }

        // Find which DAO coins we can use
        let (spent_coins, change_value) = select_coins(dao_owncoins, proposal_coinattrs.value)?;

        // Now we need to do a lookup for the zkas proof bincodes, and create
        // the circuit objects and proving keys so we can build the transaction.
        // We also do this through the RPC. First we grab the calls from money.
        let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;

        let Some(mint_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_MINT_NS_V1)
        else {
            return Err(Error::Custom("Mint circuit not found".to_string()))
        };

        let Some(burn_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_BURN_NS_V1)
        else {
            return Err(Error::Custom("Burn circuit not found".to_string()))
        };

        let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
        else {
            return Err(Error::Custom("Fee circuit not found".to_string()))
        };

        let mint_zkbin = ZkBinary::decode(&mint_zkbin.1)?;
        let burn_zkbin = ZkBinary::decode(&burn_zkbin.1)?;
        let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;

        let mint_circuit = ZkCircuit::new(empty_witnesses(&mint_zkbin)?, &mint_zkbin);
        let burn_circuit = ZkCircuit::new(empty_witnesses(&burn_zkbin)?, &burn_zkbin);
        let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);

        // Creating Mint, Burn and Fee circuits proving keys
        let mint_pk = ProvingKey::build(mint_zkbin.k, &mint_circuit);
        let burn_pk = ProvingKey::build(burn_zkbin.k, &burn_circuit);
        let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);

        // Now we grab the DAO bins
        let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;

        let Some(dao_exec_zkbin) = zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_EXEC_NS)
        else {
            return Err(Error::Custom("[dao_exec_transfer] DAO Exec circuit not found".to_string()))
        };

        let Some(dao_auth_transfer_zkbin) =
            zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_AUTH_MONEY_TRANSFER_NS)
        else {
            return Err(Error::Custom(
                "[dao_exec_transfer] DAO AuthTransfer circuit not found".to_string(),
            ))
        };

        let Some(dao_auth_transfer_enc_coin_zkbin) =
            zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_AUTH_MONEY_TRANSFER_ENC_COIN_NS)
        else {
            return Err(Error::Custom(
                "[dao_exec_transfer] DAO AuthTransferEncCoin circuit not found".to_string(),
            ))
        };

        let dao_exec_zkbin = ZkBinary::decode(&dao_exec_zkbin.1)?;
        let dao_auth_transfer_zkbin = ZkBinary::decode(&dao_auth_transfer_zkbin.1)?;
        let dao_auth_transfer_enc_coin_zkbin =
            ZkBinary::decode(&dao_auth_transfer_enc_coin_zkbin.1)?;

        let dao_exec_circuit = ZkCircuit::new(empty_witnesses(&dao_exec_zkbin)?, &dao_exec_zkbin);
        let dao_auth_transfer_circuit =
            ZkCircuit::new(empty_witnesses(&dao_auth_transfer_zkbin)?, &dao_auth_transfer_zkbin);
        let dao_auth_transfer_enc_coin_circuit = ZkCircuit::new(
            empty_witnesses(&dao_auth_transfer_enc_coin_zkbin)?,
            &dao_auth_transfer_enc_coin_zkbin,
        );

        // Creating DAO Exec, AuthTransfer and AuthTransferEncCoin circuits proving keys
        let dao_exec_pk = ProvingKey::build(dao_exec_zkbin.k, &dao_exec_circuit);
        let dao_auth_transfer_pk =
            ProvingKey::build(dao_auth_transfer_zkbin.k, &dao_auth_transfer_circuit);
        let dao_auth_transfer_enc_coin_pk = ProvingKey::build(
            dao_auth_transfer_enc_coin_zkbin.k,
            &dao_auth_transfer_enc_coin_circuit,
        );

        // Fetch our money Merkle tree
        let tree = self.get_money_tree().await?;

        // Now we can create the transfer call parameters
        let input_user_data_blind = Blind::random(&mut OsRng);
        let mut inputs = vec![];
        for coin in &spent_coins {
            inputs.push(TransferCallInput {
                coin: coin.clone(),
                merkle_path: tree.witness(coin.leaf_position, 0).unwrap(),
                user_data_blind: input_user_data_blind,
            });
        }

        let mut outputs = vec![];
        outputs.push(proposal_coinattrs.clone());

        let dao_coin_attrs = CoinAttributes {
            public_key: dao.keypair().public,
            value: change_value,
            token_id: proposal_coinattrs.token_id,
            spend_hook: dao_spend_hook,
            user_data: proposal.proposal.dao_bulla.inner(),
            blind: Blind::random(&mut OsRng),
        };
        outputs.push(dao_coin_attrs.clone());

        // Create the transfer call
        let transfer_builder = TransferCallBuilder {
            clear_inputs: vec![],
            inputs,
            outputs,
            mint_zkbin: mint_zkbin.clone(),
            mint_pk: mint_pk.clone(),
            burn_zkbin: burn_zkbin.clone(),
            burn_pk: burn_pk.clone(),
        };
        let (transfer_params, transfer_secrets) = transfer_builder.build()?;

        // Encode the call
        let mut data = vec![MoneyFunction::TransferV1 as u8];
        transfer_params.encode_async(&mut data).await?;
        let transfer_call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };

        // Now we need to extract the exec call parameters
        let mut input_value = 0;
        let mut input_value_blind = Blind::ZERO;
        for (input, blind) in spent_coins.iter().zip(transfer_secrets.input_value_blinds.iter()) {
            input_value += input.note.value;
            input_value_blind += *blind;
        }

        // Create the exec call
        let exec_signature_secret = SecretKey::random(&mut OsRng);
        let exec_builder = DaoExecCall {
            proposal: proposal.proposal.clone(),
            dao: dao.params.dao.clone(),
            yes_vote_value,
            all_vote_value,
            yes_vote_blind,
            all_vote_blind,
            input_value,
            input_value_blind,
            input_user_data_blind,
            hook_dao_exec: DAO_CONTRACT_ID.inner(),
            signature_secret: exec_signature_secret,
        };
        let (exec_params, exec_proofs) = exec_builder.make(&dao_exec_zkbin, &dao_exec_pk)?;

        // Encode the call
        let mut data = vec![DaoFunction::Exec as u8];
        exec_params.encode_async(&mut data).await?;
        let exec_call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };

        // Now we can create the auth call
        // Auth module
        let auth_transfer_builder = DaoAuthMoneyTransferCall {
            proposal: proposal.proposal.clone(),
            proposal_coinattrs: vec![proposal_coinattrs],
            dao: dao.params.dao.clone(),
            input_user_data_blind,
            dao_coin_attrs,
        };
        let (auth_transfer_params, auth_transfer_proofs) = auth_transfer_builder.make(
            &dao_auth_transfer_zkbin,
            &dao_auth_transfer_pk,
            &dao_auth_transfer_enc_coin_zkbin,
            &dao_auth_transfer_enc_coin_pk,
        )?;

        // Encode the call
        let mut data = vec![DaoFunction::AuthMoneyTransfer as u8];
        auth_transfer_params.encode_async(&mut data).await?;
        let auth_transfer_call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };

        // Create the TransactionBuilder containing above calls
        let mut tx_builder = TransactionBuilder::new(
            ContractCallLeaf { call: exec_call, proofs: exec_proofs },
            vec![
                DarkTree::new(
                    ContractCallLeaf { call: auth_transfer_call, proofs: auth_transfer_proofs },
                    vec![],
                    None,
                    None,
                ),
                DarkTree::new(
                    ContractCallLeaf { call: transfer_call, proofs: transfer_secrets.proofs },
                    vec![],
                    None,
                    None,
                ),
            ],
        )?;

        // We first have to execute the fee-less tx to gather its used gas, and then we feed
        // it into the fee-creating function.
        let mut tx = tx_builder.build()?;
        let auth_transfer_sigs = tx.create_sigs(&[])?;
        let transfer_sigs = tx.create_sigs(&transfer_secrets.signature_secrets)?;
        let exec_sigs = tx.create_sigs(&[exec_signature_secret])?;
        tx.signatures = vec![auth_transfer_sigs, transfer_sigs, exec_sigs];

        let (fee_call, fee_proofs, fee_secrets) =
            self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;

        // Append the fee call to the transaction
        tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;

        // Now build the actual transaction and sign it with all necessary keys.
        let mut tx = tx_builder.build()?;
        let sigs = tx.create_sigs(&[])?;
        tx.signatures.push(sigs);
        let sigs = tx.create_sigs(&transfer_secrets.signature_secrets)?;
        tx.signatures.push(sigs);
        let sigs = tx.create_sigs(&[exec_signature_secret])?;
        tx.signatures.push(sigs);
        let sigs = tx.create_sigs(&fee_secrets)?;
        tx.signatures.push(sigs);

        Ok(tx)
    }
}