dao.rs 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{collections::HashMap, fmt};
  19. use lazy_static::lazy_static;
  20. use num_bigint::BigUint;
  21. use rand::rngs::OsRng;
  22. use rusqlite::types::Value;
  23. use darkfi::{
  24. tx::{ContractCallLeaf, Transaction, TransactionBuilder},
  25. util::parse::{decode_base10, encode_base10},
  26. zk::{empty_witnesses, halo2::Field, ProvingKey, ZkCircuit},
  27. zkas::ZkBinary,
  28. Error, Result,
  29. };
  30. use darkfi_dao_contract::{
  31. blockwindow,
  32. client::{
  33. make_mint_call, DaoAuthMoneyTransferCall, DaoExecCall, DaoProposeCall,
  34. DaoProposeStakeInput, DaoVoteCall, DaoVoteInput,
  35. },
  36. model::{
  37. Dao, DaoAuthCall, DaoBulla, DaoExecParams, DaoMintParams, DaoProposal, DaoProposalBulla,
  38. DaoProposeParams, DaoVoteParams,
  39. },
  40. DaoFunction, DAO_CONTRACT_ZKAS_DAO_AUTH_MONEY_TRANSFER_ENC_COIN_NS,
  41. DAO_CONTRACT_ZKAS_DAO_AUTH_MONEY_TRANSFER_NS, DAO_CONTRACT_ZKAS_DAO_EXEC_NS,
  42. DAO_CONTRACT_ZKAS_DAO_MINT_NS, DAO_CONTRACT_ZKAS_DAO_PROPOSE_INPUT_NS,
  43. DAO_CONTRACT_ZKAS_DAO_PROPOSE_MAIN_NS, DAO_CONTRACT_ZKAS_DAO_VOTE_INPUT_NS,
  44. DAO_CONTRACT_ZKAS_DAO_VOTE_MAIN_NS,
  45. };
  46. use darkfi_money_contract::{
  47. client::transfer_v1::{select_coins, TransferCallBuilder, TransferCallInput},
  48. model::{CoinAttributes, Nullifier, TokenId},
  49. MoneyFunction, MONEY_CONTRACT_ZKAS_BURN_NS_V1, MONEY_CONTRACT_ZKAS_FEE_NS_V1,
  50. MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  51. };
  52. use darkfi_sdk::{
  53. bridgetree,
  54. crypto::{
  55. poseidon_hash,
  56. smt::{MemoryStorageFp, PoseidonFp, SmtMemoryFp, EMPTY_NODES_FP},
  57. util::{fp_mod_fv, fp_to_u64},
  58. BaseBlind, Blind, FuncId, FuncRef, Keypair, MerkleNode, MerkleTree, PublicKey, ScalarBlind,
  59. SecretKey, DAO_CONTRACT_ID, MONEY_CONTRACT_ID,
  60. },
  61. dark_tree::DarkTree,
  62. pasta::pallas,
  63. tx::TransactionHash,
  64. ContractCall,
  65. };
  66. use darkfi_serial::{
  67. async_trait, deserialize_async, serialize_async, AsyncEncodable, SerialDecodable,
  68. SerialEncodable,
  69. };
  70. use crate::{
  71. convert_named_params,
  72. error::{WalletDbError, WalletDbResult},
  73. money::{BALANCE_BASE10_DECIMALS, MONEY_SMT_COL_KEY, MONEY_SMT_COL_VALUE, MONEY_SMT_TABLE},
  74. walletdb::{WalletSmt, WalletStorage},
  75. Drk,
  76. };
  77. // Wallet SQL table constant names. These have to represent the `wallet.sql`
  78. // SQL schema. Table names are prefixed with the contract ID to avoid collisions.
  79. lazy_static! {
  80. pub static ref DAO_DAOS_TABLE: String = format!("{}_dao_daos", DAO_CONTRACT_ID.to_string());
  81. pub static ref DAO_TREES_TABLE: String = format!("{}_dao_trees", DAO_CONTRACT_ID.to_string());
  82. pub static ref DAO_COINS_TABLE: String = format!("{}_dao_coins", DAO_CONTRACT_ID.to_string());
  83. pub static ref DAO_PROPOSALS_TABLE: String =
  84. format!("{}_dao_proposals", DAO_CONTRACT_ID.to_string());
  85. pub static ref DAO_VOTES_TABLE: String = format!("{}_dao_votes", DAO_CONTRACT_ID.to_string());
  86. }
  87. // DAO_DAOS_TABLE
  88. pub const DAO_DAOS_COL_BULLA: &str = "bulla";
  89. pub const DAO_DAOS_COL_NAME: &str = "name";
  90. pub const DAO_DAOS_COL_PARAMS: &str = "params";
  91. pub const DAO_DAOS_COL_LEAF_POSITION: &str = "leaf_position";
  92. pub const DAO_DAOS_COL_TX_HASH: &str = "tx_hash";
  93. pub const DAO_DAOS_COL_CALL_INDEX: &str = "call_index";
  94. // DAO_TREES_TABLE
  95. pub const DAO_TREES_COL_DAOS_TREE: &str = "daos_tree";
  96. pub const DAO_TREES_COL_PROPOSALS_TREE: &str = "proposals_tree";
  97. // DAO_PROPOSALS_TABLE
  98. pub const DAO_PROPOSALS_COL_BULLA: &str = "bulla";
  99. pub const DAO_PROPOSALS_COL_DAO_BULLA: &str = "dao_bulla";
  100. pub const DAO_PROPOSALS_COL_PROPOSAL: &str = "proposal";
  101. pub const DAO_PROPOSALS_COL_DATA: &str = "data";
  102. pub const DAO_PROPOSALS_COL_LEAF_POSITION: &str = "leaf_position";
  103. pub const DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE: &str = "money_snapshot_tree";
  104. pub const DAO_PROPOSALS_COL_NULLIFIERS_SMT_SNAPSHOT: &str = "nullifiers_smt_snapshot";
  105. pub const DAO_PROPOSALS_COL_TX_HASH: &str = "tx_hash";
  106. pub const DAO_PROPOSALS_COL_CALL_INDEX: &str = "call_index";
  107. pub const DAO_PROPOSALS_COL_EXEC_TX_HASH: &str = "exec_tx_hash";
  108. // DAO_VOTES_TABLE
  109. pub const DAO_VOTES_COL_PROPOSAL_BULLA: &str = "proposal_bulla";
  110. pub const DAO_VOTES_COL_VOTE_OPTION: &str = "vote_option";
  111. pub const DAO_VOTES_COL_YES_VOTE_BLIND: &str = "yes_vote_blind";
  112. pub const DAO_VOTES_COL_ALL_VOTE_VALUE: &str = "all_vote_value";
  113. pub const DAO_VOTES_COL_ALL_VOTE_BLIND: &str = "all_vote_blind";
  114. pub const DAO_VOTES_COL_TX_HASH: &str = "tx_hash";
  115. pub const DAO_VOTES_COL_CALL_INDEX: &str = "call_index";
  116. pub const DAO_VOTES_COL_NULLIFIERS: &str = "nullifiers";
  117. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  118. /// Parameters representing a DAO to be initialized
  119. pub struct DaoParams {
  120. /// The on chain representation of the DAO
  121. pub dao: Dao,
  122. /// Secret key for the DAO
  123. pub secret_key: SecretKey,
  124. }
  125. impl DaoParams {
  126. pub fn new(
  127. proposer_limit: u64,
  128. quorum: u64,
  129. approval_ratio_base: u64,
  130. approval_ratio_quot: u64,
  131. gov_token_id: TokenId,
  132. secret_key: SecretKey,
  133. bulla_blind: BaseBlind,
  134. ) -> Self {
  135. let dao = Dao {
  136. proposer_limit,
  137. quorum,
  138. approval_ratio_base,
  139. approval_ratio_quot,
  140. gov_token_id,
  141. public_key: PublicKey::from_secret(secret_key),
  142. bulla_blind,
  143. };
  144. Self { dao, secret_key }
  145. }
  146. }
  147. impl fmt::Display for DaoParams {
  148. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  149. let s = format!(
  150. "{}\n{}\n{}: {} ({})\n{}: {} ({})\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {:?}",
  151. "DAO Parameters",
  152. "==============",
  153. "Proposer limit",
  154. encode_base10(self.dao.proposer_limit, BALANCE_BASE10_DECIMALS),
  155. self.dao.proposer_limit,
  156. "Quorum",
  157. encode_base10(self.dao.quorum, BALANCE_BASE10_DECIMALS),
  158. self.dao.quorum,
  159. "Approval ratio",
  160. self.dao.approval_ratio_quot as f64 / self.dao.approval_ratio_base as f64,
  161. "Governance Token ID",
  162. self.dao.gov_token_id,
  163. "Public key",
  164. self.dao.public_key,
  165. "Secret key",
  166. self.secret_key,
  167. "Bulla blind",
  168. self.dao.bulla_blind,
  169. );
  170. write!(f, "{}", s)
  171. }
  172. }
  173. #[derive(Debug, Clone)]
  174. /// Structure representing a `DAO_DAOS_TABLE` record.
  175. pub struct DaoRecord {
  176. /// Name identifier for the DAO
  177. pub name: String,
  178. /// DAO parameters
  179. pub params: DaoParams,
  180. /// Leaf position of the DAO in the Merkle tree of DAOs
  181. pub leaf_position: Option<bridgetree::Position>,
  182. /// The transaction hash where the DAO was deployed
  183. pub tx_hash: Option<TransactionHash>,
  184. /// The call index in the transaction where the DAO was deployed
  185. pub call_index: Option<u8>,
  186. }
  187. impl DaoRecord {
  188. pub fn new(
  189. name: String,
  190. params: DaoParams,
  191. leaf_position: Option<bridgetree::Position>,
  192. tx_hash: Option<TransactionHash>,
  193. call_index: Option<u8>,
  194. ) -> Self {
  195. Self { name, params, leaf_position, tx_hash, call_index }
  196. }
  197. pub fn bulla(&self) -> DaoBulla {
  198. self.params.dao.to_bulla()
  199. }
  200. pub fn keypair(&self) -> Keypair {
  201. let public = PublicKey::from_secret(self.params.secret_key);
  202. Keypair { public, secret: self.params.secret_key }
  203. }
  204. }
  205. impl fmt::Display for DaoRecord {
  206. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  207. let leaf_position = match self.leaf_position {
  208. Some(p) => format!("{p:?}"),
  209. None => "None".to_string(),
  210. };
  211. let tx_hash = match self.tx_hash {
  212. Some(t) => format!("{t}"),
  213. None => "None".to_string(),
  214. };
  215. let call_index = match self.call_index {
  216. Some(c) => format!("{c}"),
  217. None => "None".to_string(),
  218. };
  219. let s = format!(
  220. "{}\n{}\n{}: {}\n{}: {}\n{}: {} ({})\n{}: {} ({})\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}",
  221. "DAO Parameters",
  222. "==============",
  223. "Name",
  224. self.name,
  225. "Bulla",
  226. self.bulla(),
  227. "Proposer limit",
  228. encode_base10(self.params.dao.proposer_limit, BALANCE_BASE10_DECIMALS),
  229. self.params.dao.proposer_limit,
  230. "Quorum",
  231. encode_base10(self.params.dao.quorum, BALANCE_BASE10_DECIMALS),
  232. self.params.dao.quorum,
  233. "Approval ratio",
  234. self.params.dao.approval_ratio_quot as f64 / self.params.dao.approval_ratio_base as f64,
  235. "Governance Token ID",
  236. self.params.dao.gov_token_id,
  237. "Public key",
  238. self.params.dao.public_key,
  239. "Secret key",
  240. self.params.secret_key,
  241. "Bulla blind",
  242. self.params.dao.bulla_blind,
  243. "Leaf position",
  244. leaf_position,
  245. "Transaction hash",
  246. tx_hash,
  247. "Call index",
  248. call_index,
  249. );
  250. write!(f, "{}", s)
  251. }
  252. }
  253. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  254. /// Structure representing a `DAO_PROPOSALS_TABLE` record.
  255. pub struct ProposalRecord {
  256. /// The on chain representation of the proposal
  257. pub proposal: DaoProposal,
  258. /// Plaintext proposal call data the members share between them
  259. pub data: Option<Vec<u8>>,
  260. /// Leaf position of the proposal in the Merkle tree of proposals
  261. pub leaf_position: Option<bridgetree::Position>,
  262. /// Money merkle tree snapshot for reproducing the snapshot Merkle root
  263. pub money_snapshot_tree: Option<MerkleTree>,
  264. /// Money nullifiers SMT snapshot for reproducing the snapshot Merkle root
  265. pub nullifiers_smt_snapshot: Option<HashMap<BigUint, pallas::Base>>,
  266. /// The transaction hash where the proposal was deployed
  267. pub tx_hash: Option<TransactionHash>,
  268. /// The call index in the transaction where the proposal was deployed
  269. pub call_index: Option<u8>,
  270. /// The transaction hash where the proposal was executed
  271. pub exec_tx_hash: Option<TransactionHash>,
  272. }
  273. impl ProposalRecord {
  274. pub fn bulla(&self) -> DaoProposalBulla {
  275. self.proposal.to_bulla()
  276. }
  277. }
  278. impl fmt::Display for ProposalRecord {
  279. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  280. let leaf_position = match self.leaf_position {
  281. Some(p) => format!("{p:?}"),
  282. None => "None".to_string(),
  283. };
  284. let tx_hash = match self.tx_hash {
  285. Some(t) => format!("{t}"),
  286. None => "None".to_string(),
  287. };
  288. let call_index = match self.call_index {
  289. Some(c) => format!("{c}"),
  290. None => "None".to_string(),
  291. };
  292. let s = format!(
  293. "{}\n{}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {} ({})",
  294. "Proposal parameters",
  295. "===================",
  296. "Bulla",
  297. self.bulla(),
  298. "DAO Bulla",
  299. self.proposal.dao_bulla,
  300. "Proposal leaf position",
  301. leaf_position,
  302. "Proposal transaction hash",
  303. tx_hash,
  304. "Proposal call index",
  305. call_index,
  306. "Creation block window",
  307. self.proposal.creation_blockwindow,
  308. "Duration",
  309. self.proposal.duration_blockwindows,
  310. "Block windows"
  311. );
  312. write!(f, "{}", s)
  313. }
  314. }
  315. #[derive(Debug, Clone)]
  316. /// Structure representing a `DAO_VOTES_TABLE` record.
  317. pub struct VoteRecord {
  318. /// Numeric identifier for the vote
  319. pub id: u64,
  320. /// Bulla identifier of the proposal this vote is for
  321. pub proposal: DaoProposalBulla,
  322. /// The vote
  323. pub vote_option: bool,
  324. /// Blinding factor for the yes vote
  325. pub yes_vote_blind: ScalarBlind,
  326. /// Value of all votes
  327. pub all_vote_value: u64,
  328. /// Blinding facfor of all votes
  329. pub all_vote_blind: ScalarBlind,
  330. /// Transaction hash where this vote was casted
  331. pub tx_hash: TransactionHash,
  332. /// Call index in the transaction where this vote was casted
  333. pub call_index: u8,
  334. /// Vote input nullifiers
  335. pub nullifiers: Vec<Nullifier>,
  336. }
  337. impl Drk {
  338. /// Initialize wallet with tables for the DAO contract.
  339. pub async fn initialize_dao(&self) -> WalletDbResult<()> {
  340. // Initialize DAO wallet schema
  341. let wallet_schema = include_str!("../dao.sql");
  342. self.wallet.exec_batch_sql(wallet_schema)?;
  343. // Check if we have to initialize the Merkle trees.
  344. // We check if one exists, but we actually create two. This should be written
  345. // a bit better and safer.
  346. // For now, on success, we don't care what's returned, but in the future
  347. // we should actually check it.
  348. if self.wallet.query_single(&DAO_TREES_TABLE, &[DAO_TREES_COL_DAOS_TREE], &[]).is_err() {
  349. println!("Initializing DAO Merkle trees");
  350. let tree = MerkleTree::new(1);
  351. self.put_dao_trees(&tree, &tree).await?;
  352. println!("Successfully initialized Merkle trees for the DAO contract");
  353. }
  354. Ok(())
  355. }
  356. /// Replace the DAO Merkle trees in the wallet.
  357. pub async fn put_dao_trees(
  358. &self,
  359. daos_tree: &MerkleTree,
  360. proposals_tree: &MerkleTree,
  361. ) -> WalletDbResult<()> {
  362. // First we remove old records
  363. let query = format!("DELETE FROM {};", *DAO_TREES_TABLE);
  364. self.wallet.exec_sql(&query, &[])?;
  365. // then we insert the new one
  366. let query = format!(
  367. "INSERT INTO {} ({}, {}) VALUES (?1, ?2);",
  368. *DAO_TREES_TABLE, DAO_TREES_COL_DAOS_TREE, DAO_TREES_COL_PROPOSALS_TREE,
  369. );
  370. self.wallet.exec_sql(
  371. &query,
  372. rusqlite::params![
  373. serialize_async(daos_tree).await,
  374. serialize_async(proposals_tree).await
  375. ],
  376. )
  377. }
  378. /// Fetch DAO Merkle trees from the wallet.
  379. pub async fn get_dao_trees(&self) -> Result<(MerkleTree, MerkleTree)> {
  380. let row = match self.wallet.query_single(&DAO_TREES_TABLE, &[], &[]) {
  381. Ok(r) => r,
  382. Err(e) => {
  383. return Err(Error::DatabaseError(format!(
  384. "[get_dao_trees] Trees retrieval failed: {e:?}"
  385. )))
  386. }
  387. };
  388. let Value::Blob(ref daos_tree_bytes) = row[0] else {
  389. return Err(Error::ParseFailed("[get_dao_trees] DAO tree bytes parsing failed"))
  390. };
  391. let daos_tree = deserialize_async(daos_tree_bytes).await?;
  392. let Value::Blob(ref proposals_tree_bytes) = row[1] else {
  393. return Err(Error::ParseFailed("[get_dao_trees] Proposals tree bytes parsing failed"))
  394. };
  395. let proposals_tree = deserialize_async(proposals_tree_bytes).await?;
  396. Ok((daos_tree, proposals_tree))
  397. }
  398. /// Fetch all DAO secret keys from the wallet.
  399. pub async fn get_dao_secrets(&self) -> Result<Vec<SecretKey>> {
  400. let daos = self.get_daos().await?;
  401. let mut ret = Vec::with_capacity(daos.len());
  402. for dao in daos {
  403. ret.push(dao.params.secret_key);
  404. }
  405. Ok(ret)
  406. }
  407. /// Auxiliary function to parse a `DAO_DAOS_TABLE` record.
  408. async fn parse_dao_record(&self, row: &[Value]) -> Result<DaoRecord> {
  409. let Value::Text(ref name) = row[1] else {
  410. return Err(Error::ParseFailed("[parse_dao_record] Name parsing failed"))
  411. };
  412. let name = name.clone();
  413. let Value::Blob(ref params_bytes) = row[2] else {
  414. return Err(Error::ParseFailed("[parse_dao_record] Params bytes parsing failed"))
  415. };
  416. let params = deserialize_async(params_bytes).await?;
  417. let leaf_position = match row[3] {
  418. Value::Blob(ref leaf_position_bytes) => {
  419. Some(deserialize_async(leaf_position_bytes).await?)
  420. }
  421. Value::Null => None,
  422. _ => {
  423. return Err(Error::ParseFailed(
  424. "[parse_dao_record] Leaf position bytes parsing failed",
  425. ))
  426. }
  427. };
  428. let tx_hash = match row[4] {
  429. Value::Blob(ref tx_hash_bytes) => Some(deserialize_async(tx_hash_bytes).await?),
  430. Value::Null => None,
  431. _ => {
  432. return Err(Error::ParseFailed(
  433. "[parse_dao_record] Transaction hash bytes parsing failed",
  434. ))
  435. }
  436. };
  437. let call_index = match row[5] {
  438. Value::Integer(call_index) => {
  439. let Ok(call_index) = u8::try_from(call_index) else {
  440. return Err(Error::ParseFailed("[parse_dao_record] Call index parsing failed"))
  441. };
  442. Some(call_index)
  443. }
  444. Value::Null => None,
  445. _ => return Err(Error::ParseFailed("[parse_dao_record] Call index parsing failed")),
  446. };
  447. let dao = DaoRecord::new(name, params, leaf_position, tx_hash, call_index);
  448. Ok(dao)
  449. }
  450. /// Fetch all known DAOs from the wallet.
  451. pub async fn get_daos(&self) -> Result<Vec<DaoRecord>> {
  452. let rows = match self.wallet.query_multiple(&DAO_DAOS_TABLE, &[], &[]) {
  453. Ok(r) => r,
  454. Err(e) => {
  455. return Err(Error::DatabaseError(format!("[get_daos] DAOs retrieval failed: {e:?}")))
  456. }
  457. };
  458. let mut daos = Vec::with_capacity(rows.len());
  459. for row in rows {
  460. daos.push(self.parse_dao_record(&row).await?);
  461. }
  462. Ok(daos)
  463. }
  464. /// Auxiliary function to parse a proposal record row.
  465. async fn parse_dao_proposal(&self, row: &[Value]) -> Result<ProposalRecord> {
  466. let Value::Blob(ref proposal_bytes) = row[2] else {
  467. return Err(Error::ParseFailed(
  468. "[get_dao_proposals] Proposal bytes bytes parsing failed",
  469. ))
  470. };
  471. let proposal = deserialize_async(proposal_bytes).await?;
  472. let data = match row[3] {
  473. Value::Blob(ref data_bytes) => Some(data_bytes.clone()),
  474. Value::Null => None,
  475. _ => return Err(Error::ParseFailed("[get_dao_proposals] Data bytes parsing failed")),
  476. };
  477. let leaf_position = match row[4] {
  478. Value::Blob(ref leaf_position_bytes) => {
  479. Some(deserialize_async(leaf_position_bytes).await?)
  480. }
  481. Value::Null => None,
  482. _ => {
  483. return Err(Error::ParseFailed(
  484. "[get_dao_proposals] Leaf position bytes parsing failed",
  485. ))
  486. }
  487. };
  488. let money_snapshot_tree = match row[5] {
  489. Value::Blob(ref money_snapshot_tree_bytes) => {
  490. Some(deserialize_async(money_snapshot_tree_bytes).await?)
  491. }
  492. Value::Null => None,
  493. _ => {
  494. return Err(Error::ParseFailed(
  495. "[get_dao_proposals] Money snapshot tree bytes parsing failed",
  496. ))
  497. }
  498. };
  499. let nullifiers_smt_snapshot = match row[6] {
  500. Value::Blob(ref nullifiers_smt_snapshot_bytes) => {
  501. Some(deserialize_async(nullifiers_smt_snapshot_bytes).await?)
  502. }
  503. Value::Null => None,
  504. _ => {
  505. return Err(Error::ParseFailed(
  506. "[get_dao_proposals] Nullifiers SMT snapshot bytes parsing failed",
  507. ))
  508. }
  509. };
  510. let tx_hash = match row[7] {
  511. Value::Blob(ref tx_hash_bytes) => Some(deserialize_async(tx_hash_bytes).await?),
  512. Value::Null => None,
  513. _ => {
  514. return Err(Error::ParseFailed(
  515. "[get_dao_proposals] Transaction hash bytes parsing failed",
  516. ))
  517. }
  518. };
  519. let call_index = match row[8] {
  520. Value::Integer(call_index) => {
  521. let Ok(call_index) = u8::try_from(call_index) else {
  522. return Err(Error::ParseFailed("[get_dao_proposals] Call index parsing failed"))
  523. };
  524. Some(call_index)
  525. }
  526. Value::Null => None,
  527. _ => return Err(Error::ParseFailed("[get_dao_proposals] Call index parsing failed")),
  528. };
  529. let exec_tx_hash = match row[9] {
  530. Value::Blob(ref exec_tx_hash_bytes) => {
  531. Some(deserialize_async(exec_tx_hash_bytes).await?)
  532. }
  533. Value::Null => None,
  534. _ => {
  535. return Err(Error::ParseFailed(
  536. "[get_dao_proposals] Execution transaction hash bytes parsing failed",
  537. ))
  538. }
  539. };
  540. Ok(ProposalRecord {
  541. proposal,
  542. data,
  543. leaf_position,
  544. money_snapshot_tree,
  545. nullifiers_smt_snapshot,
  546. tx_hash,
  547. call_index,
  548. exec_tx_hash,
  549. })
  550. }
  551. /// Fetch all known DAO proposals from the wallet given a DAO name.
  552. pub async fn get_dao_proposals(&self, name: &str) -> Result<Vec<ProposalRecord>> {
  553. let Ok(dao) = self.get_dao_by_name(name).await else {
  554. return Err(Error::DatabaseError(format!(
  555. "[get_dao_proposals] DAO with name {name} not found in wallet"
  556. )))
  557. };
  558. let rows = match self.wallet.query_multiple(
  559. &DAO_PROPOSALS_TABLE,
  560. &[],
  561. convert_named_params! {(DAO_PROPOSALS_COL_DAO_BULLA, serialize_async(&dao.bulla()).await)},
  562. ) {
  563. Ok(r) => r,
  564. Err(e) => {
  565. return Err(Error::DatabaseError(format!(
  566. "[get_dao_proposals] Proposals retrieval failed: {e:?}"
  567. )))
  568. }
  569. };
  570. let mut proposals = Vec::with_capacity(rows.len());
  571. for row in rows {
  572. let proposal = self.parse_dao_proposal(&row).await?;
  573. proposals.push(proposal);
  574. }
  575. Ok(proposals)
  576. }
  577. // Auxiliary function to apply `DaoFunction::Mint` call data to the wallet.
  578. async fn apply_dao_mint_data(
  579. &self,
  580. new_bulla: DaoBulla,
  581. tx_hash: TransactionHash,
  582. call_index: u8,
  583. ) -> Result<()> {
  584. let daos = self.get_daos().await?;
  585. let (mut daos_tree, proposals_tree) = self.get_dao_trees().await?;
  586. daos_tree.append(MerkleNode::from(new_bulla.inner()));
  587. for dao in &daos {
  588. if dao.bulla() == new_bulla {
  589. println!(
  590. "[apply_dao_mint_data] Found minted DAO {}, noting down for wallet update",
  591. new_bulla
  592. );
  593. // We have this DAO imported in our wallet. Add the metadata:
  594. let mut dao_to_confirm = dao.clone();
  595. dao_to_confirm.leaf_position = daos_tree.mark();
  596. dao_to_confirm.tx_hash = Some(tx_hash);
  597. dao_to_confirm.call_index = Some(call_index);
  598. // Update wallet data
  599. if let Err(e) = self.put_dao_trees(&daos_tree, &proposals_tree).await {
  600. return Err(Error::DatabaseError(format!(
  601. "[apply_dao_mint_data] Put DAO tree failed: {e:?}"
  602. )))
  603. }
  604. if let Err(e) = self.confirm_dao(&dao_to_confirm).await {
  605. return Err(Error::DatabaseError(format!(
  606. "[apply_dao_mint_data] Confirm DAO failed: {e:?}"
  607. )))
  608. }
  609. break
  610. }
  611. }
  612. Ok(())
  613. }
  614. // Auxiliary function to apply `DaoFunction::Propose` call data to the wallet.
  615. async fn apply_dao_propose_data(
  616. &self,
  617. params: DaoProposeParams,
  618. tx_hash: TransactionHash,
  619. call_index: u8,
  620. ) -> Result<()> {
  621. let daos = self.get_daos().await?;
  622. let (daos_tree, mut proposals_tree) = self.get_dao_trees().await?;
  623. proposals_tree.append(MerkleNode::from(params.proposal_bulla.inner()));
  624. // If we're able to decrypt this note, that's the way to link it
  625. // to a specific DAO.
  626. for dao in &daos {
  627. if let Ok(note) = params.note.decrypt::<DaoProposal>(&dao.params.secret_key) {
  628. // We managed to decrypt it. Let's place this in a proper ProposalRecord object
  629. println!("[apply_dao_propose_data] Managed to decrypt DAO proposal note");
  630. // We need to clone the trees here for reproducing the snapshot Merkle roots
  631. let money_tree = self.get_money_tree().await?;
  632. let nullifiers_smt = self.get_nullifiers_smt().await?;
  633. // Check if we already got the record
  634. let our_proposal =
  635. match self.get_dao_proposal_by_bulla(&params.proposal_bulla).await {
  636. Ok(p) => {
  637. let mut our_proposal = p;
  638. our_proposal.leaf_position = proposals_tree.mark();
  639. our_proposal.money_snapshot_tree = Some(money_tree);
  640. our_proposal.nullifiers_smt_snapshot = Some(nullifiers_smt);
  641. our_proposal.tx_hash = Some(tx_hash);
  642. our_proposal.call_index = Some(call_index);
  643. our_proposal
  644. }
  645. Err(_) => ProposalRecord {
  646. proposal: note,
  647. data: None,
  648. leaf_position: proposals_tree.mark(),
  649. money_snapshot_tree: Some(money_tree),
  650. nullifiers_smt_snapshot: Some(nullifiers_smt),
  651. tx_hash: Some(tx_hash),
  652. call_index: Some(call_index),
  653. exec_tx_hash: None,
  654. },
  655. };
  656. if let Err(e) = self.put_dao_trees(&daos_tree, &proposals_tree).await {
  657. return Err(Error::DatabaseError(format!(
  658. "[apply_dao_propose_data] Put DAO tree failed: {e:?}"
  659. )))
  660. }
  661. if let Err(e) = self.put_dao_proposal(&our_proposal).await {
  662. return Err(Error::DatabaseError(format!(
  663. "[apply_dao_propose_data] Put DAO proposals failed: {e:?}"
  664. )))
  665. }
  666. break
  667. }
  668. }
  669. Ok(())
  670. }
  671. // Auxiliary function to apply `DaoFunction::Vote` call data to the wallet.
  672. async fn apply_dao_vote_data(
  673. &self,
  674. params: DaoVoteParams,
  675. tx_hash: TransactionHash,
  676. call_index: u8,
  677. ) -> Result<()> {
  678. // Check if we got the corresponding proposal
  679. let Ok(proposal) = self.get_dao_proposal_by_bulla(&params.proposal_bulla).await else {
  680. return Ok(())
  681. };
  682. // Grab the proposal DAO
  683. let dao = match self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
  684. Ok(d) => d,
  685. Err(e) => {
  686. return Err(Error::DatabaseError(format!(
  687. "[apply_dao_vote_data] Couldn't find proposal {} DAO {}: {e}",
  688. proposal.bulla(),
  689. proposal.proposal.dao_bulla,
  690. )))
  691. }
  692. };
  693. // Decrypt the vote note
  694. let note = match params.note.decrypt_unsafe(&dao.params.secret_key) {
  695. Ok(n) => n,
  696. Err(e) => {
  697. return Err(Error::DatabaseError(format!(
  698. "[apply_dao_vote_data] Couldn't decrypt proposal {} vote with DAO {} keys: {e}",
  699. proposal.bulla(),
  700. proposal.proposal.dao_bulla,
  701. )))
  702. }
  703. };
  704. // Create the DAO vote record
  705. let vote_option = fp_to_u64(note[0]).unwrap();
  706. if vote_option > 1 {
  707. return Err(Error::DatabaseError(format!(
  708. "[apply_dao_vote_data] Malformed vote for proposal {}: {vote_option}",
  709. proposal.bulla(),
  710. )))
  711. }
  712. let vote_option = vote_option != 0;
  713. let yes_vote_blind = Blind(fp_mod_fv(note[1]));
  714. let all_vote_value = fp_to_u64(note[2]).unwrap();
  715. let all_vote_blind = Blind(fp_mod_fv(note[3]));
  716. let v = VoteRecord {
  717. id: 0, // This will be set by SQLite AUTOINCREMENT
  718. proposal: params.proposal_bulla,
  719. vote_option,
  720. yes_vote_blind,
  721. all_vote_value,
  722. all_vote_blind,
  723. tx_hash,
  724. call_index,
  725. nullifiers: params.inputs.iter().map(|i| i.vote_nullifier).collect(),
  726. };
  727. if let Err(e) = self.put_dao_vote(&v).await {
  728. return Err(Error::DatabaseError(format!(
  729. "[apply_dao_vote_data] Put DAO votes failed: {e:?}"
  730. )))
  731. }
  732. Ok(())
  733. }
  734. // Auxiliary function to apply `DaoFunction::Exec` call data to the wallet.
  735. async fn apply_dao_exec_data(
  736. &self,
  737. params: DaoExecParams,
  738. tx_hash: TransactionHash,
  739. ) -> Result<()> {
  740. // Check if we got the corresponding proposal
  741. let Ok(mut proposal) = self.get_dao_proposal_by_bulla(&params.proposal_bulla).await else {
  742. return Ok(())
  743. };
  744. // Update its exec transaction hash
  745. proposal.exec_tx_hash = Some(tx_hash);
  746. if let Err(e) = self.put_dao_proposal(&proposal).await {
  747. return Err(Error::DatabaseError(format!(
  748. "[apply_dao_exec_data] Put DAO proposal failed: {e:?}"
  749. )))
  750. }
  751. Ok(())
  752. }
  753. /// Append data related to DAO contract transactions into the wallet database.
  754. pub async fn apply_tx_dao_data(
  755. &self,
  756. data: &[u8],
  757. tx_hash: TransactionHash,
  758. call_idx: u8,
  759. ) -> Result<()> {
  760. // Run through the transaction call data and see what we got:
  761. match DaoFunction::try_from(data[0])? {
  762. DaoFunction::Mint => {
  763. println!("[apply_tx_dao_data] Found Dao::Mint call");
  764. let params: DaoMintParams = deserialize_async(&data[1..]).await?;
  765. self.apply_dao_mint_data(params.dao_bulla, tx_hash, call_idx).await
  766. }
  767. DaoFunction::Propose => {
  768. println!("[apply_tx_dao_data] Found Dao::Propose call");
  769. let params: DaoProposeParams = deserialize_async(&data[1..]).await?;
  770. self.apply_dao_propose_data(params, tx_hash, call_idx).await
  771. }
  772. DaoFunction::Vote => {
  773. println!("[apply_tx_dao_data] Found Dao::Vote call");
  774. let params: DaoVoteParams = deserialize_async(&data[1..]).await?;
  775. self.apply_dao_vote_data(params, tx_hash, call_idx).await
  776. }
  777. DaoFunction::Exec => {
  778. println!("[apply_tx_dao_data] Found Dao::Exec call");
  779. let params: DaoExecParams = deserialize_async(&data[1..]).await?;
  780. self.apply_dao_exec_data(params, tx_hash).await
  781. }
  782. DaoFunction::AuthMoneyTransfer => {
  783. println!("[apply_tx_dao_data] Found Dao::AuthMoneyTransfer call");
  784. // Does nothing, just verifies the other calls are correct
  785. Ok(())
  786. }
  787. }
  788. }
  789. /// Confirm already imported DAO metadata into the wallet.
  790. /// Here we just write the leaf position, tx hash, and call index.
  791. /// Panics if the fields are None.
  792. pub async fn confirm_dao(&self, dao: &DaoRecord) -> WalletDbResult<()> {
  793. let query = format!(
  794. "UPDATE {} SET {} = ?1, {} = ?2, {} = ?3 WHERE {} = ?4;",
  795. *DAO_DAOS_TABLE,
  796. DAO_DAOS_COL_LEAF_POSITION,
  797. DAO_DAOS_COL_TX_HASH,
  798. DAO_DAOS_COL_CALL_INDEX,
  799. DAO_DAOS_COL_BULLA
  800. );
  801. self.wallet.exec_sql(
  802. &query,
  803. rusqlite::params![
  804. serialize_async(&dao.leaf_position.unwrap()).await,
  805. serialize_async(&dao.tx_hash.unwrap()).await,
  806. dao.call_index.unwrap(),
  807. serialize_async(&dao.bulla()).await,
  808. ],
  809. )
  810. }
  811. /// Unconfirm imported DAOs by removing the leaf position, tx hash, and call index.
  812. pub async fn unconfirm_daos(&self, daos: &[DaoRecord]) -> WalletDbResult<()> {
  813. for dao in daos {
  814. let query = format!(
  815. "UPDATE {} SET {} = ?1, {} = ?2, {} = ?3 WHERE {} = ?4;",
  816. *DAO_DAOS_TABLE,
  817. DAO_DAOS_COL_LEAF_POSITION,
  818. DAO_DAOS_COL_TX_HASH,
  819. DAO_DAOS_COL_CALL_INDEX,
  820. DAO_DAOS_COL_BULLA
  821. );
  822. self.wallet.exec_sql(
  823. &query,
  824. rusqlite::params![
  825. None::<Vec<u8>>,
  826. None::<Vec<u8>>,
  827. None::<u64>,
  828. serialize_async(&dao.bulla()).await
  829. ],
  830. )?;
  831. }
  832. Ok(())
  833. }
  834. /// Import given DAO proposal into the wallet.
  835. pub async fn put_dao_proposal(&self, proposal: &ProposalRecord) -> Result<()> {
  836. if let Err(e) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
  837. return Err(Error::DatabaseError(format!(
  838. "[put_dao_proposal] Couldn't find proposal {} DAO {}: {e}",
  839. proposal.bulla(),
  840. proposal.proposal.dao_bulla
  841. )))
  842. }
  843. let query = format!(
  844. "INSERT OR REPLACE INTO {} ({}, {}, {}, {}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10);",
  845. *DAO_PROPOSALS_TABLE,
  846. DAO_PROPOSALS_COL_BULLA,
  847. DAO_PROPOSALS_COL_DAO_BULLA,
  848. DAO_PROPOSALS_COL_PROPOSAL,
  849. DAO_PROPOSALS_COL_DATA,
  850. DAO_PROPOSALS_COL_LEAF_POSITION,
  851. DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE,
  852. DAO_PROPOSALS_COL_NULLIFIERS_SMT_SNAPSHOT,
  853. DAO_PROPOSALS_COL_TX_HASH,
  854. DAO_PROPOSALS_COL_CALL_INDEX,
  855. DAO_PROPOSALS_COL_EXEC_TX_HASH,
  856. );
  857. let data = match &proposal.data {
  858. Some(data) => Some(data),
  859. None => None,
  860. };
  861. let leaf_position = match &proposal.leaf_position {
  862. Some(leaf_position) => Some(serialize_async(leaf_position).await),
  863. None => None,
  864. };
  865. let money_snapshot_tree = match &proposal.money_snapshot_tree {
  866. Some(money_snapshot_tree) => Some(serialize_async(money_snapshot_tree).await),
  867. None => None,
  868. };
  869. let nullifiers_smt_snapshot = match &proposal.nullifiers_smt_snapshot {
  870. Some(nullifiers_smt_snapshot) => Some(serialize_async(nullifiers_smt_snapshot).await),
  871. None => None,
  872. };
  873. let tx_hash = match &proposal.tx_hash {
  874. Some(tx_hash) => Some(serialize_async(tx_hash).await),
  875. None => None,
  876. };
  877. let exec_tx_hash = match &proposal.exec_tx_hash {
  878. Some(exec_tx_hash) => Some(serialize_async(exec_tx_hash).await),
  879. None => None,
  880. };
  881. if let Err(e) = self.wallet.exec_sql(
  882. &query,
  883. rusqlite::params![
  884. serialize_async(&proposal.bulla()).await,
  885. serialize_async(&proposal.proposal.dao_bulla).await,
  886. serialize_async(&proposal.proposal).await,
  887. data,
  888. leaf_position,
  889. money_snapshot_tree,
  890. nullifiers_smt_snapshot,
  891. tx_hash,
  892. proposal.call_index,
  893. exec_tx_hash,
  894. ],
  895. ) {
  896. return Err(Error::DatabaseError(format!(
  897. "[put_dao_proposal] Proposal insert failed: {e:?}"
  898. )))
  899. };
  900. Ok(())
  901. }
  902. /// Unconfirm imported DAO proposals by removing the leaf position, tx hash, and call index.
  903. pub async fn unconfirm_proposals(&self, proposals: &[ProposalRecord]) -> WalletDbResult<()> {
  904. for proposal in proposals {
  905. let query = format!(
  906. "UPDATE {} SET {} = ?1, {} = ?2, {} = ?3, {} = ?4, {} = ?5, {} = ?6 WHERE {} = ?7;",
  907. *DAO_PROPOSALS_TABLE,
  908. DAO_PROPOSALS_COL_LEAF_POSITION,
  909. DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE,
  910. DAO_PROPOSALS_COL_NULLIFIERS_SMT_SNAPSHOT,
  911. DAO_PROPOSALS_COL_TX_HASH,
  912. DAO_PROPOSALS_COL_CALL_INDEX,
  913. DAO_PROPOSALS_COL_EXEC_TX_HASH,
  914. DAO_PROPOSALS_COL_BULLA
  915. );
  916. self.wallet.exec_sql(
  917. &query,
  918. rusqlite::params![
  919. None::<Vec<u8>>,
  920. None::<Vec<u8>>,
  921. None::<Vec<u8>>,
  922. None::<Vec<u8>>,
  923. None::<u64>,
  924. None::<Vec<u8>>,
  925. serialize_async(&proposal.bulla()).await
  926. ],
  927. )?;
  928. }
  929. Ok(())
  930. }
  931. /// Import given DAO votes into the wallet.
  932. pub async fn put_dao_vote(&self, vote: &VoteRecord) -> WalletDbResult<()> {
  933. eprintln!("Importing DAO vote into wallet");
  934. let query = format!(
  935. "INSERT INTO {} ({}, {}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8);",
  936. *DAO_VOTES_TABLE,
  937. DAO_VOTES_COL_PROPOSAL_BULLA,
  938. DAO_VOTES_COL_VOTE_OPTION,
  939. DAO_VOTES_COL_YES_VOTE_BLIND,
  940. DAO_VOTES_COL_ALL_VOTE_VALUE,
  941. DAO_VOTES_COL_ALL_VOTE_BLIND,
  942. DAO_VOTES_COL_TX_HASH,
  943. DAO_VOTES_COL_CALL_INDEX,
  944. DAO_VOTES_COL_NULLIFIERS,
  945. );
  946. self.wallet.exec_sql(
  947. &query,
  948. rusqlite::params![
  949. serialize_async(&vote.proposal).await,
  950. vote.vote_option as u64,
  951. serialize_async(&vote.yes_vote_blind).await,
  952. serialize_async(&vote.all_vote_value).await,
  953. serialize_async(&vote.all_vote_blind).await,
  954. serialize_async(&vote.tx_hash).await,
  955. vote.call_index,
  956. serialize_async(&vote.nullifiers).await,
  957. ],
  958. )?;
  959. println!("DAO vote added to wallet");
  960. Ok(())
  961. }
  962. /// Reset the DAO Merkle trees in the wallet.
  963. pub async fn reset_dao_trees(&self) -> WalletDbResult<()> {
  964. println!("Resetting DAO Merkle trees");
  965. let tree = MerkleTree::new(1);
  966. self.put_dao_trees(&tree, &tree).await?;
  967. println!("Successfully reset DAO Merkle trees");
  968. Ok(())
  969. }
  970. /// Reset confirmed DAOs in the wallet.
  971. pub async fn reset_daos(&self) -> WalletDbResult<()> {
  972. println!("Resetting DAO confirmations");
  973. let daos = match self.get_daos().await {
  974. Ok(d) => d,
  975. Err(e) => {
  976. println!("[reset_daos] DAOs retrieval failed: {e:?}");
  977. return Err(WalletDbError::GenericError);
  978. }
  979. };
  980. self.unconfirm_daos(&daos).await?;
  981. println!("Successfully unconfirmed DAOs");
  982. Ok(())
  983. }
  984. /// Reset all DAO proposals in the wallet.
  985. pub async fn reset_dao_proposals(&self) -> WalletDbResult<()> {
  986. println!("Resetting DAO proposals confirmations");
  987. let proposals = match self.get_proposals().await {
  988. Ok(p) => p,
  989. Err(e) => {
  990. println!("[reset_dao_proposals] DAO proposals retrieval failed: {e:?}");
  991. return Err(WalletDbError::GenericError);
  992. }
  993. };
  994. self.unconfirm_proposals(&proposals).await?;
  995. println!("Successfully unconfirmed DAO proposals");
  996. Ok(())
  997. }
  998. /// Reset all DAO votes in the wallet.
  999. pub fn reset_dao_votes(&self) -> WalletDbResult<()> {
  1000. println!("Resetting DAO votes");
  1001. let query = format!("DELETE FROM {};", *DAO_VOTES_TABLE);
  1002. self.wallet.exec_sql(&query, &[])
  1003. }
  1004. /// Import given DAO params into the wallet with a given name.
  1005. pub async fn import_dao(&self, name: &str, params: DaoParams) -> Result<()> {
  1006. // First let's check if we've imported this DAO with the given name before.
  1007. if self.get_dao_by_name(name).await.is_ok() {
  1008. return Err(Error::DatabaseError(
  1009. "[import_dao] This DAO has already been imported".to_string(),
  1010. ))
  1011. }
  1012. println!("Importing \"{name}\" DAO into the wallet");
  1013. let query = format!(
  1014. "INSERT INTO {} ({}, {}, {}) VALUES (?1, ?2, ?3);",
  1015. *DAO_DAOS_TABLE, DAO_DAOS_COL_BULLA, DAO_DAOS_COL_NAME, DAO_DAOS_COL_PARAMS,
  1016. );
  1017. if let Err(e) = self.wallet.exec_sql(
  1018. &query,
  1019. rusqlite::params![
  1020. serialize_async(&params.dao.to_bulla()).await,
  1021. name,
  1022. serialize_async(&params).await,
  1023. ],
  1024. ) {
  1025. return Err(Error::DatabaseError(format!("[import_dao] DAO insert failed: {e:?}")))
  1026. };
  1027. Ok(())
  1028. }
  1029. /// Fetch a DAO given its bulla.
  1030. pub async fn get_dao_by_bulla(&self, bulla: &DaoBulla) -> Result<DaoRecord> {
  1031. let row = match self.wallet.query_single(
  1032. &DAO_DAOS_TABLE,
  1033. &[],
  1034. convert_named_params! {(DAO_DAOS_COL_BULLA, serialize_async(bulla).await)},
  1035. ) {
  1036. Ok(r) => r,
  1037. Err(e) => {
  1038. return Err(Error::DatabaseError(format!(
  1039. "[get_dao_by_bulla] DAO retrieval failed: {e:?}"
  1040. )))
  1041. }
  1042. };
  1043. self.parse_dao_record(&row).await
  1044. }
  1045. /// Fetch a DAO given its name.
  1046. pub async fn get_dao_by_name(&self, name: &str) -> Result<DaoRecord> {
  1047. let row = match self.wallet.query_single(
  1048. &DAO_DAOS_TABLE,
  1049. &[],
  1050. convert_named_params! {(DAO_DAOS_COL_NAME, name)},
  1051. ) {
  1052. Ok(r) => r,
  1053. Err(e) => {
  1054. return Err(Error::DatabaseError(format!(
  1055. "[get_dao_by_name] DAO retrieval failed: {e:?}"
  1056. )))
  1057. }
  1058. };
  1059. self.parse_dao_record(&row).await
  1060. }
  1061. /// List DAO(s) imported in the wallet. If a name is given, just print the
  1062. /// metadata for that specific one, if found.
  1063. pub async fn dao_list(&self, name: &Option<String>) -> Result<()> {
  1064. if let Some(name) = name {
  1065. let dao = self.get_dao_by_name(name).await?;
  1066. println!("{dao}");
  1067. return Ok(());
  1068. }
  1069. let daos = self.get_daos().await?;
  1070. for (i, dao) in daos.iter().enumerate() {
  1071. println!("{i}. {}", dao.name);
  1072. }
  1073. Ok(())
  1074. }
  1075. /// Fetch known unspent balances from the wallet for the given DAO name.
  1076. pub async fn dao_balance(&self, name: &str) -> Result<HashMap<String, u64>> {
  1077. let dao = self.get_dao_by_name(name).await?;
  1078. let dao_spend_hook =
  1079. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  1080. .to_func_id();
  1081. let mut coins = self.get_coins(false).await?;
  1082. coins.retain(|x| x.0.note.spend_hook == dao_spend_hook);
  1083. coins.retain(|x| x.0.note.user_data == dao.bulla().inner());
  1084. // Fill this map with balances
  1085. let mut balmap: HashMap<String, u64> = HashMap::new();
  1086. for coin in coins {
  1087. let mut value = coin.0.note.value;
  1088. if let Some(prev) = balmap.get(&coin.0.note.token_id.to_string()) {
  1089. value += prev;
  1090. }
  1091. balmap.insert(coin.0.note.token_id.to_string(), value);
  1092. }
  1093. Ok(balmap)
  1094. }
  1095. /// Fetch all known DAO proposalss from the wallet.
  1096. pub async fn get_proposals(&self) -> Result<Vec<ProposalRecord>> {
  1097. let rows = match self.wallet.query_multiple(&DAO_PROPOSALS_TABLE, &[], &[]) {
  1098. Ok(r) => r,
  1099. Err(e) => {
  1100. return Err(Error::DatabaseError(format!(
  1101. "[get_proposals] DAO proposalss retrieval failed: {e:?}"
  1102. )))
  1103. }
  1104. };
  1105. let mut daos = Vec::with_capacity(rows.len());
  1106. for row in rows {
  1107. daos.push(self.parse_dao_proposal(&row).await?);
  1108. }
  1109. Ok(daos)
  1110. }
  1111. /// Fetch a DAO proposal by its bulla.
  1112. pub async fn get_dao_proposal_by_bulla(
  1113. &self,
  1114. bulla: &DaoProposalBulla,
  1115. ) -> Result<ProposalRecord> {
  1116. // Grab the proposal record
  1117. let row = match self.wallet.query_single(
  1118. &DAO_PROPOSALS_TABLE,
  1119. &[],
  1120. convert_named_params! {(DAO_PROPOSALS_COL_BULLA, serialize_async(bulla).await)},
  1121. ) {
  1122. Ok(r) => r,
  1123. Err(e) => {
  1124. return Err(Error::DatabaseError(format!(
  1125. "[get_dao_proposal_by_bulla] DAO proposal retrieval failed: {e:?}"
  1126. )))
  1127. }
  1128. };
  1129. // Parse rest of the record
  1130. self.parse_dao_proposal(&row).await
  1131. }
  1132. // Fetch all known DAO proposal votes from the wallet given a proposal ID.
  1133. pub async fn get_dao_proposal_votes(
  1134. &self,
  1135. proposal: &DaoProposalBulla,
  1136. ) -> Result<Vec<VoteRecord>> {
  1137. let rows = match self.wallet.query_multiple(
  1138. &DAO_VOTES_TABLE,
  1139. &[],
  1140. convert_named_params! {(DAO_VOTES_COL_PROPOSAL_BULLA, serialize_async(proposal).await)},
  1141. ) {
  1142. Ok(r) => r,
  1143. Err(e) => {
  1144. return Err(Error::DatabaseError(format!(
  1145. "[get_dao_proposal_votes] Votes retrieval failed: {e:?}"
  1146. )))
  1147. }
  1148. };
  1149. let mut votes = Vec::with_capacity(rows.len());
  1150. for row in rows {
  1151. let Value::Integer(id) = row[0] else {
  1152. return Err(Error::ParseFailed("[get_dao_proposal_votes] ID parsing failed"))
  1153. };
  1154. let Ok(id) = u64::try_from(id) else {
  1155. return Err(Error::ParseFailed("[get_dao_proposal_votes] ID parsing failed"))
  1156. };
  1157. let Value::Blob(ref proposal_bytes) = row[1] else {
  1158. return Err(Error::ParseFailed(
  1159. "[get_dao_proposal_votes] Proposal bytes bytes parsing failed",
  1160. ))
  1161. };
  1162. let proposal = deserialize_async(proposal_bytes).await?;
  1163. let Value::Integer(vote_option) = row[2] else {
  1164. return Err(Error::ParseFailed(
  1165. "[get_dao_proposal_votes] Vote option parsing failed",
  1166. ))
  1167. };
  1168. let Ok(vote_option) = u32::try_from(vote_option) else {
  1169. return Err(Error::ParseFailed(
  1170. "[get_dao_proposal_votes] Vote option parsing failed",
  1171. ))
  1172. };
  1173. let vote_option = vote_option != 0;
  1174. let Value::Blob(ref yes_vote_blind_bytes) = row[3] else {
  1175. return Err(Error::ParseFailed(
  1176. "[get_dao_proposal_votes] Yes vote blind bytes parsing failed",
  1177. ))
  1178. };
  1179. let yes_vote_blind = deserialize_async(yes_vote_blind_bytes).await?;
  1180. let Value::Blob(ref all_vote_value_bytes) = row[4] else {
  1181. return Err(Error::ParseFailed(
  1182. "[get_dao_proposal_votes] All vote value bytes parsing failed",
  1183. ))
  1184. };
  1185. let all_vote_value = deserialize_async(all_vote_value_bytes).await?;
  1186. let Value::Blob(ref all_vote_blind_bytes) = row[5] else {
  1187. return Err(Error::ParseFailed(
  1188. "[get_dao_proposal_votes] All vote blind bytes parsing failed",
  1189. ))
  1190. };
  1191. let all_vote_blind = deserialize_async(all_vote_blind_bytes).await?;
  1192. let Value::Blob(ref tx_hash_bytes) = row[6] else {
  1193. return Err(Error::ParseFailed(
  1194. "[get_dao_proposal_votes] Transaction hash bytes parsing failed",
  1195. ))
  1196. };
  1197. let tx_hash = deserialize_async(tx_hash_bytes).await?;
  1198. let Value::Integer(call_index) = row[7] else {
  1199. return Err(Error::ParseFailed("[get_dao_proposal_votes] Call index parsing failed"))
  1200. };
  1201. let Ok(call_index) = u8::try_from(call_index) else {
  1202. return Err(Error::ParseFailed("[get_dao_proposal_votes] Call index parsing failed"))
  1203. };
  1204. let Value::Blob(ref nullifiers_bytes) = row[8] else {
  1205. return Err(Error::ParseFailed(
  1206. "[get_dao_proposal_votes] Nullifiers bytes parsing failed",
  1207. ))
  1208. };
  1209. let nullifiers = deserialize_async(nullifiers_bytes).await?;
  1210. let vote = VoteRecord {
  1211. id,
  1212. proposal,
  1213. vote_option,
  1214. yes_vote_blind,
  1215. all_vote_value,
  1216. all_vote_blind,
  1217. tx_hash,
  1218. call_index,
  1219. nullifiers,
  1220. };
  1221. votes.push(vote);
  1222. }
  1223. Ok(votes)
  1224. }
  1225. /// Mint a DAO on-chain.
  1226. pub async fn dao_mint(&self, name: &str) -> Result<Transaction> {
  1227. // Retrieve the dao record
  1228. let dao = self.get_dao_by_name(name).await?;
  1229. // Check its not already minted
  1230. if dao.tx_hash.is_some() {
  1231. return Err(Error::Custom(
  1232. "[dao_mint] This DAO seems to have already been minted on-chain".to_string(),
  1233. ))
  1234. }
  1235. // Now we need to do a lookup for the zkas proof bincodes, and create
  1236. // the circuit objects and proving keys so we can build the transaction.
  1237. // We also do this through the RPC. First we grab the fee call from money.
  1238. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  1239. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  1240. else {
  1241. return Err(Error::Custom("Fee circuit not found".to_string()))
  1242. };
  1243. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  1244. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  1245. // Creating Fee circuit proving key
  1246. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  1247. // Now we grab the DAO mint
  1248. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  1249. let Some(dao_mint_zkbin) = zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_MINT_NS)
  1250. else {
  1251. return Err(Error::DatabaseError("[dao_mint] DAO Mint circuit not found".to_string()))
  1252. };
  1253. let dao_mint_zkbin = ZkBinary::decode(&dao_mint_zkbin.1)?;
  1254. let dao_mint_circuit = ZkCircuit::new(empty_witnesses(&dao_mint_zkbin)?, &dao_mint_zkbin);
  1255. // Creating DAO Mint circuit proving key
  1256. let dao_mint_pk = ProvingKey::build(dao_mint_zkbin.k, &dao_mint_circuit);
  1257. // Create the DAO mint call
  1258. let (params, proofs) =
  1259. make_mint_call(&dao.params.dao, &dao.params.secret_key, &dao_mint_zkbin, &dao_mint_pk)?;
  1260. let mut data = vec![DaoFunction::Mint as u8];
  1261. params.encode_async(&mut data).await?;
  1262. let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  1263. // Create the TransactionBuilder containing above call
  1264. let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;
  1265. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  1266. // it into the fee-creating function.
  1267. let mut tx = tx_builder.build()?;
  1268. let sigs = tx.create_sigs(&[dao.params.secret_key])?;
  1269. tx.signatures.push(sigs);
  1270. let tree = self.get_money_tree().await?;
  1271. let (fee_call, fee_proofs, fee_secrets) =
  1272. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  1273. // Append the fee call to the transaction
  1274. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  1275. // Now build the actual transaction and sign it with all necessary keys.
  1276. let mut tx = tx_builder.build()?;
  1277. let sigs = tx.create_sigs(&[dao.params.secret_key])?;
  1278. tx.signatures.push(sigs);
  1279. let sigs = tx.create_sigs(&fee_secrets)?;
  1280. tx.signatures.push(sigs);
  1281. Ok(tx)
  1282. }
  1283. /// Create a DAO transfer proposal.
  1284. #[allow(clippy::too_many_arguments)]
  1285. pub async fn dao_propose_transfer(
  1286. &self,
  1287. name: &str,
  1288. duration_blockwindows: u64,
  1289. amount: &str,
  1290. token_id: TokenId,
  1291. recipient: PublicKey,
  1292. spend_hook: Option<FuncId>,
  1293. user_data: Option<pallas::Base>,
  1294. ) -> Result<ProposalRecord> {
  1295. // Fetch DAO and check its deployed
  1296. let dao = self.get_dao_by_name(name).await?;
  1297. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  1298. return Err(Error::Custom(
  1299. "[dao_propose_transfer] DAO seems to not have been deployed yet".to_string(),
  1300. ))
  1301. }
  1302. // Fetch DAO unspent OwnCoins to see what its balance is
  1303. let dao_spend_hook =
  1304. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  1305. .to_func_id();
  1306. let dao_bulla = dao.bulla();
  1307. let dao_owncoins =
  1308. self.get_contract_token_coins(&token_id, &dao_spend_hook, &dao_bulla.inner()).await?;
  1309. if dao_owncoins.is_empty() {
  1310. return Err(Error::Custom(format!(
  1311. "[dao_propose_transfer] Did not find any {token_id} unspent coins owned by this DAO"
  1312. )))
  1313. }
  1314. // Check DAO balance is sufficient
  1315. let amount = decode_base10(amount, BALANCE_BASE10_DECIMALS, false)?;
  1316. if dao_owncoins.iter().map(|x| x.note.value).sum::<u64>() < amount {
  1317. return Err(Error::Custom(format!(
  1318. "[dao_propose_transfer] Not enough DAO balance for token ID: {token_id}",
  1319. )))
  1320. }
  1321. // Generate proposal coin attributes
  1322. let proposal_coinattrs = CoinAttributes {
  1323. public_key: recipient,
  1324. value: amount,
  1325. token_id,
  1326. spend_hook: spend_hook.unwrap_or(FuncId::none()),
  1327. user_data: user_data.unwrap_or(pallas::Base::ZERO),
  1328. blind: Blind::random(&mut OsRng),
  1329. };
  1330. // Convert coin_params to actual coins
  1331. let proposal_coins = vec![proposal_coinattrs.to_coin()];
  1332. let mut proposal_data = vec![];
  1333. proposal_coins.encode_async(&mut proposal_data).await?;
  1334. // Create Auth calls
  1335. let auth_calls = vec![
  1336. DaoAuthCall {
  1337. contract_id: *DAO_CONTRACT_ID,
  1338. function_code: DaoFunction::AuthMoneyTransfer as u8,
  1339. auth_data: proposal_data,
  1340. },
  1341. DaoAuthCall {
  1342. contract_id: *MONEY_CONTRACT_ID,
  1343. function_code: MoneyFunction::TransferV1 as u8,
  1344. auth_data: vec![],
  1345. },
  1346. ];
  1347. // Retrieve next block height and current block time target,
  1348. // to compute their window.
  1349. let next_block_height = self.get_next_block_height().await?;
  1350. let block_target = self.get_block_target().await?;
  1351. let creation_blockwindow = blockwindow(next_block_height, block_target);
  1352. // Create the actual proposal
  1353. let proposal = DaoProposal {
  1354. auth_calls,
  1355. creation_blockwindow,
  1356. duration_blockwindows,
  1357. user_data: user_data.unwrap_or(pallas::Base::ZERO),
  1358. dao_bulla,
  1359. blind: Blind::random(&mut OsRng),
  1360. };
  1361. let proposal_record = ProposalRecord {
  1362. proposal,
  1363. data: Some(serialize_async(&proposal_coinattrs).await),
  1364. leaf_position: None,
  1365. money_snapshot_tree: None,
  1366. nullifiers_smt_snapshot: None,
  1367. tx_hash: None,
  1368. call_index: None,
  1369. exec_tx_hash: None,
  1370. };
  1371. if let Err(e) = self.put_dao_proposal(&proposal_record).await {
  1372. return Err(Error::DatabaseError(format!(
  1373. "[dao_propose_transfer] Put DAO proposal failed: {e:?}"
  1374. )))
  1375. }
  1376. Ok(proposal_record)
  1377. }
  1378. /// Create a DAO transfer proposal transaction.
  1379. pub async fn dao_transfer_proposal_tx(&self, proposal: &ProposalRecord) -> Result<Transaction> {
  1380. // Check we know the plaintext data
  1381. if proposal.data.is_none() {
  1382. return Err(Error::Custom(
  1383. "[dao_transfer_proposal_tx] Proposal plainext data is empty".to_string(),
  1384. ))
  1385. }
  1386. let proposal_coinattrs: CoinAttributes =
  1387. deserialize_async(proposal.data.as_ref().unwrap()).await?;
  1388. // Fetch DAO and check its deployed
  1389. let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
  1390. return Err(Error::Custom(format!(
  1391. "[dao_transfer_proposal_tx] DAO {} was not found",
  1392. proposal.proposal.dao_bulla
  1393. )))
  1394. };
  1395. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  1396. return Err(Error::Custom(
  1397. "[dao_transfer_proposal_tx] DAO seems to not have been deployed yet".to_string(),
  1398. ))
  1399. }
  1400. // Fetch DAO unspent OwnCoins to see what its balance is for the coin
  1401. let dao_spend_hook =
  1402. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  1403. .to_func_id();
  1404. let dao_owncoins = self
  1405. .get_contract_token_coins(
  1406. &proposal_coinattrs.token_id,
  1407. &dao_spend_hook,
  1408. &proposal.proposal.dao_bulla.inner(),
  1409. )
  1410. .await?;
  1411. if dao_owncoins.is_empty() {
  1412. return Err(Error::Custom(format!(
  1413. "[dao_transfer_proposal_tx] Did not find any {} unspent coins owned by this DAO",
  1414. proposal_coinattrs.token_id,
  1415. )))
  1416. }
  1417. // Check DAO balance is sufficient
  1418. if dao_owncoins.iter().map(|x| x.note.value).sum::<u64>() < proposal_coinattrs.value {
  1419. return Err(Error::Custom(format!(
  1420. "[dao_transfer_proposal_tx] Not enough DAO balance for token ID: {}",
  1421. proposal_coinattrs.token_id,
  1422. )))
  1423. }
  1424. // Fetch our own governance OwnCoins to see what our balance is
  1425. let gov_owncoins = self.get_token_coins(&dao.params.dao.gov_token_id).await?;
  1426. if gov_owncoins.is_empty() {
  1427. return Err(Error::Custom(format!(
  1428. "[dao_transfer_proposal_tx] Did not find any governance {} coins in wallet",
  1429. dao.params.dao.gov_token_id
  1430. )))
  1431. }
  1432. // Find which governance coins we can use
  1433. let mut total_value = 0;
  1434. let mut gov_owncoins_to_use = vec![];
  1435. for gov_owncoin in gov_owncoins {
  1436. if total_value >= dao.params.dao.proposer_limit {
  1437. break
  1438. }
  1439. total_value += gov_owncoin.note.value;
  1440. gov_owncoins_to_use.push(gov_owncoin);
  1441. }
  1442. // Check our governance coins balance is sufficient
  1443. if total_value < dao.params.dao.proposer_limit {
  1444. return Err(Error::Custom(format!(
  1445. "[dao_transfer_proposal_tx] Not enough gov token {} balance to propose",
  1446. dao.params.dao.gov_token_id
  1447. )))
  1448. }
  1449. // Now we need to do a lookup for the zkas proof bincodes, and create
  1450. // the circuit objects and proving keys so we can build the transaction.
  1451. // We also do this through the RPC. First we grab the fee call from money.
  1452. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  1453. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  1454. else {
  1455. return Err(Error::Custom(
  1456. "[dao_transfer_proposal_tx] Fee circuit not found".to_string(),
  1457. ))
  1458. };
  1459. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  1460. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  1461. // Creating Fee circuit proving key
  1462. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  1463. // Now we grab the DAO bins
  1464. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  1465. let Some(propose_burn_zkbin) =
  1466. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_PROPOSE_INPUT_NS)
  1467. else {
  1468. return Err(Error::Custom(
  1469. "[dao_transfer_proposal_tx] Propose Burn circuit not found".to_string(),
  1470. ))
  1471. };
  1472. let Some(propose_main_zkbin) =
  1473. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_PROPOSE_MAIN_NS)
  1474. else {
  1475. return Err(Error::Custom(
  1476. "[dao_transfer_proposal_tx] Propose Main circuit not found".to_string(),
  1477. ))
  1478. };
  1479. let propose_burn_zkbin = ZkBinary::decode(&propose_burn_zkbin.1)?;
  1480. let propose_main_zkbin = ZkBinary::decode(&propose_main_zkbin.1)?;
  1481. let propose_burn_circuit =
  1482. ZkCircuit::new(empty_witnesses(&propose_burn_zkbin)?, &propose_burn_zkbin);
  1483. let propose_main_circuit =
  1484. ZkCircuit::new(empty_witnesses(&propose_main_zkbin)?, &propose_main_zkbin);
  1485. // Creating DAO ProposeBurn and ProposeMain circuits proving keys
  1486. let propose_burn_pk = ProvingKey::build(propose_burn_zkbin.k, &propose_burn_circuit);
  1487. let propose_main_pk = ProvingKey::build(propose_main_zkbin.k, &propose_main_circuit);
  1488. // Fetch our money Merkle tree
  1489. let money_merkle_tree = self.get_money_tree().await?;
  1490. // Now we can create the proposal transaction parameters.
  1491. // We first generate the `DaoProposeStakeInput` inputs,
  1492. // using our governance OwnCoins.
  1493. let mut inputs = Vec::with_capacity(gov_owncoins_to_use.len());
  1494. for gov_owncoin in gov_owncoins_to_use {
  1495. let input = DaoProposeStakeInput {
  1496. secret: gov_owncoin.secret,
  1497. note: gov_owncoin.note.clone(),
  1498. leaf_position: gov_owncoin.leaf_position,
  1499. merkle_path: money_merkle_tree.witness(gov_owncoin.leaf_position, 0).unwrap(),
  1500. };
  1501. inputs.push(input);
  1502. }
  1503. // Now create the parameters for the proposal tx
  1504. let signature_secret = SecretKey::random(&mut OsRng);
  1505. // Fetch the daos Merkle tree to compute the DAO Merkle path and root
  1506. let (daos_tree, _) = self.get_dao_trees().await?;
  1507. let (dao_merkle_path, dao_merkle_root) = {
  1508. let root = daos_tree.root(0).unwrap();
  1509. let leaf_pos = dao.leaf_position.unwrap();
  1510. let dao_merkle_path = daos_tree.witness(leaf_pos, 0).unwrap();
  1511. (dao_merkle_path, root)
  1512. };
  1513. // Generate the Money nullifiers Sparse Merkle Tree
  1514. let store = WalletStorage::new(
  1515. &self.wallet,
  1516. &MONEY_SMT_TABLE,
  1517. MONEY_SMT_COL_KEY,
  1518. MONEY_SMT_COL_VALUE,
  1519. );
  1520. let money_null_smt = WalletSmt::new(store, PoseidonFp::new(), &EMPTY_NODES_FP);
  1521. // Create the proposal call
  1522. let call = DaoProposeCall {
  1523. money_null_smt: &money_null_smt,
  1524. inputs,
  1525. proposal: proposal.proposal.clone(),
  1526. dao: dao.params.dao,
  1527. dao_leaf_position: dao.leaf_position.unwrap(),
  1528. dao_merkle_path,
  1529. dao_merkle_root,
  1530. signature_secret,
  1531. };
  1532. let (params, proofs) = call.make(
  1533. &propose_burn_zkbin,
  1534. &propose_burn_pk,
  1535. &propose_main_zkbin,
  1536. &propose_main_pk,
  1537. )?;
  1538. // Encode the call
  1539. let mut data = vec![DaoFunction::Propose as u8];
  1540. params.encode_async(&mut data).await?;
  1541. let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  1542. // Create the TransactionBuilder containing above call
  1543. let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;
  1544. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  1545. // it into the fee-creating function.
  1546. let mut tx = tx_builder.build()?;
  1547. let sigs = tx.create_sigs(&[signature_secret])?;
  1548. tx.signatures = vec![sigs];
  1549. let tree = self.get_money_tree().await?;
  1550. let (fee_call, fee_proofs, fee_secrets) =
  1551. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  1552. // Append the fee call to the transaction
  1553. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  1554. // Now build the actual transaction and sign it with all necessary keys.
  1555. let mut tx = tx_builder.build()?;
  1556. let sigs = tx.create_sigs(&[signature_secret])?;
  1557. tx.signatures.push(sigs);
  1558. let sigs = tx.create_sigs(&fee_secrets)?;
  1559. tx.signatures.push(sigs);
  1560. Ok(tx)
  1561. }
  1562. /// Vote on a DAO proposal
  1563. pub async fn dao_vote(
  1564. &self,
  1565. proposal_bulla: &DaoProposalBulla,
  1566. vote_option: bool,
  1567. weight: Option<u64>,
  1568. ) -> Result<Transaction> {
  1569. // Feth the proposal and check its deployed
  1570. let Ok(proposal) = self.get_dao_proposal_by_bulla(proposal_bulla).await else {
  1571. return Err(Error::Custom(format!("[dao_vote] Proposal {proposal_bulla} was not found")))
  1572. };
  1573. if proposal.leaf_position.is_none() ||
  1574. proposal.money_snapshot_tree.is_none() ||
  1575. proposal.nullifiers_smt_snapshot.is_none() ||
  1576. proposal.tx_hash.is_none() ||
  1577. proposal.call_index.is_none()
  1578. {
  1579. return Err(Error::Custom(
  1580. "[dao_vote] Proposal seems to not have been deployed yet".to_string(),
  1581. ))
  1582. }
  1583. // Check proposal is not executed
  1584. if let Some(exec_tx_hash) = proposal.exec_tx_hash {
  1585. return Err(Error::Custom(format!(
  1586. "[dao_vote] Proposal was executed on transaction: {exec_tx_hash}"
  1587. )))
  1588. }
  1589. // Check we know the plaintext data
  1590. if proposal.data.is_none() {
  1591. return Err(Error::Custom("[dao_vote] Proposal plainext data is empty".to_string()))
  1592. }
  1593. // Fetch DAO and check its deployed
  1594. let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
  1595. return Err(Error::Custom(format!(
  1596. "[dao_vote] DAO {} was not found",
  1597. proposal.proposal.dao_bulla
  1598. )))
  1599. };
  1600. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  1601. return Err(Error::Custom(
  1602. "[dao_vote] DAO seems to not have been deployed yet".to_string(),
  1603. ))
  1604. }
  1605. // Fetch all the proposal votes to check for duplicate nullifiers
  1606. let votes = self.get_dao_proposal_votes(proposal_bulla).await?;
  1607. let mut votes_nullifiers = vec![];
  1608. for vote in votes {
  1609. for nullifier in vote.nullifiers {
  1610. if !votes_nullifiers.contains(&nullifier) {
  1611. votes_nullifiers.push(nullifier);
  1612. }
  1613. }
  1614. }
  1615. // Fetch our own governance OwnCoins to see what our balance is
  1616. let gov_owncoins = self.get_token_coins(&dao.params.dao.gov_token_id).await?;
  1617. if gov_owncoins.is_empty() {
  1618. return Err(Error::Custom(format!(
  1619. "[dao_vote] Did not find any governance {} coins in wallet",
  1620. dao.params.dao.gov_token_id
  1621. )))
  1622. }
  1623. // Find which governance coins we can use
  1624. let gov_owncoins_to_use = match weight {
  1625. Some(_weight) => {
  1626. // TODO: Build a proper coin selection algorithm so that we can use a
  1627. // coins combination that matches the requested weight
  1628. return Err(Error::Custom(
  1629. "[dao_vote] Fractional vote weight not supported yet".to_string(),
  1630. ))
  1631. }
  1632. // If no weight was specified, use them all
  1633. None => gov_owncoins,
  1634. };
  1635. // Now we need to do a lookup for the zkas proof bincodes, and create
  1636. // the circuit objects and proving keys so we can build the transaction.
  1637. // We also do this through the RPC. First we grab the fee call from money.
  1638. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  1639. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  1640. else {
  1641. return Err(Error::Custom("[dao_vote] Fee circuit not found".to_string()))
  1642. };
  1643. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  1644. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  1645. // Creating Fee circuit proving key
  1646. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  1647. // Now we grab the DAO bins
  1648. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  1649. let Some(dao_vote_burn_zkbin) =
  1650. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_VOTE_INPUT_NS)
  1651. else {
  1652. return Err(Error::Custom("[dao_vote] DAO Vote Burn circuit not found".to_string()))
  1653. };
  1654. let Some(dao_vote_main_zkbin) =
  1655. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_VOTE_MAIN_NS)
  1656. else {
  1657. return Err(Error::Custom("[dao_vote] DAO Vote Main circuit not found".to_string()))
  1658. };
  1659. let dao_vote_burn_zkbin = ZkBinary::decode(&dao_vote_burn_zkbin.1)?;
  1660. let dao_vote_main_zkbin = ZkBinary::decode(&dao_vote_main_zkbin.1)?;
  1661. let dao_vote_burn_circuit =
  1662. ZkCircuit::new(empty_witnesses(&dao_vote_burn_zkbin)?, &dao_vote_burn_zkbin);
  1663. let dao_vote_main_circuit =
  1664. ZkCircuit::new(empty_witnesses(&dao_vote_main_zkbin)?, &dao_vote_main_zkbin);
  1665. // Creating DAO VoteBurn and VoteMain circuits proving keys
  1666. let dao_vote_burn_pk = ProvingKey::build(dao_vote_burn_zkbin.k, &dao_vote_burn_circuit);
  1667. let dao_vote_main_pk = ProvingKey::build(dao_vote_main_zkbin.k, &dao_vote_main_circuit);
  1668. // Now create the parameters for the vote tx
  1669. let signature_secret = SecretKey::random(&mut OsRng);
  1670. let mut inputs = Vec::with_capacity(gov_owncoins_to_use.len());
  1671. for gov_owncoin in gov_owncoins_to_use {
  1672. let nullifier = poseidon_hash([gov_owncoin.secret.inner(), gov_owncoin.coin.inner()]);
  1673. let vote_nullifier =
  1674. poseidon_hash([nullifier, gov_owncoin.secret.inner(), proposal_bulla.inner()]);
  1675. if votes_nullifiers.contains(&vote_nullifier.into()) {
  1676. return Err(Error::Custom("[dao_vote] Duplicate input nullifier found".to_string()))
  1677. };
  1678. let input = DaoVoteInput {
  1679. secret: gov_owncoin.secret,
  1680. note: gov_owncoin.note.clone(),
  1681. leaf_position: gov_owncoin.leaf_position,
  1682. merkle_path: proposal
  1683. .money_snapshot_tree
  1684. .as_ref()
  1685. .unwrap()
  1686. .witness(gov_owncoin.leaf_position, 0)
  1687. .unwrap(),
  1688. signature_secret,
  1689. };
  1690. inputs.push(input);
  1691. }
  1692. // Retrieve next block height and current block time target,
  1693. // to compute their window.
  1694. let next_block_height = self.get_next_block_height().await?;
  1695. let block_target = self.get_block_target().await?;
  1696. let current_blockwindow = blockwindow(next_block_height, block_target);
  1697. // Generate the Money nullifiers Sparse Merkle Tree
  1698. let store = MemoryStorageFp { tree: proposal.nullifiers_smt_snapshot.unwrap() };
  1699. let money_null_smt = SmtMemoryFp::new(store, PoseidonFp::new(), &EMPTY_NODES_FP);
  1700. // Create the vote call
  1701. let call = DaoVoteCall {
  1702. money_null_smt: &money_null_smt,
  1703. inputs,
  1704. vote_option,
  1705. proposal: proposal.proposal.clone(),
  1706. dao: dao.params.dao.clone(),
  1707. dao_keypair: dao.keypair(),
  1708. current_blockwindow,
  1709. };
  1710. let (params, proofs) = call.make(
  1711. &dao_vote_burn_zkbin,
  1712. &dao_vote_burn_pk,
  1713. &dao_vote_main_zkbin,
  1714. &dao_vote_main_pk,
  1715. )?;
  1716. // Encode the call
  1717. let mut data = vec![DaoFunction::Vote as u8];
  1718. params.encode_async(&mut data).await?;
  1719. let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  1720. // Create the TransactionBuilder containing above call
  1721. let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;
  1722. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  1723. // it into the fee-creating function.
  1724. let mut tx = tx_builder.build()?;
  1725. let sigs = tx.create_sigs(&[signature_secret])?;
  1726. tx.signatures = vec![sigs];
  1727. let tree = self.get_money_tree().await?;
  1728. let (fee_call, fee_proofs, fee_secrets) =
  1729. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  1730. // Append the fee call to the transaction
  1731. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  1732. // Now build the actual transaction and sign it with all necessary keys.
  1733. let mut tx = tx_builder.build()?;
  1734. let sigs = tx.create_sigs(&[signature_secret])?;
  1735. tx.signatures.push(sigs);
  1736. let sigs = tx.create_sigs(&fee_secrets)?;
  1737. tx.signatures.push(sigs);
  1738. Ok(tx)
  1739. }
  1740. /// Execute a DAO transfer proposal.
  1741. pub async fn dao_exec_transfer(&self, proposal: &ProposalRecord) -> Result<Transaction> {
  1742. if proposal.leaf_position.is_none() ||
  1743. proposal.money_snapshot_tree.is_none() ||
  1744. proposal.nullifiers_smt_snapshot.is_none() ||
  1745. proposal.tx_hash.is_none() ||
  1746. proposal.call_index.is_none()
  1747. {
  1748. return Err(Error::Custom(
  1749. "[dao_exec_transfer] Proposal seems to not have been deployed yet".to_string(),
  1750. ))
  1751. }
  1752. // Check proposal is not executed
  1753. if let Some(exec_tx_hash) = proposal.exec_tx_hash {
  1754. return Err(Error::Custom(format!(
  1755. "[dao_exec_transfer] Proposal was executed on transaction: {exec_tx_hash}"
  1756. )))
  1757. }
  1758. // Check we know the plaintext data and they are valid
  1759. if proposal.data.is_none() {
  1760. return Err(Error::Custom(
  1761. "[dao_exec_transfer] Proposal plainext data is empty".to_string(),
  1762. ))
  1763. }
  1764. let proposal_coinattrs: CoinAttributes =
  1765. deserialize_async(proposal.data.as_ref().unwrap()).await?;
  1766. // Fetch DAO and check its deployed
  1767. let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
  1768. return Err(Error::Custom(format!(
  1769. "[dao_exec_transfer] DAO {} was not found",
  1770. proposal.proposal.dao_bulla
  1771. )))
  1772. };
  1773. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  1774. return Err(Error::Custom(
  1775. "[dao_exec_transfer] DAO seems to not have been deployed yet".to_string(),
  1776. ))
  1777. }
  1778. // Check proposal is approved
  1779. let votes = self.get_dao_proposal_votes(&proposal.bulla()).await?;
  1780. let mut yes_vote_value = 0;
  1781. let mut yes_vote_blind = Blind::ZERO;
  1782. let mut all_vote_value = 0;
  1783. let mut all_vote_blind = Blind::ZERO;
  1784. for vote in votes {
  1785. if vote.vote_option {
  1786. yes_vote_value += vote.all_vote_value;
  1787. };
  1788. yes_vote_blind += vote.yes_vote_blind;
  1789. all_vote_value += vote.all_vote_value;
  1790. all_vote_blind += vote.all_vote_blind;
  1791. }
  1792. let approval_ratio = (yes_vote_value as f64 * 100.0) / all_vote_value as f64;
  1793. if all_vote_value < dao.params.dao.quorum ||
  1794. approval_ratio <
  1795. (dao.params.dao.approval_ratio_quot / dao.params.dao.approval_ratio_base)
  1796. as f64
  1797. {
  1798. return Err(Error::Custom(
  1799. "[dao_exec_transfer] Proposal is not approved yet".to_string(),
  1800. ))
  1801. };
  1802. // Fetch DAO unspent OwnCoins to see what its balance is for the coin
  1803. let dao_spend_hook =
  1804. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  1805. .to_func_id();
  1806. let dao_owncoins = self
  1807. .get_contract_token_coins(
  1808. &proposal_coinattrs.token_id,
  1809. &dao_spend_hook,
  1810. &proposal.proposal.dao_bulla.inner(),
  1811. )
  1812. .await?;
  1813. if dao_owncoins.is_empty() {
  1814. return Err(Error::Custom(format!(
  1815. "[dao_exec_transfer] Did not find any {} unspent coins owned by this DAO",
  1816. proposal_coinattrs.token_id,
  1817. )))
  1818. }
  1819. // Check DAO balance is sufficient
  1820. if dao_owncoins.iter().map(|x| x.note.value).sum::<u64>() < proposal_coinattrs.value {
  1821. return Err(Error::Custom(format!(
  1822. "[dao_exec_transfer] Not enough DAO balance for token ID: {}",
  1823. proposal_coinattrs.token_id,
  1824. )))
  1825. }
  1826. // Find which DAO coins we can use
  1827. let (spent_coins, change_value) = select_coins(dao_owncoins, proposal_coinattrs.value)?;
  1828. // Now we need to do a lookup for the zkas proof bincodes, and create
  1829. // the circuit objects and proving keys so we can build the transaction.
  1830. // We also do this through the RPC. First we grab the calls from money.
  1831. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  1832. let Some(mint_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_MINT_NS_V1)
  1833. else {
  1834. return Err(Error::Custom("Mint circuit not found".to_string()))
  1835. };
  1836. let Some(burn_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_BURN_NS_V1)
  1837. else {
  1838. return Err(Error::Custom("Burn circuit not found".to_string()))
  1839. };
  1840. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  1841. else {
  1842. return Err(Error::Custom("Fee circuit not found".to_string()))
  1843. };
  1844. let mint_zkbin = ZkBinary::decode(&mint_zkbin.1)?;
  1845. let burn_zkbin = ZkBinary::decode(&burn_zkbin.1)?;
  1846. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  1847. let mint_circuit = ZkCircuit::new(empty_witnesses(&mint_zkbin)?, &mint_zkbin);
  1848. let burn_circuit = ZkCircuit::new(empty_witnesses(&burn_zkbin)?, &burn_zkbin);
  1849. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  1850. // Creating Mint, Burn and Fee circuits proving keys
  1851. let mint_pk = ProvingKey::build(mint_zkbin.k, &mint_circuit);
  1852. let burn_pk = ProvingKey::build(burn_zkbin.k, &burn_circuit);
  1853. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  1854. // Now we grab the DAO bins
  1855. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  1856. let Some(dao_exec_zkbin) = zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_EXEC_NS)
  1857. else {
  1858. return Err(Error::Custom("[dao_exec_transfer] DAO Exec circuit not found".to_string()))
  1859. };
  1860. let Some(dao_auth_transfer_zkbin) =
  1861. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_AUTH_MONEY_TRANSFER_NS)
  1862. else {
  1863. return Err(Error::Custom(
  1864. "[dao_exec_transfer] DAO AuthTransfer circuit not found".to_string(),
  1865. ))
  1866. };
  1867. let Some(dao_auth_transfer_enc_coin_zkbin) =
  1868. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_AUTH_MONEY_TRANSFER_ENC_COIN_NS)
  1869. else {
  1870. return Err(Error::Custom(
  1871. "[dao_exec_transfer] DAO AuthTransferEncCoin circuit not found".to_string(),
  1872. ))
  1873. };
  1874. let dao_exec_zkbin = ZkBinary::decode(&dao_exec_zkbin.1)?;
  1875. let dao_auth_transfer_zkbin = ZkBinary::decode(&dao_auth_transfer_zkbin.1)?;
  1876. let dao_auth_transfer_enc_coin_zkbin =
  1877. ZkBinary::decode(&dao_auth_transfer_enc_coin_zkbin.1)?;
  1878. let dao_exec_circuit = ZkCircuit::new(empty_witnesses(&dao_exec_zkbin)?, &dao_exec_zkbin);
  1879. let dao_auth_transfer_circuit =
  1880. ZkCircuit::new(empty_witnesses(&dao_auth_transfer_zkbin)?, &dao_auth_transfer_zkbin);
  1881. let dao_auth_transfer_enc_coin_circuit = ZkCircuit::new(
  1882. empty_witnesses(&dao_auth_transfer_enc_coin_zkbin)?,
  1883. &dao_auth_transfer_enc_coin_zkbin,
  1884. );
  1885. // Creating DAO Exec, AuthTransfer and AuthTransferEncCoin circuits proving keys
  1886. let dao_exec_pk = ProvingKey::build(dao_exec_zkbin.k, &dao_exec_circuit);
  1887. let dao_auth_transfer_pk =
  1888. ProvingKey::build(dao_auth_transfer_zkbin.k, &dao_auth_transfer_circuit);
  1889. let dao_auth_transfer_enc_coin_pk = ProvingKey::build(
  1890. dao_auth_transfer_enc_coin_zkbin.k,
  1891. &dao_auth_transfer_enc_coin_circuit,
  1892. );
  1893. // Fetch our money Merkle tree
  1894. let tree = self.get_money_tree().await?;
  1895. // Now we can create the transfer call parameters
  1896. let input_user_data_blind = Blind::random(&mut OsRng);
  1897. let mut inputs = vec![];
  1898. for coin in &spent_coins {
  1899. inputs.push(TransferCallInput {
  1900. coin: coin.clone(),
  1901. merkle_path: tree.witness(coin.leaf_position, 0).unwrap(),
  1902. user_data_blind: input_user_data_blind,
  1903. });
  1904. }
  1905. let mut outputs = vec![];
  1906. outputs.push(proposal_coinattrs.clone());
  1907. let dao_coin_attrs = CoinAttributes {
  1908. public_key: dao.keypair().public,
  1909. value: change_value,
  1910. token_id: proposal_coinattrs.token_id,
  1911. spend_hook: dao_spend_hook,
  1912. user_data: proposal.proposal.dao_bulla.inner(),
  1913. blind: Blind::random(&mut OsRng),
  1914. };
  1915. outputs.push(dao_coin_attrs.clone());
  1916. // Create the transfer call
  1917. let transfer_builder = TransferCallBuilder {
  1918. clear_inputs: vec![],
  1919. inputs,
  1920. outputs,
  1921. mint_zkbin: mint_zkbin.clone(),
  1922. mint_pk: mint_pk.clone(),
  1923. burn_zkbin: burn_zkbin.clone(),
  1924. burn_pk: burn_pk.clone(),
  1925. };
  1926. let (transfer_params, transfer_secrets) = transfer_builder.build()?;
  1927. // Encode the call
  1928. let mut data = vec![MoneyFunction::TransferV1 as u8];
  1929. transfer_params.encode_async(&mut data).await?;
  1930. let transfer_call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  1931. // Now we need to extract the exec call parameters
  1932. let mut input_value = 0;
  1933. let mut input_value_blind = Blind::ZERO;
  1934. for (input, blind) in spent_coins.iter().zip(transfer_secrets.input_value_blinds.iter()) {
  1935. input_value += input.note.value;
  1936. input_value_blind += *blind;
  1937. }
  1938. // Create the exec call
  1939. let exec_signature_secret = SecretKey::random(&mut OsRng);
  1940. let exec_builder = DaoExecCall {
  1941. proposal: proposal.proposal.clone(),
  1942. dao: dao.params.dao.clone(),
  1943. yes_vote_value,
  1944. all_vote_value,
  1945. yes_vote_blind,
  1946. all_vote_blind,
  1947. input_value,
  1948. input_value_blind,
  1949. input_user_data_blind,
  1950. hook_dao_exec: DAO_CONTRACT_ID.inner(),
  1951. signature_secret: exec_signature_secret,
  1952. };
  1953. let (exec_params, exec_proofs) = exec_builder.make(&dao_exec_zkbin, &dao_exec_pk)?;
  1954. // Encode the call
  1955. let mut data = vec![DaoFunction::Exec as u8];
  1956. exec_params.encode_async(&mut data).await?;
  1957. let exec_call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  1958. // Now we can create the auth call
  1959. // Auth module
  1960. let auth_transfer_builder = DaoAuthMoneyTransferCall {
  1961. proposal: proposal.proposal.clone(),
  1962. proposal_coinattrs: vec![proposal_coinattrs],
  1963. dao: dao.params.dao.clone(),
  1964. input_user_data_blind,
  1965. dao_coin_attrs,
  1966. };
  1967. let (auth_transfer_params, auth_transfer_proofs) = auth_transfer_builder.make(
  1968. &dao_auth_transfer_zkbin,
  1969. &dao_auth_transfer_pk,
  1970. &dao_auth_transfer_enc_coin_zkbin,
  1971. &dao_auth_transfer_enc_coin_pk,
  1972. )?;
  1973. // Encode the call
  1974. let mut data = vec![DaoFunction::AuthMoneyTransfer as u8];
  1975. auth_transfer_params.encode_async(&mut data).await?;
  1976. let auth_transfer_call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  1977. // Create the TransactionBuilder containing above calls
  1978. let mut tx_builder = TransactionBuilder::new(
  1979. ContractCallLeaf { call: exec_call, proofs: exec_proofs },
  1980. vec![
  1981. DarkTree::new(
  1982. ContractCallLeaf { call: auth_transfer_call, proofs: auth_transfer_proofs },
  1983. vec![],
  1984. None,
  1985. None,
  1986. ),
  1987. DarkTree::new(
  1988. ContractCallLeaf { call: transfer_call, proofs: transfer_secrets.proofs },
  1989. vec![],
  1990. None,
  1991. None,
  1992. ),
  1993. ],
  1994. )?;
  1995. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  1996. // it into the fee-creating function.
  1997. let mut tx = tx_builder.build()?;
  1998. let auth_transfer_sigs = tx.create_sigs(&[])?;
  1999. let transfer_sigs = tx.create_sigs(&transfer_secrets.signature_secrets)?;
  2000. let exec_sigs = tx.create_sigs(&[exec_signature_secret])?;
  2001. tx.signatures = vec![auth_transfer_sigs, transfer_sigs, exec_sigs];
  2002. let (fee_call, fee_proofs, fee_secrets) =
  2003. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  2004. // Append the fee call to the transaction
  2005. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  2006. // Now build the actual transaction and sign it with all necessary keys.
  2007. let mut tx = tx_builder.build()?;
  2008. let sigs = tx.create_sigs(&[])?;
  2009. tx.signatures.push(sigs);
  2010. let sigs = tx.create_sigs(&transfer_secrets.signature_secrets)?;
  2011. tx.signatures.push(sigs);
  2012. let sigs = tx.create_sigs(&[exec_signature_secret])?;
  2013. tx.signatures.push(sigs);
  2014. let sigs = tx.create_sigs(&fee_secrets)?;
  2015. tx.signatures.push(sigs);
  2016. Ok(tx)
  2017. }
  2018. }