dao.rs 138 KB

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