dao.rs 132 KB

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