dao.rs 134 KB

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