dao.rs 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458
  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 = \"{secret_key}\"\n\n"),
  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 = \"{secret_key}\"\n\n"),
  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 = \"{secret_key}\"\n\n"),
  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 = \"{secret_key}\"\n\n"),
  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 = \"{secret_key}\"\n\n"),
  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. let mut wallet_tx = false;
  1120. for dao in &daos {
  1121. if dao.bulla() != new_bulla {
  1122. continue
  1123. }
  1124. println!(
  1125. "[apply_dao_mint_data] Found minted DAO {new_bulla}, noting down for wallet update"
  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. // Confirm it
  1133. if let Err(e) = self.confirm_dao(&dao_to_confirm).await {
  1134. return Err(Error::DatabaseError(format!(
  1135. "[apply_dao_mint_data] Confirm DAO failed: {e:?}"
  1136. )))
  1137. }
  1138. wallet_tx = true;
  1139. break
  1140. }
  1141. // Update wallet data
  1142. if let Err(e) = self.put_dao_trees(&daos_tree, &proposals_tree).await {
  1143. return Err(Error::DatabaseError(format!(
  1144. "[apply_dao_mint_data] Put DAO tree failed: {e:?}"
  1145. )))
  1146. }
  1147. Ok(wallet_tx)
  1148. }
  1149. /// Auxiliary function to apply `DaoFunction::Propose` call data to the wallet,
  1150. /// and store its inverse query into the cache.
  1151. /// Returns a flag indicating if the provided call refers to our own wallet.
  1152. async fn apply_dao_propose_data(
  1153. &self,
  1154. params: DaoProposeParams,
  1155. tx_hash: TransactionHash,
  1156. call_index: u8,
  1157. ) -> Result<bool> {
  1158. let daos = self.get_daos().await?;
  1159. let (daos_tree, mut proposals_tree) = self.get_dao_trees().await?;
  1160. proposals_tree.append(MerkleNode::from(params.proposal_bulla.inner()));
  1161. // If we're able to decrypt this note, that's the way to link it
  1162. // to a specific DAO.
  1163. let mut wallet_tx = false;
  1164. for dao in &daos {
  1165. // Check if we have the proposals key
  1166. let Some(proposals_secret_key) = dao.params.proposals_secret_key else { continue };
  1167. // Try to decrypt the proposal note
  1168. let Ok(note) = params.note.decrypt::<DaoProposal>(&proposals_secret_key) else {
  1169. continue
  1170. };
  1171. // We managed to decrypt it. Let's place this in a proper ProposalRecord object
  1172. println!("[apply_dao_propose_data] Managed to decrypt DAO proposal note");
  1173. // We need to clone the trees here for reproducing the snapshot Merkle roots
  1174. let money_tree = self.get_money_tree().await?;
  1175. let nullifiers_smt = self.get_nullifiers_smt().await?;
  1176. // Check if we already got the record
  1177. let our_proposal = match self.get_dao_proposal_by_bulla(&params.proposal_bulla).await {
  1178. Ok(p) => {
  1179. let mut our_proposal = p;
  1180. our_proposal.leaf_position = proposals_tree.mark();
  1181. our_proposal.money_snapshot_tree = Some(money_tree);
  1182. our_proposal.nullifiers_smt_snapshot = Some(nullifiers_smt);
  1183. our_proposal.tx_hash = Some(tx_hash);
  1184. our_proposal.call_index = Some(call_index);
  1185. our_proposal
  1186. }
  1187. Err(_) => ProposalRecord {
  1188. proposal: note,
  1189. data: None,
  1190. leaf_position: proposals_tree.mark(),
  1191. money_snapshot_tree: Some(money_tree),
  1192. nullifiers_smt_snapshot: Some(nullifiers_smt),
  1193. tx_hash: Some(tx_hash),
  1194. call_index: Some(call_index),
  1195. exec_tx_hash: None,
  1196. },
  1197. };
  1198. // Update/store our record
  1199. if let Err(e) = self.put_dao_proposal(&our_proposal).await {
  1200. return Err(Error::DatabaseError(format!(
  1201. "[apply_dao_propose_data] Put DAO proposals failed: {e:?}"
  1202. )))
  1203. }
  1204. wallet_tx = true;
  1205. break
  1206. }
  1207. // Update wallet data
  1208. if let Err(e) = self.put_dao_trees(&daos_tree, &proposals_tree).await {
  1209. return Err(Error::DatabaseError(format!(
  1210. "[apply_dao_propose_data] Put DAO tree failed: {e:?}"
  1211. )))
  1212. }
  1213. Ok(wallet_tx)
  1214. }
  1215. /// Auxiliary function to apply `DaoFunction::Vote` call data to the wallet,
  1216. /// and store its inverse query into the cache.
  1217. /// Returns a flag indicating if the provided call refers to our own wallet.
  1218. async fn apply_dao_vote_data(
  1219. &self,
  1220. params: DaoVoteParams,
  1221. tx_hash: TransactionHash,
  1222. call_index: u8,
  1223. ) -> Result<bool> {
  1224. // Check if we got the corresponding proposal
  1225. let Ok(proposal) = self.get_dao_proposal_by_bulla(&params.proposal_bulla).await else {
  1226. return Ok(false)
  1227. };
  1228. // Grab the proposal DAO
  1229. let dao = match self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
  1230. Ok(d) => d,
  1231. Err(e) => {
  1232. return Err(Error::DatabaseError(format!(
  1233. "[apply_dao_vote_data] Couldn't find proposal {} DAO {}: {e}",
  1234. proposal.bulla(),
  1235. proposal.proposal.dao_bulla,
  1236. )))
  1237. }
  1238. };
  1239. // Check if we have the votes key
  1240. let Some(votes_secret_key) = dao.params.votes_secret_key else { return Ok(false) };
  1241. // Decrypt the vote note
  1242. let note = match params.note.decrypt_unsafe(&votes_secret_key) {
  1243. Ok(n) => n,
  1244. Err(e) => {
  1245. return Err(Error::DatabaseError(format!(
  1246. "[apply_dao_vote_data] Couldn't decrypt proposal {} vote with DAO {} keys: {e}",
  1247. proposal.bulla(),
  1248. proposal.proposal.dao_bulla,
  1249. )))
  1250. }
  1251. };
  1252. // Create the DAO vote record
  1253. let vote_option = fp_to_u64(note[0]).unwrap();
  1254. if vote_option > 1 {
  1255. return Err(Error::DatabaseError(format!(
  1256. "[apply_dao_vote_data] Malformed vote for proposal {}: {vote_option}",
  1257. proposal.bulla(),
  1258. )))
  1259. }
  1260. let vote_option = vote_option != 0;
  1261. let yes_vote_blind = Blind(fp_mod_fv(note[1]));
  1262. let all_vote_value = fp_to_u64(note[2]).unwrap();
  1263. let all_vote_blind = Blind(fp_mod_fv(note[3]));
  1264. let v = VoteRecord {
  1265. id: 0, // This will be set by SQLite AUTOINCREMENT
  1266. proposal: params.proposal_bulla,
  1267. vote_option,
  1268. yes_vote_blind,
  1269. all_vote_value,
  1270. all_vote_blind,
  1271. tx_hash,
  1272. call_index,
  1273. nullifiers: params.inputs.iter().map(|i| i.vote_nullifier).collect(),
  1274. };
  1275. if let Err(e) = self.put_dao_vote(&v).await {
  1276. return Err(Error::DatabaseError(format!(
  1277. "[apply_dao_vote_data] Put DAO votes failed: {e:?}"
  1278. )))
  1279. }
  1280. Ok(true)
  1281. }
  1282. /// Auxiliary function to apply `DaoFunction::Exec` call data to the wallet,
  1283. /// and store its inverse query into the cache.
  1284. /// Returns a flag indicating if the provided call refers to our own wallet.
  1285. async fn apply_dao_exec_data(
  1286. &self,
  1287. params: DaoExecParams,
  1288. tx_hash: TransactionHash,
  1289. ) -> Result<bool> {
  1290. // Check if we got the corresponding proposal
  1291. if self.get_dao_proposal_by_bulla(&params.proposal_bulla).await.is_err() {
  1292. return Ok(false)
  1293. };
  1294. // Grab proposal record key
  1295. let key = serialize_async(&params.proposal_bulla).await;
  1296. // Create an SQL `UPDATE` query to update proposal exec transaction hash
  1297. let query = format!(
  1298. "UPDATE {} SET {} = ?1 WHERE {} = ?2;",
  1299. *DAO_PROPOSALS_TABLE, DAO_PROPOSALS_COL_EXEC_TX_HASH, DAO_PROPOSALS_COL_BULLA,
  1300. );
  1301. // Create its inverse query
  1302. let inverse = match self.wallet.create_prepared_statement(
  1303. &format!(
  1304. "UPDATE {} SET {} = NULL WHERE {} = ?1;",
  1305. *DAO_PROPOSALS_TABLE, DAO_PROPOSALS_COL_EXEC_TX_HASH, DAO_PROPOSALS_COL_BULLA,
  1306. ),
  1307. rusqlite::params![key],
  1308. ) {
  1309. Ok(q) => q,
  1310. Err(e) => {
  1311. return Err(Error::DatabaseError(format!(
  1312. "[apply_dao_exec_data] Creating DAO proposal update inverse query failed: {e:?}"
  1313. )))
  1314. }
  1315. };
  1316. // Execute the query
  1317. if let Err(e) = self
  1318. .wallet
  1319. .exec_sql(&query, rusqlite::params![Some(serialize_async(&tx_hash).await), key])
  1320. {
  1321. return Err(Error::DatabaseError(format!(
  1322. "[apply_dao_exec_data] Update DAO proposal failed: {e:?}"
  1323. )))
  1324. }
  1325. // Store its inverse
  1326. if let Err(e) = self.wallet.cache_inverse(inverse) {
  1327. return Err(Error::DatabaseError(format!(
  1328. "[apply_dao_exec_data] Inserting inverse query into cache failed: {e:?}"
  1329. )))
  1330. }
  1331. Ok(true)
  1332. }
  1333. /// Append data related to DAO contract transactions into the wallet database,
  1334. /// and store their inverse queries into the cache.
  1335. /// Returns a flag indicating if the provided data refer to our own wallet.
  1336. pub async fn apply_tx_dao_data(
  1337. &self,
  1338. data: &[u8],
  1339. tx_hash: TransactionHash,
  1340. call_idx: u8,
  1341. ) -> Result<bool> {
  1342. // Run through the transaction call data and see what we got:
  1343. match DaoFunction::try_from(data[0])? {
  1344. DaoFunction::Mint => {
  1345. println!("[apply_tx_dao_data] Found Dao::Mint call");
  1346. let params: DaoMintParams = deserialize_async(&data[1..]).await?;
  1347. self.apply_dao_mint_data(params.dao_bulla, tx_hash, call_idx).await
  1348. }
  1349. DaoFunction::Propose => {
  1350. println!("[apply_tx_dao_data] Found Dao::Propose call");
  1351. let params: DaoProposeParams = deserialize_async(&data[1..]).await?;
  1352. self.apply_dao_propose_data(params, tx_hash, call_idx).await
  1353. }
  1354. DaoFunction::Vote => {
  1355. println!("[apply_tx_dao_data] Found Dao::Vote call");
  1356. let params: DaoVoteParams = deserialize_async(&data[1..]).await?;
  1357. self.apply_dao_vote_data(params, tx_hash, call_idx).await
  1358. }
  1359. DaoFunction::Exec => {
  1360. println!("[apply_tx_dao_data] Found Dao::Exec call");
  1361. let params: DaoExecParams = deserialize_async(&data[1..]).await?;
  1362. self.apply_dao_exec_data(params, tx_hash).await
  1363. }
  1364. DaoFunction::AuthMoneyTransfer => {
  1365. println!("[apply_tx_dao_data] Found Dao::AuthMoneyTransfer call");
  1366. // Does nothing, just verifies the other calls are correct
  1367. Ok(false)
  1368. }
  1369. }
  1370. }
  1371. /// Confirm already imported DAO metadata into the wallet,
  1372. /// and store its inverse query into the cache.
  1373. /// Here we just write the leaf position, tx hash, and call index.
  1374. /// Panics if the fields are None.
  1375. pub async fn confirm_dao(&self, dao: &DaoRecord) -> WalletDbResult<()> {
  1376. // Grab dao record key
  1377. let key = serialize_async(&dao.bulla()).await;
  1378. // Create an SQL `UPDATE` query
  1379. let query = format!(
  1380. "UPDATE {} SET {} = ?1, {} = ?2, {} = ?3 WHERE {} = ?4;",
  1381. *DAO_DAOS_TABLE,
  1382. DAO_DAOS_COL_LEAF_POSITION,
  1383. DAO_DAOS_COL_TX_HASH,
  1384. DAO_DAOS_COL_CALL_INDEX,
  1385. DAO_DAOS_COL_BULLA
  1386. );
  1387. // Create its params
  1388. let params = rusqlite::params![
  1389. serialize_async(&dao.leaf_position.unwrap()).await,
  1390. serialize_async(&dao.tx_hash.unwrap()).await,
  1391. dao.call_index.unwrap(),
  1392. key,
  1393. ];
  1394. // Create its inverse query
  1395. let inverse_query = format!(
  1396. "UPDATE {} SET {} = NULL, {} = NULL, {} = NULL WHERE {} = ?1;",
  1397. *DAO_DAOS_TABLE,
  1398. DAO_DAOS_COL_LEAF_POSITION,
  1399. DAO_DAOS_COL_TX_HASH,
  1400. DAO_DAOS_COL_CALL_INDEX,
  1401. DAO_DAOS_COL_BULLA
  1402. );
  1403. let inverse =
  1404. self.wallet.create_prepared_statement(&inverse_query, rusqlite::params![key])?;
  1405. // Execute the query
  1406. self.wallet.exec_sql(&query, params)?;
  1407. // Store its inverse
  1408. self.wallet.cache_inverse(inverse)
  1409. }
  1410. /// Import given DAO proposal into the wallet,
  1411. /// and store its inverse query into the cache.
  1412. pub async fn put_dao_proposal(&self, proposal: &ProposalRecord) -> Result<()> {
  1413. // Check that we already have the proposal DAO
  1414. if let Err(e) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
  1415. return Err(Error::DatabaseError(format!(
  1416. "[put_dao_proposal] Couldn't find proposal {} DAO {}: {e}",
  1417. proposal.bulla(),
  1418. proposal.proposal.dao_bulla
  1419. )))
  1420. }
  1421. // Grab proposal record key
  1422. let key = serialize_async(&proposal.bulla()).await;
  1423. // Create an SQL `INSERT OR REPLACE` query
  1424. let query = format!(
  1425. "INSERT OR REPLACE INTO {} ({}, {}, {}, {}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10);",
  1426. *DAO_PROPOSALS_TABLE,
  1427. DAO_PROPOSALS_COL_BULLA,
  1428. DAO_PROPOSALS_COL_DAO_BULLA,
  1429. DAO_PROPOSALS_COL_PROPOSAL,
  1430. DAO_PROPOSALS_COL_DATA,
  1431. DAO_PROPOSALS_COL_LEAF_POSITION,
  1432. DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE,
  1433. DAO_PROPOSALS_COL_NULLIFIERS_SMT_SNAPSHOT,
  1434. DAO_PROPOSALS_COL_TX_HASH,
  1435. DAO_PROPOSALS_COL_CALL_INDEX,
  1436. DAO_PROPOSALS_COL_EXEC_TX_HASH,
  1437. );
  1438. // Create its params
  1439. let data = match &proposal.data {
  1440. Some(data) => Some(data),
  1441. None => None,
  1442. };
  1443. let leaf_position = match &proposal.leaf_position {
  1444. Some(leaf_position) => Some(serialize_async(leaf_position).await),
  1445. None => None,
  1446. };
  1447. let money_snapshot_tree = match &proposal.money_snapshot_tree {
  1448. Some(money_snapshot_tree) => Some(serialize_async(money_snapshot_tree).await),
  1449. None => None,
  1450. };
  1451. let nullifiers_smt_snapshot = match &proposal.nullifiers_smt_snapshot {
  1452. Some(nullifiers_smt_snapshot) => Some(serialize_async(nullifiers_smt_snapshot).await),
  1453. None => None,
  1454. };
  1455. let tx_hash = match &proposal.tx_hash {
  1456. Some(tx_hash) => Some(serialize_async(tx_hash).await),
  1457. None => None,
  1458. };
  1459. let exec_tx_hash = match &proposal.exec_tx_hash {
  1460. Some(exec_tx_hash) => Some(serialize_async(exec_tx_hash).await),
  1461. None => None,
  1462. };
  1463. let params = rusqlite::params![
  1464. key,
  1465. serialize_async(&proposal.proposal.dao_bulla).await,
  1466. serialize_async(&proposal.proposal).await,
  1467. data,
  1468. leaf_position,
  1469. money_snapshot_tree,
  1470. nullifiers_smt_snapshot,
  1471. tx_hash,
  1472. proposal.call_index,
  1473. exec_tx_hash,
  1474. ];
  1475. // Create its inverse query
  1476. let inverse_query = format!(
  1477. "UPDATE {} SET {} = NULL, {} = NULL, {} = NULL, {} = NULL, {} = NULL, {} = NULL WHERE {} = ?1;",
  1478. *DAO_PROPOSALS_TABLE,
  1479. DAO_PROPOSALS_COL_LEAF_POSITION,
  1480. DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE,
  1481. DAO_PROPOSALS_COL_NULLIFIERS_SMT_SNAPSHOT,
  1482. DAO_PROPOSALS_COL_TX_HASH,
  1483. DAO_PROPOSALS_COL_CALL_INDEX,
  1484. DAO_PROPOSALS_COL_EXEC_TX_HASH,
  1485. DAO_PROPOSALS_COL_BULLA
  1486. );
  1487. let inverse =
  1488. match self.wallet.create_prepared_statement(&inverse_query, rusqlite::params![key]) {
  1489. Ok(q) => q,
  1490. Err(e) => {
  1491. return Err(Error::DatabaseError(format!(
  1492. "[put_dao_proposal] Creating DAO proposal insert inverse query failed: {e:?}"
  1493. )))
  1494. }
  1495. };
  1496. // Execute the query
  1497. if let Err(e) = self.wallet.exec_sql(&query, params) {
  1498. return Err(Error::DatabaseError(format!(
  1499. "[put_dao_proposal] Proposal insert failed: {e:?}"
  1500. )))
  1501. };
  1502. // Store its inverse
  1503. if let Err(e) = self.wallet.cache_inverse(inverse) {
  1504. return Err(Error::DatabaseError(format!(
  1505. "[put_dao_proposal] Inserting inverse query into cache failed: {e:?}"
  1506. )))
  1507. }
  1508. Ok(())
  1509. }
  1510. /// Unconfirm imported DAO proposals by removing the leaf position, tx hash, and call index.
  1511. pub async fn unconfirm_proposals(&self, proposals: &[ProposalRecord]) -> WalletDbResult<()> {
  1512. for proposal in proposals {
  1513. let query = format!(
  1514. "UPDATE {} SET {} = NULL, {} = NULL, {} = NULL, {} = NULL, {} = NULL, {} = NULL WHERE {} = ?1;",
  1515. *DAO_PROPOSALS_TABLE,
  1516. DAO_PROPOSALS_COL_LEAF_POSITION,
  1517. DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE,
  1518. DAO_PROPOSALS_COL_NULLIFIERS_SMT_SNAPSHOT,
  1519. DAO_PROPOSALS_COL_TX_HASH,
  1520. DAO_PROPOSALS_COL_CALL_INDEX,
  1521. DAO_PROPOSALS_COL_EXEC_TX_HASH,
  1522. DAO_PROPOSALS_COL_BULLA
  1523. );
  1524. self.wallet
  1525. .exec_sql(&query, rusqlite::params![serialize_async(&proposal.bulla()).await])?;
  1526. }
  1527. Ok(())
  1528. }
  1529. /// Import given DAO vote into the wallet,
  1530. /// and store its inverse query into the cache.
  1531. pub async fn put_dao_vote(&self, vote: &VoteRecord) -> WalletDbResult<()> {
  1532. println!("Importing DAO vote into wallet");
  1533. // Create an SQL `INSERT OR REPLACE` query
  1534. let query = format!(
  1535. "INSERT INTO {} ({}, {}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8);",
  1536. *DAO_VOTES_TABLE,
  1537. DAO_VOTES_COL_PROPOSAL_BULLA,
  1538. DAO_VOTES_COL_VOTE_OPTION,
  1539. DAO_VOTES_COL_YES_VOTE_BLIND,
  1540. DAO_VOTES_COL_ALL_VOTE_VALUE,
  1541. DAO_VOTES_COL_ALL_VOTE_BLIND,
  1542. DAO_VOTES_COL_TX_HASH,
  1543. DAO_VOTES_COL_CALL_INDEX,
  1544. DAO_VOTES_COL_NULLIFIERS,
  1545. );
  1546. // Create its params
  1547. let params = rusqlite::params![
  1548. serialize_async(&vote.proposal).await,
  1549. vote.vote_option as u64,
  1550. serialize_async(&vote.yes_vote_blind).await,
  1551. serialize_async(&vote.all_vote_value).await,
  1552. serialize_async(&vote.all_vote_blind).await,
  1553. serialize_async(&vote.tx_hash).await,
  1554. vote.call_index,
  1555. serialize_async(&vote.nullifiers).await,
  1556. ];
  1557. // Create its inverse query.
  1558. // Since we don't know the record ID we will remove it
  1559. // using all its fields.
  1560. let inverse_query = format!(
  1561. "DELETE FROM {} WHERE {} = ?1 AND {} = ?2 AND {} = ?3 AND {} = ?4 AND {} = ?5 AND {} = ?6 AND {} = ?7 AND {} = ?8;",
  1562. *DAO_VOTES_TABLE,
  1563. DAO_VOTES_COL_PROPOSAL_BULLA,
  1564. DAO_VOTES_COL_VOTE_OPTION,
  1565. DAO_VOTES_COL_YES_VOTE_BLIND,
  1566. DAO_VOTES_COL_ALL_VOTE_VALUE,
  1567. DAO_VOTES_COL_ALL_VOTE_BLIND,
  1568. DAO_VOTES_COL_TX_HASH,
  1569. DAO_VOTES_COL_CALL_INDEX,
  1570. DAO_VOTES_COL_NULLIFIERS,
  1571. );
  1572. let inverse = self.wallet.create_prepared_statement(&inverse_query, params)?;
  1573. // Execute the query
  1574. self.wallet.exec_sql(&query, params)?;
  1575. // Store its inverse
  1576. self.wallet.cache_inverse(inverse)?;
  1577. println!("DAO vote added to wallet");
  1578. Ok(())
  1579. }
  1580. /// Reset the DAO Merkle trees in the wallet.
  1581. pub async fn reset_dao_trees(&self) -> WalletDbResult<()> {
  1582. println!("Resetting DAO Merkle trees");
  1583. let tree = MerkleTree::new(1);
  1584. self.put_dao_trees(&tree, &tree).await?;
  1585. println!("Successfully reset DAO Merkle trees");
  1586. Ok(())
  1587. }
  1588. /// Reset confirmed DAOs in the wallet.
  1589. pub async fn reset_daos(&self) -> WalletDbResult<()> {
  1590. println!("Resetting DAO confirmations");
  1591. let query = format!(
  1592. "UPDATE {} SET {} = NULL, {} = NULL, {} = NULL;",
  1593. *DAO_DAOS_TABLE,
  1594. DAO_DAOS_COL_LEAF_POSITION,
  1595. DAO_DAOS_COL_TX_HASH,
  1596. DAO_DAOS_COL_CALL_INDEX,
  1597. );
  1598. self.wallet.exec_sql(&query, &[])?;
  1599. println!("Successfully unconfirmed DAOs");
  1600. Ok(())
  1601. }
  1602. /// Reset all DAO proposals in the wallet.
  1603. pub async fn reset_dao_proposals(&self) -> WalletDbResult<()> {
  1604. println!("Resetting DAO proposals confirmations");
  1605. let proposals = match self.get_proposals().await {
  1606. Ok(p) => p,
  1607. Err(e) => {
  1608. println!("[reset_dao_proposals] DAO proposals retrieval failed: {e:?}");
  1609. return Err(WalletDbError::GenericError);
  1610. }
  1611. };
  1612. self.unconfirm_proposals(&proposals).await?;
  1613. println!("Successfully unconfirmed DAO proposals");
  1614. Ok(())
  1615. }
  1616. /// Reset all DAO votes in the wallet.
  1617. pub fn reset_dao_votes(&self) -> WalletDbResult<()> {
  1618. println!("Resetting DAO votes");
  1619. let query = format!("DELETE FROM {};", *DAO_VOTES_TABLE);
  1620. self.wallet.exec_sql(&query, &[])
  1621. }
  1622. /// Import given DAO params into the wallet with a given name.
  1623. pub async fn import_dao(&self, name: &str, params: &DaoParams) -> Result<()> {
  1624. // First let's check if we've imported this DAO with the given name before.
  1625. if self.get_dao_by_name(name).await.is_ok() {
  1626. return Err(Error::DatabaseError(
  1627. "[import_dao] This DAO has already been imported".to_string(),
  1628. ))
  1629. }
  1630. println!("Importing \"{name}\" DAO into the wallet");
  1631. let query = format!(
  1632. "INSERT INTO {} ({}, {}, {}) VALUES (?1, ?2, ?3);",
  1633. *DAO_DAOS_TABLE, DAO_DAOS_COL_BULLA, DAO_DAOS_COL_NAME, DAO_DAOS_COL_PARAMS,
  1634. );
  1635. if let Err(e) = self.wallet.exec_sql(
  1636. &query,
  1637. rusqlite::params![
  1638. serialize_async(&params.dao.to_bulla()).await,
  1639. name,
  1640. serialize_async(params).await,
  1641. ],
  1642. ) {
  1643. return Err(Error::DatabaseError(format!("[import_dao] DAO insert failed: {e:?}")))
  1644. };
  1645. Ok(())
  1646. }
  1647. /// Update given DAO params into the wallet, if the corresponding DAO exists.
  1648. pub async fn update_dao_keys(&self, params: &DaoParams) -> Result<()> {
  1649. // Grab the params DAO
  1650. let bulla = params.dao.to_bulla();
  1651. let Ok(dao) = self.get_dao_by_bulla(&bulla).await else {
  1652. return Err(Error::DatabaseError(format!("[import_dao] DAO {bulla} was not found")))
  1653. };
  1654. println!("Updating \"{}\" DAO keys into the wallet", dao.name);
  1655. let query = format!(
  1656. "UPDATE {} SET {} = ?1 WHERE {} = ?2;",
  1657. *DAO_DAOS_TABLE, DAO_DAOS_COL_PARAMS, DAO_DAOS_COL_BULLA,
  1658. );
  1659. if let Err(e) = self.wallet.exec_sql(
  1660. &query,
  1661. rusqlite::params![serialize_async(params).await, serialize_async(&bulla).await,],
  1662. ) {
  1663. return Err(Error::DatabaseError(format!("[update_dao_keys] DAO update failed: {e:?}")))
  1664. };
  1665. Ok(())
  1666. }
  1667. /// Fetch a DAO given its bulla.
  1668. pub async fn get_dao_by_bulla(&self, bulla: &DaoBulla) -> Result<DaoRecord> {
  1669. let row = match self.wallet.query_single(
  1670. &DAO_DAOS_TABLE,
  1671. &[],
  1672. convert_named_params! {(DAO_DAOS_COL_BULLA, serialize_async(bulla).await)},
  1673. ) {
  1674. Ok(r) => r,
  1675. Err(e) => {
  1676. return Err(Error::DatabaseError(format!(
  1677. "[get_dao_by_bulla] DAO retrieval failed: {e:?}"
  1678. )))
  1679. }
  1680. };
  1681. self.parse_dao_record(&row).await
  1682. }
  1683. /// Fetch a DAO given its name.
  1684. pub async fn get_dao_by_name(&self, name: &str) -> Result<DaoRecord> {
  1685. let row = match self.wallet.query_single(
  1686. &DAO_DAOS_TABLE,
  1687. &[],
  1688. convert_named_params! {(DAO_DAOS_COL_NAME, name)},
  1689. ) {
  1690. Ok(r) => r,
  1691. Err(e) => {
  1692. return Err(Error::DatabaseError(format!(
  1693. "[get_dao_by_name] DAO retrieval failed: {e:?}"
  1694. )))
  1695. }
  1696. };
  1697. self.parse_dao_record(&row).await
  1698. }
  1699. /// List DAO(s) imported in the wallet. If a name is given, just print the
  1700. /// metadata for that specific one, if found.
  1701. pub async fn dao_list(&self, name: &Option<String>) -> Result<()> {
  1702. if let Some(name) = name {
  1703. let dao = self.get_dao_by_name(name).await?;
  1704. println!("{dao}");
  1705. return Ok(());
  1706. }
  1707. let daos = self.get_daos().await?;
  1708. for (i, dao) in daos.iter().enumerate() {
  1709. println!("{i}. {}", dao.name);
  1710. }
  1711. Ok(())
  1712. }
  1713. /// Fetch known unspent balances from the wallet for the given DAO name.
  1714. pub async fn dao_balance(&self, name: &str) -> Result<HashMap<String, u64>> {
  1715. let dao = self.get_dao_by_name(name).await?;
  1716. let dao_spend_hook =
  1717. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  1718. .to_func_id();
  1719. let mut coins = self.get_coins(false).await?;
  1720. coins.retain(|x| x.0.note.spend_hook == dao_spend_hook);
  1721. coins.retain(|x| x.0.note.user_data == dao.bulla().inner());
  1722. // Fill this map with balances
  1723. let mut balmap: HashMap<String, u64> = HashMap::new();
  1724. for coin in coins {
  1725. let mut value = coin.0.note.value;
  1726. if let Some(prev) = balmap.get(&coin.0.note.token_id.to_string()) {
  1727. value += prev;
  1728. }
  1729. balmap.insert(coin.0.note.token_id.to_string(), value);
  1730. }
  1731. Ok(balmap)
  1732. }
  1733. /// Fetch all known DAO proposalss from the wallet.
  1734. pub async fn get_proposals(&self) -> Result<Vec<ProposalRecord>> {
  1735. let rows = match self.wallet.query_multiple(&DAO_PROPOSALS_TABLE, &[], &[]) {
  1736. Ok(r) => r,
  1737. Err(e) => {
  1738. return Err(Error::DatabaseError(format!(
  1739. "[get_proposals] DAO proposalss retrieval failed: {e:?}"
  1740. )))
  1741. }
  1742. };
  1743. let mut daos = Vec::with_capacity(rows.len());
  1744. for row in rows {
  1745. daos.push(self.parse_dao_proposal(&row).await?);
  1746. }
  1747. Ok(daos)
  1748. }
  1749. /// Fetch a DAO proposal by its bulla.
  1750. pub async fn get_dao_proposal_by_bulla(
  1751. &self,
  1752. bulla: &DaoProposalBulla,
  1753. ) -> Result<ProposalRecord> {
  1754. // Grab the proposal record
  1755. let row = match self.wallet.query_single(
  1756. &DAO_PROPOSALS_TABLE,
  1757. &[],
  1758. convert_named_params! {(DAO_PROPOSALS_COL_BULLA, serialize_async(bulla).await)},
  1759. ) {
  1760. Ok(r) => r,
  1761. Err(e) => {
  1762. return Err(Error::DatabaseError(format!(
  1763. "[get_dao_proposal_by_bulla] DAO proposal retrieval failed: {e:?}"
  1764. )))
  1765. }
  1766. };
  1767. // Parse rest of the record
  1768. self.parse_dao_proposal(&row).await
  1769. }
  1770. // Fetch all known DAO proposal votes from the wallet given a proposal ID.
  1771. pub async fn get_dao_proposal_votes(
  1772. &self,
  1773. proposal: &DaoProposalBulla,
  1774. ) -> Result<Vec<VoteRecord>> {
  1775. let rows = match self.wallet.query_multiple(
  1776. &DAO_VOTES_TABLE,
  1777. &[],
  1778. convert_named_params! {(DAO_VOTES_COL_PROPOSAL_BULLA, serialize_async(proposal).await)},
  1779. ) {
  1780. Ok(r) => r,
  1781. Err(e) => {
  1782. return Err(Error::DatabaseError(format!(
  1783. "[get_dao_proposal_votes] Votes retrieval failed: {e:?}"
  1784. )))
  1785. }
  1786. };
  1787. let mut votes = Vec::with_capacity(rows.len());
  1788. for row in rows {
  1789. let Value::Integer(id) = row[0] else {
  1790. return Err(Error::ParseFailed("[get_dao_proposal_votes] ID parsing failed"))
  1791. };
  1792. let Ok(id) = u64::try_from(id) else {
  1793. return Err(Error::ParseFailed("[get_dao_proposal_votes] ID parsing failed"))
  1794. };
  1795. let Value::Blob(ref proposal_bytes) = row[1] else {
  1796. return Err(Error::ParseFailed(
  1797. "[get_dao_proposal_votes] Proposal bytes bytes parsing failed",
  1798. ))
  1799. };
  1800. let proposal = deserialize_async(proposal_bytes).await?;
  1801. let Value::Integer(vote_option) = row[2] else {
  1802. return Err(Error::ParseFailed(
  1803. "[get_dao_proposal_votes] Vote option parsing failed",
  1804. ))
  1805. };
  1806. let Ok(vote_option) = u32::try_from(vote_option) else {
  1807. return Err(Error::ParseFailed(
  1808. "[get_dao_proposal_votes] Vote option parsing failed",
  1809. ))
  1810. };
  1811. let vote_option = vote_option != 0;
  1812. let Value::Blob(ref yes_vote_blind_bytes) = row[3] else {
  1813. return Err(Error::ParseFailed(
  1814. "[get_dao_proposal_votes] Yes vote blind bytes parsing failed",
  1815. ))
  1816. };
  1817. let yes_vote_blind = deserialize_async(yes_vote_blind_bytes).await?;
  1818. let Value::Blob(ref all_vote_value_bytes) = row[4] else {
  1819. return Err(Error::ParseFailed(
  1820. "[get_dao_proposal_votes] All vote value bytes parsing failed",
  1821. ))
  1822. };
  1823. let all_vote_value = deserialize_async(all_vote_value_bytes).await?;
  1824. let Value::Blob(ref all_vote_blind_bytes) = row[5] else {
  1825. return Err(Error::ParseFailed(
  1826. "[get_dao_proposal_votes] All vote blind bytes parsing failed",
  1827. ))
  1828. };
  1829. let all_vote_blind = deserialize_async(all_vote_blind_bytes).await?;
  1830. let Value::Blob(ref tx_hash_bytes) = row[6] else {
  1831. return Err(Error::ParseFailed(
  1832. "[get_dao_proposal_votes] Transaction hash bytes parsing failed",
  1833. ))
  1834. };
  1835. let tx_hash = deserialize_async(tx_hash_bytes).await?;
  1836. let Value::Integer(call_index) = row[7] else {
  1837. return Err(Error::ParseFailed("[get_dao_proposal_votes] Call index parsing failed"))
  1838. };
  1839. let Ok(call_index) = u8::try_from(call_index) else {
  1840. return Err(Error::ParseFailed("[get_dao_proposal_votes] Call index parsing failed"))
  1841. };
  1842. let Value::Blob(ref nullifiers_bytes) = row[8] else {
  1843. return Err(Error::ParseFailed(
  1844. "[get_dao_proposal_votes] Nullifiers bytes parsing failed",
  1845. ))
  1846. };
  1847. let nullifiers = deserialize_async(nullifiers_bytes).await?;
  1848. let vote = VoteRecord {
  1849. id,
  1850. proposal,
  1851. vote_option,
  1852. yes_vote_blind,
  1853. all_vote_value,
  1854. all_vote_blind,
  1855. tx_hash,
  1856. call_index,
  1857. nullifiers,
  1858. };
  1859. votes.push(vote);
  1860. }
  1861. Ok(votes)
  1862. }
  1863. /// Mint a DAO on-chain.
  1864. pub async fn dao_mint(&self, name: &str) -> Result<Transaction> {
  1865. // Retrieve the dao record
  1866. let dao = self.get_dao_by_name(name).await?;
  1867. // Check its not already minted
  1868. if dao.tx_hash.is_some() {
  1869. return Err(Error::Custom(
  1870. "[dao_mint] This DAO seems to have already been minted on-chain".to_string(),
  1871. ))
  1872. }
  1873. // Check that we have all the keys
  1874. if dao.params.notes_secret_key.is_none() ||
  1875. dao.params.proposer_secret_key.is_none() ||
  1876. dao.params.proposals_secret_key.is_none() ||
  1877. dao.params.votes_secret_key.is_none() ||
  1878. dao.params.exec_secret_key.is_none() ||
  1879. dao.params.early_exec_secret_key.is_none()
  1880. {
  1881. return Err(Error::Custom(
  1882. "[dao_mint] We need all the secrets key to mint the DAO on-chain".to_string(),
  1883. ))
  1884. }
  1885. // Now we need to do a lookup for the zkas proof bincodes, and create
  1886. // the circuit objects and proving keys so we can build the transaction.
  1887. // We also do this through the RPC. First we grab the fee call from money.
  1888. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  1889. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  1890. else {
  1891. return Err(Error::Custom("Fee circuit not found".to_string()))
  1892. };
  1893. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  1894. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  1895. // Creating Fee circuit proving key
  1896. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  1897. // Now we grab the DAO mint
  1898. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  1899. let Some(dao_mint_zkbin) = zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_MINT_NS)
  1900. else {
  1901. return Err(Error::DatabaseError("[dao_mint] DAO Mint circuit not found".to_string()))
  1902. };
  1903. let dao_mint_zkbin = ZkBinary::decode(&dao_mint_zkbin.1)?;
  1904. let dao_mint_circuit = ZkCircuit::new(empty_witnesses(&dao_mint_zkbin)?, &dao_mint_zkbin);
  1905. // Creating DAO Mint circuit proving key
  1906. let dao_mint_pk = ProvingKey::build(dao_mint_zkbin.k, &dao_mint_circuit);
  1907. // Create the DAO mint call
  1908. let notes_secret_key = dao.params.notes_secret_key.unwrap();
  1909. let (params, proofs) = make_mint_call(
  1910. &dao.params.dao,
  1911. &notes_secret_key,
  1912. &dao.params.proposer_secret_key.unwrap(),
  1913. &dao.params.proposals_secret_key.unwrap(),
  1914. &dao.params.votes_secret_key.unwrap(),
  1915. &dao.params.exec_secret_key.unwrap(),
  1916. &dao.params.early_exec_secret_key.unwrap(),
  1917. &dao_mint_zkbin,
  1918. &dao_mint_pk,
  1919. )?;
  1920. let mut data = vec![DaoFunction::Mint as u8];
  1921. params.encode_async(&mut data).await?;
  1922. let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  1923. // Create the TransactionBuilder containing above call
  1924. let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;
  1925. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  1926. // it into the fee-creating function.
  1927. let mut tx = tx_builder.build()?;
  1928. let sigs = tx.create_sigs(&[notes_secret_key])?;
  1929. tx.signatures.push(sigs);
  1930. let tree = self.get_money_tree().await?;
  1931. let (fee_call, fee_proofs, fee_secrets) =
  1932. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  1933. // Append the fee call to the transaction
  1934. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  1935. // Now build the actual transaction and sign it with all necessary keys.
  1936. let mut tx = tx_builder.build()?;
  1937. let sigs = tx.create_sigs(&[notes_secret_key])?;
  1938. tx.signatures.push(sigs);
  1939. let sigs = tx.create_sigs(&fee_secrets)?;
  1940. tx.signatures.push(sigs);
  1941. Ok(tx)
  1942. }
  1943. /// Create a DAO transfer proposal.
  1944. #[allow(clippy::too_many_arguments)]
  1945. pub async fn dao_propose_transfer(
  1946. &self,
  1947. name: &str,
  1948. duration_blockwindows: u64,
  1949. amount: &str,
  1950. token_id: TokenId,
  1951. recipient: PublicKey,
  1952. spend_hook: Option<FuncId>,
  1953. user_data: Option<pallas::Base>,
  1954. ) -> Result<ProposalRecord> {
  1955. // Fetch DAO and check its deployed
  1956. let dao = self.get_dao_by_name(name).await?;
  1957. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  1958. return Err(Error::Custom(
  1959. "[dao_propose_transfer] DAO seems to not have been deployed yet".to_string(),
  1960. ))
  1961. }
  1962. // Check that we have the proposer key
  1963. if dao.params.proposer_secret_key.is_none() {
  1964. return Err(Error::Custom(
  1965. "[dao_propose_transfer] We need the proposer secret key to create proposals for this DAO".to_string(),
  1966. ))
  1967. }
  1968. // Fetch DAO unspent OwnCoins to see what its balance is
  1969. let dao_spend_hook =
  1970. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  1971. .to_func_id();
  1972. let dao_bulla = dao.bulla();
  1973. let dao_owncoins =
  1974. self.get_contract_token_coins(&token_id, &dao_spend_hook, &dao_bulla.inner()).await?;
  1975. if dao_owncoins.is_empty() {
  1976. return Err(Error::Custom(format!(
  1977. "[dao_propose_transfer] Did not find any {token_id} unspent coins owned by this DAO"
  1978. )))
  1979. }
  1980. // Check DAO balance is sufficient
  1981. let amount = decode_base10(amount, BALANCE_BASE10_DECIMALS, false)?;
  1982. if dao_owncoins.iter().map(|x| x.note.value).sum::<u64>() < amount {
  1983. return Err(Error::Custom(format!(
  1984. "[dao_propose_transfer] Not enough DAO balance for token ID: {token_id}",
  1985. )))
  1986. }
  1987. // Generate proposal coin attributes
  1988. let proposal_coinattrs = CoinAttributes {
  1989. public_key: recipient,
  1990. value: amount,
  1991. token_id,
  1992. spend_hook: spend_hook.unwrap_or(FuncId::none()),
  1993. user_data: user_data.unwrap_or(pallas::Base::ZERO),
  1994. blind: Blind::random(&mut OsRng),
  1995. };
  1996. // Convert coin_params to actual coins
  1997. let proposal_coins = vec![proposal_coinattrs.to_coin()];
  1998. let mut proposal_data = vec![];
  1999. proposal_coins.encode_async(&mut proposal_data).await?;
  2000. // Create Auth calls
  2001. let auth_calls = vec![
  2002. DaoAuthCall {
  2003. contract_id: *DAO_CONTRACT_ID,
  2004. function_code: DaoFunction::AuthMoneyTransfer as u8,
  2005. auth_data: proposal_data,
  2006. },
  2007. DaoAuthCall {
  2008. contract_id: *MONEY_CONTRACT_ID,
  2009. function_code: MoneyFunction::TransferV1 as u8,
  2010. auth_data: vec![],
  2011. },
  2012. ];
  2013. // Retrieve next block height and current block time target,
  2014. // to compute their window.
  2015. let next_block_height = self.get_next_block_height().await?;
  2016. let block_target = self.get_block_target().await?;
  2017. let creation_blockwindow = blockwindow(next_block_height, block_target);
  2018. // Create the actual proposal
  2019. let proposal = DaoProposal {
  2020. auth_calls,
  2021. creation_blockwindow,
  2022. duration_blockwindows,
  2023. user_data: user_data.unwrap_or(pallas::Base::ZERO),
  2024. dao_bulla,
  2025. blind: Blind::random(&mut OsRng),
  2026. };
  2027. let proposal_record = ProposalRecord {
  2028. proposal,
  2029. data: Some(serialize_async(&proposal_coinattrs).await),
  2030. leaf_position: None,
  2031. money_snapshot_tree: None,
  2032. nullifiers_smt_snapshot: None,
  2033. tx_hash: None,
  2034. call_index: None,
  2035. exec_tx_hash: None,
  2036. };
  2037. if let Err(e) = self.put_dao_proposal(&proposal_record).await {
  2038. return Err(Error::DatabaseError(format!(
  2039. "[dao_propose_transfer] Put DAO proposal failed: {e:?}"
  2040. )))
  2041. }
  2042. Ok(proposal_record)
  2043. }
  2044. /// Create a DAO generic proposal.
  2045. pub async fn dao_propose_generic(
  2046. &self,
  2047. name: &str,
  2048. duration_blockwindows: u64,
  2049. user_data: Option<pallas::Base>,
  2050. ) -> Result<ProposalRecord> {
  2051. // Fetch DAO and check its deployed
  2052. let dao = self.get_dao_by_name(name).await?;
  2053. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  2054. return Err(Error::Custom(
  2055. "[dao_propose_generic] DAO seems to not have been deployed yet".to_string(),
  2056. ))
  2057. }
  2058. // Check that we have the proposer key
  2059. if dao.params.proposer_secret_key.is_none() {
  2060. return Err(Error::Custom(
  2061. "[dao_propose_generic] We need the proposer secret key to create proposals for this DAO".to_string(),
  2062. ))
  2063. }
  2064. // Retrieve next block height and current block time target,
  2065. // to compute their window.
  2066. let next_block_height = self.get_next_block_height().await?;
  2067. let block_target = self.get_block_target().await?;
  2068. let creation_blockwindow = blockwindow(next_block_height, block_target);
  2069. // Create the actual proposal
  2070. let proposal = DaoProposal {
  2071. auth_calls: vec![],
  2072. creation_blockwindow,
  2073. duration_blockwindows,
  2074. user_data: user_data.unwrap_or(pallas::Base::ZERO),
  2075. dao_bulla: dao.bulla(),
  2076. blind: Blind::random(&mut OsRng),
  2077. };
  2078. let proposal_record = ProposalRecord {
  2079. proposal,
  2080. data: None,
  2081. leaf_position: None,
  2082. money_snapshot_tree: None,
  2083. nullifiers_smt_snapshot: None,
  2084. tx_hash: None,
  2085. call_index: None,
  2086. exec_tx_hash: None,
  2087. };
  2088. if let Err(e) = self.put_dao_proposal(&proposal_record).await {
  2089. return Err(Error::DatabaseError(format!(
  2090. "[dao_propose_generic] Put DAO proposal failed: {e:?}"
  2091. )))
  2092. }
  2093. Ok(proposal_record)
  2094. }
  2095. /// Create a DAO transfer proposal transaction.
  2096. pub async fn dao_transfer_proposal_tx(&self, proposal: &ProposalRecord) -> Result<Transaction> {
  2097. // Check we know the plaintext data
  2098. if proposal.data.is_none() {
  2099. return Err(Error::Custom(
  2100. "[dao_transfer_proposal_tx] Proposal plainext data is empty".to_string(),
  2101. ))
  2102. }
  2103. let proposal_coinattrs: CoinAttributes =
  2104. deserialize_async(proposal.data.as_ref().unwrap()).await?;
  2105. // Fetch DAO and check its deployed
  2106. let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
  2107. return Err(Error::Custom(format!(
  2108. "[dao_transfer_proposal_tx] DAO {} was not found",
  2109. proposal.proposal.dao_bulla
  2110. )))
  2111. };
  2112. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  2113. return Err(Error::Custom(
  2114. "[dao_transfer_proposal_tx] DAO seems to not have been deployed yet".to_string(),
  2115. ))
  2116. }
  2117. // Check that we have the proposer key
  2118. if dao.params.proposer_secret_key.is_none() {
  2119. return Err(Error::Custom(
  2120. "[dao_transfer_proposal_tx] We need the proposer secret key to create proposals for this DAO".to_string(),
  2121. ))
  2122. }
  2123. // Fetch DAO unspent OwnCoins to see what its balance is for the coin
  2124. let dao_spend_hook =
  2125. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  2126. .to_func_id();
  2127. let dao_owncoins = self
  2128. .get_contract_token_coins(
  2129. &proposal_coinattrs.token_id,
  2130. &dao_spend_hook,
  2131. &proposal.proposal.dao_bulla.inner(),
  2132. )
  2133. .await?;
  2134. if dao_owncoins.is_empty() {
  2135. return Err(Error::Custom(format!(
  2136. "[dao_transfer_proposal_tx] Did not find any {} unspent coins owned by this DAO",
  2137. proposal_coinattrs.token_id,
  2138. )))
  2139. }
  2140. // Check DAO balance is sufficient
  2141. if dao_owncoins.iter().map(|x| x.note.value).sum::<u64>() < proposal_coinattrs.value {
  2142. return Err(Error::Custom(format!(
  2143. "[dao_transfer_proposal_tx] Not enough DAO balance for token ID: {}",
  2144. proposal_coinattrs.token_id,
  2145. )))
  2146. }
  2147. // Fetch our own governance OwnCoins to see what our balance is
  2148. let gov_owncoins = self.get_token_coins(&dao.params.dao.gov_token_id).await?;
  2149. if gov_owncoins.is_empty() {
  2150. return Err(Error::Custom(format!(
  2151. "[dao_transfer_proposal_tx] Did not find any governance {} coins in wallet",
  2152. dao.params.dao.gov_token_id
  2153. )))
  2154. }
  2155. // Find which governance coins we can use
  2156. let mut total_value = 0;
  2157. let mut gov_owncoins_to_use = vec![];
  2158. for gov_owncoin in gov_owncoins {
  2159. if total_value >= dao.params.dao.proposer_limit {
  2160. break
  2161. }
  2162. total_value += gov_owncoin.note.value;
  2163. gov_owncoins_to_use.push(gov_owncoin);
  2164. }
  2165. // Check our governance coins balance is sufficient
  2166. if total_value < dao.params.dao.proposer_limit {
  2167. return Err(Error::Custom(format!(
  2168. "[dao_transfer_proposal_tx] Not enough gov token {} balance to propose",
  2169. dao.params.dao.gov_token_id
  2170. )))
  2171. }
  2172. // Now we need to do a lookup for the zkas proof bincodes, and create
  2173. // the circuit objects and proving keys so we can build the transaction.
  2174. // We also do this through the RPC. First we grab the fee call from money.
  2175. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  2176. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  2177. else {
  2178. return Err(Error::Custom(
  2179. "[dao_transfer_proposal_tx] Fee circuit not found".to_string(),
  2180. ))
  2181. };
  2182. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  2183. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  2184. // Creating Fee circuit proving key
  2185. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  2186. // Now we grab the DAO bins
  2187. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  2188. let Some(propose_burn_zkbin) =
  2189. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_PROPOSE_INPUT_NS)
  2190. else {
  2191. return Err(Error::Custom(
  2192. "[dao_transfer_proposal_tx] Propose Burn circuit not found".to_string(),
  2193. ))
  2194. };
  2195. let Some(propose_main_zkbin) =
  2196. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_PROPOSE_MAIN_NS)
  2197. else {
  2198. return Err(Error::Custom(
  2199. "[dao_transfer_proposal_tx] Propose Main circuit not found".to_string(),
  2200. ))
  2201. };
  2202. let propose_burn_zkbin = ZkBinary::decode(&propose_burn_zkbin.1)?;
  2203. let propose_main_zkbin = ZkBinary::decode(&propose_main_zkbin.1)?;
  2204. let propose_burn_circuit =
  2205. ZkCircuit::new(empty_witnesses(&propose_burn_zkbin)?, &propose_burn_zkbin);
  2206. let propose_main_circuit =
  2207. ZkCircuit::new(empty_witnesses(&propose_main_zkbin)?, &propose_main_zkbin);
  2208. // Creating DAO ProposeBurn and ProposeMain circuits proving keys
  2209. let propose_burn_pk = ProvingKey::build(propose_burn_zkbin.k, &propose_burn_circuit);
  2210. let propose_main_pk = ProvingKey::build(propose_main_zkbin.k, &propose_main_circuit);
  2211. // Fetch our money Merkle tree
  2212. let money_merkle_tree = self.get_money_tree().await?;
  2213. // Now we can create the proposal transaction parameters.
  2214. // We first generate the `DaoProposeStakeInput` inputs,
  2215. // using our governance OwnCoins.
  2216. let mut inputs = Vec::with_capacity(gov_owncoins_to_use.len());
  2217. for gov_owncoin in gov_owncoins_to_use {
  2218. let input = DaoProposeStakeInput {
  2219. secret: gov_owncoin.secret,
  2220. note: gov_owncoin.note.clone(),
  2221. leaf_position: gov_owncoin.leaf_position,
  2222. merkle_path: money_merkle_tree.witness(gov_owncoin.leaf_position, 0).unwrap(),
  2223. };
  2224. inputs.push(input);
  2225. }
  2226. // Now create the parameters for the proposal tx
  2227. let signature_secret = SecretKey::random(&mut OsRng);
  2228. // Fetch the daos Merkle tree to compute the DAO Merkle path and root
  2229. let (daos_tree, _) = self.get_dao_trees().await?;
  2230. let (dao_merkle_path, dao_merkle_root) = {
  2231. let root = daos_tree.root(0).unwrap();
  2232. let leaf_pos = dao.leaf_position.unwrap();
  2233. let dao_merkle_path = daos_tree.witness(leaf_pos, 0).unwrap();
  2234. (dao_merkle_path, root)
  2235. };
  2236. // Generate the Money nullifiers Sparse Merkle Tree
  2237. let store = WalletStorage::new(
  2238. &self.wallet,
  2239. &MONEY_SMT_TABLE,
  2240. MONEY_SMT_COL_KEY,
  2241. MONEY_SMT_COL_VALUE,
  2242. );
  2243. let money_null_smt = WalletSmt::new(store, PoseidonFp::new(), &EMPTY_NODES_FP);
  2244. // Create the proposal call
  2245. let call = DaoProposeCall {
  2246. money_null_smt: &money_null_smt,
  2247. inputs,
  2248. proposal: proposal.proposal.clone(),
  2249. dao: dao.params.dao,
  2250. dao_leaf_position: dao.leaf_position.unwrap(),
  2251. dao_merkle_path,
  2252. dao_merkle_root,
  2253. signature_secret,
  2254. };
  2255. let (params, proofs) = call.make(
  2256. &dao.params.proposer_secret_key.unwrap(),
  2257. &propose_burn_zkbin,
  2258. &propose_burn_pk,
  2259. &propose_main_zkbin,
  2260. &propose_main_pk,
  2261. )?;
  2262. // Encode the call
  2263. let mut data = vec![DaoFunction::Propose as u8];
  2264. params.encode_async(&mut data).await?;
  2265. let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  2266. // Create the TransactionBuilder containing above call
  2267. let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;
  2268. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  2269. // it into the fee-creating function.
  2270. let mut tx = tx_builder.build()?;
  2271. let sigs = tx.create_sigs(&[signature_secret])?;
  2272. tx.signatures = vec![sigs];
  2273. let tree = self.get_money_tree().await?;
  2274. let (fee_call, fee_proofs, fee_secrets) =
  2275. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  2276. // Append the fee call to the transaction
  2277. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  2278. // Now build the actual transaction and sign it with all necessary keys.
  2279. let mut tx = tx_builder.build()?;
  2280. let sigs = tx.create_sigs(&[signature_secret])?;
  2281. tx.signatures.push(sigs);
  2282. let sigs = tx.create_sigs(&fee_secrets)?;
  2283. tx.signatures.push(sigs);
  2284. Ok(tx)
  2285. }
  2286. /// Create a DAO generic proposal transaction.
  2287. pub async fn dao_generic_proposal_tx(&self, proposal: &ProposalRecord) -> Result<Transaction> {
  2288. // Fetch DAO and check its deployed
  2289. let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
  2290. return Err(Error::Custom(format!(
  2291. "[dao_generic_proposal_tx] DAO {} was not found",
  2292. proposal.proposal.dao_bulla
  2293. )))
  2294. };
  2295. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  2296. return Err(Error::Custom(
  2297. "[dao_generic_proposal_tx] DAO seems to not have been deployed yet".to_string(),
  2298. ))
  2299. }
  2300. // Check that we have the proposer key
  2301. if dao.params.proposer_secret_key.is_none() {
  2302. return Err(Error::Custom(
  2303. "[dao_generic_proposal_tx] We need the proposer secret key to create proposals for this DAO".to_string(),
  2304. ))
  2305. }
  2306. // Fetch our own governance OwnCoins to see what our balance is
  2307. let gov_owncoins = self.get_token_coins(&dao.params.dao.gov_token_id).await?;
  2308. if gov_owncoins.is_empty() {
  2309. return Err(Error::Custom(format!(
  2310. "[dao_generic_proposal_tx] Did not find any governance {} coins in wallet",
  2311. dao.params.dao.gov_token_id
  2312. )))
  2313. }
  2314. // Find which governance coins we can use
  2315. let mut total_value = 0;
  2316. let mut gov_owncoins_to_use = vec![];
  2317. for gov_owncoin in gov_owncoins {
  2318. if total_value >= dao.params.dao.proposer_limit {
  2319. break
  2320. }
  2321. total_value += gov_owncoin.note.value;
  2322. gov_owncoins_to_use.push(gov_owncoin);
  2323. }
  2324. // Check our governance coins balance is sufficient
  2325. if total_value < dao.params.dao.proposer_limit {
  2326. return Err(Error::Custom(format!(
  2327. "[dao_generic_proposal_tx] Not enough gov token {} balance to propose",
  2328. dao.params.dao.gov_token_id
  2329. )))
  2330. }
  2331. // Now we need to do a lookup for the zkas proof bincodes, and create
  2332. // the circuit objects and proving keys so we can build the transaction.
  2333. // We also do this through the RPC. First we grab the fee call from money.
  2334. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  2335. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  2336. else {
  2337. return Err(Error::Custom("[dao_generic_proposal_tx] Fee circuit not found".to_string()))
  2338. };
  2339. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  2340. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  2341. // Creating Fee circuit proving key
  2342. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  2343. // Now we grab the DAO bins
  2344. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  2345. let Some(propose_burn_zkbin) =
  2346. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_PROPOSE_INPUT_NS)
  2347. else {
  2348. return Err(Error::Custom(
  2349. "[dao_generic_proposal_tx] Propose Burn circuit not found".to_string(),
  2350. ))
  2351. };
  2352. let Some(propose_main_zkbin) =
  2353. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_PROPOSE_MAIN_NS)
  2354. else {
  2355. return Err(Error::Custom(
  2356. "[dao_generic_proposal_tx] Propose Main circuit not found".to_string(),
  2357. ))
  2358. };
  2359. let propose_burn_zkbin = ZkBinary::decode(&propose_burn_zkbin.1)?;
  2360. let propose_main_zkbin = ZkBinary::decode(&propose_main_zkbin.1)?;
  2361. let propose_burn_circuit =
  2362. ZkCircuit::new(empty_witnesses(&propose_burn_zkbin)?, &propose_burn_zkbin);
  2363. let propose_main_circuit =
  2364. ZkCircuit::new(empty_witnesses(&propose_main_zkbin)?, &propose_main_zkbin);
  2365. // Creating DAO ProposeBurn and ProposeMain circuits proving keys
  2366. let propose_burn_pk = ProvingKey::build(propose_burn_zkbin.k, &propose_burn_circuit);
  2367. let propose_main_pk = ProvingKey::build(propose_main_zkbin.k, &propose_main_circuit);
  2368. // Fetch our money Merkle tree
  2369. let money_merkle_tree = self.get_money_tree().await?;
  2370. // Now we can create the proposal transaction parameters.
  2371. // We first generate the `DaoProposeStakeInput` inputs,
  2372. // using our governance OwnCoins.
  2373. let mut inputs = Vec::with_capacity(gov_owncoins_to_use.len());
  2374. for gov_owncoin in gov_owncoins_to_use {
  2375. let input = DaoProposeStakeInput {
  2376. secret: gov_owncoin.secret,
  2377. note: gov_owncoin.note.clone(),
  2378. leaf_position: gov_owncoin.leaf_position,
  2379. merkle_path: money_merkle_tree.witness(gov_owncoin.leaf_position, 0).unwrap(),
  2380. };
  2381. inputs.push(input);
  2382. }
  2383. // Now create the parameters for the proposal tx
  2384. let signature_secret = SecretKey::random(&mut OsRng);
  2385. // Fetch the daos Merkle tree to compute the DAO Merkle path and root
  2386. let (daos_tree, _) = self.get_dao_trees().await?;
  2387. let (dao_merkle_path, dao_merkle_root) = {
  2388. let root = daos_tree.root(0).unwrap();
  2389. let leaf_pos = dao.leaf_position.unwrap();
  2390. let dao_merkle_path = daos_tree.witness(leaf_pos, 0).unwrap();
  2391. (dao_merkle_path, root)
  2392. };
  2393. // Generate the Money nullifiers Sparse Merkle Tree
  2394. let store = WalletStorage::new(
  2395. &self.wallet,
  2396. &MONEY_SMT_TABLE,
  2397. MONEY_SMT_COL_KEY,
  2398. MONEY_SMT_COL_VALUE,
  2399. );
  2400. let money_null_smt = WalletSmt::new(store, PoseidonFp::new(), &EMPTY_NODES_FP);
  2401. // Create the proposal call
  2402. let call = DaoProposeCall {
  2403. money_null_smt: &money_null_smt,
  2404. inputs,
  2405. proposal: proposal.proposal.clone(),
  2406. dao: dao.params.dao,
  2407. dao_leaf_position: dao.leaf_position.unwrap(),
  2408. dao_merkle_path,
  2409. dao_merkle_root,
  2410. signature_secret,
  2411. };
  2412. let (params, proofs) = call.make(
  2413. &dao.params.proposer_secret_key.unwrap(),
  2414. &propose_burn_zkbin,
  2415. &propose_burn_pk,
  2416. &propose_main_zkbin,
  2417. &propose_main_pk,
  2418. )?;
  2419. // Encode the call
  2420. let mut data = vec![DaoFunction::Propose as u8];
  2421. params.encode_async(&mut data).await?;
  2422. let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  2423. // Create the TransactionBuilder containing above call
  2424. let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;
  2425. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  2426. // it into the fee-creating function.
  2427. let mut tx = tx_builder.build()?;
  2428. let sigs = tx.create_sigs(&[signature_secret])?;
  2429. tx.signatures = vec![sigs];
  2430. let tree = self.get_money_tree().await?;
  2431. let (fee_call, fee_proofs, fee_secrets) =
  2432. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  2433. // Append the fee call to the transaction
  2434. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  2435. // Now build the actual transaction and sign it with all necessary keys.
  2436. let mut tx = tx_builder.build()?;
  2437. let sigs = tx.create_sigs(&[signature_secret])?;
  2438. tx.signatures.push(sigs);
  2439. let sigs = tx.create_sigs(&fee_secrets)?;
  2440. tx.signatures.push(sigs);
  2441. Ok(tx)
  2442. }
  2443. /// Vote on a DAO proposal
  2444. pub async fn dao_vote(
  2445. &self,
  2446. proposal_bulla: &DaoProposalBulla,
  2447. vote_option: bool,
  2448. weight: Option<u64>,
  2449. ) -> Result<Transaction> {
  2450. // Feth the proposal and check its deployed
  2451. let Ok(proposal) = self.get_dao_proposal_by_bulla(proposal_bulla).await else {
  2452. return Err(Error::Custom(format!("[dao_vote] Proposal {proposal_bulla} was not found")))
  2453. };
  2454. if proposal.leaf_position.is_none() ||
  2455. proposal.money_snapshot_tree.is_none() ||
  2456. proposal.nullifiers_smt_snapshot.is_none() ||
  2457. proposal.tx_hash.is_none() ||
  2458. proposal.call_index.is_none()
  2459. {
  2460. return Err(Error::Custom(
  2461. "[dao_vote] Proposal seems to not have been deployed yet".to_string(),
  2462. ))
  2463. }
  2464. // Check proposal is not executed
  2465. if let Some(exec_tx_hash) = proposal.exec_tx_hash {
  2466. return Err(Error::Custom(format!(
  2467. "[dao_vote] Proposal was executed on transaction: {exec_tx_hash}"
  2468. )))
  2469. }
  2470. // Fetch DAO and check its deployed
  2471. let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
  2472. return Err(Error::Custom(format!(
  2473. "[dao_vote] DAO {} was not found",
  2474. proposal.proposal.dao_bulla
  2475. )))
  2476. };
  2477. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  2478. return Err(Error::Custom(
  2479. "[dao_vote] DAO seems to not have been deployed yet".to_string(),
  2480. ))
  2481. }
  2482. // Fetch all the proposal votes to check for duplicate nullifiers
  2483. let votes = self.get_dao_proposal_votes(proposal_bulla).await?;
  2484. let mut votes_nullifiers = vec![];
  2485. for vote in votes {
  2486. for nullifier in vote.nullifiers {
  2487. if !votes_nullifiers.contains(&nullifier) {
  2488. votes_nullifiers.push(nullifier);
  2489. }
  2490. }
  2491. }
  2492. // Fetch our own governance OwnCoins to see what our balance is
  2493. let gov_owncoins = self.get_token_coins(&dao.params.dao.gov_token_id).await?;
  2494. if gov_owncoins.is_empty() {
  2495. return Err(Error::Custom(format!(
  2496. "[dao_vote] Did not find any governance {} coins in wallet",
  2497. dao.params.dao.gov_token_id
  2498. )))
  2499. }
  2500. // Find which governance coins we can use
  2501. let gov_owncoins_to_use = match weight {
  2502. Some(_weight) => {
  2503. // TODO: Build a proper coin selection algorithm so that we can use a
  2504. // coins combination that matches the requested weight
  2505. return Err(Error::Custom(
  2506. "[dao_vote] Fractional vote weight not supported yet".to_string(),
  2507. ))
  2508. }
  2509. // If no weight was specified, use them all
  2510. None => gov_owncoins,
  2511. };
  2512. // Now we need to do a lookup for the zkas proof bincodes, and create
  2513. // the circuit objects and proving keys so we can build the transaction.
  2514. // We also do this through the RPC. First we grab the fee call from money.
  2515. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  2516. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  2517. else {
  2518. return Err(Error::Custom("[dao_vote] Fee circuit not found".to_string()))
  2519. };
  2520. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  2521. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  2522. // Creating Fee circuit proving key
  2523. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  2524. // Now we grab the DAO bins
  2525. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  2526. let Some(dao_vote_burn_zkbin) =
  2527. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_VOTE_INPUT_NS)
  2528. else {
  2529. return Err(Error::Custom("[dao_vote] DAO Vote Burn circuit not found".to_string()))
  2530. };
  2531. let Some(dao_vote_main_zkbin) =
  2532. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_VOTE_MAIN_NS)
  2533. else {
  2534. return Err(Error::Custom("[dao_vote] DAO Vote Main circuit not found".to_string()))
  2535. };
  2536. let dao_vote_burn_zkbin = ZkBinary::decode(&dao_vote_burn_zkbin.1)?;
  2537. let dao_vote_main_zkbin = ZkBinary::decode(&dao_vote_main_zkbin.1)?;
  2538. let dao_vote_burn_circuit =
  2539. ZkCircuit::new(empty_witnesses(&dao_vote_burn_zkbin)?, &dao_vote_burn_zkbin);
  2540. let dao_vote_main_circuit =
  2541. ZkCircuit::new(empty_witnesses(&dao_vote_main_zkbin)?, &dao_vote_main_zkbin);
  2542. // Creating DAO VoteBurn and VoteMain circuits proving keys
  2543. let dao_vote_burn_pk = ProvingKey::build(dao_vote_burn_zkbin.k, &dao_vote_burn_circuit);
  2544. let dao_vote_main_pk = ProvingKey::build(dao_vote_main_zkbin.k, &dao_vote_main_circuit);
  2545. // Now create the parameters for the vote tx
  2546. let signature_secret = SecretKey::random(&mut OsRng);
  2547. let mut inputs = Vec::with_capacity(gov_owncoins_to_use.len());
  2548. for gov_owncoin in gov_owncoins_to_use {
  2549. let nullifier = poseidon_hash([gov_owncoin.secret.inner(), gov_owncoin.coin.inner()]);
  2550. let vote_nullifier =
  2551. poseidon_hash([nullifier, gov_owncoin.secret.inner(), proposal_bulla.inner()]);
  2552. if votes_nullifiers.contains(&vote_nullifier.into()) {
  2553. return Err(Error::Custom("[dao_vote] Duplicate input nullifier found".to_string()))
  2554. };
  2555. let input = DaoVoteInput {
  2556. secret: gov_owncoin.secret,
  2557. note: gov_owncoin.note.clone(),
  2558. leaf_position: gov_owncoin.leaf_position,
  2559. merkle_path: proposal
  2560. .money_snapshot_tree
  2561. .as_ref()
  2562. .unwrap()
  2563. .witness(gov_owncoin.leaf_position, 0)
  2564. .unwrap(),
  2565. signature_secret,
  2566. };
  2567. inputs.push(input);
  2568. }
  2569. // Retrieve next block height and current block time target,
  2570. // to compute their window.
  2571. let next_block_height = self.get_next_block_height().await?;
  2572. let block_target = self.get_block_target().await?;
  2573. let current_blockwindow = blockwindow(next_block_height, block_target);
  2574. // Generate the Money nullifiers Sparse Merkle Tree
  2575. let store = MemoryStorageFp { tree: proposal.nullifiers_smt_snapshot.unwrap() };
  2576. let money_null_smt = SmtMemoryFp::new(store, PoseidonFp::new(), &EMPTY_NODES_FP);
  2577. // Create the vote call
  2578. let call = DaoVoteCall {
  2579. money_null_smt: &money_null_smt,
  2580. inputs,
  2581. vote_option,
  2582. proposal: proposal.proposal.clone(),
  2583. dao: dao.params.dao.clone(),
  2584. current_blockwindow,
  2585. };
  2586. let (params, proofs) = call.make(
  2587. &dao_vote_burn_zkbin,
  2588. &dao_vote_burn_pk,
  2589. &dao_vote_main_zkbin,
  2590. &dao_vote_main_pk,
  2591. )?;
  2592. // Encode the call
  2593. let mut data = vec![DaoFunction::Vote as u8];
  2594. params.encode_async(&mut data).await?;
  2595. let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  2596. // Create the TransactionBuilder containing above call
  2597. let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;
  2598. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  2599. // it into the fee-creating function.
  2600. let mut tx = tx_builder.build()?;
  2601. let sigs = tx.create_sigs(&[signature_secret])?;
  2602. tx.signatures = vec![sigs];
  2603. let tree = self.get_money_tree().await?;
  2604. let (fee_call, fee_proofs, fee_secrets) =
  2605. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  2606. // Append the fee call to the transaction
  2607. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  2608. // Now build the actual transaction and sign it with all necessary keys.
  2609. let mut tx = tx_builder.build()?;
  2610. let sigs = tx.create_sigs(&[signature_secret])?;
  2611. tx.signatures.push(sigs);
  2612. let sigs = tx.create_sigs(&fee_secrets)?;
  2613. tx.signatures.push(sigs);
  2614. Ok(tx)
  2615. }
  2616. /// Execute a DAO transfer proposal.
  2617. pub async fn dao_exec_transfer(
  2618. &self,
  2619. proposal: &ProposalRecord,
  2620. early: bool,
  2621. ) -> Result<Transaction> {
  2622. if proposal.leaf_position.is_none() ||
  2623. proposal.money_snapshot_tree.is_none() ||
  2624. proposal.nullifiers_smt_snapshot.is_none() ||
  2625. proposal.tx_hash.is_none() ||
  2626. proposal.call_index.is_none()
  2627. {
  2628. return Err(Error::Custom(
  2629. "[dao_exec_transfer] Proposal seems to not have been deployed yet".to_string(),
  2630. ))
  2631. }
  2632. // Check proposal is not executed
  2633. if let Some(exec_tx_hash) = proposal.exec_tx_hash {
  2634. return Err(Error::Custom(format!(
  2635. "[dao_exec_transfer] Proposal was executed on transaction: {exec_tx_hash}"
  2636. )))
  2637. }
  2638. // Check we know the plaintext data and they are valid
  2639. if proposal.data.is_none() {
  2640. return Err(Error::Custom(
  2641. "[dao_exec_transfer] Proposal plainext data is empty".to_string(),
  2642. ))
  2643. }
  2644. let proposal_coinattrs: CoinAttributes =
  2645. deserialize_async(proposal.data.as_ref().unwrap()).await?;
  2646. // Fetch DAO and check its deployed
  2647. let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
  2648. return Err(Error::Custom(format!(
  2649. "[dao_exec_transfer] DAO {} was not found",
  2650. proposal.proposal.dao_bulla
  2651. )))
  2652. };
  2653. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  2654. return Err(Error::Custom(
  2655. "[dao_exec_transfer] DAO seems to not have been deployed yet".to_string(),
  2656. ))
  2657. }
  2658. // Check that we have the exec key
  2659. if dao.params.exec_secret_key.is_none() {
  2660. return Err(Error::Custom(
  2661. "[dao_exec_transfer] We need the exec secret key to execute proposals for this DAO"
  2662. .to_string(),
  2663. ))
  2664. }
  2665. // If early flag is provided, check that we have the early exec key
  2666. if early && dao.params.early_exec_secret_key.is_none() {
  2667. return Err(Error::Custom(
  2668. "[dao_exec_transfer] We need the early exec secret key to execute proposals early for this DAO"
  2669. .to_string(),
  2670. ))
  2671. }
  2672. // Check proposal is approved
  2673. let votes = self.get_dao_proposal_votes(&proposal.bulla()).await?;
  2674. let mut yes_vote_value = 0;
  2675. let mut yes_vote_blind = Blind::ZERO;
  2676. let mut all_vote_value = 0;
  2677. let mut all_vote_blind = Blind::ZERO;
  2678. for vote in votes {
  2679. if vote.vote_option {
  2680. yes_vote_value += vote.all_vote_value;
  2681. };
  2682. yes_vote_blind += vote.yes_vote_blind;
  2683. all_vote_value += vote.all_vote_value;
  2684. all_vote_blind += vote.all_vote_blind;
  2685. }
  2686. let approval_ratio = (yes_vote_value as f64 * 100.0) / all_vote_value as f64;
  2687. if all_vote_value < dao.params.dao.quorum ||
  2688. approval_ratio <
  2689. (dao.params.dao.approval_ratio_quot / dao.params.dao.approval_ratio_base)
  2690. as f64
  2691. {
  2692. return Err(Error::Custom(
  2693. "[dao_exec_transfer] Proposal is not approved yet".to_string(),
  2694. ))
  2695. };
  2696. // Fetch DAO unspent OwnCoins to see what its balance is for the coin
  2697. let dao_spend_hook =
  2698. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  2699. .to_func_id();
  2700. let dao_owncoins = self
  2701. .get_contract_token_coins(
  2702. &proposal_coinattrs.token_id,
  2703. &dao_spend_hook,
  2704. &proposal.proposal.dao_bulla.inner(),
  2705. )
  2706. .await?;
  2707. if dao_owncoins.is_empty() {
  2708. return Err(Error::Custom(format!(
  2709. "[dao_exec_transfer] Did not find any {} unspent coins owned by this DAO",
  2710. proposal_coinattrs.token_id,
  2711. )))
  2712. }
  2713. // Check DAO balance is sufficient
  2714. if dao_owncoins.iter().map(|x| x.note.value).sum::<u64>() < proposal_coinattrs.value {
  2715. return Err(Error::Custom(format!(
  2716. "[dao_exec_transfer] Not enough DAO balance for token ID: {}",
  2717. proposal_coinattrs.token_id,
  2718. )))
  2719. }
  2720. // Find which DAO coins we can use
  2721. let (spent_coins, change_value) = select_coins(dao_owncoins, proposal_coinattrs.value)?;
  2722. // Now we need to do a lookup for the zkas proof bincodes, and create
  2723. // the circuit objects and proving keys so we can build the transaction.
  2724. // We also do this through the RPC. First we grab the calls from money.
  2725. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  2726. let Some(mint_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_MINT_NS_V1)
  2727. else {
  2728. return Err(Error::Custom("[dao_exec_transfer] Mint circuit not found".to_string()))
  2729. };
  2730. let Some(burn_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_BURN_NS_V1)
  2731. else {
  2732. return Err(Error::Custom("[dao_exec_transfer] Burn circuit not found".to_string()))
  2733. };
  2734. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  2735. else {
  2736. return Err(Error::Custom("[dao_exec_transfer] Fee circuit not found".to_string()))
  2737. };
  2738. let mint_zkbin = ZkBinary::decode(&mint_zkbin.1)?;
  2739. let burn_zkbin = ZkBinary::decode(&burn_zkbin.1)?;
  2740. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  2741. let mint_circuit = ZkCircuit::new(empty_witnesses(&mint_zkbin)?, &mint_zkbin);
  2742. let burn_circuit = ZkCircuit::new(empty_witnesses(&burn_zkbin)?, &burn_zkbin);
  2743. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  2744. // Creating Mint, Burn and Fee circuits proving keys
  2745. let mint_pk = ProvingKey::build(mint_zkbin.k, &mint_circuit);
  2746. let burn_pk = ProvingKey::build(burn_zkbin.k, &burn_circuit);
  2747. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  2748. // Now we grab the DAO bins
  2749. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  2750. let (namespace, early_exec_secret_key) = match early {
  2751. true => (
  2752. DAO_CONTRACT_ZKAS_DAO_EARLY_EXEC_NS,
  2753. Some(dao.params.early_exec_secret_key.unwrap()),
  2754. ),
  2755. false => (DAO_CONTRACT_ZKAS_DAO_EXEC_NS, None),
  2756. };
  2757. let Some(dao_exec_zkbin) = zkas_bins.iter().find(|x| x.0 == namespace) else {
  2758. return Err(Error::Custom(format!(
  2759. "[dao_exec_transfer] DAO {namespace} circuit not found"
  2760. )))
  2761. };
  2762. let Some(dao_auth_transfer_zkbin) =
  2763. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_AUTH_MONEY_TRANSFER_NS)
  2764. else {
  2765. return Err(Error::Custom(
  2766. "[dao_exec_transfer] DAO AuthTransfer circuit not found".to_string(),
  2767. ))
  2768. };
  2769. let Some(dao_auth_transfer_enc_coin_zkbin) =
  2770. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_AUTH_MONEY_TRANSFER_ENC_COIN_NS)
  2771. else {
  2772. return Err(Error::Custom(
  2773. "[dao_exec_transfer] DAO AuthTransferEncCoin circuit not found".to_string(),
  2774. ))
  2775. };
  2776. let dao_exec_zkbin = ZkBinary::decode(&dao_exec_zkbin.1)?;
  2777. let dao_auth_transfer_zkbin = ZkBinary::decode(&dao_auth_transfer_zkbin.1)?;
  2778. let dao_auth_transfer_enc_coin_zkbin =
  2779. ZkBinary::decode(&dao_auth_transfer_enc_coin_zkbin.1)?;
  2780. let dao_exec_circuit = ZkCircuit::new(empty_witnesses(&dao_exec_zkbin)?, &dao_exec_zkbin);
  2781. let dao_auth_transfer_circuit =
  2782. ZkCircuit::new(empty_witnesses(&dao_auth_transfer_zkbin)?, &dao_auth_transfer_zkbin);
  2783. let dao_auth_transfer_enc_coin_circuit = ZkCircuit::new(
  2784. empty_witnesses(&dao_auth_transfer_enc_coin_zkbin)?,
  2785. &dao_auth_transfer_enc_coin_zkbin,
  2786. );
  2787. // Creating DAO Exec, AuthTransfer and AuthTransferEncCoin circuits proving keys
  2788. let dao_exec_pk = ProvingKey::build(dao_exec_zkbin.k, &dao_exec_circuit);
  2789. let dao_auth_transfer_pk =
  2790. ProvingKey::build(dao_auth_transfer_zkbin.k, &dao_auth_transfer_circuit);
  2791. let dao_auth_transfer_enc_coin_pk = ProvingKey::build(
  2792. dao_auth_transfer_enc_coin_zkbin.k,
  2793. &dao_auth_transfer_enc_coin_circuit,
  2794. );
  2795. // Fetch our money Merkle tree
  2796. let tree = self.get_money_tree().await?;
  2797. // Retrieve next block height and current block time target,
  2798. // to compute their window.
  2799. let next_block_height = self.get_next_block_height().await?;
  2800. let block_target = self.get_block_target().await?;
  2801. let current_blockwindow = blockwindow(next_block_height, block_target);
  2802. // Now we can create the transfer call parameters
  2803. let input_user_data_blind = Blind::random(&mut OsRng);
  2804. let mut inputs = vec![];
  2805. for coin in &spent_coins {
  2806. inputs.push(TransferCallInput {
  2807. coin: coin.clone(),
  2808. merkle_path: tree.witness(coin.leaf_position, 0).unwrap(),
  2809. user_data_blind: input_user_data_blind,
  2810. });
  2811. }
  2812. let mut outputs = vec![];
  2813. outputs.push(proposal_coinattrs.clone());
  2814. let dao_coin_attrs = CoinAttributes {
  2815. public_key: dao.params.dao.notes_public_key,
  2816. value: change_value,
  2817. token_id: proposal_coinattrs.token_id,
  2818. spend_hook: dao_spend_hook,
  2819. user_data: proposal.proposal.dao_bulla.inner(),
  2820. blind: Blind::random(&mut OsRng),
  2821. };
  2822. outputs.push(dao_coin_attrs.clone());
  2823. // Create the transfer call
  2824. let transfer_builder = TransferCallBuilder {
  2825. clear_inputs: vec![],
  2826. inputs,
  2827. outputs,
  2828. mint_zkbin: mint_zkbin.clone(),
  2829. mint_pk: mint_pk.clone(),
  2830. burn_zkbin: burn_zkbin.clone(),
  2831. burn_pk: burn_pk.clone(),
  2832. };
  2833. let (transfer_params, transfer_secrets) = transfer_builder.build()?;
  2834. // Encode the call
  2835. let mut data = vec![MoneyFunction::TransferV1 as u8];
  2836. transfer_params.encode_async(&mut data).await?;
  2837. let transfer_call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  2838. // Create the exec call
  2839. let exec_signature_secret = SecretKey::random(&mut OsRng);
  2840. let exec_builder = DaoExecCall {
  2841. proposal: proposal.proposal.clone(),
  2842. dao: dao.params.dao.clone(),
  2843. yes_vote_value,
  2844. all_vote_value,
  2845. yes_vote_blind,
  2846. all_vote_blind,
  2847. signature_secret: exec_signature_secret,
  2848. current_blockwindow,
  2849. };
  2850. let (exec_params, exec_proofs) = exec_builder.make(
  2851. &dao.params.exec_secret_key.unwrap(),
  2852. &early_exec_secret_key,
  2853. &dao_exec_zkbin,
  2854. &dao_exec_pk,
  2855. )?;
  2856. // Encode the call
  2857. let mut data = vec![DaoFunction::Exec as u8];
  2858. exec_params.encode_async(&mut data).await?;
  2859. let exec_call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  2860. // Now we can create the auth call
  2861. // Auth module
  2862. let auth_transfer_builder = DaoAuthMoneyTransferCall {
  2863. proposal: proposal.proposal.clone(),
  2864. proposal_coinattrs: vec![proposal_coinattrs],
  2865. dao: dao.params.dao.clone(),
  2866. input_user_data_blind,
  2867. dao_coin_attrs,
  2868. };
  2869. let (auth_transfer_params, auth_transfer_proofs) = auth_transfer_builder.make(
  2870. &dao_auth_transfer_zkbin,
  2871. &dao_auth_transfer_pk,
  2872. &dao_auth_transfer_enc_coin_zkbin,
  2873. &dao_auth_transfer_enc_coin_pk,
  2874. )?;
  2875. // Encode the call
  2876. let mut data = vec![DaoFunction::AuthMoneyTransfer as u8];
  2877. auth_transfer_params.encode_async(&mut data).await?;
  2878. let auth_transfer_call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  2879. // Create the TransactionBuilder containing above calls
  2880. let mut tx_builder = TransactionBuilder::new(
  2881. ContractCallLeaf { call: exec_call, proofs: exec_proofs },
  2882. vec![
  2883. DarkTree::new(
  2884. ContractCallLeaf { call: auth_transfer_call, proofs: auth_transfer_proofs },
  2885. vec![],
  2886. None,
  2887. None,
  2888. ),
  2889. DarkTree::new(
  2890. ContractCallLeaf { call: transfer_call, proofs: transfer_secrets.proofs },
  2891. vec![],
  2892. None,
  2893. None,
  2894. ),
  2895. ],
  2896. )?;
  2897. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  2898. // it into the fee-creating function.
  2899. let mut tx = tx_builder.build()?;
  2900. let auth_transfer_sigs = tx.create_sigs(&[])?;
  2901. let transfer_sigs = tx.create_sigs(&transfer_secrets.signature_secrets)?;
  2902. let exec_sigs = tx.create_sigs(&[exec_signature_secret])?;
  2903. tx.signatures = vec![auth_transfer_sigs, transfer_sigs, exec_sigs];
  2904. let (fee_call, fee_proofs, fee_secrets) =
  2905. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  2906. // Append the fee call to the transaction
  2907. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  2908. // Now build the actual transaction and sign it with all necessary keys.
  2909. let mut tx = tx_builder.build()?;
  2910. let sigs = tx.create_sigs(&[])?;
  2911. tx.signatures.push(sigs);
  2912. let sigs = tx.create_sigs(&transfer_secrets.signature_secrets)?;
  2913. tx.signatures.push(sigs);
  2914. let sigs = tx.create_sigs(&[exec_signature_secret])?;
  2915. tx.signatures.push(sigs);
  2916. let sigs = tx.create_sigs(&fee_secrets)?;
  2917. tx.signatures.push(sigs);
  2918. Ok(tx)
  2919. }
  2920. /// Execute a DAO generic proposal.
  2921. pub async fn dao_exec_generic(
  2922. &self,
  2923. proposal: &ProposalRecord,
  2924. early: bool,
  2925. ) -> Result<Transaction> {
  2926. if proposal.leaf_position.is_none() ||
  2927. proposal.money_snapshot_tree.is_none() ||
  2928. proposal.nullifiers_smt_snapshot.is_none() ||
  2929. proposal.tx_hash.is_none() ||
  2930. proposal.call_index.is_none()
  2931. {
  2932. return Err(Error::Custom(
  2933. "[dao_exec_generic] Proposal seems to not have been deployed yet".to_string(),
  2934. ))
  2935. }
  2936. // Check proposal is not executed
  2937. if let Some(exec_tx_hash) = proposal.exec_tx_hash {
  2938. return Err(Error::Custom(format!(
  2939. "[dao_exec_generic] Proposal was executed on transaction: {exec_tx_hash}"
  2940. )))
  2941. }
  2942. // Fetch DAO and check its deployed
  2943. let Ok(dao) = self.get_dao_by_bulla(&proposal.proposal.dao_bulla).await else {
  2944. return Err(Error::Custom(format!(
  2945. "[dao_exec_generic] DAO {} was not found",
  2946. proposal.proposal.dao_bulla
  2947. )))
  2948. };
  2949. if dao.leaf_position.is_none() || dao.tx_hash.is_none() || dao.call_index.is_none() {
  2950. return Err(Error::Custom(
  2951. "[dao_exec_generic] DAO seems to not have been deployed yet".to_string(),
  2952. ))
  2953. }
  2954. // Check that we have the exec key
  2955. if dao.params.exec_secret_key.is_none() {
  2956. return Err(Error::Custom(
  2957. "[dao_exec_generic] We need the exec secret key to execute proposals for this DAO"
  2958. .to_string(),
  2959. ))
  2960. }
  2961. // If early flag is provided, check that we have the early exec key
  2962. if early && dao.params.early_exec_secret_key.is_none() {
  2963. return Err(Error::Custom(
  2964. "[dao_exec_generic] We need the early exec secret key to execute proposals early for this DAO"
  2965. .to_string(),
  2966. ))
  2967. }
  2968. // Check proposal is approved
  2969. let votes = self.get_dao_proposal_votes(&proposal.bulla()).await?;
  2970. let mut yes_vote_value = 0;
  2971. let mut yes_vote_blind = Blind::ZERO;
  2972. let mut all_vote_value = 0;
  2973. let mut all_vote_blind = Blind::ZERO;
  2974. for vote in votes {
  2975. if vote.vote_option {
  2976. yes_vote_value += vote.all_vote_value;
  2977. };
  2978. yes_vote_blind += vote.yes_vote_blind;
  2979. all_vote_value += vote.all_vote_value;
  2980. all_vote_blind += vote.all_vote_blind;
  2981. }
  2982. let approval_ratio = (yes_vote_value as f64 * 100.0) / all_vote_value as f64;
  2983. if all_vote_value < dao.params.dao.quorum ||
  2984. approval_ratio <
  2985. (dao.params.dao.approval_ratio_quot / dao.params.dao.approval_ratio_base)
  2986. as f64
  2987. {
  2988. return Err(Error::Custom("[dao_exec_generic] Proposal is not approved yet".to_string()))
  2989. };
  2990. // Now we need to do a lookup for the zkas proof bincodes, and create
  2991. // the circuit objects and proving keys so we can build the transaction.
  2992. // We also do this through the RPC. First we grab the calls from money.
  2993. let zkas_bins = self.lookup_zkas(&MONEY_CONTRACT_ID).await?;
  2994. let Some(fee_zkbin) = zkas_bins.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_FEE_NS_V1)
  2995. else {
  2996. return Err(Error::Custom("[dao_exec_generic] Fee circuit not found".to_string()))
  2997. };
  2998. let fee_zkbin = ZkBinary::decode(&fee_zkbin.1)?;
  2999. let fee_circuit = ZkCircuit::new(empty_witnesses(&fee_zkbin)?, &fee_zkbin);
  3000. let fee_pk = ProvingKey::build(fee_zkbin.k, &fee_circuit);
  3001. // Now we grab the DAO bins
  3002. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  3003. let (namespace, early_exec_secret_key) = match early {
  3004. true => (
  3005. DAO_CONTRACT_ZKAS_DAO_EARLY_EXEC_NS,
  3006. Some(dao.params.early_exec_secret_key.unwrap()),
  3007. ),
  3008. false => (DAO_CONTRACT_ZKAS_DAO_EXEC_NS, None),
  3009. };
  3010. let Some(dao_exec_zkbin) = zkas_bins.iter().find(|x| x.0 == namespace) else {
  3011. return Err(Error::Custom(format!(
  3012. "[dao_exec_generic] DAO {namespace} circuit not found"
  3013. )))
  3014. };
  3015. let dao_exec_zkbin = ZkBinary::decode(&dao_exec_zkbin.1)?;
  3016. let dao_exec_circuit = ZkCircuit::new(empty_witnesses(&dao_exec_zkbin)?, &dao_exec_zkbin);
  3017. let dao_exec_pk = ProvingKey::build(dao_exec_zkbin.k, &dao_exec_circuit);
  3018. // Fetch our money Merkle tree
  3019. let tree = self.get_money_tree().await?;
  3020. // Retrieve next block height and current block time target,
  3021. // to compute their window.
  3022. let next_block_height = self.get_next_block_height().await?;
  3023. let block_target = self.get_block_target().await?;
  3024. let current_blockwindow = blockwindow(next_block_height, block_target);
  3025. // Create the exec call
  3026. let exec_signature_secret = SecretKey::random(&mut OsRng);
  3027. let exec_builder = DaoExecCall {
  3028. proposal: proposal.proposal.clone(),
  3029. dao: dao.params.dao.clone(),
  3030. yes_vote_value,
  3031. all_vote_value,
  3032. yes_vote_blind,
  3033. all_vote_blind,
  3034. signature_secret: exec_signature_secret,
  3035. current_blockwindow,
  3036. };
  3037. let (exec_params, exec_proofs) = exec_builder.make(
  3038. &dao.params.exec_secret_key.unwrap(),
  3039. &early_exec_secret_key,
  3040. &dao_exec_zkbin,
  3041. &dao_exec_pk,
  3042. )?;
  3043. // Encode the call
  3044. let mut data = vec![DaoFunction::Exec as u8];
  3045. exec_params.encode_async(&mut data).await?;
  3046. let exec_call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  3047. // Create the TransactionBuilder containing above calls
  3048. let mut tx_builder = TransactionBuilder::new(
  3049. ContractCallLeaf { call: exec_call, proofs: exec_proofs },
  3050. vec![],
  3051. )?;
  3052. // We first have to execute the fee-less tx to gather its used gas, and then we feed
  3053. // it into the fee-creating function.
  3054. let mut tx = tx_builder.build()?;
  3055. let exec_sigs = tx.create_sigs(&[exec_signature_secret])?;
  3056. tx.signatures = vec![exec_sigs];
  3057. let (fee_call, fee_proofs, fee_secrets) =
  3058. self.append_fee_call(&tx, &tree, &fee_pk, &fee_zkbin, None).await?;
  3059. // Append the fee call to the transaction
  3060. tx_builder.append(ContractCallLeaf { call: fee_call, proofs: fee_proofs }, vec![])?;
  3061. // Now build the actual transaction and sign it with all necessary keys.
  3062. let mut tx = tx_builder.build()?;
  3063. let sigs = tx.create_sigs(&[exec_signature_secret])?;
  3064. tx.signatures.push(sigs);
  3065. let sigs = tx.create_sigs(&fee_secrets)?;
  3066. tx.signatures.push(sigs);
  3067. Ok(tx)
  3068. }
  3069. }