dao.rs 139 KB

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