dao.rs 135 KB

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