dao.rs 134 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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, str::FromStr};
  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_EARLY_EXEC_NS,
  42. DAO_CONTRACT_ZKAS_DAO_EXEC_NS, DAO_CONTRACT_ZKAS_DAO_MINT_NS,
  43. DAO_CONTRACT_ZKAS_DAO_PROPOSE_INPUT_NS, DAO_CONTRACT_ZKAS_DAO_PROPOSE_MAIN_NS,
  44. DAO_CONTRACT_ZKAS_DAO_VOTE_INPUT_NS, 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, 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. /// DAO notes decryption secret key
  123. pub notes_secret_key: Option<SecretKey>,
  124. /// DAO proposals creator secret key
  125. pub proposer_secret_key: Option<SecretKey>,
  126. /// DAO proposals viewer secret key
  127. pub proposals_secret_key: Option<SecretKey>,
  128. /// DAO votes viewer secret key
  129. pub votes_secret_key: Option<SecretKey>,
  130. /// DAO proposals executor secret key
  131. pub exec_secret_key: Option<SecretKey>,
  132. /// DAO strongly supported proposals executor secret key
  133. pub early_exec_secret_key: Option<SecretKey>,
  134. }
  135. impl DaoParams {
  136. /// Generate new `DaoParams`. If a specific secret key is provided,
  137. /// the corresponding public key will be derived from it and ignore the provided one.
  138. #[allow(clippy::too_many_arguments)]
  139. pub fn new(
  140. proposer_limit: u64,
  141. quorum: u64,
  142. early_exec_quorum: u64,
  143. approval_ratio_base: u64,
  144. approval_ratio_quot: u64,
  145. gov_token_id: TokenId,
  146. notes_secret_key: Option<SecretKey>,
  147. notes_public_key: PublicKey,
  148. proposer_secret_key: Option<SecretKey>,
  149. proposer_public_key: PublicKey,
  150. proposals_secret_key: Option<SecretKey>,
  151. proposals_public_key: PublicKey,
  152. votes_secret_key: Option<SecretKey>,
  153. votes_public_key: PublicKey,
  154. exec_secret_key: Option<SecretKey>,
  155. exec_public_key: PublicKey,
  156. early_exec_secret_key: Option<SecretKey>,
  157. early_exec_public_key: PublicKey,
  158. bulla_blind: BaseBlind,
  159. ) -> Self {
  160. // Derive corresponding keys from their secret or use the provided ones.
  161. let notes_public_key = match notes_secret_key {
  162. Some(secret_key) => PublicKey::from_secret(secret_key),
  163. None => notes_public_key,
  164. };
  165. let proposer_public_key = match proposer_secret_key {
  166. Some(secret_key) => PublicKey::from_secret(secret_key),
  167. None => proposer_public_key,
  168. };
  169. let proposals_public_key = match proposals_secret_key {
  170. Some(secret_key) => PublicKey::from_secret(secret_key),
  171. None => proposals_public_key,
  172. };
  173. let votes_public_key = match votes_secret_key {
  174. Some(secret_key) => PublicKey::from_secret(secret_key),
  175. None => votes_public_key,
  176. };
  177. let exec_public_key = match exec_secret_key {
  178. Some(secret_key) => PublicKey::from_secret(secret_key),
  179. None => exec_public_key,
  180. };
  181. let early_exec_public_key = match early_exec_secret_key {
  182. Some(secret_key) => PublicKey::from_secret(secret_key),
  183. None => early_exec_public_key,
  184. };
  185. let dao = Dao {
  186. proposer_limit,
  187. quorum,
  188. early_exec_quorum,
  189. approval_ratio_base,
  190. approval_ratio_quot,
  191. gov_token_id,
  192. notes_public_key,
  193. proposer_public_key,
  194. proposals_public_key,
  195. votes_public_key,
  196. exec_public_key,
  197. early_exec_public_key,
  198. bulla_blind,
  199. };
  200. Self {
  201. dao,
  202. notes_secret_key,
  203. proposer_secret_key,
  204. proposals_secret_key,
  205. votes_secret_key,
  206. exec_secret_key,
  207. early_exec_secret_key,
  208. }
  209. }
  210. /// Parse provided toml string into `DaoParams`.
  211. /// If a specific secret key is provided, the corresponding public key
  212. /// will be derived from it and ignore the provided one.
  213. pub fn from_toml_str(toml: &str) -> Result<Self> {
  214. // Parse TOML file contents
  215. let Ok(contents) = toml::from_str::<toml::Value>(toml) else {
  216. return Err(Error::ParseFailed("Failed parsing TOML config"))
  217. };
  218. let Some(table) = contents.as_table() else {
  219. return Err(Error::ParseFailed("TOML not a map"))
  220. };
  221. // Grab configuration parameters
  222. let Some(proposer_limit) = table.get("proposer_limit") else {
  223. return Err(Error::ParseFailed("TOML does not contain proposer limit"))
  224. };
  225. let Some(proposer_limit) = proposer_limit.as_str() else {
  226. return Err(Error::ParseFailed("Invalid proposer limit: Not a string"))
  227. };
  228. if f64::from_str(proposer_limit).is_err() {
  229. return Err(Error::ParseFailed("Invalid proposer limit: Cannot be parsed to float"))
  230. }
  231. let proposer_limit = decode_base10(proposer_limit, BALANCE_BASE10_DECIMALS, true)?;
  232. let Some(quorum) = table.get("quorum") else {
  233. return Err(Error::ParseFailed("TOML does not contain quorum"))
  234. };
  235. let Some(quorum) = quorum.as_str() else {
  236. return Err(Error::ParseFailed("Invalid quorum: Not a string"))
  237. };
  238. if f64::from_str(quorum).is_err() {
  239. return Err(Error::ParseFailed("Invalid quorum: Cannot be parsed to float"))
  240. }
  241. let quorum = decode_base10(quorum, BALANCE_BASE10_DECIMALS, true)?;
  242. let Some(early_exec_quorum) = table.get("early_exec_quorum") else {
  243. return Err(Error::ParseFailed("TOML does not contain early exec quorum"))
  244. };
  245. let Some(early_exec_quorum) = early_exec_quorum.as_str() else {
  246. return Err(Error::ParseFailed("Invalid early exec quorum: Not a string"))
  247. };
  248. if f64::from_str(early_exec_quorum).is_err() {
  249. return Err(Error::ParseFailed("Invalid early exec quorum: Cannot be parsed to float"))
  250. }
  251. let early_exec_quorum = decode_base10(early_exec_quorum, BALANCE_BASE10_DECIMALS, true)?;
  252. let Some(approval_ratio) = table.get("approval_ratio") else {
  253. return Err(Error::ParseFailed("TOML does not contain approval ratio"))
  254. };
  255. let Some(approval_ratio) = approval_ratio.as_float() else {
  256. return Err(Error::ParseFailed("Invalid approval ratio: Not a float"))
  257. };
  258. if approval_ratio > 1.0 {
  259. return Err(Error::ParseFailed("Approval ratio cannot be >1.0"))
  260. }
  261. let approval_ratio_base = 100_u64;
  262. let approval_ratio_quot = (approval_ratio * approval_ratio_base as f64) as u64;
  263. let Some(gov_token_id) = table.get("gov_token_id") else {
  264. return Err(Error::ParseFailed("TOML does not contain gov token id"))
  265. };
  266. let Some(gov_token_id) = gov_token_id.as_str() else {
  267. return Err(Error::ParseFailed("Invalid gov token id: Not a string"))
  268. };
  269. let gov_token_id = TokenId::from_str(gov_token_id)?;
  270. let Some(bulla_blind) = table.get("bulla_blind") else {
  271. return Err(Error::ParseFailed("TOML does not contain bulla blind"))
  272. };
  273. let Some(bulla_blind) = bulla_blind.as_str() else {
  274. return Err(Error::ParseFailed("Invalid bulla blind: Not a string"))
  275. };
  276. let bulla_blind = BaseBlind::from_str(bulla_blind)?;
  277. // Grab DAO actions keypairs
  278. let notes_secret_key = match table.get("notes_secret_key") {
  279. Some(notes_secret_key) => {
  280. let Some(notes_secret_key) = notes_secret_key.as_str() else {
  281. return Err(Error::ParseFailed("Invalid notes secret key: Not a string"))
  282. };
  283. let Ok(notes_secret_key) = SecretKey::from_str(notes_secret_key) else {
  284. return Err(Error::ParseFailed("Invalid notes secret key: Decoding failed"))
  285. };
  286. Some(notes_secret_key)
  287. }
  288. None => None,
  289. };
  290. let notes_public_key = match notes_secret_key {
  291. Some(notes_secret_key) => PublicKey::from_secret(notes_secret_key),
  292. None => {
  293. let Some(notes_public_key) = table.get("notes_public_key") else {
  294. return Err(Error::ParseFailed("TOML does not contain notes public key"))
  295. };
  296. let Some(notes_public_key) = notes_public_key.as_str() else {
  297. return Err(Error::ParseFailed("Invalid notes public key: Not a string"))
  298. };
  299. let Ok(notes_public_key) = PublicKey::from_str(notes_public_key) else {
  300. return Err(Error::ParseFailed("Invalid notes public key: Decoding failed"))
  301. };
  302. notes_public_key
  303. }
  304. };
  305. let proposer_secret_key = match table.get("proposer_secret_key") {
  306. Some(proposer_secret_key) => {
  307. let Some(proposer_secret_key) = proposer_secret_key.as_str() else {
  308. return Err(Error::ParseFailed("Invalid proposer secret key: Not a string"))
  309. };
  310. let Ok(proposer_secret_key) = SecretKey::from_str(proposer_secret_key) else {
  311. return Err(Error::ParseFailed("Invalid proposer secret key: Decoding failed"))
  312. };
  313. Some(proposer_secret_key)
  314. }
  315. None => None,
  316. };
  317. let proposer_public_key = match proposer_secret_key {
  318. Some(proposer_secret_key) => PublicKey::from_secret(proposer_secret_key),
  319. None => {
  320. let Some(proposer_public_key) = table.get("proposer_public_key") else {
  321. return Err(Error::ParseFailed("TOML does not contain proposer public key"))
  322. };
  323. let Some(proposer_public_key) = proposer_public_key.as_str() else {
  324. return Err(Error::ParseFailed("Invalid proposer public key: Not a string"))
  325. };
  326. let Ok(proposer_public_key) = PublicKey::from_str(proposer_public_key) else {
  327. return Err(Error::ParseFailed("Invalid proposer public key: Decoding failed"))
  328. };
  329. proposer_public_key
  330. }
  331. };
  332. let proposals_secret_key = match table.get("proposals_secret_key") {
  333. Some(proposals_secret_key) => {
  334. let Some(proposals_secret_key) = proposals_secret_key.as_str() else {
  335. return Err(Error::ParseFailed("Invalid proposals secret key: Not a string"))
  336. };
  337. let Ok(proposals_secret_key) = SecretKey::from_str(proposals_secret_key) else {
  338. return Err(Error::ParseFailed("Invalid proposals secret key: Decoding failed"))
  339. };
  340. Some(proposals_secret_key)
  341. }
  342. None => None,
  343. };
  344. let proposals_public_key = match proposals_secret_key {
  345. Some(proposals_secret_key) => PublicKey::from_secret(proposals_secret_key),
  346. None => {
  347. let Some(proposals_public_key) = table.get("proposals_public_key") else {
  348. return Err(Error::ParseFailed("TOML does not contain proposals public key"))
  349. };
  350. let Some(proposals_public_key) = proposals_public_key.as_str() else {
  351. return Err(Error::ParseFailed("Invalid proposals public key: Not a string"))
  352. };
  353. let Ok(proposals_public_key) = PublicKey::from_str(proposals_public_key) else {
  354. return Err(Error::ParseFailed("Invalid proposals public key: Decoding failed"))
  355. };
  356. proposals_public_key
  357. }
  358. };
  359. let votes_secret_key = match table.get("votes_secret_key") {
  360. Some(votes_secret_key) => {
  361. let Some(votes_secret_key) = votes_secret_key.as_str() else {
  362. return Err(Error::ParseFailed("Invalid votes secret key: Not a string"))
  363. };
  364. let Ok(votes_secret_key) = SecretKey::from_str(votes_secret_key) else {
  365. return Err(Error::ParseFailed("Invalid votes secret key: Decoding failed"))
  366. };
  367. Some(votes_secret_key)
  368. }
  369. None => None,
  370. };
  371. let votes_public_key = match votes_secret_key {
  372. Some(votes_secret_key) => PublicKey::from_secret(votes_secret_key),
  373. None => {
  374. let Some(votes_public_key) = table.get("votes_public_key") else {
  375. return Err(Error::ParseFailed("TOML does not contain votes public key"))
  376. };
  377. let Some(votes_public_key) = votes_public_key.as_str() else {
  378. return Err(Error::ParseFailed("Invalid votes public key: Not a string"))
  379. };
  380. let Ok(votes_public_key) = PublicKey::from_str(votes_public_key) else {
  381. return Err(Error::ParseFailed("Invalid votes public key: Decoding failed"))
  382. };
  383. votes_public_key
  384. }
  385. };
  386. let exec_secret_key = match table.get("exec_secret_key") {
  387. Some(exec_secret_key) => {
  388. let Some(exec_secret_key) = exec_secret_key.as_str() else {
  389. return Err(Error::ParseFailed("Invalid exec secret key: Not a string"))
  390. };
  391. let Ok(exec_secret_key) = SecretKey::from_str(exec_secret_key) else {
  392. return Err(Error::ParseFailed("Invalid exec secret key: Decoding failed"))
  393. };
  394. Some(exec_secret_key)
  395. }
  396. None => None,
  397. };
  398. let exec_public_key = match exec_secret_key {
  399. Some(exec_secret_key) => PublicKey::from_secret(exec_secret_key),
  400. None => {
  401. let Some(exec_public_key) = table.get("exec_public_key") else {
  402. return Err(Error::ParseFailed("TOML does not contain exec public key"))
  403. };
  404. let Some(exec_public_key) = exec_public_key.as_str() else {
  405. return Err(Error::ParseFailed("Invalid exec public key: Not a string"))
  406. };
  407. let Ok(exec_public_key) = PublicKey::from_str(exec_public_key) else {
  408. return Err(Error::ParseFailed("Invalid exec public key: Decoding failed"))
  409. };
  410. exec_public_key
  411. }
  412. };
  413. let early_exec_secret_key = match table.get("early_exec_secret_key") {
  414. Some(early_exec_secret_key) => {
  415. let Some(early_exec_secret_key) = early_exec_secret_key.as_str() else {
  416. return Err(Error::ParseFailed("Invalid early exec secret key: Not a string"))
  417. };
  418. let Ok(early_exec_secret_key) = SecretKey::from_str(early_exec_secret_key) else {
  419. return Err(Error::ParseFailed("Invalid early exec secret key: Decoding failed"))
  420. };
  421. Some(early_exec_secret_key)
  422. }
  423. None => None,
  424. };
  425. let early_exec_public_key = match early_exec_secret_key {
  426. Some(early_exec_secret_key) => PublicKey::from_secret(early_exec_secret_key),
  427. None => {
  428. let Some(early_exec_public_key) = table.get("early_exec_public_key") else {
  429. return Err(Error::ParseFailed("TOML does not contain early exec public key"))
  430. };
  431. let Some(early_exec_public_key) = early_exec_public_key.as_str() else {
  432. return Err(Error::ParseFailed("Invalid early exec public key: Not a string"))
  433. };
  434. let Ok(early_exec_public_key) = PublicKey::from_str(early_exec_public_key) else {
  435. return Err(Error::ParseFailed("Invalid early exec public key: Decoding failed"))
  436. };
  437. early_exec_public_key
  438. }
  439. };
  440. Ok(Self::new(
  441. proposer_limit,
  442. quorum,
  443. early_exec_quorum,
  444. approval_ratio_base,
  445. approval_ratio_quot,
  446. gov_token_id,
  447. notes_secret_key,
  448. notes_public_key,
  449. proposer_secret_key,
  450. proposer_public_key,
  451. proposals_secret_key,
  452. proposals_public_key,
  453. votes_secret_key,
  454. votes_public_key,
  455. exec_secret_key,
  456. exec_public_key,
  457. early_exec_secret_key,
  458. early_exec_public_key,
  459. bulla_blind,
  460. ))
  461. }
  462. /// Generate a toml string containing the DAO configuration.
  463. pub fn toml_str(&self) -> String {
  464. // Header comments
  465. let mut toml = String::from(
  466. "## DAO configuration file\n\
  467. ##\n\
  468. ## Please make sure you go through all the settings so you can configure\n\
  469. ## your DAO properly.\n\
  470. ##\n\
  471. ## If you want to restrict access to certain actions, the corresponding\n\
  472. ## secret key can be ommited. All public keys, along with the DAO configuration\n\
  473. ## parameters must be shared.\n\
  474. ##\n\
  475. ## If you want to combine access to certain actions, you can use the same\n\
  476. ## secret and public key combination for them.\n\n",
  477. );
  478. // Configuration parameters
  479. toml += &format!(
  480. "## ====== DAO configuration parameters =====\n\n\
  481. ## The minimum amount of governance tokens needed to open a proposal for this DAO\n\
  482. proposer_limit = \"{}\"\n\n\
  483. ## Minimal threshold of participating total tokens needed for a proposal to pass\n\
  484. quorum = \"{}\"\n\n\
  485. ## Minimal threshold of participating total tokens needed for a proposal to\n\
  486. ## be considered as strongly supported, enabling early execution.\n\
  487. ## Must be greater or equal to normal quorum.\n\
  488. early_exec_quorum = \"{}\"\n\n\
  489. ## The ratio of winning votes/total votes needed for a proposal to pass (2 decimals)\n\
  490. approval_ratio = {}\n\n\
  491. ## DAO's governance token ID\n\
  492. gov_token_id = \"{}\"\n\n\
  493. ## Bulla blind\n\
  494. bulla_blind = \"{}\"\n\n",
  495. encode_base10(self.dao.proposer_limit, BALANCE_BASE10_DECIMALS),
  496. encode_base10(self.dao.quorum, BALANCE_BASE10_DECIMALS),
  497. encode_base10(self.dao.early_exec_quorum, BALANCE_BASE10_DECIMALS),
  498. self.dao.approval_ratio_quot as f64 / self.dao.approval_ratio_base as f64,
  499. self.dao.gov_token_id,
  500. self.dao.bulla_blind,
  501. );
  502. // DAO actions keypairs
  503. toml += &format!(
  504. "## ====== DAO actions keypairs =====\n\n\
  505. ## DAO notes decryption keypair\n\
  506. notes_public_key = \"{}\"\n",
  507. self.dao.notes_public_key,
  508. );
  509. match self.notes_secret_key {
  510. Some(secret_key) => toml += &format!("notes_secret_key = \"{}\"\n\n", secret_key),
  511. None => toml += "\n",
  512. }
  513. toml += &format!(
  514. "## DAO proposals creator keypair\n\
  515. proposer_public_key = \"{}\"\n",
  516. self.dao.proposer_public_key,
  517. );
  518. match self.proposer_secret_key {
  519. Some(secret_key) => toml += &format!("proposer_secret_key = \"{}\"\n\n", secret_key),
  520. None => toml += "\n",
  521. }
  522. toml += &format!(
  523. "## DAO proposals viewer keypair\n\
  524. proposals_public_key = \"{}\"\n",
  525. self.dao.proposals_public_key,
  526. );
  527. match self.proposals_secret_key {
  528. Some(secret_key) => toml += &format!("proposals_secret_key = \"{}\"\n\n", secret_key),
  529. None => toml += "\n",
  530. }
  531. toml += &format!(
  532. "## DAO votes viewer keypair\n\
  533. votes_public_key = \"{}\"\n",
  534. self.dao.votes_public_key,
  535. );
  536. match self.votes_secret_key {
  537. Some(secret_key) => toml += &format!("votes_secret_key = \"{}\"\n\n", secret_key),
  538. None => toml += "\n",
  539. }
  540. toml += &format!(
  541. "## DAO proposals executor keypair\n\
  542. exec_public_key = \"{}\"\n",
  543. self.dao.exec_public_key,
  544. );
  545. match self.exec_secret_key {
  546. Some(secret_key) => toml += &format!("exec_secret_key = \"{}\"\n\n", secret_key),
  547. None => toml += "\n",
  548. }
  549. toml += &format!(
  550. "## DAO strongly supported proposals executor keypair\n\
  551. early_exec_public_key = \"{}\"",
  552. self.dao.early_exec_public_key,
  553. );
  554. if let Some(secret_key) = self.early_exec_secret_key {
  555. toml += &format!("\nearly_exec_secret_key = \"{}\"", secret_key)
  556. }
  557. toml
  558. }
  559. }
  560. impl fmt::Display for DaoParams {
  561. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  562. // Grab known secret keys
  563. let notes_secret_key = match self.notes_secret_key {
  564. Some(secret_key) => format!("{secret_key}"),
  565. None => "None".to_string(),
  566. };
  567. let proposer_secret_key = match self.proposer_secret_key {
  568. Some(secret_key) => format!("{secret_key}"),
  569. None => "None".to_string(),
  570. };
  571. let proposals_secret_key = match self.proposals_secret_key {
  572. Some(secret_key) => format!("{secret_key}"),
  573. None => "None".to_string(),
  574. };
  575. let votes_secret_key = match self.votes_secret_key {
  576. Some(secret_key) => format!("{secret_key}"),
  577. None => "None".to_string(),
  578. };
  579. let exec_secret_key = match self.exec_secret_key {
  580. Some(secret_key) => format!("{secret_key}"),
  581. None => "None".to_string(),
  582. };
  583. let early_exec_secret_key = match self.early_exec_secret_key {
  584. Some(secret_key) => format!("{secret_key}"),
  585. None => "None".to_string(),
  586. };
  587. let s = format!(
  588. "{}\n{}\n{}: {} ({})\n{}: {} ({})\n{}: {} ({})\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}",
  589. "DAO Parameters",
  590. "==============",
  591. "Proposer limit",
  592. encode_base10(self.dao.proposer_limit, BALANCE_BASE10_DECIMALS),
  593. self.dao.proposer_limit,
  594. "Quorum",
  595. encode_base10(self.dao.quorum, BALANCE_BASE10_DECIMALS),
  596. self.dao.quorum,
  597. "Early Exec Quorum",
  598. encode_base10(self.dao.early_exec_quorum, BALANCE_BASE10_DECIMALS),
  599. self.dao.early_exec_quorum,
  600. "Approval ratio",
  601. self.dao.approval_ratio_quot as f64 / self.dao.approval_ratio_base as f64,
  602. "Governance Token ID",
  603. self.dao.gov_token_id,
  604. "Notes Public key",
  605. self.dao.notes_public_key,
  606. "Notes Secret key",
  607. notes_secret_key,
  608. "Proposer Public key",
  609. self.dao.proposer_public_key,
  610. "Proposer Secret key",
  611. proposer_secret_key,
  612. "Proposals Public key",
  613. self.dao.proposals_public_key,
  614. "Proposals Secret key",
  615. proposals_secret_key,
  616. "Votes Public key",
  617. self.dao.votes_public_key,
  618. "Votes Secret key",
  619. votes_secret_key,
  620. "Exec Public key",
  621. self.dao.exec_public_key,
  622. "Exec Secret key",
  623. exec_secret_key,
  624. "Early Exec Public key",
  625. self.dao.early_exec_public_key,
  626. "Early Exec Secret key",
  627. early_exec_secret_key,
  628. "Bulla blind",
  629. self.dao.bulla_blind,
  630. );
  631. write!(f, "{}", s)
  632. }
  633. }
  634. #[derive(Debug, Clone)]
  635. /// Structure representing a `DAO_DAOS_TABLE` record.
  636. pub struct DaoRecord {
  637. /// Name identifier for the DAO
  638. pub name: String,
  639. /// DAO parameters
  640. pub params: DaoParams,
  641. /// Leaf position of the DAO in the Merkle tree of DAOs
  642. pub leaf_position: Option<bridgetree::Position>,
  643. /// The transaction hash where the DAO was deployed
  644. pub tx_hash: Option<TransactionHash>,
  645. /// The call index in the transaction where the DAO was deployed
  646. pub call_index: Option<u8>,
  647. }
  648. impl DaoRecord {
  649. pub fn new(
  650. name: String,
  651. params: DaoParams,
  652. leaf_position: Option<bridgetree::Position>,
  653. tx_hash: Option<TransactionHash>,
  654. call_index: Option<u8>,
  655. ) -> Self {
  656. Self { name, params, leaf_position, tx_hash, call_index }
  657. }
  658. pub fn bulla(&self) -> DaoBulla {
  659. self.params.dao.to_bulla()
  660. }
  661. }
  662. impl fmt::Display for DaoRecord {
  663. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  664. // Grab known secret keys
  665. let notes_secret_key = match self.params.notes_secret_key {
  666. Some(secret_key) => format!("{secret_key}"),
  667. None => "None".to_string(),
  668. };
  669. let proposer_secret_key = match self.params.proposer_secret_key {
  670. Some(secret_key) => format!("{secret_key}"),
  671. None => "None".to_string(),
  672. };
  673. let proposals_secret_key = match self.params.proposals_secret_key {
  674. Some(secret_key) => format!("{secret_key}"),
  675. None => "None".to_string(),
  676. };
  677. let votes_secret_key = match self.params.votes_secret_key {
  678. Some(secret_key) => format!("{secret_key}"),
  679. None => "None".to_string(),
  680. };
  681. let exec_secret_key = match self.params.exec_secret_key {
  682. Some(secret_key) => format!("{secret_key}"),
  683. None => "None".to_string(),
  684. };
  685. let early_exec_secret_key = match self.params.early_exec_secret_key {
  686. Some(secret_key) => format!("{secret_key}"),
  687. None => "None".to_string(),
  688. };
  689. // Grab mint information
  690. let leaf_position = match self.leaf_position {
  691. Some(p) => format!("{p:?}"),
  692. None => "None".to_string(),
  693. };
  694. let tx_hash = match self.tx_hash {
  695. Some(t) => format!("{t}"),
  696. None => "None".to_string(),
  697. };
  698. let call_index = match self.call_index {
  699. Some(c) => format!("{c}"),
  700. None => "None".to_string(),
  701. };
  702. let s = format!(
  703. "{}\n{}\n{}: {}\n{}: {}\n{}: {} ({})\n{}: {} ({})\n{}: {} ({})\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}",
  704. "DAO Parameters",
  705. "==============",
  706. "Name",
  707. self.name,
  708. "Bulla",
  709. self.bulla(),
  710. "Proposer limit",
  711. encode_base10(self.params.dao.proposer_limit, BALANCE_BASE10_DECIMALS),
  712. self.params.dao.proposer_limit,
  713. "Quorum",
  714. encode_base10(self.params.dao.quorum, BALANCE_BASE10_DECIMALS),
  715. self.params.dao.quorum,
  716. "Early Exec Quorum",
  717. encode_base10(self.params.dao.early_exec_quorum, BALANCE_BASE10_DECIMALS),
  718. self.params.dao.early_exec_quorum,
  719. "Approval ratio",
  720. self.params.dao.approval_ratio_quot as f64 / self.params.dao.approval_ratio_base as f64,
  721. "Governance Token ID",
  722. self.params.dao.gov_token_id,
  723. "Notes Public key",
  724. self.params.dao.notes_public_key,
  725. "Notes Secret key",
  726. notes_secret_key,
  727. "Proposer Public key",
  728. self.params.dao.proposer_public_key,
  729. "Proposer Secret key",
  730. proposer_secret_key,
  731. "Proposals Public key",
  732. self.params.dao.proposals_public_key,
  733. "Proposals Secret key",
  734. proposals_secret_key,
  735. "Votes Public key",
  736. self.params.dao.votes_public_key,
  737. "Votes Secret key",
  738. votes_secret_key,
  739. "Exec Public key",
  740. self.params.dao.exec_public_key,
  741. "Exec Secret key",
  742. exec_secret_key,
  743. "Early Exec Public key",
  744. self.params.dao.early_exec_public_key,
  745. "Early Exec Secret key",
  746. early_exec_secret_key,
  747. "Bulla blind",
  748. self.params.dao.bulla_blind,
  749. "Leaf position",
  750. leaf_position,
  751. "Transaction hash",
  752. tx_hash,
  753. "Call index",
  754. call_index,
  755. );
  756. write!(f, "{}", s)
  757. }
  758. }
  759. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  760. /// Structure representing a `DAO_PROPOSALS_TABLE` record.
  761. pub struct ProposalRecord {
  762. /// The on chain representation of the proposal
  763. pub proposal: DaoProposal,
  764. /// Plaintext proposal call data the members share between them
  765. pub data: Option<Vec<u8>>,
  766. /// Leaf position of the proposal in the Merkle tree of proposals
  767. pub leaf_position: Option<bridgetree::Position>,
  768. /// Money merkle tree snapshot for reproducing the snapshot Merkle root
  769. pub money_snapshot_tree: Option<MerkleTree>,
  770. /// Money nullifiers SMT snapshot for reproducing the snapshot Merkle root
  771. pub nullifiers_smt_snapshot: Option<HashMap<BigUint, pallas::Base>>,
  772. /// The transaction hash where the proposal was deployed
  773. pub tx_hash: Option<TransactionHash>,
  774. /// The call index in the transaction where the proposal was deployed
  775. pub call_index: Option<u8>,
  776. /// The transaction hash where the proposal was executed
  777. pub exec_tx_hash: Option<TransactionHash>,
  778. }
  779. impl ProposalRecord {
  780. pub fn bulla(&self) -> DaoProposalBulla {
  781. self.proposal.to_bulla()
  782. }
  783. }
  784. impl fmt::Display for ProposalRecord {
  785. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  786. let leaf_position = match self.leaf_position {
  787. Some(p) => format!("{p:?}"),
  788. None => "None".to_string(),
  789. };
  790. let tx_hash = match self.tx_hash {
  791. Some(t) => format!("{t}"),
  792. None => "None".to_string(),
  793. };
  794. let call_index = match self.call_index {
  795. Some(c) => format!("{c}"),
  796. None => "None".to_string(),
  797. };
  798. let s = format!(
  799. "{}\n{}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {} ({})",
  800. "Proposal parameters",
  801. "===================",
  802. "Bulla",
  803. self.bulla(),
  804. "DAO Bulla",
  805. self.proposal.dao_bulla,
  806. "Proposal leaf position",
  807. leaf_position,
  808. "Proposal transaction hash",
  809. tx_hash,
  810. "Proposal call index",
  811. call_index,
  812. "Creation block window",
  813. self.proposal.creation_blockwindow,
  814. "Duration",
  815. self.proposal.duration_blockwindows,
  816. "Block windows"
  817. );
  818. write!(f, "{}", s)
  819. }
  820. }
  821. #[derive(Debug, Clone)]
  822. /// Structure representing a `DAO_VOTES_TABLE` record.
  823. pub struct VoteRecord {
  824. /// Numeric identifier for the vote
  825. pub id: u64,
  826. /// Bulla identifier of the proposal this vote is for
  827. pub proposal: DaoProposalBulla,
  828. /// The vote
  829. pub vote_option: bool,
  830. /// Blinding factor for the yes vote
  831. pub yes_vote_blind: ScalarBlind,
  832. /// Value of all votes
  833. pub all_vote_value: u64,
  834. /// Blinding facfor of all votes
  835. pub all_vote_blind: ScalarBlind,
  836. /// Transaction hash where this vote was casted
  837. pub tx_hash: TransactionHash,
  838. /// Call index in the transaction where this vote was casted
  839. pub call_index: u8,
  840. /// Vote input nullifiers
  841. pub nullifiers: Vec<Nullifier>,
  842. }
  843. impl Drk {
  844. /// Initialize wallet with tables for the DAO contract.
  845. pub async fn initialize_dao(&self) -> WalletDbResult<()> {
  846. // Initialize DAO wallet schema
  847. let wallet_schema = include_str!("../dao.sql");
  848. self.wallet.exec_batch_sql(wallet_schema)?;
  849. // Check if we have to initialize the Merkle trees.
  850. // We check if one exists, but we actually create two. This should be written
  851. // a bit better and safer.
  852. // For now, on success, we don't care what's returned, but in the future
  853. // we should actually check it.
  854. if self.get_dao_trees().await.is_err() {
  855. println!("Initializing DAO Merkle trees");
  856. let tree = serialize_async(&MerkleTree::new(1)).await;
  857. let query = format!(
  858. "INSERT INTO {} ({}, {}) VALUES (?1, ?2);",
  859. *DAO_TREES_TABLE, DAO_TREES_COL_DAOS_TREE, DAO_TREES_COL_PROPOSALS_TREE
  860. );
  861. self.wallet.exec_sql(&query, rusqlite::params![tree, tree])?;
  862. println!("Successfully initialized Merkle trees for the DAO contract");
  863. }
  864. Ok(())
  865. }
  866. /// Replace the DAO Merkle trees in the wallet.
  867. pub async fn put_dao_trees(
  868. &self,
  869. daos_tree: &MerkleTree,
  870. proposals_tree: &MerkleTree,
  871. ) -> WalletDbResult<()> {
  872. let query = format!(
  873. "UPDATE {} SET {} = ?1, {} = ?2;",
  874. *DAO_TREES_TABLE, DAO_TREES_COL_DAOS_TREE, DAO_TREES_COL_PROPOSALS_TREE
  875. );
  876. self.wallet.exec_sql(
  877. &query,
  878. rusqlite::params![
  879. serialize_async(daos_tree).await,
  880. serialize_async(proposals_tree).await
  881. ],
  882. )
  883. }
  884. /// Fetch DAO Merkle trees from the wallet.
  885. pub async fn get_dao_trees(&self) -> Result<(MerkleTree, MerkleTree)> {
  886. let row = match self.wallet.query_single(&DAO_TREES_TABLE, &[], &[]) {
  887. Ok(r) => r,
  888. Err(e) => {
  889. return Err(Error::DatabaseError(format!(
  890. "[get_dao_trees] Trees retrieval failed: {e:?}"
  891. )))
  892. }
  893. };
  894. let Value::Blob(ref daos_tree_bytes) = row[0] else {
  895. return Err(Error::ParseFailed("[get_dao_trees] DAO tree bytes parsing failed"))
  896. };
  897. let daos_tree = deserialize_async(daos_tree_bytes).await?;
  898. let Value::Blob(ref proposals_tree_bytes) = row[1] else {
  899. return Err(Error::ParseFailed("[get_dao_trees] Proposals tree bytes parsing failed"))
  900. };
  901. let proposals_tree = deserialize_async(proposals_tree_bytes).await?;
  902. Ok((daos_tree, proposals_tree))
  903. }
  904. /// Auxiliary function to fetch the current DAO Merkle trees state,
  905. /// as an update query.
  906. pub async fn get_dao_trees_state_query(&self) -> Result<String> {
  907. // Grab current DAO trees
  908. let (daos_tree, proposals_tree) = self.get_dao_trees().await?;
  909. // Create the update query
  910. match self.wallet.create_prepared_statement(
  911. &format!(
  912. "UPDATE {} SET {} = ?1, {} = ?2;",
  913. *DAO_TREES_TABLE, DAO_TREES_COL_DAOS_TREE, DAO_TREES_COL_PROPOSALS_TREE
  914. ),
  915. rusqlite::params![
  916. serialize_async(&daos_tree).await,
  917. serialize_async(&proposals_tree).await
  918. ],
  919. ) {
  920. Ok(q) => Ok(q),
  921. Err(e) => Err(Error::DatabaseError(format!(
  922. "[get_dao_trees_state_query] Creating query for DAO trees failed: {e:?}"
  923. ))),
  924. }
  925. }
  926. /// Fetch all DAO notes secret keys from the wallet.
  927. pub async fn get_dao_notes_secrets(&self) -> Result<Vec<SecretKey>> {
  928. let daos = self.get_daos().await?;
  929. let mut ret = Vec::with_capacity(daos.len());
  930. for dao in daos {
  931. if let Some(secret_key) = dao.params.notes_secret_key {
  932. ret.push(secret_key);
  933. }
  934. }
  935. Ok(ret)
  936. }
  937. /// Auxiliary function to parse a `DAO_DAOS_TABLE` record.
  938. async fn parse_dao_record(&self, row: &[Value]) -> Result<DaoRecord> {
  939. let Value::Text(ref name) = row[1] else {
  940. return Err(Error::ParseFailed("[parse_dao_record] Name parsing failed"))
  941. };
  942. let name = name.clone();
  943. let Value::Blob(ref params_bytes) = row[2] else {
  944. return Err(Error::ParseFailed("[parse_dao_record] Params bytes parsing failed"))
  945. };
  946. let params = deserialize_async(params_bytes).await?;
  947. let leaf_position = match row[3] {
  948. Value::Blob(ref leaf_position_bytes) => {
  949. Some(deserialize_async(leaf_position_bytes).await?)
  950. }
  951. Value::Null => None,
  952. _ => {
  953. return Err(Error::ParseFailed(
  954. "[parse_dao_record] Leaf position bytes parsing failed",
  955. ))
  956. }
  957. };
  958. let tx_hash = match row[4] {
  959. Value::Blob(ref tx_hash_bytes) => Some(deserialize_async(tx_hash_bytes).await?),
  960. Value::Null => None,
  961. _ => {
  962. return Err(Error::ParseFailed(
  963. "[parse_dao_record] Transaction hash bytes parsing failed",
  964. ))
  965. }
  966. };
  967. let call_index = match row[5] {
  968. Value::Integer(call_index) => {
  969. let Ok(call_index) = u8::try_from(call_index) else {
  970. return Err(Error::ParseFailed("[parse_dao_record] Call index parsing failed"))
  971. };
  972. Some(call_index)
  973. }
  974. Value::Null => None,
  975. _ => return Err(Error::ParseFailed("[parse_dao_record] Call index parsing failed")),
  976. };
  977. let dao = DaoRecord::new(name, params, leaf_position, tx_hash, call_index);
  978. Ok(dao)
  979. }
  980. /// Fetch all known DAOs from the wallet.
  981. pub async fn get_daos(&self) -> Result<Vec<DaoRecord>> {
  982. let rows = match self.wallet.query_multiple(&DAO_DAOS_TABLE, &[], &[]) {
  983. Ok(r) => r,
  984. Err(e) => {
  985. return Err(Error::DatabaseError(format!("[get_daos] DAOs retrieval failed: {e:?}")))
  986. }
  987. };
  988. let mut daos = Vec::with_capacity(rows.len());
  989. for row in rows {
  990. daos.push(self.parse_dao_record(&row).await?);
  991. }
  992. Ok(daos)
  993. }
  994. /// Auxiliary function to parse a proposal record row.
  995. async fn parse_dao_proposal(&self, row: &[Value]) -> Result<ProposalRecord> {
  996. let Value::Blob(ref proposal_bytes) = row[2] else {
  997. return Err(Error::ParseFailed(
  998. "[get_dao_proposals] Proposal bytes bytes parsing failed",
  999. ))
  1000. };
  1001. let proposal = deserialize_async(proposal_bytes).await?;
  1002. let data = match row[3] {
  1003. Value::Blob(ref data_bytes) => Some(data_bytes.clone()),
  1004. Value::Null => None,
  1005. _ => return Err(Error::ParseFailed("[get_dao_proposals] Data bytes parsing failed")),
  1006. };
  1007. let leaf_position = match row[4] {
  1008. Value::Blob(ref leaf_position_bytes) => {
  1009. Some(deserialize_async(leaf_position_bytes).await?)
  1010. }
  1011. Value::Null => None,
  1012. _ => {
  1013. return Err(Error::ParseFailed(
  1014. "[get_dao_proposals] Leaf position bytes parsing failed",
  1015. ))
  1016. }
  1017. };
  1018. let money_snapshot_tree = match row[5] {
  1019. Value::Blob(ref money_snapshot_tree_bytes) => {
  1020. Some(deserialize_async(money_snapshot_tree_bytes).await?)
  1021. }
  1022. Value::Null => None,
  1023. _ => {
  1024. return Err(Error::ParseFailed(
  1025. "[get_dao_proposals] Money snapshot tree bytes parsing failed",
  1026. ))
  1027. }
  1028. };
  1029. let nullifiers_smt_snapshot = match row[6] {
  1030. Value::Blob(ref nullifiers_smt_snapshot_bytes) => {
  1031. Some(deserialize_async(nullifiers_smt_snapshot_bytes).await?)
  1032. }
  1033. Value::Null => None,
  1034. _ => {
  1035. return Err(Error::ParseFailed(
  1036. "[get_dao_proposals] Nullifiers SMT snapshot bytes parsing failed",
  1037. ))
  1038. }
  1039. };
  1040. let tx_hash = match row[7] {
  1041. Value::Blob(ref tx_hash_bytes) => Some(deserialize_async(tx_hash_bytes).await?),
  1042. Value::Null => None,
  1043. _ => {
  1044. return Err(Error::ParseFailed(
  1045. "[get_dao_proposals] Transaction hash bytes parsing failed",
  1046. ))
  1047. }
  1048. };
  1049. let call_index = match row[8] {
  1050. Value::Integer(call_index) => {
  1051. let Ok(call_index) = u8::try_from(call_index) else {
  1052. return Err(Error::ParseFailed("[get_dao_proposals] Call index parsing failed"))
  1053. };
  1054. Some(call_index)
  1055. }
  1056. Value::Null => None,
  1057. _ => return Err(Error::ParseFailed("[get_dao_proposals] Call index parsing failed")),
  1058. };
  1059. let exec_tx_hash = match row[9] {
  1060. Value::Blob(ref exec_tx_hash_bytes) => {
  1061. Some(deserialize_async(exec_tx_hash_bytes).await?)
  1062. }
  1063. Value::Null => None,
  1064. _ => {
  1065. return Err(Error::ParseFailed(
  1066. "[get_dao_proposals] Execution transaction hash bytes parsing failed",
  1067. ))
  1068. }
  1069. };
  1070. Ok(ProposalRecord {
  1071. proposal,
  1072. data,
  1073. leaf_position,
  1074. money_snapshot_tree,
  1075. nullifiers_smt_snapshot,
  1076. tx_hash,
  1077. call_index,
  1078. exec_tx_hash,
  1079. })
  1080. }
  1081. /// Fetch all known DAO proposals from the wallet given a DAO name.
  1082. pub async fn get_dao_proposals(&self, name: &str) -> Result<Vec<ProposalRecord>> {
  1083. let Ok(dao) = self.get_dao_by_name(name).await else {
  1084. return Err(Error::DatabaseError(format!(
  1085. "[get_dao_proposals] DAO with name {name} not found in wallet"
  1086. )))
  1087. };
  1088. let rows = match self.wallet.query_multiple(
  1089. &DAO_PROPOSALS_TABLE,
  1090. &[],
  1091. convert_named_params! {(DAO_PROPOSALS_COL_DAO_BULLA, serialize_async(&dao.bulla()).await)},
  1092. ) {
  1093. Ok(r) => r,
  1094. Err(e) => {
  1095. return Err(Error::DatabaseError(format!(
  1096. "[get_dao_proposals] Proposals retrieval failed: {e:?}"
  1097. )))
  1098. }
  1099. };
  1100. let mut proposals = Vec::with_capacity(rows.len());
  1101. for row in rows {
  1102. let proposal = self.parse_dao_proposal(&row).await?;
  1103. proposals.push(proposal);
  1104. }
  1105. Ok(proposals)
  1106. }
  1107. /// Auxiliary function to apply `DaoFunction::Mint` call data to the wallet,
  1108. /// and store its inverse query into the cache.
  1109. /// Returns a flag indicating if the provided call refers to our own wallet.
  1110. async fn apply_dao_mint_data(
  1111. &self,
  1112. new_bulla: DaoBulla,
  1113. tx_hash: TransactionHash,
  1114. call_index: u8,
  1115. ) -> Result<bool> {
  1116. let daos = self.get_daos().await?;
  1117. let (mut daos_tree, proposals_tree) = self.get_dao_trees().await?;
  1118. daos_tree.append(MerkleNode::from(new_bulla.inner()));
  1119. let mut wallet_tx = false;
  1120. for dao in &daos {
  1121. if dao.bulla() != new_bulla {
  1122. continue
  1123. }
  1124. println!(
  1125. "[apply_dao_mint_data] Found minted DAO {}, noting down for wallet update",
  1126. new_bulla
  1127. );
  1128. // We have this DAO imported in our wallet. Add the metadata:
  1129. let mut dao_to_confirm = dao.clone();
  1130. dao_to_confirm.leaf_position = daos_tree.mark();
  1131. dao_to_confirm.tx_hash = Some(tx_hash);
  1132. dao_to_confirm.call_index = Some(call_index);
  1133. // Confirm it
  1134. if let Err(e) = self.confirm_dao(&dao_to_confirm).await {
  1135. return Err(Error::DatabaseError(format!(
  1136. "[apply_dao_mint_data] Confirm DAO failed: {e:?}"
  1137. )))
  1138. }
  1139. wallet_tx = true;
  1140. break
  1141. }
  1142. // Update wallet data
  1143. if let Err(e) = self.put_dao_trees(&daos_tree, &proposals_tree).await {
  1144. return Err(Error::DatabaseError(format!(
  1145. "[apply_dao_mint_data] Put DAO tree failed: {e:?}"
  1146. )))
  1147. }
  1148. Ok(wallet_tx)
  1149. }
  1150. /// Auxiliary function to apply `DaoFunction::Propose` call data to the wallet,
  1151. /// and store its inverse query into the cache.
  1152. /// Returns a flag indicating if the provided call refers to our own wallet.
  1153. async fn apply_dao_propose_data(
  1154. &self,
  1155. params: DaoProposeParams,
  1156. tx_hash: TransactionHash,
  1157. call_index: u8,
  1158. ) -> Result<bool> {
  1159. let daos = self.get_daos().await?;
  1160. let (daos_tree, mut proposals_tree) = self.get_dao_trees().await?;
  1161. proposals_tree.append(MerkleNode::from(params.proposal_bulla.inner()));
  1162. // If we're able to decrypt this note, that's the way to link it
  1163. // to a specific DAO.
  1164. let mut wallet_tx = false;
  1165. for dao in &daos {
  1166. // Check if we have the proposals key
  1167. let Some(proposals_secret_key) = dao.params.proposals_secret_key else { continue };
  1168. // Try to decrypt the proposal note
  1169. let Ok(note) = params.note.decrypt::<DaoProposal>(&proposals_secret_key) else {
  1170. continue
  1171. };
  1172. // We managed to decrypt it. Let's place this in a proper ProposalRecord object
  1173. println!("[apply_dao_propose_data] Managed to decrypt DAO proposal note");
  1174. // We need to clone the trees here for reproducing the snapshot Merkle roots
  1175. let money_tree = self.get_money_tree().await?;
  1176. let nullifiers_smt = self.get_nullifiers_smt().await?;
  1177. // Check if we already got the record
  1178. let our_proposal = match self.get_dao_proposal_by_bulla(&params.proposal_bulla).await {
  1179. Ok(p) => {
  1180. let mut our_proposal = p;
  1181. our_proposal.leaf_position = proposals_tree.mark();
  1182. our_proposal.money_snapshot_tree = Some(money_tree);
  1183. our_proposal.nullifiers_smt_snapshot = Some(nullifiers_smt);
  1184. our_proposal.tx_hash = Some(tx_hash);
  1185. our_proposal.call_index = Some(call_index);
  1186. our_proposal
  1187. }
  1188. Err(_) => ProposalRecord {
  1189. proposal: note,
  1190. data: None,
  1191. leaf_position: proposals_tree.mark(),
  1192. money_snapshot_tree: Some(money_tree),
  1193. nullifiers_smt_snapshot: Some(nullifiers_smt),
  1194. tx_hash: Some(tx_hash),
  1195. call_index: Some(call_index),
  1196. exec_tx_hash: None,
  1197. },
  1198. };
  1199. // Update/store our record
  1200. if let Err(e) = self.put_dao_proposal(&our_proposal).await {
  1201. return Err(Error::DatabaseError(format!(
  1202. "[apply_dao_propose_data] Put DAO proposals failed: {e:?}"
  1203. )))
  1204. }
  1205. wallet_tx = true;
  1206. break
  1207. }
  1208. // Update wallet data
  1209. if let Err(e) = self.put_dao_trees(&daos_tree, &proposals_tree).await {
  1210. return Err(Error::DatabaseError(format!(
  1211. "[apply_dao_propose_data] Put DAO tree failed: {e:?}"
  1212. )))
  1213. }
  1214. Ok(wallet_tx)
  1215. }
  1216. /// Auxiliary function to apply `DaoFunction::Vote` call data to the wallet,
  1217. /// and store its inverse query into the cache.
  1218. /// Returns a flag indicating if the provided call refers to our own wallet.
  1219. async fn apply_dao_vote_data(
  1220. &self,
  1221. params: DaoVoteParams,
  1222. tx_hash: TransactionHash,
  1223. call_index: u8,
  1224. ) -> Result<bool> {
  1225. // Check if we got the corresponding proposal
  1226. let Ok(proposal) = self.get_dao_proposal_by_bulla(&params.proposal_bulla).await else {
  1227. return Ok(false)
  1228. };
  1229. // Grab the proposal DAO
  1230. let dao = match self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
  1231. Ok(d) => d,
  1232. Err(e) => {
  1233. return Err(Error::DatabaseError(format!(
  1234. "[apply_dao_vote_data] Couldn't find proposal {} DAO {}: {e}",
  1235. proposal.bulla(),
  1236. proposal.proposal.dao_bulla,
  1237. )))
  1238. }
  1239. };
  1240. // Check if we have the votes key
  1241. let Some(votes_secret_key) = dao.params.votes_secret_key else { return Ok(false) };
  1242. // Decrypt the vote note
  1243. let note = match params.note.decrypt_unsafe(&votes_secret_key) {
  1244. Ok(n) => n,
  1245. Err(e) => {
  1246. return Err(Error::DatabaseError(format!(
  1247. "[apply_dao_vote_data] Couldn't decrypt proposal {} vote with DAO {} keys: {e}",
  1248. proposal.bulla(),
  1249. proposal.proposal.dao_bulla,
  1250. )))
  1251. }
  1252. };
  1253. // Create the DAO vote record
  1254. let vote_option = fp_to_u64(note[0]).unwrap();
  1255. if vote_option > 1 {
  1256. return Err(Error::DatabaseError(format!(
  1257. "[apply_dao_vote_data] Malformed vote for proposal {}: {vote_option}",
  1258. proposal.bulla(),
  1259. )))
  1260. }
  1261. let vote_option = vote_option != 0;
  1262. let yes_vote_blind = Blind(fp_mod_fv(note[1]));
  1263. let all_vote_value = fp_to_u64(note[2]).unwrap();
  1264. let all_vote_blind = Blind(fp_mod_fv(note[3]));
  1265. let v = VoteRecord {
  1266. id: 0, // This will be set by SQLite AUTOINCREMENT
  1267. proposal: params.proposal_bulla,
  1268. vote_option,
  1269. yes_vote_blind,
  1270. all_vote_value,
  1271. all_vote_blind,
  1272. tx_hash,
  1273. call_index,
  1274. nullifiers: params.inputs.iter().map(|i| i.vote_nullifier).collect(),
  1275. };
  1276. if let Err(e) = self.put_dao_vote(&v).await {
  1277. return Err(Error::DatabaseError(format!(
  1278. "[apply_dao_vote_data] Put DAO votes failed: {e:?}"
  1279. )))
  1280. }
  1281. Ok(true)
  1282. }
  1283. /// Auxiliary function to apply `DaoFunction::Exec` call data to the wallet,
  1284. /// and store its inverse query into the cache.
  1285. /// Returns a flag indicating if the provided call refers to our own wallet.
  1286. async fn apply_dao_exec_data(
  1287. &self,
  1288. params: DaoExecParams,
  1289. tx_hash: TransactionHash,
  1290. ) -> Result<bool> {
  1291. // Check if we got the corresponding proposal
  1292. if self.get_dao_proposal_by_bulla(&params.proposal_bulla).await.is_err() {
  1293. return Ok(false)
  1294. };
  1295. // Grab proposal record key
  1296. let key = serialize_async(&params.proposal_bulla).await;
  1297. // Create an SQL `UPDATE` query to update proposal exec transaction hash
  1298. let query = format!(
  1299. "UPDATE {} SET {} = ?1 WHERE {} = ?2;",
  1300. *DAO_PROPOSALS_TABLE, DAO_PROPOSALS_COL_EXEC_TX_HASH, DAO_PROPOSALS_COL_BULLA,
  1301. );
  1302. // Create its inverse query
  1303. let inverse = match self.wallet.create_prepared_statement(
  1304. &format!(
  1305. "UPDATE {} SET {} = NULL WHERE {} = ?1;",
  1306. *DAO_PROPOSALS_TABLE, DAO_PROPOSALS_COL_EXEC_TX_HASH, DAO_PROPOSALS_COL_BULLA,
  1307. ),
  1308. rusqlite::params![key],
  1309. ) {
  1310. Ok(q) => q,
  1311. Err(e) => {
  1312. return Err(Error::DatabaseError(format!(
  1313. "[apply_dao_exec_data] Creating DAO proposal update inverse query failed: {e:?}"
  1314. )))
  1315. }
  1316. };
  1317. // Execute the query
  1318. if let Err(e) = self
  1319. .wallet
  1320. .exec_sql(&query, rusqlite::params![Some(serialize_async(&tx_hash).await), key])
  1321. {
  1322. return Err(Error::DatabaseError(format!(
  1323. "[apply_dao_exec_data] Update DAO proposal failed: {e:?}"
  1324. )))
  1325. }
  1326. // Store its inverse
  1327. if let Err(e) = self.wallet.cache_inverse(inverse) {
  1328. return Err(Error::DatabaseError(format!(
  1329. "[apply_dao_exec_data] Inserting inverse query into cache failed: {e:?}"
  1330. )))
  1331. }
  1332. Ok(true)
  1333. }
  1334. /// Append data related to DAO contract transactions into the wallet database,
  1335. /// and store their inverse queries into the cache.
  1336. /// Returns a flag indicating if the provided data refer to our own wallet.
  1337. pub async fn apply_tx_dao_data(
  1338. &self,
  1339. data: &[u8],
  1340. tx_hash: TransactionHash,
  1341. call_idx: u8,
  1342. ) -> Result<bool> {
  1343. // Run through the transaction call data and see what we got:
  1344. match DaoFunction::try_from(data[0])? {
  1345. DaoFunction::Mint => {
  1346. println!("[apply_tx_dao_data] Found Dao::Mint call");
  1347. let params: DaoMintParams = deserialize_async(&data[1..]).await?;
  1348. self.apply_dao_mint_data(params.dao_bulla, tx_hash, call_idx).await
  1349. }
  1350. DaoFunction::Propose => {
  1351. println!("[apply_tx_dao_data] Found Dao::Propose call");
  1352. let params: DaoProposeParams = deserialize_async(&data[1..]).await?;
  1353. self.apply_dao_propose_data(params, tx_hash, call_idx).await
  1354. }
  1355. DaoFunction::Vote => {
  1356. println!("[apply_tx_dao_data] Found Dao::Vote call");
  1357. let params: DaoVoteParams = deserialize_async(&data[1..]).await?;
  1358. self.apply_dao_vote_data(params, tx_hash, call_idx).await
  1359. }
  1360. DaoFunction::Exec => {
  1361. println!("[apply_tx_dao_data] Found Dao::Exec call");
  1362. let params: DaoExecParams = deserialize_async(&data[1..]).await?;
  1363. self.apply_dao_exec_data(params, tx_hash).await
  1364. }
  1365. DaoFunction::AuthMoneyTransfer => {
  1366. println!("[apply_tx_dao_data] Found Dao::AuthMoneyTransfer call");
  1367. // Does nothing, just verifies the other calls are correct
  1368. Ok(false)
  1369. }
  1370. }
  1371. }
  1372. /// Confirm already imported DAO metadata into the wallet,
  1373. /// and store its inverse query into the cache.
  1374. /// Here we just write the leaf position, tx hash, and call index.
  1375. /// Panics if the fields are None.
  1376. pub async fn confirm_dao(&self, dao: &DaoRecord) -> WalletDbResult<()> {
  1377. // Grab dao record key
  1378. let key = serialize_async(&dao.bulla()).await;
  1379. // Create an SQL `UPDATE` query
  1380. let query = format!(
  1381. "UPDATE {} SET {} = ?1, {} = ?2, {} = ?3 WHERE {} = ?4;",
  1382. *DAO_DAOS_TABLE,
  1383. DAO_DAOS_COL_LEAF_POSITION,
  1384. DAO_DAOS_COL_TX_HASH,
  1385. DAO_DAOS_COL_CALL_INDEX,
  1386. DAO_DAOS_COL_BULLA
  1387. );
  1388. // Create its params
  1389. let params = rusqlite::params![
  1390. serialize_async(&dao.leaf_position.unwrap()).await,
  1391. serialize_async(&dao.tx_hash.unwrap()).await,
  1392. dao.call_index.unwrap(),
  1393. key,
  1394. ];
  1395. // Create its inverse query
  1396. let inverse_query = format!(
  1397. "UPDATE {} SET {} = NULL, {} = NULL, {} = NULL WHERE {} = ?1;",
  1398. *DAO_DAOS_TABLE,
  1399. DAO_DAOS_COL_LEAF_POSITION,
  1400. DAO_DAOS_COL_TX_HASH,
  1401. DAO_DAOS_COL_CALL_INDEX,
  1402. DAO_DAOS_COL_BULLA
  1403. );
  1404. let inverse =
  1405. self.wallet.create_prepared_statement(&inverse_query, rusqlite::params![key])?;
  1406. // Execute the query
  1407. self.wallet.exec_sql(&query, params)?;
  1408. // Store its inverse
  1409. self.wallet.cache_inverse(inverse)
  1410. }
  1411. /// Import given DAO proposal into the wallet,
  1412. /// and store its inverse query into the cache.
  1413. pub async fn put_dao_proposal(&self, proposal: &ProposalRecord) -> Result<()> {
  1414. // Check that we already have the proposal DAO
  1415. if let Err(e) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
  1416. return Err(Error::DatabaseError(format!(
  1417. "[put_dao_proposal] Couldn't find proposal {} DAO {}: {e}",
  1418. proposal.bulla(),
  1419. proposal.proposal.dao_bulla
  1420. )))
  1421. }
  1422. // Grab proposal record key
  1423. let key = serialize_async(&proposal.bulla()).await;
  1424. // Create an SQL `INSERT OR REPLACE` query
  1425. let query = format!(
  1426. "INSERT OR REPLACE INTO {} ({}, {}, {}, {}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10);",
  1427. *DAO_PROPOSALS_TABLE,
  1428. DAO_PROPOSALS_COL_BULLA,
  1429. DAO_PROPOSALS_COL_DAO_BULLA,
  1430. DAO_PROPOSALS_COL_PROPOSAL,
  1431. DAO_PROPOSALS_COL_DATA,
  1432. DAO_PROPOSALS_COL_LEAF_POSITION,
  1433. DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE,
  1434. DAO_PROPOSALS_COL_NULLIFIERS_SMT_SNAPSHOT,
  1435. DAO_PROPOSALS_COL_TX_HASH,
  1436. DAO_PROPOSALS_COL_CALL_INDEX,
  1437. DAO_PROPOSALS_COL_EXEC_TX_HASH,
  1438. );
  1439. // Create its params
  1440. let data = match &proposal.data {
  1441. Some(data) => Some(data),
  1442. None => None,
  1443. };
  1444. let leaf_position = match &proposal.leaf_position {
  1445. Some(leaf_position) => Some(serialize_async(leaf_position).await),
  1446. None => None,
  1447. };
  1448. let money_snapshot_tree = match &proposal.money_snapshot_tree {
  1449. Some(money_snapshot_tree) => Some(serialize_async(money_snapshot_tree).await),
  1450. None => None,
  1451. };
  1452. let nullifiers_smt_snapshot = match &proposal.nullifiers_smt_snapshot {
  1453. Some(nullifiers_smt_snapshot) => Some(serialize_async(nullifiers_smt_snapshot).await),
  1454. None => None,
  1455. };
  1456. let tx_hash = match &proposal.tx_hash {
  1457. Some(tx_hash) => Some(serialize_async(tx_hash).await),
  1458. None => None,
  1459. };
  1460. let exec_tx_hash = match &proposal.exec_tx_hash {
  1461. Some(exec_tx_hash) => Some(serialize_async(exec_tx_hash).await),
  1462. None => None,
  1463. };
  1464. let params = rusqlite::params![
  1465. key,
  1466. serialize_async(&proposal.proposal.dao_bulla).await,
  1467. serialize_async(&proposal.proposal).await,
  1468. data,
  1469. leaf_position,
  1470. money_snapshot_tree,
  1471. nullifiers_smt_snapshot,
  1472. tx_hash,
  1473. proposal.call_index,
  1474. exec_tx_hash,
  1475. ];
  1476. // Create its inverse query
  1477. let inverse_query = format!(
  1478. "UPDATE {} SET {} = NULL, {} = NULL, {} = NULL, {} = NULL, {} = NULL, {} = NULL WHERE {} = ?1;",
  1479. *DAO_PROPOSALS_TABLE,
  1480. DAO_PROPOSALS_COL_LEAF_POSITION,
  1481. DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE,
  1482. DAO_PROPOSALS_COL_NULLIFIERS_SMT_SNAPSHOT,
  1483. DAO_PROPOSALS_COL_TX_HASH,
  1484. DAO_PROPOSALS_COL_CALL_INDEX,
  1485. DAO_PROPOSALS_COL_EXEC_TX_HASH,
  1486. DAO_PROPOSALS_COL_BULLA
  1487. );
  1488. let inverse =
  1489. match self.wallet.create_prepared_statement(&inverse_query, rusqlite::params![key]) {
  1490. Ok(q) => q,
  1491. Err(e) => {
  1492. return Err(Error::DatabaseError(format!(
  1493. "[put_dao_proposal] Creating DAO proposal insert inverse query failed: {e:?}"
  1494. )))
  1495. }
  1496. };
  1497. // Execute the query
  1498. if let Err(e) = self.wallet.exec_sql(&query, params) {
  1499. return Err(Error::DatabaseError(format!(
  1500. "[put_dao_proposal] Proposal insert failed: {e:?}"
  1501. )))
  1502. };
  1503. // Store its inverse
  1504. if let Err(e) = self.wallet.cache_inverse(inverse) {
  1505. return Err(Error::DatabaseError(format!(
  1506. "[put_dao_proposal] Inserting inverse query into cache failed: {e:?}"
  1507. )))
  1508. }
  1509. Ok(())
  1510. }
  1511. /// Unconfirm imported DAO proposals by removing the leaf position, tx hash, and call index.
  1512. pub async fn unconfirm_proposals(&self, proposals: &[ProposalRecord]) -> WalletDbResult<()> {
  1513. for proposal in proposals {
  1514. let query = format!(
  1515. "UPDATE {} SET {} = NULL, {} = NULL, {} = NULL, {} = NULL, {} = NULL, {} = NULL WHERE {} = ?1;",
  1516. *DAO_PROPOSALS_TABLE,
  1517. DAO_PROPOSALS_COL_LEAF_POSITION,
  1518. DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE,
  1519. DAO_PROPOSALS_COL_NULLIFIERS_SMT_SNAPSHOT,
  1520. DAO_PROPOSALS_COL_TX_HASH,
  1521. DAO_PROPOSALS_COL_CALL_INDEX,
  1522. DAO_PROPOSALS_COL_EXEC_TX_HASH,
  1523. DAO_PROPOSALS_COL_BULLA
  1524. );
  1525. self.wallet
  1526. .exec_sql(&query, rusqlite::params![serialize_async(&proposal.bulla()).await])?;
  1527. }
  1528. Ok(())
  1529. }
  1530. /// Import given DAO vote into the wallet,
  1531. /// and store its inverse query into the cache.
  1532. pub async fn put_dao_vote(&self, vote: &VoteRecord) -> WalletDbResult<()> {
  1533. println!("Importing DAO vote into wallet");
  1534. // Create an SQL `INSERT OR REPLACE` query
  1535. let query = format!(
  1536. "INSERT INTO {} ({}, {}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8);",
  1537. *DAO_VOTES_TABLE,
  1538. DAO_VOTES_COL_PROPOSAL_BULLA,
  1539. DAO_VOTES_COL_VOTE_OPTION,
  1540. DAO_VOTES_COL_YES_VOTE_BLIND,
  1541. DAO_VOTES_COL_ALL_VOTE_VALUE,
  1542. DAO_VOTES_COL_ALL_VOTE_BLIND,
  1543. DAO_VOTES_COL_TX_HASH,
  1544. DAO_VOTES_COL_CALL_INDEX,
  1545. DAO_VOTES_COL_NULLIFIERS,
  1546. );
  1547. // Create its params
  1548. let params = rusqlite::params![
  1549. serialize_async(&vote.proposal).await,
  1550. vote.vote_option as u64,
  1551. serialize_async(&vote.yes_vote_blind).await,
  1552. serialize_async(&vote.all_vote_value).await,
  1553. serialize_async(&vote.all_vote_blind).await,
  1554. serialize_async(&vote.tx_hash).await,
  1555. vote.call_index,
  1556. serialize_async(&vote.nullifiers).await,
  1557. ];
  1558. // Create its inverse query.
  1559. // Since we don't know the record ID we will remove it
  1560. // using all its fields.
  1561. let inverse_query = format!(
  1562. "DELETE FROM {} WHERE {} = ?1 AND {} = ?2 AND {} = ?3 AND {} = ?4 AND {} = ?5 AND {} = ?6 AND {} = ?7 AND {} = ?8;",
  1563. *DAO_VOTES_TABLE,
  1564. DAO_VOTES_COL_PROPOSAL_BULLA,
  1565. DAO_VOTES_COL_VOTE_OPTION,
  1566. DAO_VOTES_COL_YES_VOTE_BLIND,
  1567. DAO_VOTES_COL_ALL_VOTE_VALUE,
  1568. DAO_VOTES_COL_ALL_VOTE_BLIND,
  1569. DAO_VOTES_COL_TX_HASH,
  1570. DAO_VOTES_COL_CALL_INDEX,
  1571. DAO_VOTES_COL_NULLIFIERS,
  1572. );
  1573. let inverse = self.wallet.create_prepared_statement(&inverse_query, params)?;
  1574. // Execute the query
  1575. self.wallet.exec_sql(&query, params)?;
  1576. // Store its inverse
  1577. self.wallet.cache_inverse(inverse)?;
  1578. println!("DAO vote added to wallet");
  1579. Ok(())
  1580. }
  1581. /// Reset the DAO Merkle trees in the wallet.
  1582. pub async fn reset_dao_trees(&self) -> WalletDbResult<()> {
  1583. println!("Resetting DAO Merkle trees");
  1584. let tree = MerkleTree::new(1);
  1585. self.put_dao_trees(&tree, &tree).await?;
  1586. println!("Successfully reset DAO Merkle trees");
  1587. Ok(())
  1588. }
  1589. /// Reset confirmed DAOs in the wallet.
  1590. pub async fn reset_daos(&self) -> WalletDbResult<()> {
  1591. println!("Resetting DAO confirmations");
  1592. let query = format!(
  1593. "UPDATE {} SET {} = NULL, {} = NULL, {} = NULL;",
  1594. *DAO_DAOS_TABLE,
  1595. DAO_DAOS_COL_LEAF_POSITION,
  1596. DAO_DAOS_COL_TX_HASH,
  1597. DAO_DAOS_COL_CALL_INDEX,
  1598. );
  1599. self.wallet.exec_sql(&query, &[])?;
  1600. println!("Successfully unconfirmed DAOs");
  1601. Ok(())
  1602. }
  1603. /// Reset all DAO proposals in the wallet.
  1604. pub async fn reset_dao_proposals(&self) -> WalletDbResult<()> {
  1605. println!("Resetting DAO proposals confirmations");
  1606. let proposals = match self.get_proposals().await {
  1607. Ok(p) => p,
  1608. Err(e) => {
  1609. println!("[reset_dao_proposals] DAO proposals retrieval failed: {e:?}");
  1610. return Err(WalletDbError::GenericError);
  1611. }
  1612. };
  1613. self.unconfirm_proposals(&proposals).await?;
  1614. println!("Successfully unconfirmed DAO proposals");
  1615. Ok(())
  1616. }
  1617. /// Reset all DAO votes in the wallet.
  1618. pub fn reset_dao_votes(&self) -> WalletDbResult<()> {
  1619. println!("Resetting DAO votes");
  1620. let query = format!("DELETE FROM {};", *DAO_VOTES_TABLE);
  1621. self.wallet.exec_sql(&query, &[])
  1622. }
  1623. /// Import given DAO params into the wallet with a given name.
  1624. pub async fn import_dao(&self, name: &str, params: &DaoParams) -> Result<()> {
  1625. // First let's check if we've imported this DAO with the given name before.
  1626. if self.get_dao_by_name(name).await.is_ok() {
  1627. return Err(Error::DatabaseError(
  1628. "[import_dao] This DAO has already been imported".to_string(),
  1629. ))
  1630. }
  1631. println!("Importing \"{name}\" DAO into the wallet");
  1632. let query = format!(
  1633. "INSERT INTO {} ({}, {}, {}) VALUES (?1, ?2, ?3);",
  1634. *DAO_DAOS_TABLE, DAO_DAOS_COL_BULLA, DAO_DAOS_COL_NAME, DAO_DAOS_COL_PARAMS,
  1635. );
  1636. if let Err(e) = self.wallet.exec_sql(
  1637. &query,
  1638. rusqlite::params![
  1639. serialize_async(&params.dao.to_bulla()).await,
  1640. name,
  1641. serialize_async(params).await,
  1642. ],
  1643. ) {
  1644. return Err(Error::DatabaseError(format!("[import_dao] DAO insert failed: {e:?}")))
  1645. };
  1646. Ok(())
  1647. }
  1648. /// Update given DAO params into the wallet, if the corresponding DAO exists.
  1649. pub async fn update_dao_keys(&self, params: &DaoParams) -> Result<()> {
  1650. // Grab the params DAO
  1651. let bulla = params.dao.to_bulla();
  1652. let Ok(dao) = self.get_dao_by_bulla(&bulla).await else {
  1653. return Err(Error::DatabaseError(format!("[import_dao] DAO {bulla} was not found")))
  1654. };
  1655. println!("Updating \"{}\" DAO keys into the wallet", dao.name);
  1656. let query = format!(
  1657. "UPDATE {} SET {} = ?1 WHERE {} = ?2;",
  1658. *DAO_DAOS_TABLE, DAO_DAOS_COL_PARAMS, DAO_DAOS_COL_BULLA,
  1659. );
  1660. if let Err(e) = self.wallet.exec_sql(
  1661. &query,
  1662. rusqlite::params![serialize_async(params).await, serialize_async(&bulla).await,],
  1663. ) {
  1664. return Err(Error::DatabaseError(format!("[update_dao_keys] DAO update failed: {e:?}")))
  1665. };
  1666. Ok(())
  1667. }
  1668. /// Fetch a DAO given its bulla.
  1669. pub async fn get_dao_by_bulla(&self, bulla: &DaoBulla) -> Result<DaoRecord> {
  1670. let row = match self.wallet.query_single(
  1671. &DAO_DAOS_TABLE,
  1672. &[],
  1673. convert_named_params! {(DAO_DAOS_COL_BULLA, serialize_async(bulla).await)},
  1674. ) {
  1675. Ok(r) => r,
  1676. Err(e) => {
  1677. return Err(Error::DatabaseError(format!(
  1678. "[get_dao_by_bulla] DAO retrieval failed: {e:?}"
  1679. )))
  1680. }
  1681. };
  1682. self.parse_dao_record(&row).await
  1683. }
  1684. /// Fetch a DAO given its name.
  1685. pub async fn get_dao_by_name(&self, name: &str) -> Result<DaoRecord> {
  1686. let row = match self.wallet.query_single(
  1687. &DAO_DAOS_TABLE,
  1688. &[],
  1689. convert_named_params! {(DAO_DAOS_COL_NAME, name)},
  1690. ) {
  1691. Ok(r) => r,
  1692. Err(e) => {
  1693. return Err(Error::DatabaseError(format!(
  1694. "[get_dao_by_name] DAO retrieval failed: {e:?}"
  1695. )))
  1696. }
  1697. };
  1698. self.parse_dao_record(&row).await
  1699. }
  1700. /// List DAO(s) imported in the wallet. If a name is given, just print the
  1701. /// metadata for that specific one, if found.
  1702. pub async fn dao_list(&self, name: &Option<String>) -> Result<()> {
  1703. if let Some(name) = name {
  1704. let dao = self.get_dao_by_name(name).await?;
  1705. println!("{dao}");
  1706. return Ok(());
  1707. }
  1708. let daos = self.get_daos().await?;
  1709. for (i, dao) in daos.iter().enumerate() {
  1710. println!("{i}. {}", dao.name);
  1711. }
  1712. Ok(())
  1713. }
  1714. /// Fetch known unspent balances from the wallet for the given DAO name.
  1715. pub async fn dao_balance(&self, name: &str) -> Result<HashMap<String, u64>> {
  1716. let dao = self.get_dao_by_name(name).await?;
  1717. let dao_spend_hook =
  1718. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  1719. .to_func_id();
  1720. let mut coins = self.get_coins(false).await?;
  1721. coins.retain(|x| x.0.note.spend_hook == dao_spend_hook);
  1722. coins.retain(|x| x.0.note.user_data == dao.bulla().inner());
  1723. // Fill this map with balances
  1724. let mut balmap: HashMap<String, u64> = HashMap::new();
  1725. for coin in coins {
  1726. let mut value = coin.0.note.value;
  1727. if let Some(prev) = balmap.get(&coin.0.note.token_id.to_string()) {
  1728. value += prev;
  1729. }
  1730. balmap.insert(coin.0.note.token_id.to_string(), value);
  1731. }
  1732. Ok(balmap)
  1733. }
  1734. /// Fetch all known DAO proposalss from the wallet.
  1735. pub async fn get_proposals(&self) -> Result<Vec<ProposalRecord>> {
  1736. let rows = match self.wallet.query_multiple(&DAO_PROPOSALS_TABLE, &[], &[]) {
  1737. Ok(r) => r,
  1738. Err(e) => {
  1739. return Err(Error::DatabaseError(format!(
  1740. "[get_proposals] DAO proposalss retrieval failed: {e:?}"
  1741. )))
  1742. }
  1743. };
  1744. let mut daos = Vec::with_capacity(rows.len());
  1745. for row in rows {
  1746. daos.push(self.parse_dao_proposal(&row).await?);
  1747. }
  1748. Ok(daos)
  1749. }
  1750. /// Fetch a DAO proposal by its bulla.
  1751. pub async fn get_dao_proposal_by_bulla(
  1752. &self,
  1753. bulla: &DaoProposalBulla,
  1754. ) -> Result<ProposalRecord> {
  1755. // Grab the proposal record
  1756. let row = match self.wallet.query_single(
  1757. &DAO_PROPOSALS_TABLE,
  1758. &[],
  1759. convert_named_params! {(DAO_PROPOSALS_COL_BULLA, serialize_async(bulla).await)},
  1760. ) {
  1761. Ok(r) => r,
  1762. Err(e) => {
  1763. return Err(Error::DatabaseError(format!(
  1764. "[get_dao_proposal_by_bulla] DAO proposal retrieval failed: {e:?}"
  1765. )))
  1766. }
  1767. };
  1768. // Parse rest of the record
  1769. self.parse_dao_proposal(&row).await
  1770. }
  1771. // Fetch all known DAO proposal votes from the wallet given a proposal ID.
  1772. pub async fn get_dao_proposal_votes(
  1773. &self,
  1774. proposal: &DaoProposalBulla,
  1775. ) -> Result<Vec<VoteRecord>> {
  1776. let rows = match self.wallet.query_multiple(
  1777. &DAO_VOTES_TABLE,
  1778. &[],
  1779. convert_named_params! {(DAO_VOTES_COL_PROPOSAL_BULLA, serialize_async(proposal).await)},
  1780. ) {
  1781. Ok(r) => r,
  1782. Err(e) => {
  1783. return Err(Error::DatabaseError(format!(
  1784. "[get_dao_proposal_votes] Votes retrieval failed: {e:?}"
  1785. )))
  1786. }
  1787. };
  1788. let mut votes = Vec::with_capacity(rows.len());
  1789. for row in rows {
  1790. let Value::Integer(id) = row[0] else {
  1791. return Err(Error::ParseFailed("[get_dao_proposal_votes] ID parsing failed"))
  1792. };
  1793. let Ok(id) = u64::try_from(id) else {
  1794. return Err(Error::ParseFailed("[get_dao_proposal_votes] ID parsing failed"))
  1795. };
  1796. let Value::Blob(ref proposal_bytes) = row[1] else {
  1797. return Err(Error::ParseFailed(
  1798. "[get_dao_proposal_votes] Proposal bytes bytes parsing failed",
  1799. ))
  1800. };
  1801. let proposal = deserialize_async(proposal_bytes).await?;
  1802. let Value::Integer(vote_option) = row[2] else {
  1803. return Err(Error::ParseFailed(
  1804. "[get_dao_proposal_votes] Vote option parsing failed",
  1805. ))
  1806. };
  1807. let Ok(vote_option) = u32::try_from(vote_option) else {
  1808. return Err(Error::ParseFailed(
  1809. "[get_dao_proposal_votes] Vote option parsing failed",
  1810. ))
  1811. };
  1812. let vote_option = vote_option != 0;
  1813. let Value::Blob(ref yes_vote_blind_bytes) = row[3] else {
  1814. return Err(Error::ParseFailed(
  1815. "[get_dao_proposal_votes] Yes vote blind bytes parsing failed",
  1816. ))
  1817. };
  1818. let yes_vote_blind = deserialize_async(yes_vote_blind_bytes).await?;
  1819. let Value::Blob(ref all_vote_value_bytes) = row[4] else {
  1820. return Err(Error::ParseFailed(
  1821. "[get_dao_proposal_votes] All vote value bytes parsing failed",
  1822. ))
  1823. };
  1824. let all_vote_value = deserialize_async(all_vote_value_bytes).await?;
  1825. let Value::Blob(ref all_vote_blind_bytes) = row[5] else {
  1826. return Err(Error::ParseFailed(
  1827. "[get_dao_proposal_votes] All vote blind bytes parsing failed",
  1828. ))
  1829. };
  1830. let all_vote_blind = deserialize_async(all_vote_blind_bytes).await?;
  1831. let Value::Blob(ref tx_hash_bytes) = row[6] else {
  1832. return Err(Error::ParseFailed(
  1833. "[get_dao_proposal_votes] Transaction hash bytes parsing failed",
  1834. ))
  1835. };
  1836. let tx_hash = deserialize_async(tx_hash_bytes).await?;
  1837. let Value::Integer(call_index) = row[7] else {
  1838. return Err(Error::ParseFailed("[get_dao_proposal_votes] Call index parsing failed"))
  1839. };
  1840. let Ok(call_index) = u8::try_from(call_index) else {
  1841. return Err(Error::ParseFailed("[get_dao_proposal_votes] Call index parsing failed"))
  1842. };
  1843. let Value::Blob(ref nullifiers_bytes) = row[8] else {
  1844. return Err(Error::ParseFailed(
  1845. "[get_dao_proposal_votes] Nullifiers bytes parsing failed",
  1846. ))
  1847. };
  1848. let nullifiers = deserialize_async(nullifiers_bytes).await?;
  1849. let vote = VoteRecord {
  1850. id,
  1851. proposal,
  1852. vote_option,
  1853. yes_vote_blind,
  1854. all_vote_value,
  1855. all_vote_blind,
  1856. tx_hash,
  1857. call_index,
  1858. nullifiers,
  1859. };
  1860. votes.push(vote);
  1861. }
  1862. Ok(votes)
  1863. }
  1864. /// Mint a DAO on-chain.
  1865. pub async fn dao_mint(&self, name: &str) -> Result<Transaction> {
  1866. // Retrieve the dao record
  1867. let dao = self.get_dao_by_name(name).await?;
  1868. // Check its not already minted
  1869. if dao.tx_hash.is_some() {
  1870. return Err(Error::Custom(
  1871. "[dao_mint] This DAO seems to have already been minted on-chain".to_string(),
  1872. ))
  1873. }
  1874. // Check that we have all the keys
  1875. if dao.params.notes_secret_key.is_none() ||
  1876. dao.params.proposer_secret_key.is_none() ||
  1877. dao.params.proposals_secret_key.is_none() ||
  1878. dao.params.votes_secret_key.is_none() ||
  1879. dao.params.exec_secret_key.is_none() ||
  1880. dao.params.early_exec_secret_key.is_none()
  1881. {
  1882. return Err(Error::Custom(
  1883. "[dao_mint] We need all the secrets key to mint the DAO on-chain".to_string(),
  1884. ))
  1885. }
  1886. // Now we need to do a lookup for the zkas proof bincodes, and create
  1887. // the circuit objects and proving keys so we can build the transaction.
  1888. // We also do this through the RPC. First we grab the fee call from money.
  1889. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  1890. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  1891. else {
  1892. return Err(Error::Custom("Fee circuit not found".to_string()))
  1893. };
  1894. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  1895. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  1896. // Creating Fee circuit proving key
  1897. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  1898. // Now we grab the DAO mint
  1899. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  1900. let Some(dao_mint_zkbin) = zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_MINT_NS)
  1901. else {
  1902. return Err(Error::DatabaseError("[dao_mint] DAO Mint circuit not found".to_string()))
  1903. };
  1904. let dao_mint_zkbin = ZkBinary::decode(&dao_mint_zkbin.1)?;
  1905. let dao_mint_circuit = ZkCircuit::new(empty_witnesses(&dao_mint_zkbin)?, &dao_mint_zkbin);
  1906. // Creating DAO Mint circuit proving key
  1907. let dao_mint_pk = ProvingKey::build(dao_mint_zkbin.k, &dao_mint_circuit);
  1908. // Create the DAO mint call
  1909. let notes_secret_key = dao.params.notes_secret_key.unwrap();
  1910. let (params, proofs) = make_mint_call(
  1911. &dao.params.dao,
  1912. &notes_secret_key,
  1913. &dao.params.proposer_secret_key.unwrap(),
  1914. &dao.params.proposals_secret_key.unwrap(),
  1915. &dao.params.votes_secret_key.unwrap(),
  1916. &dao.params.exec_secret_key.unwrap(),
  1917. &dao.params.early_exec_secret_key.unwrap(),
  1918. &dao_mint_zkbin,
  1919. &dao_mint_pk,
  1920. )?;
  1921. let mut data = vec![DaoFunction::Mint as u8];
  1922. params.encode_async(&mut data).await?;
  1923. let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  1924. // Create the TransactionBuilder containing above call
  1925. let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;
  1926. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  1927. // it into the fee-creating function.
  1928. let mut tx = tx_builder.build()?;
  1929. let sigs = tx.create_sigs(&[notes_secret_key])?;
  1930. tx.signatures.push(sigs);
  1931. let tree = self.get_money_tree().await?;
  1932. let (fee_call, fee_proofs, fee_secrets) =
  1933. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  1934. // Append the fee call to the transaction
  1935. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  1936. // Now build the actual transaction and sign it with all necessary keys.
  1937. let mut tx = tx_builder.build()?;
  1938. let sigs = tx.create_sigs(&[notes_secret_key])?;
  1939. tx.signatures.push(sigs);
  1940. let sigs = tx.create_sigs(&fee_secrets)?;
  1941. tx.signatures.push(sigs);
  1942. Ok(tx)
  1943. }
  1944. /// Create a DAO transfer proposal.
  1945. #[allow(clippy::too_many_arguments)]
  1946. pub async fn dao_propose_transfer(
  1947. &self,
  1948. name: &str,
  1949. duration_blockwindows: u64,
  1950. amount: &str,
  1951. token_id: TokenId,
  1952. recipient: PublicKey,
  1953. spend_hook: Option<FuncId>,
  1954. user_data: Option<pallas::Base>,
  1955. ) -> Result<ProposalRecord> {
  1956. // Fetch DAO and check its deployed
  1957. let dao = self.get_dao_by_name(name).await?;
  1958. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  1959. return Err(Error::Custom(
  1960. "[dao_propose_transfer] DAO seems to not have been deployed yet".to_string(),
  1961. ))
  1962. }
  1963. // Check that we have the proposer key
  1964. if dao.params.proposer_secret_key.is_none() {
  1965. return Err(Error::Custom(
  1966. "[dao_propose_transfer] We need the proposer secret key to create proposals for this DAO".to_string(),
  1967. ))
  1968. }
  1969. // Fetch DAO unspent OwnCoins to see what its balance is
  1970. let dao_spend_hook =
  1971. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  1972. .to_func_id();
  1973. let dao_bulla = dao.bulla();
  1974. let dao_owncoins =
  1975. self.get_contract_token_coins(&token_id, &dao_spend_hook, &dao_bulla.inner()).await?;
  1976. if dao_owncoins.is_empty() {
  1977. return Err(Error::Custom(format!(
  1978. "[dao_propose_transfer] Did not find any {token_id} unspent coins owned by this DAO"
  1979. )))
  1980. }
  1981. // Check DAO balance is sufficient
  1982. let amount = decode_base10(amount, BALANCE_BASE10_DECIMALS, false)?;
  1983. if dao_owncoins.iter().map(|x| x.note.value).sum::<u64>() < amount {
  1984. return Err(Error::Custom(format!(
  1985. "[dao_propose_transfer] Not enough DAO balance for token ID: {token_id}",
  1986. )))
  1987. }
  1988. // Generate proposal coin attributes
  1989. let proposal_coinattrs = CoinAttributes {
  1990. public_key: recipient,
  1991. value: amount,
  1992. token_id,
  1993. spend_hook: spend_hook.unwrap_or(FuncId::none()),
  1994. user_data: user_data.unwrap_or(pallas::Base::ZERO),
  1995. blind: Blind::random(&mut OsRng),
  1996. };
  1997. // Convert coin_params to actual coins
  1998. let proposal_coins = vec![proposal_coinattrs.to_coin()];
  1999. let mut proposal_data = vec![];
  2000. proposal_coins.encode_async(&mut proposal_data).await?;
  2001. // Create Auth calls
  2002. let auth_calls = vec![
  2003. DaoAuthCall {
  2004. contract_id: *DAO_CONTRACT_ID,
  2005. function_code: DaoFunction::AuthMoneyTransfer as u8,
  2006. auth_data: proposal_data,
  2007. },
  2008. DaoAuthCall {
  2009. contract_id: *MONEY_CONTRACT_ID,
  2010. function_code: MoneyFunction::TransferV1 as u8,
  2011. auth_data: vec![],
  2012. },
  2013. ];
  2014. // Retrieve next block height and current block time target,
  2015. // to compute their window.
  2016. let next_block_height = self.get_next_block_height().await?;
  2017. let block_target = self.get_block_target().await?;
  2018. let creation_blockwindow = blockwindow(next_block_height, block_target);
  2019. // Create the actual proposal
  2020. let proposal = DaoProposal {
  2021. auth_calls,
  2022. creation_blockwindow,
  2023. duration_blockwindows,
  2024. user_data: user_data.unwrap_or(pallas::Base::ZERO),
  2025. dao_bulla,
  2026. blind: Blind::random(&mut OsRng),
  2027. };
  2028. let proposal_record = ProposalRecord {
  2029. proposal,
  2030. data: Some(serialize_async(&proposal_coinattrs).await),
  2031. leaf_position: None,
  2032. money_snapshot_tree: None,
  2033. nullifiers_smt_snapshot: None,
  2034. tx_hash: None,
  2035. call_index: None,
  2036. exec_tx_hash: None,
  2037. };
  2038. if let Err(e) = self.put_dao_proposal(&proposal_record).await {
  2039. return Err(Error::DatabaseError(format!(
  2040. "[dao_propose_transfer] Put DAO proposal failed: {e:?}"
  2041. )))
  2042. }
  2043. Ok(proposal_record)
  2044. }
  2045. /// Create a DAO generic proposal.
  2046. pub async fn dao_propose_generic(
  2047. &self,
  2048. name: &str,
  2049. duration_blockwindows: u64,
  2050. user_data: Option<pallas::Base>,
  2051. ) -> Result<ProposalRecord> {
  2052. // Fetch DAO and check its deployed
  2053. let dao = self.get_dao_by_name(name).await?;
  2054. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  2055. return Err(Error::Custom(
  2056. "[dao_propose_generic] DAO seems to not have been deployed yet".to_string(),
  2057. ))
  2058. }
  2059. // Check that we have the proposer key
  2060. if dao.params.proposer_secret_key.is_none() {
  2061. return Err(Error::Custom(
  2062. "[dao_propose_generic] We need the proposer secret key to create proposals for this DAO".to_string(),
  2063. ))
  2064. }
  2065. // Retrieve next block height and current block time target,
  2066. // to compute their window.
  2067. let next_block_height = self.get_next_block_height().await?;
  2068. let block_target = self.get_block_target().await?;
  2069. let creation_blockwindow = blockwindow(next_block_height, block_target);
  2070. // Create the actual proposal
  2071. let proposal = DaoProposal {
  2072. auth_calls: vec![],
  2073. creation_blockwindow,
  2074. duration_blockwindows,
  2075. user_data: user_data.unwrap_or(pallas::Base::ZERO),
  2076. dao_bulla: dao.bulla(),
  2077. blind: Blind::random(&mut OsRng),
  2078. };
  2079. let proposal_record = ProposalRecord {
  2080. proposal,
  2081. data: None,
  2082. leaf_position: None,
  2083. money_snapshot_tree: None,
  2084. nullifiers_smt_snapshot: None,
  2085. tx_hash: None,
  2086. call_index: None,
  2087. exec_tx_hash: None,
  2088. };
  2089. if let Err(e) = self.put_dao_proposal(&proposal_record).await {
  2090. return Err(Error::DatabaseError(format!(
  2091. "[dao_propose_generic] Put DAO proposal failed: {e:?}"
  2092. )))
  2093. }
  2094. Ok(proposal_record)
  2095. }
  2096. /// Create a DAO transfer proposal transaction.
  2097. pub async fn dao_transfer_proposal_tx(&self, proposal: &ProposalRecord) -> Result<Transaction> {
  2098. // Check we know the plaintext data
  2099. if proposal.data.is_none() {
  2100. return Err(Error::Custom(
  2101. "[dao_transfer_proposal_tx] Proposal plainext data is empty".to_string(),
  2102. ))
  2103. }
  2104. let proposal_coinattrs: CoinAttributes =
  2105. deserialize_async(proposal.data.as_ref().unwrap()).await?;
  2106. // Fetch DAO and check its deployed
  2107. let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
  2108. return Err(Error::Custom(format!(
  2109. "[dao_transfer_proposal_tx] DAO {} was not found",
  2110. proposal.proposal.dao_bulla
  2111. )))
  2112. };
  2113. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  2114. return Err(Error::Custom(
  2115. "[dao_transfer_proposal_tx] DAO seems to not have been deployed yet".to_string(),
  2116. ))
  2117. }
  2118. // Check that we have the proposer key
  2119. if dao.params.proposer_secret_key.is_none() {
  2120. return Err(Error::Custom(
  2121. "[dao_transfer_proposal_tx] We need the proposer secret key to create proposals for this DAO".to_string(),
  2122. ))
  2123. }
  2124. // Fetch DAO unspent OwnCoins to see what its balance is for the coin
  2125. let dao_spend_hook =
  2126. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  2127. .to_func_id();
  2128. let dao_owncoins = self
  2129. .get_contract_token_coins(
  2130. &proposal_coinattrs.token_id,
  2131. &dao_spend_hook,
  2132. &proposal.proposal.dao_bulla.inner(),
  2133. )
  2134. .await?;
  2135. if dao_owncoins.is_empty() {
  2136. return Err(Error::Custom(format!(
  2137. "[dao_transfer_proposal_tx] Did not find any {} unspent coins owned by this DAO",
  2138. proposal_coinattrs.token_id,
  2139. )))
  2140. }
  2141. // Check DAO balance is sufficient
  2142. if dao_owncoins.iter().map(|x| x.note.value).sum::<u64>() < proposal_coinattrs.value {
  2143. return Err(Error::Custom(format!(
  2144. "[dao_transfer_proposal_tx] Not enough DAO balance for token ID: {}",
  2145. proposal_coinattrs.token_id,
  2146. )))
  2147. }
  2148. // Fetch our own governance OwnCoins to see what our balance is
  2149. let gov_owncoins = self.get_token_coins(&dao.params.dao.gov_token_id).await?;
  2150. if gov_owncoins.is_empty() {
  2151. return Err(Error::Custom(format!(
  2152. "[dao_transfer_proposal_tx] Did not find any governance {} coins in wallet",
  2153. dao.params.dao.gov_token_id
  2154. )))
  2155. }
  2156. // Find which governance coins we can use
  2157. let mut total_value = 0;
  2158. let mut gov_owncoins_to_use = vec![];
  2159. for gov_owncoin in gov_owncoins {
  2160. if total_value >= dao.params.dao.proposer_limit {
  2161. break
  2162. }
  2163. total_value += gov_owncoin.note.value;
  2164. gov_owncoins_to_use.push(gov_owncoin);
  2165. }
  2166. // Check our governance coins balance is sufficient
  2167. if total_value < dao.params.dao.proposer_limit {
  2168. return Err(Error::Custom(format!(
  2169. "[dao_transfer_proposal_tx] Not enough gov token {} balance to propose",
  2170. dao.params.dao.gov_token_id
  2171. )))
  2172. }
  2173. // Now we need to do a lookup for the zkas proof bincodes, and create
  2174. // the circuit objects and proving keys so we can build the transaction.
  2175. // We also do this through the RPC. First we grab the fee call from money.
  2176. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  2177. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  2178. else {
  2179. return Err(Error::Custom(
  2180. "[dao_transfer_proposal_tx] Fee circuit not found".to_string(),
  2181. ))
  2182. };
  2183. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  2184. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  2185. // Creating Fee circuit proving key
  2186. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  2187. // Now we grab the DAO bins
  2188. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  2189. let Some(propose_burn_zkbin) =
  2190. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_PROPOSE_INPUT_NS)
  2191. else {
  2192. return Err(Error::Custom(
  2193. "[dao_transfer_proposal_tx] Propose Burn circuit not found".to_string(),
  2194. ))
  2195. };
  2196. let Some(propose_main_zkbin) =
  2197. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_PROPOSE_MAIN_NS)
  2198. else {
  2199. return Err(Error::Custom(
  2200. "[dao_transfer_proposal_tx] Propose Main circuit not found".to_string(),
  2201. ))
  2202. };
  2203. let propose_burn_zkbin = ZkBinary::decode(&propose_burn_zkbin.1)?;
  2204. let propose_main_zkbin = ZkBinary::decode(&propose_main_zkbin.1)?;
  2205. let propose_burn_circuit =
  2206. ZkCircuit::new(empty_witnesses(&propose_burn_zkbin)?, &propose_burn_zkbin);
  2207. let propose_main_circuit =
  2208. ZkCircuit::new(empty_witnesses(&propose_main_zkbin)?, &propose_main_zkbin);
  2209. // Creating DAO ProposeBurn and ProposeMain circuits proving keys
  2210. let propose_burn_pk = ProvingKey::build(propose_burn_zkbin.k, &propose_burn_circuit);
  2211. let propose_main_pk = ProvingKey::build(propose_main_zkbin.k, &propose_main_circuit);
  2212. // Fetch our money Merkle tree
  2213. let money_merkle_tree = self.get_money_tree().await?;
  2214. // Now we can create the proposal transaction parameters.
  2215. // We first generate the `DaoProposeStakeInput` inputs,
  2216. // using our governance OwnCoins.
  2217. let mut inputs = Vec::with_capacity(gov_owncoins_to_use.len());
  2218. for gov_owncoin in gov_owncoins_to_use {
  2219. let input = DaoProposeStakeInput {
  2220. secret: gov_owncoin.secret,
  2221. note: gov_owncoin.note.clone(),
  2222. leaf_position: gov_owncoin.leaf_position,
  2223. merkle_path: money_merkle_tree.witness(gov_owncoin.leaf_position, 0).unwrap(),
  2224. };
  2225. inputs.push(input);
  2226. }
  2227. // Now create the parameters for the proposal tx
  2228. let signature_secret = SecretKey::random(&mut OsRng);
  2229. // Fetch the daos Merkle tree to compute the DAO Merkle path and root
  2230. let (daos_tree, _) = self.get_dao_trees().await?;
  2231. let (dao_merkle_path, dao_merkle_root) = {
  2232. let root = daos_tree.root(0).unwrap();
  2233. let leaf_pos = dao.leaf_position.unwrap();
  2234. let dao_merkle_path = daos_tree.witness(leaf_pos, 0).unwrap();
  2235. (dao_merkle_path, root)
  2236. };
  2237. // Generate the Money nullifiers Sparse Merkle Tree
  2238. let store = WalletStorage::new(
  2239. &self.wallet,
  2240. &MONEY_SMT_TABLE,
  2241. MONEY_SMT_COL_KEY,
  2242. MONEY_SMT_COL_VALUE,
  2243. );
  2244. let money_null_smt = WalletSmt::new(store, PoseidonFp::new(), &EMPTY_NODES_FP);
  2245. // Create the proposal call
  2246. let call = DaoProposeCall {
  2247. money_null_smt: &money_null_smt,
  2248. inputs,
  2249. proposal: proposal.proposal.clone(),
  2250. dao: dao.params.dao,
  2251. dao_leaf_position: dao.leaf_position.unwrap(),
  2252. dao_merkle_path,
  2253. dao_merkle_root,
  2254. signature_secret,
  2255. };
  2256. let (params, proofs) = call.make(
  2257. &dao.params.proposer_secret_key.unwrap(),
  2258. &propose_burn_zkbin,
  2259. &propose_burn_pk,
  2260. &propose_main_zkbin,
  2261. &propose_main_pk,
  2262. )?;
  2263. // Encode the call
  2264. let mut data = vec![DaoFunction::Propose as u8];
  2265. params.encode_async(&mut data).await?;
  2266. let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  2267. // Create the TransactionBuilder containing above call
  2268. let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;
  2269. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  2270. // it into the fee-creating function.
  2271. let mut tx = tx_builder.build()?;
  2272. let sigs = tx.create_sigs(&[signature_secret])?;
  2273. tx.signatures = vec![sigs];
  2274. let tree = self.get_money_tree().await?;
  2275. let (fee_call, fee_proofs, fee_secrets) =
  2276. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  2277. // Append the fee call to the transaction
  2278. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  2279. // Now build the actual transaction and sign it with all necessary keys.
  2280. let mut tx = tx_builder.build()?;
  2281. let sigs = tx.create_sigs(&[signature_secret])?;
  2282. tx.signatures.push(sigs);
  2283. let sigs = tx.create_sigs(&fee_secrets)?;
  2284. tx.signatures.push(sigs);
  2285. Ok(tx)
  2286. }
  2287. /// Create a DAO generic proposal transaction.
  2288. pub async fn dao_generic_proposal_tx(&self, proposal: &ProposalRecord) -> Result<Transaction> {
  2289. // Fetch DAO and check its deployed
  2290. let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
  2291. return Err(Error::Custom(format!(
  2292. "[dao_generic_proposal_tx] DAO {} was not found",
  2293. proposal.proposal.dao_bulla
  2294. )))
  2295. };
  2296. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  2297. return Err(Error::Custom(
  2298. "[dao_generic_proposal_tx] DAO seems to not have been deployed yet".to_string(),
  2299. ))
  2300. }
  2301. // Check that we have the proposer key
  2302. if dao.params.proposer_secret_key.is_none() {
  2303. return Err(Error::Custom(
  2304. "[dao_generic_proposal_tx] We need the proposer secret key to create proposals for this DAO".to_string(),
  2305. ))
  2306. }
  2307. // Fetch our own governance OwnCoins to see what our balance is
  2308. let gov_owncoins = self.get_token_coins(&dao.params.dao.gov_token_id).await?;
  2309. if gov_owncoins.is_empty() {
  2310. return Err(Error::Custom(format!(
  2311. "[dao_generic_proposal_tx] Did not find any governance {} coins in wallet",
  2312. dao.params.dao.gov_token_id
  2313. )))
  2314. }
  2315. // Find which governance coins we can use
  2316. let mut total_value = 0;
  2317. let mut gov_owncoins_to_use = vec![];
  2318. for gov_owncoin in gov_owncoins {
  2319. if total_value >= dao.params.dao.proposer_limit {
  2320. break
  2321. }
  2322. total_value += gov_owncoin.note.value;
  2323. gov_owncoins_to_use.push(gov_owncoin);
  2324. }
  2325. // Check our governance coins balance is sufficient
  2326. if total_value < dao.params.dao.proposer_limit {
  2327. return Err(Error::Custom(format!(
  2328. "[dao_generic_proposal_tx] Not enough gov token {} balance to propose",
  2329. dao.params.dao.gov_token_id
  2330. )))
  2331. }
  2332. // Now we need to do a lookup for the zkas proof bincodes, and create
  2333. // the circuit objects and proving keys so we can build the transaction.
  2334. // We also do this through the RPC. First we grab the fee call from money.
  2335. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  2336. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  2337. else {
  2338. return Err(Error::Custom("[dao_generic_proposal_tx] Fee circuit not found".to_string()))
  2339. };
  2340. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  2341. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  2342. // Creating Fee circuit proving key
  2343. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  2344. // Now we grab the DAO bins
  2345. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  2346. let Some(propose_burn_zkbin) =
  2347. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_PROPOSE_INPUT_NS)
  2348. else {
  2349. return Err(Error::Custom(
  2350. "[dao_generic_proposal_tx] Propose Burn circuit not found".to_string(),
  2351. ))
  2352. };
  2353. let Some(propose_main_zkbin) =
  2354. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_PROPOSE_MAIN_NS)
  2355. else {
  2356. return Err(Error::Custom(
  2357. "[dao_generic_proposal_tx] Propose Main circuit not found".to_string(),
  2358. ))
  2359. };
  2360. let propose_burn_zkbin = ZkBinary::decode(&propose_burn_zkbin.1)?;
  2361. let propose_main_zkbin = ZkBinary::decode(&propose_main_zkbin.1)?;
  2362. let propose_burn_circuit =
  2363. ZkCircuit::new(empty_witnesses(&propose_burn_zkbin)?, &propose_burn_zkbin);
  2364. let propose_main_circuit =
  2365. ZkCircuit::new(empty_witnesses(&propose_main_zkbin)?, &propose_main_zkbin);
  2366. // Creating DAO ProposeBurn and ProposeMain circuits proving keys
  2367. let propose_burn_pk = ProvingKey::build(propose_burn_zkbin.k, &propose_burn_circuit);
  2368. let propose_main_pk = ProvingKey::build(propose_main_zkbin.k, &propose_main_circuit);
  2369. // Fetch our money Merkle tree
  2370. let money_merkle_tree = self.get_money_tree().await?;
  2371. // Now we can create the proposal transaction parameters.
  2372. // We first generate the `DaoProposeStakeInput` inputs,
  2373. // using our governance OwnCoins.
  2374. let mut inputs = Vec::with_capacity(gov_owncoins_to_use.len());
  2375. for gov_owncoin in gov_owncoins_to_use {
  2376. let input = DaoProposeStakeInput {
  2377. secret: gov_owncoin.secret,
  2378. note: gov_owncoin.note.clone(),
  2379. leaf_position: gov_owncoin.leaf_position,
  2380. merkle_path: money_merkle_tree.witness(gov_owncoin.leaf_position, 0).unwrap(),
  2381. };
  2382. inputs.push(input);
  2383. }
  2384. // Now create the parameters for the proposal tx
  2385. let signature_secret = SecretKey::random(&mut OsRng);
  2386. // Fetch the daos Merkle tree to compute the DAO Merkle path and root
  2387. let (daos_tree, _) = self.get_dao_trees().await?;
  2388. let (dao_merkle_path, dao_merkle_root) = {
  2389. let root = daos_tree.root(0).unwrap();
  2390. let leaf_pos = dao.leaf_position.unwrap();
  2391. let dao_merkle_path = daos_tree.witness(leaf_pos, 0).unwrap();
  2392. (dao_merkle_path, root)
  2393. };
  2394. // Generate the Money nullifiers Sparse Merkle Tree
  2395. let store = WalletStorage::new(
  2396. &self.wallet,
  2397. &MONEY_SMT_TABLE,
  2398. MONEY_SMT_COL_KEY,
  2399. MONEY_SMT_COL_VALUE,
  2400. );
  2401. let money_null_smt = WalletSmt::new(store, PoseidonFp::new(), &EMPTY_NODES_FP);
  2402. // Create the proposal call
  2403. let call = DaoProposeCall {
  2404. money_null_smt: &money_null_smt,
  2405. inputs,
  2406. proposal: proposal.proposal.clone(),
  2407. dao: dao.params.dao,
  2408. dao_leaf_position: dao.leaf_position.unwrap(),
  2409. dao_merkle_path,
  2410. dao_merkle_root,
  2411. signature_secret,
  2412. };
  2413. let (params, proofs) = call.make(
  2414. &dao.params.proposer_secret_key.unwrap(),
  2415. &propose_burn_zkbin,
  2416. &propose_burn_pk,
  2417. &propose_main_zkbin,
  2418. &propose_main_pk,
  2419. )?;
  2420. // Encode the call
  2421. let mut data = vec![DaoFunction::Propose as u8];
  2422. params.encode_async(&mut data).await?;
  2423. let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  2424. // Create the TransactionBuilder containing above call
  2425. let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;
  2426. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  2427. // it into the fee-creating function.
  2428. let mut tx = tx_builder.build()?;
  2429. let sigs = tx.create_sigs(&[signature_secret])?;
  2430. tx.signatures = vec![sigs];
  2431. let tree = self.get_money_tree().await?;
  2432. let (fee_call, fee_proofs, fee_secrets) =
  2433. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  2434. // Append the fee call to the transaction
  2435. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  2436. // Now build the actual transaction and sign it with all necessary keys.
  2437. let mut tx = tx_builder.build()?;
  2438. let sigs = tx.create_sigs(&[signature_secret])?;
  2439. tx.signatures.push(sigs);
  2440. let sigs = tx.create_sigs(&fee_secrets)?;
  2441. tx.signatures.push(sigs);
  2442. Ok(tx)
  2443. }
  2444. /// Vote on a DAO proposal
  2445. pub async fn dao_vote(
  2446. &self,
  2447. proposal_bulla: &DaoProposalBulla,
  2448. vote_option: bool,
  2449. weight: Option<u64>,
  2450. ) -> Result<Transaction> {
  2451. // Feth the proposal and check its deployed
  2452. let Ok(proposal) = self.get_dao_proposal_by_bulla(proposal_bulla).await else {
  2453. return Err(Error::Custom(format!("[dao_vote] Proposal {proposal_bulla} was not found")))
  2454. };
  2455. if proposal.leaf_position.is_none() ||
  2456. proposal.money_snapshot_tree.is_none() ||
  2457. proposal.nullifiers_smt_snapshot.is_none() ||
  2458. proposal.tx_hash.is_none() ||
  2459. proposal.call_index.is_none()
  2460. {
  2461. return Err(Error::Custom(
  2462. "[dao_vote] Proposal seems to not have been deployed yet".to_string(),
  2463. ))
  2464. }
  2465. // Check proposal is not executed
  2466. if let Some(exec_tx_hash) = proposal.exec_tx_hash {
  2467. return Err(Error::Custom(format!(
  2468. "[dao_vote] Proposal was executed on transaction: {exec_tx_hash}"
  2469. )))
  2470. }
  2471. // Fetch DAO and check its deployed
  2472. let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
  2473. return Err(Error::Custom(format!(
  2474. "[dao_vote] DAO {} was not found",
  2475. proposal.proposal.dao_bulla
  2476. )))
  2477. };
  2478. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  2479. return Err(Error::Custom(
  2480. "[dao_vote] DAO seems to not have been deployed yet".to_string(),
  2481. ))
  2482. }
  2483. // Fetch all the proposal votes to check for duplicate nullifiers
  2484. let votes = self.get_dao_proposal_votes(proposal_bulla).await?;
  2485. let mut votes_nullifiers = vec![];
  2486. for vote in votes {
  2487. for nullifier in vote.nullifiers {
  2488. if !votes_nullifiers.contains(&nullifier) {
  2489. votes_nullifiers.push(nullifier);
  2490. }
  2491. }
  2492. }
  2493. // Fetch our own governance OwnCoins to see what our balance is
  2494. let gov_owncoins = self.get_token_coins(&dao.params.dao.gov_token_id).await?;
  2495. if gov_owncoins.is_empty() {
  2496. return Err(Error::Custom(format!(
  2497. "[dao_vote] Did not find any governance {} coins in wallet",
  2498. dao.params.dao.gov_token_id
  2499. )))
  2500. }
  2501. // Find which governance coins we can use
  2502. let gov_owncoins_to_use = match weight {
  2503. Some(_weight) => {
  2504. // TODO: Build a proper coin selection algorithm so that we can use a
  2505. // coins combination that matches the requested weight
  2506. return Err(Error::Custom(
  2507. "[dao_vote] Fractional vote weight not supported yet".to_string(),
  2508. ))
  2509. }
  2510. // If no weight was specified, use them all
  2511. None => gov_owncoins,
  2512. };
  2513. // Now we need to do a lookup for the zkas proof bincodes, and create
  2514. // the circuit objects and proving keys so we can build the transaction.
  2515. // We also do this through the RPC. First we grab the fee call from money.
  2516. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  2517. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  2518. else {
  2519. return Err(Error::Custom("[dao_vote] Fee circuit not found".to_string()))
  2520. };
  2521. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  2522. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  2523. // Creating Fee circuit proving key
  2524. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  2525. // Now we grab the DAO bins
  2526. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  2527. let Some(dao_vote_burn_zkbin) =
  2528. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_VOTE_INPUT_NS)
  2529. else {
  2530. return Err(Error::Custom("[dao_vote] DAO Vote Burn circuit not found".to_string()))
  2531. };
  2532. let Some(dao_vote_main_zkbin) =
  2533. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_VOTE_MAIN_NS)
  2534. else {
  2535. return Err(Error::Custom("[dao_vote] DAO Vote Main circuit not found".to_string()))
  2536. };
  2537. let dao_vote_burn_zkbin = ZkBinary::decode(&dao_vote_burn_zkbin.1)?;
  2538. let dao_vote_main_zkbin = ZkBinary::decode(&dao_vote_main_zkbin.1)?;
  2539. let dao_vote_burn_circuit =
  2540. ZkCircuit::new(empty_witnesses(&dao_vote_burn_zkbin)?, &dao_vote_burn_zkbin);
  2541. let dao_vote_main_circuit =
  2542. ZkCircuit::new(empty_witnesses(&dao_vote_main_zkbin)?, &dao_vote_main_zkbin);
  2543. // Creating DAO VoteBurn and VoteMain circuits proving keys
  2544. let dao_vote_burn_pk = ProvingKey::build(dao_vote_burn_zkbin.k, &dao_vote_burn_circuit);
  2545. let dao_vote_main_pk = ProvingKey::build(dao_vote_main_zkbin.k, &dao_vote_main_circuit);
  2546. // Now create the parameters for the vote tx
  2547. let signature_secret = SecretKey::random(&mut OsRng);
  2548. let mut inputs = Vec::with_capacity(gov_owncoins_to_use.len());
  2549. for gov_owncoin in gov_owncoins_to_use {
  2550. let nullifier = poseidon_hash([gov_owncoin.secret.inner(), gov_owncoin.coin.inner()]);
  2551. let vote_nullifier =
  2552. poseidon_hash([nullifier, gov_owncoin.secret.inner(), proposal_bulla.inner()]);
  2553. if votes_nullifiers.contains(&vote_nullifier.into()) {
  2554. return Err(Error::Custom("[dao_vote] Duplicate input nullifier found".to_string()))
  2555. };
  2556. let input = DaoVoteInput {
  2557. secret: gov_owncoin.secret,
  2558. note: gov_owncoin.note.clone(),
  2559. leaf_position: gov_owncoin.leaf_position,
  2560. merkle_path: proposal
  2561. .money_snapshot_tree
  2562. .as_ref()
  2563. .unwrap()
  2564. .witness(gov_owncoin.leaf_position, 0)
  2565. .unwrap(),
  2566. signature_secret,
  2567. };
  2568. inputs.push(input);
  2569. }
  2570. // Retrieve next block height and current block time target,
  2571. // to compute their window.
  2572. let next_block_height = self.get_next_block_height().await?;
  2573. let block_target = self.get_block_target().await?;
  2574. let current_blockwindow = blockwindow(next_block_height, block_target);
  2575. // Generate the Money nullifiers Sparse Merkle Tree
  2576. let store = MemoryStorageFp { tree: proposal.nullifiers_smt_snapshot.unwrap() };
  2577. let money_null_smt = SmtMemoryFp::new(store, PoseidonFp::new(), &EMPTY_NODES_FP);
  2578. // Create the vote call
  2579. let call = DaoVoteCall {
  2580. money_null_smt: &money_null_smt,
  2581. inputs,
  2582. vote_option,
  2583. proposal: proposal.proposal.clone(),
  2584. dao: dao.params.dao.clone(),
  2585. current_blockwindow,
  2586. };
  2587. let (params, proofs) = call.make(
  2588. &dao_vote_burn_zkbin,
  2589. &dao_vote_burn_pk,
  2590. &dao_vote_main_zkbin,
  2591. &dao_vote_main_pk,
  2592. )?;
  2593. // Encode the call
  2594. let mut data = vec![DaoFunction::Vote as u8];
  2595. params.encode_async(&mut data).await?;
  2596. let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  2597. // Create the TransactionBuilder containing above call
  2598. let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;
  2599. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  2600. // it into the fee-creating function.
  2601. let mut tx = tx_builder.build()?;
  2602. let sigs = tx.create_sigs(&[signature_secret])?;
  2603. tx.signatures = vec![sigs];
  2604. let tree = self.get_money_tree().await?;
  2605. let (fee_call, fee_proofs, fee_secrets) =
  2606. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  2607. // Append the fee call to the transaction
  2608. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  2609. // Now build the actual transaction and sign it with all necessary keys.
  2610. let mut tx = tx_builder.build()?;
  2611. let sigs = tx.create_sigs(&[signature_secret])?;
  2612. tx.signatures.push(sigs);
  2613. let sigs = tx.create_sigs(&fee_secrets)?;
  2614. tx.signatures.push(sigs);
  2615. Ok(tx)
  2616. }
  2617. /// Execute a DAO transfer proposal.
  2618. pub async fn dao_exec_transfer(
  2619. &self,
  2620. proposal: &ProposalRecord,
  2621. early: bool,
  2622. ) -> Result<Transaction> {
  2623. if proposal.leaf_position.is_none() ||
  2624. proposal.money_snapshot_tree.is_none() ||
  2625. proposal.nullifiers_smt_snapshot.is_none() ||
  2626. proposal.tx_hash.is_none() ||
  2627. proposal.call_index.is_none()
  2628. {
  2629. return Err(Error::Custom(
  2630. "[dao_exec_transfer] Proposal seems to not have been deployed yet".to_string(),
  2631. ))
  2632. }
  2633. // Check proposal is not executed
  2634. if let Some(exec_tx_hash) = proposal.exec_tx_hash {
  2635. return Err(Error::Custom(format!(
  2636. "[dao_exec_transfer] Proposal was executed on transaction: {exec_tx_hash}"
  2637. )))
  2638. }
  2639. // Check we know the plaintext data and they are valid
  2640. if proposal.data.is_none() {
  2641. return Err(Error::Custom(
  2642. "[dao_exec_transfer] Proposal plainext data is empty".to_string(),
  2643. ))
  2644. }
  2645. let proposal_coinattrs: CoinAttributes =
  2646. deserialize_async(proposal.data.as_ref().unwrap()).await?;
  2647. // Fetch DAO and check its deployed
  2648. let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
  2649. return Err(Error::Custom(format!(
  2650. "[dao_exec_transfer] DAO {} was not found",
  2651. proposal.proposal.dao_bulla
  2652. )))
  2653. };
  2654. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  2655. return Err(Error::Custom(
  2656. "[dao_exec_transfer] DAO seems to not have been deployed yet".to_string(),
  2657. ))
  2658. }
  2659. // Check that we have the exec key
  2660. if dao.params.exec_secret_key.is_none() {
  2661. return Err(Error::Custom(
  2662. "[dao_exec_transfer] We need the exec secret key to execute proposals for this DAO"
  2663. .to_string(),
  2664. ))
  2665. }
  2666. // If early flag is provided, check that we have the early exec key
  2667. if early && dao.params.early_exec_secret_key.is_none() {
  2668. return Err(Error::Custom(
  2669. "[dao_exec_transfer] We need the early exec secret key to execute proposals early for this DAO"
  2670. .to_string(),
  2671. ))
  2672. }
  2673. // Check proposal is approved
  2674. let votes = self.get_dao_proposal_votes(&proposal.bulla()).await?;
  2675. let mut yes_vote_value = 0;
  2676. let mut yes_vote_blind = Blind::ZERO;
  2677. let mut all_vote_value = 0;
  2678. let mut all_vote_blind = Blind::ZERO;
  2679. for vote in votes {
  2680. if vote.vote_option {
  2681. yes_vote_value += vote.all_vote_value;
  2682. };
  2683. yes_vote_blind += vote.yes_vote_blind;
  2684. all_vote_value += vote.all_vote_value;
  2685. all_vote_blind += vote.all_vote_blind;
  2686. }
  2687. let approval_ratio = (yes_vote_value as f64 * 100.0) / all_vote_value as f64;
  2688. if all_vote_value < dao.params.dao.quorum ||
  2689. approval_ratio <
  2690. (dao.params.dao.approval_ratio_quot / dao.params.dao.approval_ratio_base)
  2691. as f64
  2692. {
  2693. return Err(Error::Custom(
  2694. "[dao_exec_transfer] Proposal is not approved yet".to_string(),
  2695. ))
  2696. };
  2697. // Fetch DAO unspent OwnCoins to see what its balance is for the coin
  2698. let dao_spend_hook =
  2699. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  2700. .to_func_id();
  2701. let dao_owncoins = self
  2702. .get_contract_token_coins(
  2703. &proposal_coinattrs.token_id,
  2704. &dao_spend_hook,
  2705. &proposal.proposal.dao_bulla.inner(),
  2706. )
  2707. .await?;
  2708. if dao_owncoins.is_empty() {
  2709. return Err(Error::Custom(format!(
  2710. "[dao_exec_transfer] Did not find any {} unspent coins owned by this DAO",
  2711. proposal_coinattrs.token_id,
  2712. )))
  2713. }
  2714. // Check DAO balance is sufficient
  2715. if dao_owncoins.iter().map(|x| x.note.value).sum::<u64>() < proposal_coinattrs.value {
  2716. return Err(Error::Custom(format!(
  2717. "[dao_exec_transfer] Not enough DAO balance for token ID: {}",
  2718. proposal_coinattrs.token_id,
  2719. )))
  2720. }
  2721. // Find which DAO coins we can use
  2722. let (spent_coins, change_value) = select_coins(dao_owncoins, proposal_coinattrs.value)?;
  2723. // Now we need to do a lookup for the zkas proof bincodes, and create
  2724. // the circuit objects and proving keys so we can build the transaction.
  2725. // We also do this through the RPC. First we grab the calls from money.
  2726. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  2727. let Some(mint_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_MINT_NS_V1)
  2728. else {
  2729. return Err(Error::Custom("[dao_exec_transfer] Mint circuit not found".to_string()))
  2730. };
  2731. let Some(burn_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_BURN_NS_V1)
  2732. else {
  2733. return Err(Error::Custom("[dao_exec_transfer] Burn circuit not found".to_string()))
  2734. };
  2735. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  2736. else {
  2737. return Err(Error::Custom("[dao_exec_transfer] Fee circuit not found".to_string()))
  2738. };
  2739. let mint_zkbin = ZkBinary::decode(&mint_zkbin.1)?;
  2740. let burn_zkbin = ZkBinary::decode(&burn_zkbin.1)?;
  2741. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  2742. let mint_circuit = ZkCircuit::new(empty_witnesses(&mint_zkbin)?, &mint_zkbin);
  2743. let burn_circuit = ZkCircuit::new(empty_witnesses(&burn_zkbin)?, &burn_zkbin);
  2744. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  2745. // Creating Mint, Burn and Fee circuits proving keys
  2746. let mint_pk = ProvingKey::build(mint_zkbin.k, &mint_circuit);
  2747. let burn_pk = ProvingKey::build(burn_zkbin.k, &burn_circuit);
  2748. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  2749. // Now we grab the DAO bins
  2750. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  2751. let (namespace, early_exec_secret_key) = match early {
  2752. true => (
  2753. DAO_CONTRACT_ZKAS_DAO_EARLY_EXEC_NS,
  2754. Some(dao.params.early_exec_secret_key.unwrap()),
  2755. ),
  2756. false => (DAO_CONTRACT_ZKAS_DAO_EXEC_NS, None),
  2757. };
  2758. let Some(dao_exec_zkbin) = zkas_bins.iter().find(|x| x.0 == namespace) else {
  2759. return Err(Error::Custom(format!(
  2760. "[dao_exec_transfer] DAO {namespace} circuit not found"
  2761. )))
  2762. };
  2763. let Some(dao_auth_transfer_zkbin) =
  2764. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_AUTH_MONEY_TRANSFER_NS)
  2765. else {
  2766. return Err(Error::Custom(
  2767. "[dao_exec_transfer] DAO AuthTransfer circuit not found".to_string(),
  2768. ))
  2769. };
  2770. let Some(dao_auth_transfer_enc_coin_zkbin) =
  2771. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_AUTH_MONEY_TRANSFER_ENC_COIN_NS)
  2772. else {
  2773. return Err(Error::Custom(
  2774. "[dao_exec_transfer] DAO AuthTransferEncCoin circuit not found".to_string(),
  2775. ))
  2776. };
  2777. let dao_exec_zkbin = ZkBinary::decode(&dao_exec_zkbin.1)?;
  2778. let dao_auth_transfer_zkbin = ZkBinary::decode(&dao_auth_transfer_zkbin.1)?;
  2779. let dao_auth_transfer_enc_coin_zkbin =
  2780. ZkBinary::decode(&dao_auth_transfer_enc_coin_zkbin.1)?;
  2781. let dao_exec_circuit = ZkCircuit::new(empty_witnesses(&dao_exec_zkbin)?, &dao_exec_zkbin);
  2782. let dao_auth_transfer_circuit =
  2783. ZkCircuit::new(empty_witnesses(&dao_auth_transfer_zkbin)?, &dao_auth_transfer_zkbin);
  2784. let dao_auth_transfer_enc_coin_circuit = ZkCircuit::new(
  2785. empty_witnesses(&dao_auth_transfer_enc_coin_zkbin)?,
  2786. &dao_auth_transfer_enc_coin_zkbin,
  2787. );
  2788. // Creating DAO Exec, AuthTransfer and AuthTransferEncCoin circuits proving keys
  2789. let dao_exec_pk = ProvingKey::build(dao_exec_zkbin.k, &dao_exec_circuit);
  2790. let dao_auth_transfer_pk =
  2791. ProvingKey::build(dao_auth_transfer_zkbin.k, &dao_auth_transfer_circuit);
  2792. let dao_auth_transfer_enc_coin_pk = ProvingKey::build(
  2793. dao_auth_transfer_enc_coin_zkbin.k,
  2794. &dao_auth_transfer_enc_coin_circuit,
  2795. );
  2796. // Fetch our money Merkle tree
  2797. let tree = self.get_money_tree().await?;
  2798. // Retrieve next block height and current block time target,
  2799. // to compute their window.
  2800. let next_block_height = self.get_next_block_height().await?;
  2801. let block_target = self.get_block_target().await?;
  2802. let current_blockwindow = blockwindow(next_block_height, block_target);
  2803. // Now we can create the transfer call parameters
  2804. let input_user_data_blind = Blind::random(&mut OsRng);
  2805. let mut inputs = vec![];
  2806. for coin in &spent_coins {
  2807. inputs.push(TransferCallInput {
  2808. coin: coin.clone(),
  2809. merkle_path: tree.witness(coin.leaf_position, 0).unwrap(),
  2810. user_data_blind: input_user_data_blind,
  2811. });
  2812. }
  2813. let mut outputs = vec![];
  2814. outputs.push(proposal_coinattrs.clone());
  2815. let dao_coin_attrs = CoinAttributes {
  2816. public_key: dao.params.dao.notes_public_key,
  2817. value: change_value,
  2818. token_id: proposal_coinattrs.token_id,
  2819. spend_hook: dao_spend_hook,
  2820. user_data: proposal.proposal.dao_bulla.inner(),
  2821. blind: Blind::random(&mut OsRng),
  2822. };
  2823. outputs.push(dao_coin_attrs.clone());
  2824. // Create the transfer call
  2825. let transfer_builder = TransferCallBuilder {
  2826. clear_inputs: vec![],
  2827. inputs,
  2828. outputs,
  2829. mint_zkbin: mint_zkbin.clone(),
  2830. mint_pk: mint_pk.clone(),
  2831. burn_zkbin: burn_zkbin.clone(),
  2832. burn_pk: burn_pk.clone(),
  2833. };
  2834. let (transfer_params, transfer_secrets) = transfer_builder.build()?;
  2835. // Encode the call
  2836. let mut data = vec![MoneyFunction::TransferV1 as u8];
  2837. transfer_params.encode_async(&mut data).await?;
  2838. let transfer_call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  2839. // Create the exec call
  2840. let exec_signature_secret = SecretKey::random(&mut OsRng);
  2841. let exec_builder = DaoExecCall {
  2842. proposal: proposal.proposal.clone(),
  2843. dao: dao.params.dao.clone(),
  2844. yes_vote_value,
  2845. all_vote_value,
  2846. yes_vote_blind,
  2847. all_vote_blind,
  2848. signature_secret: exec_signature_secret,
  2849. current_blockwindow,
  2850. };
  2851. let (exec_params, exec_proofs) = exec_builder.make(
  2852. &dao.params.exec_secret_key.unwrap(),
  2853. &early_exec_secret_key,
  2854. &dao_exec_zkbin,
  2855. &dao_exec_pk,
  2856. )?;
  2857. // Encode the call
  2858. let mut data = vec![DaoFunction::Exec as u8];
  2859. exec_params.encode_async(&mut data).await?;
  2860. let exec_call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  2861. // Now we can create the auth call
  2862. // Auth module
  2863. let auth_transfer_builder = DaoAuthMoneyTransferCall {
  2864. proposal: proposal.proposal.clone(),
  2865. proposal_coinattrs: vec![proposal_coinattrs],
  2866. dao: dao.params.dao.clone(),
  2867. input_user_data_blind,
  2868. dao_coin_attrs,
  2869. };
  2870. let (auth_transfer_params, auth_transfer_proofs) = auth_transfer_builder.make(
  2871. &dao_auth_transfer_zkbin,
  2872. &dao_auth_transfer_pk,
  2873. &dao_auth_transfer_enc_coin_zkbin,
  2874. &dao_auth_transfer_enc_coin_pk,
  2875. )?;
  2876. // Encode the call
  2877. let mut data = vec![DaoFunction::AuthMoneyTransfer as u8];
  2878. auth_transfer_params.encode_async(&mut data).await?;
  2879. let auth_transfer_call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  2880. // Create the TransactionBuilder containing above calls
  2881. let mut tx_builder = TransactionBuilder::new(
  2882. ContractCallLeaf { call: exec_call, proofs: exec_proofs },
  2883. vec![
  2884. DarkTree::new(
  2885. ContractCallLeaf { call: auth_transfer_call, proofs: auth_transfer_proofs },
  2886. vec![],
  2887. None,
  2888. None,
  2889. ),
  2890. DarkTree::new(
  2891. ContractCallLeaf { call: transfer_call, proofs: transfer_secrets.proofs },
  2892. vec![],
  2893. None,
  2894. None,
  2895. ),
  2896. ],
  2897. )?;
  2898. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  2899. // it into the fee-creating function.
  2900. let mut tx = tx_builder.build()?;
  2901. let auth_transfer_sigs = tx.create_sigs(&[])?;
  2902. let transfer_sigs = tx.create_sigs(&transfer_secrets.signature_secrets)?;
  2903. let exec_sigs = tx.create_sigs(&[exec_signature_secret])?;
  2904. tx.signatures = vec![auth_transfer_sigs, transfer_sigs, exec_sigs];
  2905. let (fee_call, fee_proofs, fee_secrets) =
  2906. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  2907. // Append the fee call to the transaction
  2908. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  2909. // Now build the actual transaction and sign it with all necessary keys.
  2910. let mut tx = tx_builder.build()?;
  2911. let sigs = tx.create_sigs(&[])?;
  2912. tx.signatures.push(sigs);
  2913. let sigs = tx.create_sigs(&transfer_secrets.signature_secrets)?;
  2914. tx.signatures.push(sigs);
  2915. let sigs = tx.create_sigs(&[exec_signature_secret])?;
  2916. tx.signatures.push(sigs);
  2917. let sigs = tx.create_sigs(&fee_secrets)?;
  2918. tx.signatures.push(sigs);
  2919. Ok(tx)
  2920. }
  2921. /// Execute a DAO generic proposal.
  2922. pub async fn dao_exec_generic(
  2923. &self,
  2924. proposal: &ProposalRecord,
  2925. early: bool,
  2926. ) -> Result<Transaction> {
  2927. if proposal.leaf_position.is_none() ||
  2928. proposal.money_snapshot_tree.is_none() ||
  2929. proposal.nullifiers_smt_snapshot.is_none() ||
  2930. proposal.tx_hash.is_none() ||
  2931. proposal.call_index.is_none()
  2932. {
  2933. return Err(Error::Custom(
  2934. "[dao_exec_generic] Proposal seems to not have been deployed yet".to_string(),
  2935. ))
  2936. }
  2937. // Check proposal is not executed
  2938. if let Some(exec_tx_hash) = proposal.exec_tx_hash {
  2939. return Err(Error::Custom(format!(
  2940. "[dao_exec_generic] Proposal was executed on transaction: {exec_tx_hash}"
  2941. )))
  2942. }
  2943. // Fetch DAO and check its deployed
  2944. let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
  2945. return Err(Error::Custom(format!(
  2946. "[dao_exec_generic] DAO {} was not found",
  2947. proposal.proposal.dao_bulla
  2948. )))
  2949. };
  2950. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  2951. return Err(Error::Custom(
  2952. "[dao_exec_generic] DAO seems to not have been deployed yet".to_string(),
  2953. ))
  2954. }
  2955. // Check that we have the exec key
  2956. if dao.params.exec_secret_key.is_none() {
  2957. return Err(Error::Custom(
  2958. "[dao_exec_generic] We need the exec secret key to execute proposals for this DAO"
  2959. .to_string(),
  2960. ))
  2961. }
  2962. // If early flag is provided, check that we have the early exec key
  2963. if early && dao.params.early_exec_secret_key.is_none() {
  2964. return Err(Error::Custom(
  2965. "[dao_exec_generic] We need the early exec secret key to execute proposals early for this DAO"
  2966. .to_string(),
  2967. ))
  2968. }
  2969. // Check proposal is approved
  2970. let votes = self.get_dao_proposal_votes(&proposal.bulla()).await?;
  2971. let mut yes_vote_value = 0;
  2972. let mut yes_vote_blind = Blind::ZERO;
  2973. let mut all_vote_value = 0;
  2974. let mut all_vote_blind = Blind::ZERO;
  2975. for vote in votes {
  2976. if vote.vote_option {
  2977. yes_vote_value += vote.all_vote_value;
  2978. };
  2979. yes_vote_blind += vote.yes_vote_blind;
  2980. all_vote_value += vote.all_vote_value;
  2981. all_vote_blind += vote.all_vote_blind;
  2982. }
  2983. let approval_ratio = (yes_vote_value as f64 * 100.0) / all_vote_value as f64;
  2984. if all_vote_value < dao.params.dao.quorum ||
  2985. approval_ratio <
  2986. (dao.params.dao.approval_ratio_quot / dao.params.dao.approval_ratio_base)
  2987. as f64
  2988. {
  2989. return Err(Error::Custom("[dao_exec_generic] Proposal is not approved yet".to_string()))
  2990. };
  2991. // Now we need to do a lookup for the zkas proof bincodes, and create
  2992. // the circuit objects and proving keys so we can build the transaction.
  2993. // We also do this through the RPC. First we grab the calls from money.
  2994. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  2995. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  2996. else {
  2997. return Err(Error::Custom("[dao_exec_generic] Fee circuit not found".to_string()))
  2998. };
  2999. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  3000. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  3001. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  3002. // Now we grab the DAO bins
  3003. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  3004. let (namespace, early_exec_secret_key) = match early {
  3005. true => (
  3006. DAO_CONTRACT_ZKAS_DAO_EARLY_EXEC_NS,
  3007. Some(dao.params.early_exec_secret_key.unwrap()),
  3008. ),
  3009. false => (DAO_CONTRACT_ZKAS_DAO_EXEC_NS, None),
  3010. };
  3011. let Some(dao_exec_zkbin) = zkas_bins.iter().find(|x| x.0 == namespace) else {
  3012. return Err(Error::Custom(format!(
  3013. "[dao_exec_generic] DAO {namespace} circuit not found"
  3014. )))
  3015. };
  3016. let dao_exec_zkbin = ZkBinary::decode(&dao_exec_zkbin.1)?;
  3017. let dao_exec_circuit = ZkCircuit::new(empty_witnesses(&dao_exec_zkbin)?, &dao_exec_zkbin);
  3018. let dao_exec_pk = ProvingKey::build(dao_exec_zkbin.k, &dao_exec_circuit);
  3019. // Fetch our money Merkle tree
  3020. let tree = self.get_money_tree().await?;
  3021. // Retrieve next block height and current block time target,
  3022. // to compute their window.
  3023. let next_block_height = self.get_next_block_height().await?;
  3024. let block_target = self.get_block_target().await?;
  3025. let current_blockwindow = blockwindow(next_block_height, block_target);
  3026. // Create the exec call
  3027. let exec_signature_secret = SecretKey::random(&mut OsRng);
  3028. let exec_builder = DaoExecCall {
  3029. proposal: proposal.proposal.clone(),
  3030. dao: dao.params.dao.clone(),
  3031. yes_vote_value,
  3032. all_vote_value,
  3033. yes_vote_blind,
  3034. all_vote_blind,
  3035. signature_secret: exec_signature_secret,
  3036. current_blockwindow,
  3037. };
  3038. let (exec_params, exec_proofs) = exec_builder.make(
  3039. &dao.params.exec_secret_key.unwrap(),
  3040. &early_exec_secret_key,
  3041. &dao_exec_zkbin,
  3042. &dao_exec_pk,
  3043. )?;
  3044. // Encode the call
  3045. let mut data = vec![DaoFunction::Exec as u8];
  3046. exec_params.encode_async(&mut data).await?;
  3047. let exec_call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  3048. // Create the TransactionBuilder containing above calls
  3049. let mut tx_builder = TransactionBuilder::new(
  3050. ContractCallLeaf { call: exec_call, proofs: exec_proofs },
  3051. vec![],
  3052. )?;
  3053. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  3054. // it into the fee-creating function.
  3055. let mut tx = tx_builder.build()?;
  3056. let exec_sigs = tx.create_sigs(&[exec_signature_secret])?;
  3057. tx.signatures = vec![exec_sigs];
  3058. let (fee_call, fee_proofs, fee_secrets) =
  3059. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  3060. // Append the fee call to the transaction
  3061. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  3062. // Now build the actual transaction and sign it with all necessary keys.
  3063. let mut tx = tx_builder.build()?;
  3064. let sigs = tx.create_sigs(&[exec_signature_secret])?;
  3065. tx.signatures.push(sigs);
  3066. let sigs = tx.create_sigs(&fee_secrets)?;
  3067. tx.signatures.push(sigs);
  3068. Ok(tx)
  3069. }
  3070. }