dao.rs 136 KB

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