dao.rs 135 KB

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