dao.rs 134 KB

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