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