| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266 |
- /* This file is part of DarkFi (https://dark.fi)
- *
- * Copyright (C) 2020-2025 Dyne.org foundation
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
- */
- use std::{
- fs::{File, OpenOptions},
- io::{stdin, BufRead, BufReader, ErrorKind, Read, Seek, SeekFrom, Write},
- str::FromStr,
- };
- use futures::{select, FutureExt};
- use libc::{fcntl, F_GETFL, F_SETFL, O_NONBLOCK};
- use linenoise_rs::{
- linenoise_history_add, linenoise_history_load, linenoise_history_save,
- linenoise_set_completion_callback, linenoise_set_hints_callback, LinenoiseState,
- };
- use prettytable::{format, row, Table};
- use rand::rngs::OsRng;
- use smol::channel::{Receiver, Sender};
- use url::Url;
- use darkfi::{
- cli_desc,
- system::{msleep, ExecutorPtr, StoppableTask, StoppableTaskPtr},
- util::{
- encoding::base64,
- parse::{decode_base10, encode_base10},
- path::expand_path,
- },
- zk::halo2::Field,
- Error,
- };
- use darkfi_dao_contract::{blockwindow, model::DaoProposalBulla, DaoFunction};
- use darkfi_money_contract::model::{Coin, CoinAttributes, TokenId};
- use darkfi_sdk::{
- crypto::{
- keypair::{Address, StandardAddress},
- note::AeadEncryptedNote,
- BaseBlind, ContractId, FuncId, FuncRef, Keypair, SecretKey, DAO_CONTRACT_ID,
- },
- pasta::{group::ff::PrimeField, pallas},
- tx::TransactionHash,
- };
- use darkfi_serial::{deserialize_async, serialize_async};
- use crate::{
- cli_util::{
- append_or_print, display_mining_config, generate_completions, kaching,
- parse_mining_config_from_input, parse_token_pair, parse_tx_from_input, parse_value_pair,
- print_output,
- },
- common::*,
- dao::{DaoParams, ProposalRecord},
- money::BALANCE_BASE10_DECIMALS,
- rpc::subscribe_blocks,
- swap::PartialSwapData,
- DrkPtr,
- };
- // TODO:
- // 1. Create a transactions cache in the wallet db, so you can use it to handle them.
- /// Auxiliary function to print the help message.
- fn help(output: &mut Vec<String>) {
- output.push(String::from(cli_desc!()));
- output.push(String::from("Commands:"));
- output.push(String::from("\thelp: Prints the help message"));
- output.push(String::from("\tkaching: Fun"));
- output.push(String::from("\tping: Send a ping request to the darkfid RPC endpoint"));
- output.push(String::from(
- "\tcompletions: Generate a SHELL completion script and print to stdout",
- ));
- output.push(String::from("\twallet: Wallet operations"));
- output.push(String::from(
- "\tspend: Read a transaction from stdin and mark its input coins as spent",
- ));
- output.push(String::from("\tunspend: Unspend a coin"));
- output.push(String::from("\ttransfer: Create a payment transaction"));
- output.push(String::from("\totc: OTC atomic swap"));
- output.push(String::from("\tdao: DAO functionalities"));
- output
- .push(String::from("\tattach-fee: Attach the fee call to a transaction given from stdin"));
- output.push(String::from("\tinspect: Inspect a transaction from stdin"));
- output.push(String::from("\tbroadcast: Read a transaction from stdin and broadcast it"));
- output.push(String::from(
- "\tsubscribe: Perform a scan and then subscribe to darkfid to listen for incoming blocks",
- ));
- output.push(String::from("\tunsubscribe: Stops the background subscription, if its active"));
- output.push(String::from("\tsnooze: Disables the background subscription messages printing"));
- output.push(String::from("\tunsnooze: Enables the background subscription messages printing"));
- output.push(String::from("\tscan: Scan the blockchain and parse relevant transactions"));
- output.push(String::from("\texplorer: Explorer related subcommands"));
- output.push(String::from("\talias: Token alias"));
- output.push(String::from("\ttoken: Token functionalities"));
- output.push(String::from("\tcontract: Contract functionalities"));
- }
- /// Auxiliary function to define the interactive shell completions.
- fn completion(buffer: &str, lc: &mut Vec<String>) {
- // Split commands so we always process the last one
- let commands: Vec<&str> = buffer.split('|').collect();
- // Grab the prefix
- let prefix = if commands.len() > 1 {
- commands[..commands.len() - 1].join("|") + "| "
- } else {
- String::from("")
- };
- let last = commands.last().unwrap().trim_start();
- // First we define the specific commands prefixes
- if last.starts_with("h") {
- lc.push(prefix + "help");
- return
- }
- if last.starts_with("k") {
- lc.push(prefix + "kaching");
- return
- }
- if last.starts_with("p") {
- lc.push(prefix + "ping");
- return
- }
- if last.starts_with("com") {
- lc.push(prefix + "completions");
- return
- }
- if last.starts_with("w") {
- lc.push(prefix.clone() + "wallet");
- lc.push(prefix.clone() + "wallet initialize");
- lc.push(prefix.clone() + "wallet keygen");
- lc.push(prefix.clone() + "wallet balance");
- lc.push(prefix.clone() + "wallet address");
- lc.push(prefix.clone() + "wallet addresses");
- lc.push(prefix.clone() + "wallet default-address");
- lc.push(prefix.clone() + "wallet secrets");
- lc.push(prefix.clone() + "wallet import-secrets");
- lc.push(prefix.clone() + "wallet tree");
- lc.push(prefix.clone() + "wallet coins");
- lc.push(prefix + "wallet mining-config");
- return
- }
- if last.starts_with("sp") {
- lc.push(prefix + "spend");
- return
- }
- if last.starts_with("unsp") {
- lc.push(prefix + "unspend");
- return
- }
- if last.starts_with("tr") {
- lc.push(prefix + "transfer");
- return
- }
- if last.starts_with("o") {
- lc.push(prefix.clone() + "otc");
- lc.push(prefix.clone() + "otc init");
- lc.push(prefix.clone() + "otc join");
- lc.push(prefix.clone() + "otc inspect");
- lc.push(prefix + "otc sign");
- return
- }
- if last.starts_with("d") {
- lc.push(prefix.clone() + "dao");
- lc.push(prefix.clone() + "dao create");
- lc.push(prefix.clone() + "dao view");
- lc.push(prefix.clone() + "dao import");
- lc.push(prefix.clone() + "dao list");
- lc.push(prefix.clone() + "dao balance");
- lc.push(prefix.clone() + "dao mint");
- lc.push(prefix.clone() + "dao propose-transfer");
- lc.push(prefix.clone() + "dao propose-generic");
- lc.push(prefix.clone() + "dao proposals");
- lc.push(prefix.clone() + "dao proposal");
- lc.push(prefix.clone() + "dao proposal-import");
- lc.push(prefix.clone() + "dao vote");
- lc.push(prefix.clone() + "dao exec");
- lc.push(prefix.clone() + "dao spend-hook");
- lc.push(prefix + "dao mining-config");
- return
- }
- if last.starts_with("at") {
- lc.push(prefix + "attach-fee");
- return
- }
- if last.starts_with("i") {
- lc.push(prefix + "inspect");
- return
- }
- if last.starts_with("b") {
- lc.push(prefix + "broadcast");
- return
- }
- if last.starts_with("su") {
- lc.push(prefix + "subscribe");
- return
- }
- if last.starts_with("unsu") {
- lc.push(prefix + "unsubscribe");
- return
- }
- if last.starts_with("sn") {
- lc.push(prefix + "snooze");
- return
- }
- if last.starts_with("unsn") {
- lc.push(prefix + "unsnooze");
- return
- }
- if last.starts_with("sc") {
- lc.push(prefix.clone() + "scan");
- lc.push(prefix + "scan --reset");
- return
- }
- if last.starts_with("e") {
- lc.push(prefix.clone() + "explorer");
- lc.push(prefix.clone() + "explorer fetch-tx");
- lc.push(prefix.clone() + "explorer simulate-tx");
- lc.push(prefix.clone() + "explorer txs-history");
- lc.push(prefix.clone() + "explorer clear-reverted");
- lc.push(prefix.clone() + "explorer scanned-blocks");
- lc.push(prefix + "explorer mining-config");
- return
- }
- if last.starts_with("al") {
- lc.push(prefix.clone() + "alias");
- lc.push(prefix.clone() + "alias add");
- lc.push(prefix.clone() + "alias show");
- lc.push(prefix + "alias remove");
- return
- }
- if last.starts_with("to") {
- lc.push(prefix.clone() + "token");
- lc.push(prefix.clone() + "token import");
- lc.push(prefix.clone() + "token generate-mint");
- lc.push(prefix.clone() + "token list");
- lc.push(prefix.clone() + "token mint");
- lc.push(prefix + "token freeze");
- return
- }
- if last.starts_with("con") {
- lc.push(prefix.clone() + "contract");
- lc.push(prefix.clone() + "contract generate-deploy");
- lc.push(prefix.clone() + "contract list");
- lc.push(prefix.clone() + "contract export-data");
- lc.push(prefix.clone() + "contract deploy");
- lc.push(prefix + "contract lock");
- return
- }
- // Now the catch alls
- if last.starts_with("a") {
- lc.push(prefix.clone() + "attach-fee");
- lc.push(prefix.clone() + "alias");
- lc.push(prefix.clone() + "alias add");
- lc.push(prefix.clone() + "alias show");
- lc.push(prefix + "alias remove");
- return
- }
- if last.starts_with("c") {
- lc.push(prefix.clone() + "completions");
- lc.push(prefix.clone() + "contract");
- lc.push(prefix.clone() + "contract generate-deploy");
- lc.push(prefix.clone() + "contract list");
- lc.push(prefix.clone() + "contract export-data");
- lc.push(prefix.clone() + "contract deploy");
- lc.push(prefix + "contract lock");
- return
- }
- if last.starts_with("s") {
- lc.push(prefix.clone() + "spend");
- lc.push(prefix.clone() + "subscribe");
- lc.push(prefix.clone() + "snooze");
- lc.push(prefix.clone() + "scan");
- lc.push(prefix + "scan --reset");
- return
- }
- if last.starts_with("t") {
- lc.push(prefix.clone() + "transfer");
- lc.push(prefix.clone() + "token");
- lc.push(prefix.clone() + "token import");
- lc.push(prefix.clone() + "token generate-mint");
- lc.push(prefix.clone() + "token list");
- lc.push(prefix.clone() + "token mint");
- lc.push(prefix + "token freeze");
- return
- }
- if last.starts_with("u") {
- lc.push(prefix.clone() + "unspend");
- lc.push(prefix.clone() + "unsubscribe");
- lc.push(prefix + "unsnooze");
- }
- }
- /// Auxiliary function to define the interactive shell hints.
- fn hints(buffer: &str) -> Option<(String, i32, bool)> {
- // Split commands so we always process the last one
- let commands: Vec<&str> = buffer.split('|').collect();
- let last = commands.last().unwrap().trim_start();
- let color = 35; // magenta
- let bold = false;
- match last {
- "completions " => Some(("<shell>".to_string(), color, bold)),
- "wallet " => Some(("(initialize|keygen|balance|address|addresses|default-address|secrets|import-secrets|tree|coins|mining-config)".to_string(), color, bold)),
- "wallet default-address " => Some(("<index>".to_string(), color, bold)),
- "wallet mining-config " => Some(("<index> [spend_hook] [user_data]".to_string(), color, bold)),
- "unspend " => Some(("<coin>".to_string(), color, bold)),
- "transfer " => Some(("[--half-split] <amount> <token> <recipient> [spend_hook] [user_data]".to_string(), color, bold)),
- "otc " => Some(("(init|join|inspect|sign)".to_string(), color, bold)),
- "otc init " => Some(("<value_pair> <token_pair>".to_string(), color, bold)),
- "dao " => Some(("(create|view|import|list|balance|mint|propose-transfer|propose-generic|proposals|proposal|proposal-import|vote|exec|spend-hook|mining-config)".to_string(), color, bold)),
- "dao create " => Some(("<proposer-limit> <quorum> <early-exec-quorum> <approval-ratio> <gov-token-id>".to_string(), color, bold)),
- "dao import " => Some(("<name>".to_string(), color, bold)),
- "dao list " => Some(("[name]".to_string(), color, bold)),
- "dao balance " => Some(("<name>".to_string(), color, bold)),
- "dao mint " => Some(("<name>".to_string(), color, bold)),
- "dao propose-transfer " => Some(("<name> <duration> <amount> <token> <recipient> [spend-hook] [user-data]".to_string(), color, bold)),
- "dao propose-generic" => Some(("<name> <duration> [user-data]".to_string(), color, bold)),
- "dao proposals " => Some(("<name>".to_string(), color, bold)),
- "dao proposal " => Some(("[--(export|mint-proposal)] <bulla>".to_string(), color, bold)),
- "dao vote " => Some(("<bulla> <vote> [vote-weight]".to_string(), color, bold)),
- "dao exec " => Some(("[--early] <bulla>".to_string(), color, bold)),
- "dao mining-config " => Some(("<name>".to_string(), color, bold)),
- "scan " => Some(("[--reset]".to_string(), color, bold)),
- "scan --reset " => Some(("<height>".to_string(), color, bold)),
- "explorer " => Some(("(fetch-tx|simulate-tx|txs-history|clear-reverted|scanned-blocks|mining-config)".to_string(), color, bold)),
- "explorer fetch-tx " => Some(("[--encode] <tx-hash>".to_string(), color, bold)),
- "explorer txs-history " => Some(("[--encode] [tx-hash]".to_string(), color, bold)),
- "explorer scanned-blocks " => Some(("[height]".to_string(), color, bold)),
- "alias " => Some(("(add|show|remove)".to_string(), color, bold)),
- "alias add " => Some(("<alias> <token>".to_string(), color, bold)),
- "alias show " => Some(("[-a, --alias <alias>] [-t, --token <token>]".to_string(), color, bold)),
- "alias remove " => Some(("<alias>".to_string(), color, bold)),
- "token " => Some(("(import|generate-mint|list|mint|freeze)".to_string(), color, bold)),
- "token import " => Some(("<secret-key> <token-blind>".to_string(), color, bold)),
- "token mint " => Some(("<token> <amount> <recipient> [spend-hook] [user-data]".to_string(), color, bold)),
- "token freeze " => Some(("<token>".to_string(), color, bold)),
- "contract " => Some(("(generate-deploy|list|export-data|deploy|lock)".to_string(), color, bold)),
- "contract list " => Some(("[contract-id]".to_string(), color, bold)),
- "contract export-data " => Some(("<tx-hash>".to_string(), color, bold)),
- "contract deploy " => Some(("<deploy-auth> <wasm-path> [deploy-ix]".to_string(), color, bold)),
- "contract lock " => Some(("<deploy-auth>".to_string(), color, bold)),
- _ => None,
- }
- }
- /// Auxiliary function to start provided Drk as an interactive shell.
- /// Only sane/linenoise terminals are suported.
- pub async fn interactive(
- drk: &DrkPtr,
- endpoint: &Url,
- history_path: &str,
- shell_sender: &Sender<Vec<String>>,
- shell_receiver: &Receiver<Vec<String>>,
- ex: &ExecutorPtr,
- ) {
- // Expand the history file path
- let history_path = match expand_path(history_path) {
- Ok(p) => p,
- Err(e) => {
- eprintln!("Error while expanding history file path: {e}");
- return
- }
- };
- let history_path = history_path.into_os_string();
- let history_file = history_path.to_str().unwrap();
- // Set the completion callback. This will be called every time the
- // user uses the <tab> key.
- linenoise_set_completion_callback(completion);
- // Set the shell hints
- linenoise_set_hints_callback(hints);
- // Load history from file.The history file is just a plain text file
- // where entries are separated by newlines.
- let _ = linenoise_history_load(history_file);
- // Create two detached tasks to use for block subscription
- let mut subscription_active = false;
- let mut snooze_active = false;
- let subscription_tasks = [StoppableTask::new(), StoppableTask::new()];
- // Start the interactive shell
- loop {
- // Wait for next line to process
- let line = listen_for_line(&snooze_active, shell_receiver).await;
- // Grab input or end if Ctrl-D or Ctrl-C was pressed
- let Some(line) = line else { break };
- // Check if line is empty
- if line.is_empty() {
- continue
- }
- // Add line to history
- linenoise_history_add(&line);
- // Split commands
- let commands: Vec<&str> = line.split('|').collect();
- // Process each command
- let mut output = vec![];
- 'commands_loop: for (command_index, command) in commands.iter().enumerate() {
- let mut input = output;
- output = vec![];
- // Check if we have to output to a file
- let (mut command, file, append) = if command.contains('>') {
- // Check if we write or append to the file
- let mut split = ">";
- let mut append = false;
- if command.contains(">>") {
- split = ">>";
- append = true;
- }
- // Parse command parts
- let parts: Vec<&str> = command.split(split).collect();
- if parts.len() == 1 || parts[0].contains('>') {
- output.push(format!("Malformed command output file definition: {command}"));
- continue
- }
- let file = String::from(parts[1..].join("").trim());
- if file.is_empty() || file.contains('>') {
- output.push(format!("Malformed command output file definition: {command}"));
- continue
- }
- (parts[0], Some(file), append)
- } else {
- (*command, None, false)
- };
- // Check if we have to use a file as input
- if command.contains('<') {
- // Parse command parts
- let parts: Vec<&str> = command.split('<').collect();
- if parts.len() == 1 {
- output.push(format!("Malformed command input file definition: {command}"));
- continue
- }
- // Read the input file name
- let file = String::from(parts[1..].join("").trim());
- if file.is_empty() {
- output.push(format!("Malformed command input file definition: {command}"));
- continue
- }
- // Expand the input file path
- let file_path = match expand_path(&file) {
- Ok(p) => p,
- Err(e) => {
- output.push(format!("Error while expanding input file path: {e}"));
- continue
- }
- };
- // Read the file lines
- let file = match File::open(file_path) {
- Ok(f) => f,
- Err(e) => {
- output.push(format!("Error while openning input file: {e}"));
- continue
- }
- };
- input = vec![];
- for (index, line) in BufReader::new(file).lines().enumerate() {
- match line {
- Ok(l) => input.push(l),
- Err(e) => {
- output
- .push(format!("Error while reading input file line {index}: {e}"));
- continue 'commands_loop
- }
- }
- }
- command = parts[0];
- }
- // Parse command parts
- let parts: Vec<&str> = command.split_whitespace().collect();
- if parts.is_empty() {
- continue
- }
- // Handle command
- match parts[0] {
- "help" => help(&mut output),
- "kaching" => kaching().await,
- "ping" => handle_ping(drk, &mut output).await,
- "completions" => handle_completions(&parts, &mut output),
- "wallet" => handle_wallet(drk, &parts, &input, &mut output).await,
- "spend" => handle_spend(drk, &input, &mut output).await,
- "unspend" => handle_unspend(drk, &parts, &mut output).await,
- "transfer" => handle_transfer(drk, &parts, &mut output).await,
- "otc" => handle_otc(drk, &parts, &input, &mut output).await,
- "dao" => handle_dao(drk, &parts, &input, &mut output).await,
- "attach-fee" => handle_attach_fee(drk, &input, &mut output).await,
- "inspect" => handle_inspect(&input, &mut output).await,
- "broadcast" => handle_broadcast(drk, &input, &mut output).await,
- "subscribe" => {
- handle_subscribe(
- drk,
- endpoint,
- &mut subscription_active,
- &subscription_tasks,
- shell_sender,
- ex,
- )
- .await
- }
- "unsubscribe" => {
- handle_unsubscribe(&mut subscription_active, &subscription_tasks).await
- }
- "snooze" => snooze_active = true,
- "unsnooze" => snooze_active = false,
- "scan" => {
- handle_scan(
- drk,
- &subscription_active,
- &parts,
- &mut output,
- &(command_index + 1 == commands.len() && file.is_none()),
- )
- .await
- }
- "explorer" => handle_explorer(drk, &parts, &input, &mut output).await,
- "alias" => handle_alias(drk, &parts, &mut output).await,
- "token" => handle_token(drk, &parts, &mut output).await,
- "contract" => handle_contract(drk, &parts, &mut output).await,
- _ => output.push(format!("Unrecognized command: {}", parts[0])),
- }
- // Write output to file, if requested
- if let Some(file) = file {
- // Expand the output file path
- let file_path = match expand_path(&file) {
- Ok(p) => p,
- Err(e) => {
- output.push(format!("Error while expanding output file path: {e}"));
- continue
- }
- };
- // Open the file
- let file = if append {
- OpenOptions::new().create(true).append(true).open(&file_path)
- } else {
- File::create(file_path)
- };
- let mut file = match file {
- Ok(f) => f,
- Err(e) => {
- output.push(format!("Error while openning output file: {e}"));
- continue
- }
- };
- // Seek end if we append to it
- if append {
- if let Err(e) = file.seek(SeekFrom::End(0)) {
- output.push(format!("Error while seeking end of output file: {e}"));
- continue
- }
- }
- // Write the output
- if let Err(e) = file.write_all((output.join("\n") + "\n").as_bytes()) {
- output.push(format!("Error while writing output file: {e}"));
- continue
- }
- output = vec![];
- }
- }
- // Handle last command output
- print_output(&output);
- }
- // Stop the subscription tasks if they are active
- subscription_tasks[0].stop_nowait();
- subscription_tasks[1].stop_nowait();
- // Write history file
- let _ = linenoise_history_save(history_file);
- }
- /// Auxiliary function to listen for linenoise input line and handle
- /// background task messages.
- async fn listen_for_line(
- snooze_active: &bool,
- shell_receiver: &Receiver<Vec<String>>,
- ) -> Option<String> {
- // Generate the linoise state structure
- let mut state = match LinenoiseState::edit_start(-1, -1, "drk> ") {
- Ok(s) => s,
- Err(e) => {
- eprintln!("Error while generating linenoise state: {e}");
- return None
- }
- };
- // Set stdin to non-blocking mode
- let fd = state.get_fd();
- unsafe {
- let flags = fcntl(fd, F_GETFL, 0);
- fcntl(fd, F_SETFL, flags | O_NONBLOCK);
- }
- // Read until we get a line to process
- let mut line = None;
- loop {
- // Future that polls stdin for input
- let input_future = async {
- loop {
- match state.edit_feed() {
- Ok(Some(l)) => {
- line = Some(l);
- break
- }
- Ok(None) => break,
- Err(e) if e.kind() == ErrorKind::Interrupted => break,
- Err(e) if e.kind() == ErrorKind::WouldBlock => {
- // No data available, yield and retry
- msleep(10).await;
- continue
- }
- Err(e) => {
- eprintln!("Error while reading linenoise feed: {e}");
- break
- }
- }
- }
- };
- // Future that polls the channel
- let channel_future = async {
- loop {
- if !shell_receiver.is_empty() {
- break
- }
- msleep(1000).await;
- }
- };
- // Manage the futures
- select! {
- // When input is ready we break out the loop
- _ = input_future.fuse() => break,
- // Manage filled channel
- _ = channel_future.fuse() => {
- // We only print if snooze is inactive,
- // but have to consume the message regardless,
- // so the queue gets empty.
- if *snooze_active {
- while !shell_receiver.is_empty() {
- if let Err(e) = shell_receiver.recv().await {
- eprintln!("Error while reading shell receiver channel: {e}");
- break
- }
- }
- } else {
- // Hide prompt
- if let Err(e) = state.hide() {
- eprintln!("Error while hiding linenoise state: {e}");
- break
- };
- // Restore blocking mode
- unsafe {
- let flags = fcntl(fd, F_GETFL, 0);
- fcntl(fd, F_SETFL, flags & !O_NONBLOCK);
- }
- // Print output
- while !shell_receiver.is_empty() {
- match shell_receiver.recv().await {
- Ok(msg) => {
- for line in msg {
- println!("{}\r", line.replace("\n", "\n\r"));
- }
- }
- Err(e) => {
- eprintln!("Error while reading shell receiver channel: {e}");
- break
- }
- }
- }
- // Set stdin to non-blocking mode
- unsafe {
- let flags = fcntl(fd, F_GETFL, 0);
- fcntl(fd, F_SETFL, flags | O_NONBLOCK);
- }
- // Show prompt again
- if let Err(e) = state.show() {
- eprintln!("Error while showing linenoise state: {e}");
- break
- };
- }
- }
- }
- }
- // Restore blocking mode
- unsafe {
- let flags = fcntl(fd, F_GETFL, 0);
- fcntl(fd, F_SETFL, flags & !O_NONBLOCK);
- }
- if let Err(e) = state.edit_stop() {
- eprintln!("Error while stopping linenoise state: {e}");
- };
- line
- }
- /// Auxiliary function to define the ping command handling.
- async fn handle_ping(drk: &DrkPtr, output: &mut Vec<String>) {
- if let Err(e) = drk.read().await.ping(output).await {
- output.push(format!("Error while executing ping command: {e}"))
- }
- }
- /// Auxiliary function to define the completions command handling.
- fn handle_completions(parts: &[&str], output: &mut Vec<String>) {
- // Check correct command structure
- if parts.len() != 2 {
- output.push(String::from("Malformed `completions` command"));
- output.push(String::from("Usage: completions <shell>"));
- return
- }
- match generate_completions(parts[1]) {
- Ok(completions) => output.push(completions),
- Err(e) => output.push(format!("Error while executing completions command: {e}")),
- }
- }
- /// Auxiliary function to define the wallet command handling.
- async fn handle_wallet(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
- // Check correct command structure
- if parts.len() < 2 {
- output.push(String::from("Malformed `wallet` command"));
- output.push(String::from("Usage: wallet (initialize|keygen|balance|address|addresses|default-address|secrets|import-secrets|tree|coins|mining-config)"));
- return
- }
- // Handle subcommand
- match parts[1] {
- "initialize" => handle_wallet_initialize(drk, output).await,
- "keygen" => handle_wallet_keygen(drk, output).await,
- "balance" => handle_wallet_balance(drk, output).await,
- "address" => handle_wallet_address(drk, output).await,
- "addresses" => handle_wallet_addresses(drk, output).await,
- "default-address" => handle_wallet_default_address(drk, parts, output).await,
- "secrets" => handle_wallet_secrets(drk, output).await,
- "import-secrets" => handle_wallet_import_secrets(drk, input, output).await,
- "tree" => handle_wallet_tree(drk, output).await,
- "coins" => handle_wallet_coins(drk, output).await,
- "mining-config" => handle_wallet_mining_config(drk, parts, output).await,
- _ => {
- output.push(format!("Unrecognized wallet subcommand: {}", parts[1]));
- output.push(String::from("Usage: wallet (initialize|keygen|balance|address|addresses|default-address|secrets|import-secrets|tree|coins|mining-config)"));
- }
- }
- }
- /// Auxiliary function to define the wallet initialize subcommand handling.
- async fn handle_wallet_initialize(drk: &DrkPtr, output: &mut Vec<String>) {
- let lock = drk.read().await;
- if let Err(e) = lock.initialize_wallet().await {
- output.push(format!("Error initializing wallet: {e}"));
- return
- }
- if let Err(e) = lock.initialize_money(output).await {
- output.push(format!("Failed to initialize Money: {e}"));
- return
- }
- if let Err(e) = lock.initialize_dao().await {
- output.push(format!("Failed to initialize DAO: {e}"));
- return
- }
- if let Err(e) = lock.initialize_deployooor() {
- output.push(format!("Failed to initialize Deployooor: {e}"));
- }
- }
- /// Auxiliary function to define the wallet keygen subcommand handling.
- async fn handle_wallet_keygen(drk: &DrkPtr, output: &mut Vec<String>) {
- if let Err(e) = drk.read().await.money_keygen(output).await {
- output.push(format!("Failed to generate keypair: {e}"));
- }
- }
- /// Auxiliary function to define the wallet balance subcommand handling.
- async fn handle_wallet_balance(drk: &DrkPtr, output: &mut Vec<String>) {
- let drk = drk.read().await;
- let balmap = match drk.money_balance().await {
- Ok(m) => m,
- Err(e) => {
- output.push(format!("Failed to fetch balances map: {e}"));
- return
- }
- };
- let alimap = match drk.get_aliases_mapped_by_token().await {
- Ok(m) => m,
- Err(e) => {
- output.push(format!("Failed to fetch aliases map: {e}"));
- return
- }
- };
- let table = prettytable_balance(&balmap, &alimap);
- if table.is_empty() {
- output.push(String::from("No unspent balances found"));
- } else {
- output.push(format!("{table}"));
- }
- }
- /// Auxiliary function to define the wallet address subcommand handling.
- async fn handle_wallet_address(drk: &DrkPtr, output: &mut Vec<String>) {
- let drk = drk.read().await;
- let public_key = match drk.default_address().await {
- Ok(v) => v,
- Err(e) => {
- output.push(format!("Failed to fetch default address: {e}"));
- return
- }
- };
- let addr: Address = StandardAddress::from_public(drk.network, public_key).into();
- output.push(format!("{addr}"));
- }
- /// Auxiliary function to define the wallet addresses subcommand handling.
- async fn handle_wallet_addresses(drk: &DrkPtr, output: &mut Vec<String>) {
- let drk = drk.read().await;
- let network = drk.network;
- let addresses = match drk.addresses().await {
- Ok(v) => v,
- Err(e) => {
- output.push(format!("Failed to fetch addresses: {e}"));
- return
- }
- };
- let table = prettytable_addrs(network, &addresses);
- if table.is_empty() {
- output.push(String::from("No addresses found"));
- } else {
- output.push(format!("{table}"));
- }
- }
- /// Auxiliary function to define the wallet default address subcommand handling.
- async fn handle_wallet_default_address(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- if parts.len() != 3 {
- output.push(String::from("Malformed `wallet default-address` subcommand"));
- output.push(String::from("Usage: wallet default-address <index>"));
- return
- }
- let index = match usize::from_str(parts[2]) {
- Ok(i) => i,
- Err(e) => {
- output.push(format!("Invalid address id: {e}"));
- return
- }
- };
- if let Err(e) = drk.read().await.set_default_address(index) {
- output.push(format!("Failed to set default address: {e}"));
- }
- }
- /// Auxiliary function to define the wallet secrets subcommand handling.
- async fn handle_wallet_secrets(drk: &DrkPtr, output: &mut Vec<String>) {
- match drk.read().await.get_money_secrets().await {
- Ok(secrets) => {
- for secret in secrets {
- output.push(format!("{secret}"));
- }
- }
- Err(e) => output.push(format!("Failed to fetch secrets: {e}")),
- }
- }
- /// Auxiliary function to define the wallet import secrets subcommand handling.
- async fn handle_wallet_import_secrets(drk: &DrkPtr, input: &[String], output: &mut Vec<String>) {
- let mut secrets = vec![];
- // Parse input or read from stdin
- if input.is_empty() {
- for (i, line) in stdin().lines().enumerate() {
- let Ok(line) = line else { continue };
- let Ok(bytes) = bs58::decode(&line.trim()).into_vec() else {
- output.push(format!("Warning: Failed to decode secret on line {i}"));
- continue
- };
- let Ok(secret) = deserialize_async(&bytes).await else {
- output.push(format!("Warning: Failed to deserialize secret on line {i}"));
- continue
- };
- secrets.push(secret);
- }
- } else {
- for (i, line) in input.iter().enumerate() {
- let Ok(bytes) = bs58::decode(&line.trim()).into_vec() else {
- output.push(format!("Warning: Failed to decode secret on line {i}"));
- continue
- };
- let Ok(secret) = deserialize_async(&bytes).await else {
- output.push(format!("Warning: Failed to deserialize secret on line {i}"));
- continue
- };
- secrets.push(secret);
- }
- }
- match drk.read().await.import_money_secrets(secrets, output).await {
- Ok(pubkeys) => {
- for key in pubkeys {
- output.push(format!("{key}"));
- }
- }
- Err(e) => output.push(format!("Failed to import secrets: {e}")),
- }
- }
- /// Auxiliary function to define the wallet tree subcommand handling.
- async fn handle_wallet_tree(drk: &DrkPtr, output: &mut Vec<String>) {
- match drk.read().await.get_money_tree().await {
- Ok(tree) => output.push(format!("{tree:#?}")),
- Err(e) => output.push(format!("Failed to fetch tree: {e}")),
- }
- }
- /// Auxiliary function to define the wallet coins subcommand handling.
- async fn handle_wallet_coins(drk: &DrkPtr, output: &mut Vec<String>) {
- let lock = drk.read().await;
- let coins = match lock.get_coins(true).await {
- Ok(c) => c,
- Err(e) => {
- output.push(format!("Failed to fetch coins: {e}"));
- return
- }
- };
- if coins.is_empty() {
- return
- }
- let aliases_map = match lock.get_aliases_mapped_by_token().await {
- Ok(m) => m,
- Err(e) => {
- output.push(format!("Failed to fetch aliases map: {e}"));
- return
- }
- };
- let table = prettytable_coins(&coins, &aliases_map);
- output.push(format!("{table}"));
- }
- /// Auxiliary function to define the wallet mining config subcommand handling.
- async fn handle_wallet_mining_config(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct command structure
- if parts.len() < 3 || parts.len() > 5 {
- output.push(String::from("Malformed `wallet mining-address` subcommand"));
- output.push(String::from("Usage: wallet mining-config <index> [spend_hook] [user_data]"));
- return
- }
- // Parse command
- let mut index = 2;
- let wallet_index = match usize::from_str(parts[index]) {
- Ok(i) => i,
- Err(e) => {
- output.push(format!("Invalid address id: {e}"));
- return
- }
- };
- index += 1;
- let spend_hook = if index < parts.len() {
- match FuncId::from_str(parts[index]) {
- Ok(s) => Some(s),
- Err(e) => {
- output.push(format!("Invalid spend hook: {e}"));
- return
- }
- }
- } else {
- None
- };
- index += 1;
- let user_data = if index < parts.len() {
- let bytes = match bs58::decode(&parts[index]).into_vec() {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid user data: {e}"));
- return
- }
- };
- let bytes: [u8; 32] = match bytes.try_into() {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid user data: {e:?}"));
- return
- }
- };
- let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
- Some(v) => v,
- None => {
- output.push(String::from("Invalid user data"));
- return
- }
- };
- Some(elem)
- } else {
- None
- };
- if let Err(e) =
- drk.read().await.mining_config(wallet_index, spend_hook, user_data, output).await
- {
- output.push(format!("Failed to generate wallet mining configuration: {e}"));
- }
- }
- /// Auxiliary function to define the spend command handling.
- async fn handle_spend(drk: &DrkPtr, input: &[String], output: &mut Vec<String>) {
- let tx = match parse_tx_from_input(input).await {
- Ok(t) => t,
- Err(e) => {
- output.push(format!("Error while parsing transaction: {e}"));
- return
- }
- };
- if let Err(e) = drk.read().await.mark_tx_spend(&tx, output).await {
- output.push(format!("Failed to mark transaction coins as spent: {e}"))
- }
- }
- /// Auxiliary function to define the unspend command handling.
- async fn handle_unspend(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct command structure
- if parts.len() != 2 {
- output.push(String::from("Malformed `unspend` command"));
- output.push(String::from("Usage: unspend <coin>"));
- return
- }
- let bytes = match bs58::decode(&parts[1]).into_vec() {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid coin: {e}"));
- return
- }
- };
- let bytes: [u8; 32] = match bytes.try_into() {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid coin: {e:?}"));
- return
- }
- };
- let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
- Some(v) => v,
- None => {
- output.push(String::from("Invalid coin"));
- return
- }
- };
- if let Err(e) = drk.read().await.unspend_coin(&Coin::from(elem)).await {
- output.push(format!("Failed to mark coin as unspent: {e}"))
- }
- }
- /// Auxiliary function to define the transfer command handling.
- async fn handle_transfer(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct command structure
- if parts.len() < 4 || parts.len() > 7 {
- output.push(String::from("Malformed `transfer` command"));
- output.push(String::from(
- "Usage: transfer [--half-split] <amount> <token> <recipient> [spend_hook] [user_data]",
- ));
- return
- }
- // Parse command
- let mut index = 1;
- let mut half_split = false;
- if parts[index] == "--half-split" {
- half_split = true;
- index += 1;
- }
- let amount = String::from(parts[index]);
- if let Err(e) = f64::from_str(&amount) {
- output.push(format!("Invalid amount: {e}"));
- return
- }
- index += 1;
- let lock = drk.read().await;
- let token_id = match lock.get_token(String::from(parts[index])).await {
- Ok(t) => t,
- Err(e) => {
- output.push(format!("Invalid token ID: {e}"));
- return
- }
- };
- index += 1;
- let rcpt = match Address::from_str(parts[index]) {
- Ok(r) => r,
- Err(e) => {
- output.push(format!("Invalid recipient: {e}"));
- return
- }
- };
- if rcpt.network() != lock.network {
- output.push("Mismatched recipient address prefix".to_string());
- return
- }
- index += 1;
- let spend_hook = if index < parts.len() {
- match FuncId::from_str(parts[index]) {
- Ok(s) => Some(s),
- Err(e) => {
- output.push(format!("Invalid spend hook: {e}"));
- return
- }
- }
- } else {
- None
- };
- index += 1;
- let user_data = if index < parts.len() {
- let bytes = match bs58::decode(&parts[index]).into_vec() {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid user data: {e}"));
- return
- }
- };
- let bytes: [u8; 32] = match bytes.try_into() {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid user data: {e:?}"));
- return
- }
- };
- let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
- Some(v) => v,
- None => {
- output.push(String::from("Invalid user data"));
- return
- }
- };
- Some(elem)
- } else {
- None
- };
- match lock
- .transfer(&amount, token_id, *rcpt.public_key(), spend_hook, user_data, half_split)
- .await
- {
- Ok(t) => output.push(base64::encode(&serialize_async(&t).await)),
- Err(e) => output.push(format!("Failed to create payment transaction: {e}")),
- }
- }
- /// Auxiliary function to define the otc command handling.
- async fn handle_otc(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
- // Check correct command structure
- if parts.len() < 2 {
- output.push(String::from("Malformed `otc` command"));
- output.push(String::from("Usage: otc (init|join|inspect|sign)"));
- return
- }
- // Handle subcommand
- match parts[1] {
- "init" => handle_otc_init(drk, parts, output).await,
- "join" => handle_otc_join(drk, parts, input, output).await,
- "inspect" => handle_otc_inspect(drk, parts, input, output).await,
- "sign" => handle_otc_sign(drk, parts, input, output).await,
- _ => {
- output.push(format!("Unrecognized OTC subcommand: {}", parts[1]));
- output.push(String::from("Usage: otc (init|join|inspect|sign)"));
- }
- }
- }
- /// Auxiliary function to define the otc init subcommand handling.
- async fn handle_otc_init(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 4 {
- output.push(String::from("Malformed `otc init` subcommand"));
- output.push(String::from("Usage: otc init <value_pair> <token_pair>"));
- return
- }
- let value_pair = match parse_value_pair(parts[2]) {
- Ok(v) => v,
- Err(e) => {
- output.push(format!("Invalid value pair: {e}"));
- return
- }
- };
- let lock = drk.read().await;
- let token_pair = match parse_token_pair(&lock, parts[3]).await {
- Ok(t) => t,
- Err(e) => {
- output.push(format!("Invalid token pair: {e}"));
- return
- }
- };
- match lock.init_swap(value_pair, token_pair, None, None, None).await {
- Ok(half) => output.push(base64::encode(&serialize_async(&half).await)),
- Err(e) => output.push(format!("Failed to create swap transaction half: {e}")),
- }
- }
- /// Auxiliary function to define the otc join subcommand handling.
- async fn handle_otc_join(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 2 {
- output.push(String::from("Malformed `otc join` subcommand"));
- output.push(String::from("Usage: otc join"));
- return
- }
- // Parse line from input or fallback to stdin if its empty
- let buf = match input.len() {
- 0 => {
- let mut buf = String::new();
- if let Err(e) = stdin().read_to_string(&mut buf) {
- output.push(format!("Failed to read from stdin: {e}"));
- return
- };
- buf
- }
- 1 => input[0].clone(),
- _ => {
- output.push(String::from("Multiline input provided"));
- return
- }
- };
- let Some(bytes) = base64::decode(buf.trim()) else {
- output.push(String::from("Failed to decode partial swap data"));
- return
- };
- let partial: PartialSwapData = match deserialize_async(&bytes).await {
- Ok(p) => p,
- Err(e) => {
- output.push(format!("Failed to deserialize partial swap data: {e}"));
- return
- }
- };
- match drk.read().await.join_swap(partial, None, None, None).await {
- Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
- Err(e) => output.push(format!("Failed to create a join swap transaction: {e}")),
- }
- }
- /// Auxiliary function to define the otc inspect subcommand handling.
- async fn handle_otc_inspect(
- drk: &DrkPtr,
- parts: &[&str],
- input: &[String],
- output: &mut Vec<String>,
- ) {
- // Check correct subcommand structure
- if parts.len() != 2 {
- output.push(String::from("Malformed `otc inspect` subcommand"));
- output.push(String::from("Usage: otc inspect"));
- return
- }
- // Parse line from input or fallback to stdin if its empty
- let buf = match input.len() {
- 0 => {
- let mut buf = String::new();
- if let Err(e) = stdin().read_to_string(&mut buf) {
- output.push(format!("Failed to read from stdin: {e}"));
- return
- };
- buf
- }
- 1 => input[0].clone(),
- _ => {
- output.push(String::from("Multiline input provided"));
- return
- }
- };
- let Some(bytes) = base64::decode(buf.trim()) else {
- output.push(String::from("Failed to decode swap transaction"));
- return
- };
- if let Err(e) = drk.read().await.inspect_swap(bytes, output).await {
- output.push(format!("Failed to inspect swap: {e}"));
- }
- }
- /// Auxiliary function to define the otc sign subcommand handling.
- async fn handle_otc_sign(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 2 {
- output.push(String::from("Malformed `otc sign` subcommand"));
- output.push(String::from("Usage: otc sign"));
- return
- }
- let mut tx = match parse_tx_from_input(input).await {
- Ok(t) => t,
- Err(e) => {
- output.push(format!("Error while parsing transaction: {e}"));
- return
- }
- };
- match drk.read().await.sign_swap(&mut tx).await {
- Ok(_) => output.push(base64::encode(&serialize_async(&tx).await)),
- Err(e) => output.push(format!("Failed to sign joined swap transaction: {e}")),
- }
- }
- /// Auxiliary function to define the dao command handling.
- async fn handle_dao(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
- // Check correct command structure
- if parts.len() < 2 {
- output.push(String::from("Malformed `dao` command"));
- output.push(String::from("Usage: dao (create|view|import|list|balance|mint|propose-transfer|propose-generic|proposals|proposal|proposal-import|vote|exec|spend-hook|mining-config)"));
- return
- }
- // Handle subcommand
- match parts[1] {
- "create" => handle_dao_create(drk, parts, output).await,
- "view" => handle_dao_view(parts, input, output).await,
- "import" => handle_dao_import(drk, parts, input, output).await,
- "list" => handle_dao_list(drk, parts, output).await,
- "balance" => handle_dao_balance(drk, parts, output).await,
- "mint" => handle_dao_mint(drk, parts, output).await,
- "propose-transfer" => handle_dao_propose_transfer(drk, parts, output).await,
- "propose-generic" => handle_dao_propose_generic(drk, parts, output).await,
- "proposals" => handle_dao_proposals(drk, parts, output).await,
- "proposal" => handle_dao_proposal(drk, parts, output).await,
- "proposal-import" => handle_dao_proposal_import(drk, parts, input, output).await,
- "vote" => handle_dao_vote(drk, parts, output).await,
- "exec" => handle_dao_exec(drk, parts, output).await,
- "spend-hook" => handle_dao_spend_hook(parts, output).await,
- "mining-config" => handle_dao_mining_config(drk, parts, output).await,
- _ => {
- output.push(format!("Unrecognized DAO subcommand: {}", parts[1]));
- output.push(String::from("Usage: dao (create|view|import|list|balance|mint|propose-transfer|propose-generic|proposals|proposal|proposal-import|vote|exec|spend-hook|mining-config)"));
- }
- }
- }
- /// Auxiliary function to define the dao create subcommand handling.
- async fn handle_dao_create(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 7 {
- output.push(String::from("Malformed `dao create` subcommand"));
- output.push(String::from("Usage: dao create <proposer-limit> <quorum> <early-exec-quorum> <approval-ratio> <gov-token-id>"));
- return
- }
- if let Err(e) = f64::from_str(parts[2]) {
- output.push(format!("Invalid proposer limit: {e}"));
- return
- }
- let proposer_limit = match decode_base10(parts[2], BALANCE_BASE10_DECIMALS, true) {
- Ok(p) => p,
- Err(e) => {
- output.push(format!("Error while parsing proposer limit: {e}"));
- return
- }
- };
- if let Err(e) = f64::from_str(parts[3]) {
- output.push(format!("Invalid quorum: {e}"));
- return
- }
- let quorum = match decode_base10(parts[3], BALANCE_BASE10_DECIMALS, true) {
- Ok(q) => q,
- Err(e) => {
- output.push(format!("Error while parsing quorum: {e}"));
- return
- }
- };
- if let Err(e) = f64::from_str(parts[4]) {
- output.push(format!("Invalid early exec quorum: {e}"));
- return
- }
- let early_exec_quorum = match decode_base10(parts[4], BALANCE_BASE10_DECIMALS, true) {
- Ok(e) => e,
- Err(e) => {
- output.push(format!("Error while parsing early exec quorum: {e}"));
- return
- }
- };
- let approval_ratio = match f64::from_str(parts[5]) {
- Ok(a) => {
- if a > 1.0 {
- output.push(String::from("Error: Approval ratio cannot be >1.0"));
- return
- }
- a
- }
- Err(e) => {
- output.push(format!("Invalid approval ratio: {e}"));
- return
- }
- };
- let approval_ratio_base = 100_u64;
- let approval_ratio_quot = (approval_ratio * approval_ratio_base as f64) as u64;
- let gov_token_id = match drk.read().await.get_token(String::from(parts[6])).await {
- Ok(g) => g,
- Err(e) => {
- output.push(format!("Invalid Token ID: {e}"));
- return
- }
- };
- let notes_keypair = Keypair::random(&mut OsRng);
- let proposer_keypair = Keypair::random(&mut OsRng);
- let proposals_keypair = Keypair::random(&mut OsRng);
- let votes_keypair = Keypair::random(&mut OsRng);
- let exec_keypair = Keypair::random(&mut OsRng);
- let early_exec_keypair = Keypair::random(&mut OsRng);
- let bulla_blind = BaseBlind::random(&mut OsRng);
- let params = DaoParams::new(
- proposer_limit,
- quorum,
- early_exec_quorum,
- approval_ratio_base,
- approval_ratio_quot,
- gov_token_id,
- Some(notes_keypair.secret),
- notes_keypair.public,
- Some(proposer_keypair.secret),
- proposer_keypair.public,
- Some(proposals_keypair.secret),
- proposals_keypair.public,
- Some(votes_keypair.secret),
- votes_keypair.public,
- Some(exec_keypair.secret),
- exec_keypair.public,
- Some(early_exec_keypair.secret),
- early_exec_keypair.public,
- bulla_blind,
- );
- output.push(params.toml_str());
- }
- /// Auxiliary function to define the dao view subcommand handling.
- async fn handle_dao_view(parts: &[&str], input: &[String], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 2 {
- output.push(String::from("Malformed `dao view` subcommand"));
- output.push(String::from("Usage: dao view"));
- return
- }
- // Parse lines from input or fallback to stdin if its empty
- let buf = match input.len() {
- 0 => {
- let mut buf = String::new();
- if let Err(e) = stdin().read_to_string(&mut buf) {
- output.push(format!("Failed to read from stdin: {e}"));
- return
- };
- buf
- }
- _ => input.join("\n"),
- };
- let params = match DaoParams::from_toml_str(&buf) {
- Ok(p) => p,
- Err(e) => {
- output.push(format!("Error while parsing DAO params: {e}"));
- return
- }
- };
- output.push(format!("{params}"));
- }
- /// Auxiliary function to define the dao import subcommand handling.
- async fn handle_dao_import(
- drk: &DrkPtr,
- parts: &[&str],
- input: &[String],
- output: &mut Vec<String>,
- ) {
- // Check correct subcommand structure
- if parts.len() != 3 {
- output.push(String::from("Malformed `dao import` subcommand"));
- output.push(String::from("Usage: dao import <name>"));
- return
- }
- // Parse lines from input or fallback to stdin if its empty
- let buf = match input.len() {
- 0 => {
- let mut buf = String::new();
- if let Err(e) = stdin().read_to_string(&mut buf) {
- output.push(format!("Failed to read from stdin: {e}"));
- return
- };
- buf
- }
- _ => input.join("\n"),
- };
- let params = match DaoParams::from_toml_str(&buf) {
- Ok(p) => p,
- Err(e) => {
- output.push(format!("Error while parsing DAO params: {e}"));
- return
- }
- };
- if let Err(e) = drk.read().await.import_dao(parts[2], ¶ms, output).await {
- output.push(format!("Failed to import DAO: {e}"))
- }
- }
- /// Auxiliary function to define the dao list subcommand handling.
- async fn handle_dao_list(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 2 && parts.len() != 3 {
- output.push(String::from("Malformed `dao list` subcommand"));
- output.push(String::from("Usage: dao list [name]"));
- return
- }
- let name = if parts.len() == 3 { Some(String::from(parts[2])) } else { None };
- if let Err(e) = drk.read().await.dao_list(&name, output).await {
- output.push(format!("Failed to list DAO: {e}"))
- }
- }
- /// Auxiliary function to define the dao balance subcommand handling.
- async fn handle_dao_balance(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 3 {
- output.push(String::from("Malformed `dao balance` subcommand"));
- output.push(String::from("Usage: dao balance <name>"));
- return
- }
- let lock = drk.read().await;
- let balmap = match lock.dao_balance(parts[2]).await {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Failed to fetch DAO balance: {e}"));
- return
- }
- };
- let alimap = match lock.get_aliases_mapped_by_token().await {
- Ok(m) => m,
- Err(e) => {
- output.push(format!("Failed to fetch aliases map: {e}"));
- return
- }
- };
- let table = prettytable_balance(&balmap, &alimap);
- if table.is_empty() {
- output.push(String::from("No unspent balances found"))
- } else {
- output.push(format!("{table}"));
- }
- }
- /// Auxiliary function to define the dao mint subcommand handling.
- async fn handle_dao_mint(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 3 {
- output.push(String::from("Malformed `dao mint` subcommand"));
- output.push(String::from("Usage: dao mint <name>"));
- return
- }
- match drk.read().await.dao_mint(parts[2]).await {
- Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
- Err(e) => output.push(format!("Failed to mint DAO: {e}")),
- }
- }
- /// Auxiliary function to define the dao propose transfer subcommand handling.
- async fn handle_dao_propose_transfer(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() < 7 || parts.len() > 9 {
- output.push(String::from("Malformed `dao proposal-transfer` subcommand"));
- output.push(String::from("Usage: dao proposal-transfer <name> <duration> <amount> <token> <recipient> [spend-hook] [user-data]"));
- return
- }
- let duration = match u64::from_str(parts[3]) {
- Ok(d) => d,
- Err(e) => {
- output.push(format!("Invalid duration: {e}"));
- return
- }
- };
- let amount = String::from(parts[4]);
- if let Err(e) = f64::from_str(&amount) {
- output.push(format!("Invalid amount: {e}"));
- return
- }
- let lock = drk.read().await;
- let token_id = match lock.get_token(String::from(parts[5])).await {
- Ok(t) => t,
- Err(e) => {
- output.push(format!("Invalid token ID: {e}"));
- return
- }
- };
- let rcpt = match Address::from_str(parts[6]) {
- Ok(r) => r,
- Err(e) => {
- output.push(format!("Invalid recipient: {e}"));
- return
- }
- };
- if rcpt.network() != lock.network {
- output.push("Recipient address prefix mismatch".to_string());
- return
- }
- let mut index = 7;
- let spend_hook = if index < parts.len() {
- match FuncId::from_str(parts[index]) {
- Ok(s) => Some(s),
- Err(e) => {
- output.push(format!("Invalid spend hook: {e}"));
- return
- }
- }
- } else {
- None
- };
- index += 1;
- let user_data = if index < parts.len() {
- let bytes = match bs58::decode(&parts[index]).into_vec() {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid user data: {e}"));
- return
- }
- };
- let bytes: [u8; 32] = match bytes.try_into() {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid user data: {e:?}"));
- return
- }
- };
- let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
- Some(v) => v,
- None => {
- output.push(String::from("Invalid user data"));
- return
- }
- };
- Some(elem)
- } else {
- None
- };
- match drk
- .read()
- .await
- .dao_propose_transfer(
- parts[2],
- duration,
- &amount,
- token_id,
- *rcpt.public_key(),
- spend_hook,
- user_data,
- )
- .await
- {
- Ok(proposal) => output.push(format!("Generated proposal: {}", proposal.bulla())),
- Err(e) => output.push(format!("Failed to create DAO transfer proposal: {e}")),
- }
- }
- /// Auxiliary function to define the dao propose generic subcommand handling.
- async fn handle_dao_propose_generic(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 4 && parts.len() != 5 {
- output.push(String::from("Malformed `dao proposal-generic` subcommand"));
- output.push(String::from("Usage: dao proposal-generic <name> <duration> [user-data]"));
- return
- }
- let duration = match u64::from_str(parts[3]) {
- Ok(d) => d,
- Err(e) => {
- output.push(format!("Invalid duration: {e}"));
- return
- }
- };
- let user_data = if parts.len() == 5 {
- let bytes = match bs58::decode(&parts[4]).into_vec() {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid user data: {e}"));
- return
- }
- };
- let bytes: [u8; 32] = match bytes.try_into() {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid user data: {e:?}"));
- return
- }
- };
- let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
- Some(v) => v,
- None => {
- output.push(String::from("Invalid user data"));
- return
- }
- };
- Some(elem)
- } else {
- None
- };
- match drk.read().await.dao_propose_generic(parts[2], duration, user_data).await {
- Ok(proposal) => output.push(format!("Generated proposal: {}", proposal.bulla())),
- Err(e) => output.push(format!("Failed to create DAO generic proposal: {e}")),
- }
- }
- /// Auxiliary function to define the dao proposals subcommand handling.
- async fn handle_dao_proposals(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 3 {
- output.push(String::from("Malformed `dao proposals` subcommand"));
- output.push(String::from("Usage: dao proposals <name>"));
- return
- }
- match drk.read().await.get_dao_proposals(parts[2]).await {
- Ok(proposals) => {
- for (i, proposal) in proposals.iter().enumerate() {
- output.push(format!("{i}. {}", proposal.bulla()));
- }
- }
- Err(e) => output.push(format!("Failed to retrieve DAO proposals: {e}")),
- }
- }
- /// Auxiliary function to define the dao proposal subcommand handling.
- async fn handle_dao_proposal(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 3 && parts.len() != 4 {
- output.push(String::from("Malformed `dao proposal` subcommand"));
- output.push(String::from("Usage: dao proposal [--(export|mint-proposal)] <bulla>"));
- return
- }
- let mut index = 2;
- let (export, mint_proposal) = if parts.len() == 4 {
- let flags = match parts[index] {
- "--export" => (true, false),
- "--mint-proposal" => (false, true),
- _ => {
- output.push(String::from("Malformed `dao proposal` subcommand"));
- output.push(String::from("Usage: dao proposal [--(export|mint-proposal)] <bulla>"));
- return
- }
- };
- index += 1;
- flags
- } else {
- (false, false)
- };
- let bulla = match DaoProposalBulla::from_str(parts[index]) {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid proposal bulla: {e}"));
- return
- }
- };
- let lock = drk.read().await;
- let proposal = match lock.get_dao_proposal_by_bulla(&bulla).await {
- Ok(p) => p,
- Err(e) => {
- output.push(format!("Failed to fetch DAO proposal: {e}"));
- return
- }
- };
- if export {
- // Retrieve the DAO
- let dao = match lock.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
- Ok(d) => d,
- Err(e) => {
- output.push(format!("Failed to fetch DAO: {e}"));
- return
- }
- };
- // Encypt the proposal
- let enc_note =
- AeadEncryptedNote::encrypt(&proposal, &dao.params.dao.proposals_public_key, &mut OsRng)
- .unwrap();
- // Export it to base64
- output.push(base64::encode(&serialize_async(&enc_note).await));
- return
- }
- if mint_proposal {
- // Identify proposal type by its auth calls
- for call in &proposal.proposal.auth_calls {
- // We only support transfer right now
- if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
- match lock.dao_transfer_proposal_tx(&proposal).await {
- Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
- Err(e) => output.push(format!("Failed to create DAO transfer proposal: {e}")),
- }
- return
- }
- }
- // If proposal has no auth calls, we consider it a generic one
- if proposal.proposal.auth_calls.is_empty() {
- match lock.dao_generic_proposal_tx(&proposal).await {
- Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
- Err(e) => output.push(format!("Failed to create DAO generic proposal: {e}")),
- }
- return
- }
- output.push(String::from("Unsuported DAO proposal"));
- return
- }
- output.push(format!("{proposal}"));
- let mut contract_calls = "\nInvoked contracts:\n".to_string();
- for call in proposal.proposal.auth_calls {
- contract_calls.push_str(&format!(
- "\tContract: {}\n\tFunction: {}\n\tData: ",
- call.contract_id, call.function_code
- ));
- if call.auth_data.is_empty() {
- contract_calls.push_str("-\n");
- continue;
- }
- if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
- // We know that the plaintext data live in the data plaintext vec
- if proposal.data.is_none() {
- contract_calls.push_str("-\n");
- continue;
- }
- let coin: CoinAttributes = match deserialize_async(proposal.data.as_ref().unwrap())
- .await
- {
- Ok(c) => c,
- Err(e) => {
- output.push(format!("Failed to deserialize transfer proposal coin data: {e}"));
- return
- }
- };
- let recipient: Address =
- StandardAddress::from_public(lock.network, coin.public_key).into();
- let spend_hook = if coin.spend_hook == FuncId::none() {
- "-".to_string()
- } else {
- format!("{}", coin.spend_hook)
- };
- let user_data = if coin.user_data == pallas::Base::ZERO {
- "-".to_string()
- } else {
- format!("{:?}", coin.user_data)
- };
- contract_calls.push_str(&format!(
- "\n\t\t{}: {}\n\t\t{}: {} ({})\n\t\t{}: {}\n\t\t{}: {}\n\t\t{}: {}\n\t\t{}: {}\n\n",
- "Recipient",
- recipient,
- "Amount",
- coin.value,
- encode_base10(coin.value, BALANCE_BASE10_DECIMALS),
- "Token",
- coin.token_id,
- "Spend hook",
- spend_hook,
- "User data",
- user_data,
- "Blind",
- coin.blind
- ));
- }
- }
- output.push(contract_calls);
- let votes = match lock.get_dao_proposal_votes(&bulla).await {
- Ok(v) => v,
- Err(e) => {
- output.push(format!("Failed to fetch DAO proposal votes: {e}"));
- return
- }
- };
- let mut total_yes_vote_value = 0;
- let mut total_no_vote_value = 0;
- let mut total_all_vote_value = 0;
- let mut table = Table::new();
- table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
- table.set_titles(row!["Transaction", "Tokens", "Vote"]);
- for vote in votes {
- let vote_option = if vote.vote_option {
- total_yes_vote_value += vote.all_vote_value;
- "Yes"
- } else {
- total_no_vote_value += vote.all_vote_value;
- "No"
- };
- total_all_vote_value += vote.all_vote_value;
- table.add_row(row![
- vote.tx_hash,
- encode_base10(vote.all_vote_value, BALANCE_BASE10_DECIMALS),
- vote_option
- ]);
- }
- let outcome = if table.is_empty() {
- output.push(String::from("Votes: No votes found"));
- "Unknown"
- } else {
- output.push(String::from("Votes:"));
- output.push(format!("{table}"));
- output.push(format!(
- "Total tokens votes: {}",
- encode_base10(total_all_vote_value, BALANCE_BASE10_DECIMALS)
- ));
- let approval_ratio = (total_yes_vote_value as f64 * 100.0) / total_all_vote_value as f64;
- output.push(format!(
- "Total tokens Yes votes: {} ({approval_ratio:.2}%)",
- encode_base10(total_yes_vote_value, BALANCE_BASE10_DECIMALS)
- ));
- output.push(format!(
- "Total tokens No votes: {} ({:.2}%)",
- encode_base10(total_no_vote_value, BALANCE_BASE10_DECIMALS),
- (total_no_vote_value as f64 * 100.0) / total_all_vote_value as f64
- ));
- let dao = match lock.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
- Ok(d) => d,
- Err(e) => {
- output.push(format!("Failed to fetch DAO: {e}"));
- return
- }
- };
- if total_all_vote_value >= dao.params.dao.quorum &&
- approval_ratio >=
- (dao.params.dao.approval_ratio_quot / dao.params.dao.approval_ratio_base)
- as f64
- {
- "Approved"
- } else {
- "Rejected"
- }
- };
- if let Some(exec_tx_hash) = proposal.exec_tx_hash {
- output.push(format!("Proposal was executed on transaction: {exec_tx_hash}"));
- return
- }
- // Retrieve next block height and current block time target,
- // to compute their window.
- let next_block_height = match lock.get_next_block_height().await {
- Ok(n) => n,
- Err(e) => {
- output.push(format!("Failed to fetch next block height: {e}"));
- return
- }
- };
- let block_target = match lock.get_block_target().await {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Failed to fetch block target: {e}"));
- return
- }
- };
- let current_window = blockwindow(next_block_height, block_target);
- let end_time = proposal.proposal.creation_blockwindow + proposal.proposal.duration_blockwindows;
- let (voting_status, proposal_status_message) = if current_window < end_time {
- ("Ongoing", format!("Current proposal outcome: {outcome}"))
- } else {
- ("Concluded", format!("Proposal outcome: {outcome}"))
- };
- output.push(format!("Voting status: {voting_status}"));
- output.push(proposal_status_message);
- }
- /// Auxiliary function to define the dao proposal import subcommand handling.
- async fn handle_dao_proposal_import(
- drk: &DrkPtr,
- parts: &[&str],
- input: &[String],
- output: &mut Vec<String>,
- ) {
- // Check correct subcommand structure
- if parts.len() != 2 {
- output.push(String::from("Malformed `dao proposal-import` subcommand"));
- output.push(String::from("Usage: dao proposal-import"));
- return
- }
- // Parse line from input or fallback to stdin if its empty
- let buf = match input.len() {
- 0 => {
- let mut buf = String::new();
- if let Err(e) = stdin().read_to_string(&mut buf) {
- output.push(format!("Failed to read from stdin: {e}"));
- return
- };
- buf
- }
- 1 => input[0].clone(),
- _ => {
- output.push(String::from("Multiline input provided"));
- return
- }
- };
- let Some(bytes) = base64::decode(buf.trim()) else {
- output.push(String::from("Failed to decode encrypted proposal data"));
- return
- };
- let encrypted_proposal: AeadEncryptedNote = match deserialize_async(&bytes).await {
- Ok(e) => e,
- Err(e) => {
- output.push(format!("Failed to deserialize encrypted proposal data: {e}"));
- return
- }
- };
- let lock = drk.read().await;
- let daos = match lock.get_daos().await {
- Ok(d) => d,
- Err(e) => {
- output.push(format!("Failed to retrieve DAOs: {e}"));
- return
- }
- };
- for dao in &daos {
- // Check if we have the proposals key
- let Some(proposals_secret_key) = dao.params.proposals_secret_key else { continue };
- // Try to decrypt the proposal
- let Ok(proposal) = encrypted_proposal.decrypt::<ProposalRecord>(&proposals_secret_key)
- else {
- continue
- };
- let proposal = match lock.get_dao_proposal_by_bulla(&proposal.bulla()).await {
- Ok(p) => {
- let mut our_proposal = p;
- our_proposal.data = proposal.data;
- our_proposal
- }
- Err(_) => proposal,
- };
- if let Err(e) = lock.put_dao_proposal(&proposal).await {
- output.push(format!("Failed to put DAO proposal: {e}"));
- }
- return
- }
- output.push(String::from("Couldn't decrypt the proposal with out DAO keys"));
- }
- /// Auxiliary function to define the dao vote subcommand handling.
- async fn handle_dao_vote(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 4 && parts.len() != 5 {
- output.push(String::from("Malformed `dao vote` subcommand"));
- output.push(String::from("Usage: dao vote <bulla> <vote> [vote-weight]"));
- return
- }
- let bulla = match DaoProposalBulla::from_str(parts[2]) {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid proposal bulla: {e}"));
- return
- }
- };
- let vote = match u8::from_str(parts[3]) {
- Ok(v) => {
- if v > 1 {
- output.push(String::from("Vote can be either 0 (NO) or 1 (YES)"));
- return
- }
- v != 0
- }
- Err(e) => {
- output.push(format!("Invalid vote: {e}"));
- return
- }
- };
- let weight = if parts.len() == 5 {
- if let Err(e) = f64::from_str(parts[4]) {
- output.push(format!("Invalid vote weight: {e}"));
- return
- }
- match decode_base10(parts[4], BALANCE_BASE10_DECIMALS, true) {
- Ok(w) => Some(w),
- Err(e) => {
- output.push(format!("Error while parsing vote weight: {e}"));
- return
- }
- }
- } else {
- None
- };
- match drk.read().await.dao_vote(&bulla, vote, weight).await {
- Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
- Err(e) => output.push(format!("Failed to create DAO Vote transaction: {e}")),
- }
- }
- /// Auxiliary function to define the dao exec subcommand handling.
- async fn handle_dao_exec(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 3 && parts.len() != 4 {
- output.push(String::from("Malformed `dao exec` subcommand"));
- output.push(String::from("Usage: dao exec [--early] <bulla>"));
- return
- }
- let mut index = 2;
- let mut early = false;
- if parts[index] == "--early" {
- early = true;
- index += 1;
- }
- let bulla = match DaoProposalBulla::from_str(parts[index]) {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid proposal bulla: {e}"));
- return
- }
- };
- let lock = drk.read().await;
- let proposal = match lock.get_dao_proposal_by_bulla(&bulla).await {
- Ok(p) => p,
- Err(e) => {
- output.push(format!("Failed to fetch DAO proposal: {e}"));
- return
- }
- };
- // Identify proposal type by its auth calls
- for call in &proposal.proposal.auth_calls {
- // We only support transfer right now
- if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
- match lock.dao_exec_transfer(&proposal, early).await {
- Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
- Err(e) => output.push(format!("Failed to execute DAO transfer proposal: {e}")),
- };
- return
- }
- }
- // If proposal has no auth calls, we consider it a generic one
- if proposal.proposal.auth_calls.is_empty() {
- match lock.dao_exec_generic(&proposal, early).await {
- Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
- Err(e) => output.push(format!("Failed to execute DAO generic proposal: {e}")),
- };
- return
- }
- output.push(String::from("Unsuported DAO proposal"));
- }
- /// Auxiliary function to define the dao spent hook subcommand handling.
- async fn handle_dao_spend_hook(parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 2 {
- output.push(String::from("Malformed `dao spent-hook` subcommand"));
- output.push(String::from("Usage: dao spent-hook"));
- return
- }
- let spend_hook =
- FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }.to_func_id();
- output.push(format!("{spend_hook}"));
- }
- /// Auxiliary function to define the dao mining config subcommand handling.
- async fn handle_dao_mining_config(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 3 {
- output.push(String::from("Malformed `dao mining-config` subcommand"));
- output.push(String::from("Usage: dao mining-config <name>"));
- return
- }
- if let Err(e) = drk.read().await.dao_mining_config(parts[2], output).await {
- output.push(format!("Failed to generate DAO mining configuration: {e}"));
- }
- }
- /// Auxiliary function to define the attach fee command handling.
- async fn handle_attach_fee(drk: &DrkPtr, input: &[String], output: &mut Vec<String>) {
- let mut tx = match parse_tx_from_input(input).await {
- Ok(t) => t,
- Err(e) => {
- output.push(format!("Error while parsing transaction: {e}"));
- return
- }
- };
- match drk.read().await.attach_fee(&mut tx).await {
- Ok(_) => output.push(base64::encode(&serialize_async(&tx).await)),
- Err(e) => output.push(format!("Failed to attach the fee call to the transaction: {e}")),
- }
- }
- /// Auxiliary function to define the inspect command handling.
- async fn handle_inspect(input: &[String], output: &mut Vec<String>) {
- match parse_tx_from_input(input).await {
- Ok(tx) => output.push(format!("{tx:#?}")),
- Err(e) => output.push(format!("Error while parsing transaction: {e}")),
- }
- }
- /// Auxiliary function to define the broadcast command handling.
- async fn handle_broadcast(drk: &DrkPtr, input: &[String], output: &mut Vec<String>) {
- let tx = match parse_tx_from_input(input).await {
- Ok(t) => t,
- Err(e) => {
- output.push(format!("Error while parsing transaction: {e}"));
- return
- }
- };
- let lock = drk.read().await;
- if let Err(e) = lock.simulate_tx(&tx).await {
- output.push(format!("Failed to simulate tx: {e}"));
- return
- };
- if let Err(e) = lock.mark_tx_spend(&tx, output).await {
- output.push(format!("Failed to mark transaction coins as spent: {e}"));
- return
- };
- match lock.broadcast_tx(&tx, output).await {
- Ok(txid) => output.push(format!("Transaction ID: {txid}")),
- Err(e) => output.push(format!("Failed to broadcast transaction: {e}")),
- }
- }
- /// Auxiliary function to define the subscribe command handling.
- async fn handle_subscribe(
- drk: &DrkPtr,
- endpoint: &Url,
- subscription_active: &mut bool,
- subscription_tasks: &[StoppableTaskPtr; 2],
- shell_sender: &Sender<Vec<String>>,
- ex: &ExecutorPtr,
- ) {
- // Kill zombie tasks if they failed
- subscription_tasks[0].stop_nowait();
- subscription_tasks[1].stop_nowait();
- *subscription_active = true;
- // Start the subscription task
- let drk_ = drk.clone();
- let rpc_task_ = subscription_tasks[1].clone();
- let shell_sender_ = shell_sender.clone();
- let endpoint_ = endpoint.clone();
- let ex_ = ex.clone();
- subscription_tasks[0].clone().start(
- async move { subscribe_blocks(&drk_, rpc_task_, shell_sender_, endpoint_, &ex_).await },
- |_| async { /* Do nothing */ },
- Error::DetachedTaskStopped,
- ex.clone(),
- );
- }
- /// Auxiliary function to define the unsubscribe command handling.
- async fn handle_unsubscribe(
- subscription_active: &mut bool,
- subscription_tasks: &[StoppableTaskPtr; 2],
- ) {
- subscription_tasks[0].stop_nowait();
- subscription_tasks[1].stop_nowait();
- *subscription_active = false;
- }
- /// Auxiliary function to define the scan command handling.
- async fn handle_scan(
- drk: &DrkPtr,
- subscription_active: &bool,
- parts: &[&str],
- output: &mut Vec<String>,
- print: &bool,
- ) {
- if *subscription_active {
- append_or_print(output, None, print, vec![String::from("Subscription is already active!")])
- .await;
- return
- }
- // Check correct command structure
- if parts.len() != 1 && parts.len() != 3 {
- append_or_print(output, None, print, vec![String::from("Malformed `scan` command")]).await;
- return
- }
- // Check if reset was requested
- let lock = drk.read().await;
- if parts.len() == 3 {
- if parts[1] != "--reset" {
- append_or_print(
- output,
- None,
- print,
- vec![
- String::from("Malformed `scan` command"),
- String::from("Usage: scan --reset <height>"),
- ],
- )
- .await;
- return
- }
- let height = match u32::from_str(parts[2]) {
- Ok(h) => h,
- Err(e) => {
- append_or_print(output, None, print, vec![format!("Invalid reset height: {e}")])
- .await;
- return
- }
- };
- let mut buf = vec![];
- if let Err(e) = lock.reset_to_height(height, &mut buf).await {
- buf.push(format!("Failed during wallet reset: {e}"));
- append_or_print(output, None, print, buf).await;
- return
- }
- append_or_print(output, None, print, buf).await;
- }
- if let Err(e) = lock.scan_blocks(output, None, print).await {
- append_or_print(output, None, print, vec![format!("Failed during scanning: {e}")]).await;
- return
- }
- append_or_print(output, None, print, vec![String::from("Finished scanning blockchain")]).await;
- }
- /// Auxiliary function to define the explorer command handling.
- async fn handle_explorer(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
- // Check correct command structure
- if parts.len() < 2 {
- output.push(String::from("Malformed `explorer` command"));
- output.push(String::from(
- "Usage: explorer (fetch-tx|simulate-tx|txs-history|clear-reverted|scanned-blocks|mining-config)",
- ));
- return
- }
- // Handle subcommand
- match parts[1] {
- "fetch-tx" => handle_explorer_fetch_tx(drk, parts, output).await,
- "simulate-tx" => handle_explorer_simulate_tx(drk, parts, input, output).await,
- "txs-history" => handle_explorer_txs_history(drk, parts, output).await,
- "clear-reverted" => handle_explorer_clear_reverted(drk, parts, output).await,
- "scanned-blocks" => handle_explorer_scanned_blocks(drk, parts, output).await,
- "mining-config" => handle_explorer_mining_config(parts, input, output).await,
- _ => {
- output.push(format!("Unrecognized explorer subcommand: {}", parts[1]));
- output.push(String::from(
- "Usage: explorer (fetch-tx|simulate-tx|txs-history|clear-reverted|scanned-blocks|mining-config)",
- ));
- }
- }
- }
- /// Auxiliary function to define the explorer fetch transaction subcommand handling.
- async fn handle_explorer_fetch_tx(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 3 && parts.len() != 4 {
- output.push(String::from("Malformed `explorer fetch-tx` subcommand"));
- output.push(String::from("Usage: explorer fetch-tx [--encode] <tx-hash>"));
- return
- }
- let mut index = 2;
- let mut encode = false;
- if parts[index] == "--encode" {
- encode = true;
- index += 1;
- }
- let hash = match blake3::Hash::from_hex(parts[index]) {
- Ok(h) => h,
- Err(e) => {
- output.push(format!("Invalid transaction hash: {e}"));
- return
- }
- };
- let tx_hash = TransactionHash(*hash.as_bytes());
- let tx = match drk.read().await.get_tx(&tx_hash).await {
- Ok(tx) => tx,
- Err(e) => {
- output.push(format!("Failed to fetch transaction: {e}"));
- return
- }
- };
- let Some(tx) = tx else {
- output.push(String::from("Transaction was not found"));
- return
- };
- // Make sure the tx is correct
- if tx.hash() != tx_hash {
- output.push(format!("Transaction hash missmatch: {tx_hash} - {}", tx.hash()));
- return
- }
- if encode {
- output.push(base64::encode(&serialize_async(&tx).await));
- return
- }
- output.push(format!("Transaction ID: {tx_hash}"));
- output.push(format!("{tx:?}"));
- }
- /// Auxiliary function to define the explorer simulate transaction subcommand handling.
- async fn handle_explorer_simulate_tx(
- drk: &DrkPtr,
- parts: &[&str],
- input: &[String],
- output: &mut Vec<String>,
- ) {
- // Check correct subcommand structure
- if parts.len() != 2 {
- output.push(String::from("Malformed `explorer simulate-tx` subcommand"));
- output.push(String::from("Usage: explorer simulate-tx"));
- return
- }
- let tx = match parse_tx_from_input(input).await {
- Ok(t) => t,
- Err(e) => {
- output.push(format!("Error while parsing transaction: {e}"));
- return
- }
- };
- match drk.read().await.simulate_tx(&tx).await {
- Ok(is_valid) => {
- output.push(format!("Transaction ID: {}", tx.hash()));
- output.push(format!("State: {}", if is_valid { "valid" } else { "invalid" }));
- }
- Err(e) => output.push(format!("Failed to simulate tx: {e}")),
- }
- }
- /// Auxiliary function to define the explorer transactions history subcommand handling.
- async fn handle_explorer_txs_history(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct command structure
- if parts.len() < 2 || parts.len() > 4 {
- output.push(String::from("Malformed `explorer txs-history` command"));
- output.push(String::from("Usage: explorer txs-history [--encode] [tx-hash]"));
- return
- }
- let lock = drk.read().await;
- if parts.len() > 2 {
- let mut index = 2;
- let mut encode = false;
- if parts[index] == "--encode" {
- encode = true;
- index += 1;
- }
- let (tx_hash, status, block_height, tx) =
- match lock.get_tx_history_record(parts[index]).await {
- Ok(i) => i,
- Err(e) => {
- output.push(format!("Failed to fetch transaction: {e}"));
- return
- }
- };
- if encode {
- output.push(base64::encode(&serialize_async(&tx).await));
- return
- }
- output.push(format!("Transaction ID: {tx_hash}"));
- output.push(format!("Status: {status}"));
- match block_height {
- Some(block_height) => output.push(format!("Block height: {block_height}")),
- None => output.push(String::from("Block height: -")),
- }
- output.push(format!("{tx:?}"));
- return
- }
- let map = match lock.get_txs_history() {
- Ok(m) => m,
- Err(e) => {
- output.push(format!("Failed to retrieve transactions history records: {e}"));
- return
- }
- };
- // Create a prettytable with the new data:
- let mut table = Table::new();
- table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
- table.set_titles(row!["Transaction Hash", "Status", "Block Height"]);
- for (txs_hash, status, block_height) in map.iter() {
- let block_height = match block_height {
- Some(block_height) => block_height.to_string(),
- None => String::from("-"),
- };
- table.add_row(row![txs_hash, status, block_height]);
- }
- if table.is_empty() {
- output.push(String::from("No transactions found"));
- } else {
- output.push(format!("{table}"));
- }
- }
- /// Auxiliary function to define the explorer clear reverted subcommand handling.
- async fn handle_explorer_clear_reverted(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 2 {
- output.push(String::from("Malformed `explorer clear-reverted` subcommand"));
- output.push(String::from("Usage: explorer clear-reverted"));
- return
- }
- if let Err(e) = drk.read().await.remove_reverted_txs(output) {
- output.push(format!("Failed to remove reverted transactions: {e}"));
- }
- }
- /// Auxiliary function to define the explorer scanned blocks subcommand handling.
- async fn handle_explorer_scanned_blocks(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 2 && parts.len() != 3 {
- output.push(String::from("Malformed `explorer scanned-blocks` subcommand"));
- output.push(String::from("Usage: explorer scanned-blocks [height]"));
- return
- }
- let lock = drk.read().await;
- if parts.len() == 3 {
- let height = match u32::from_str(parts[2]) {
- Ok(d) => d,
- Err(e) => {
- output.push(format!("Invalid height: {e}"));
- return
- }
- };
- match lock.get_scanned_block(&height) {
- Ok((hash, signing_key)) => {
- output.push(format!("Height: {height}"));
- output.push(format!("Hash: {hash}"));
- output.push(format!("Signing key: {signing_key}"));
- }
- Err(e) => output.push(format!("Failed to retrieve scanned block record: {e}")),
- };
- return
- }
- let map = match lock.get_scanned_block_records() {
- Ok(m) => m,
- Err(e) => {
- output.push(format!("Failed to retrieve scanned blocks records: {e}"));
- return
- }
- };
- let table = prettytable_scanned_blocks(&map);
- if table.is_empty() {
- output.push(String::from("No scanned blocks records found"));
- } else {
- output.push(format!("{table}"));
- }
- }
- /// Auxiliary function to define the explorer mining config subcommand handling.
- async fn handle_explorer_mining_config(parts: &[&str], input: &[String], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 2 {
- output.push(String::from("Malformed `explorer mining-config` subcommand"));
- output.push(String::from("Usage: explorer mining-config"));
- return
- }
- let (config, recipient, spend_hook, user_data) =
- match parse_mining_config_from_input(input).await {
- Ok(c) => c,
- Err(e) => {
- output.push(format!("Error while parsing mining config: {e}"));
- return
- }
- };
- display_mining_config(&config, &recipient, &spend_hook, &user_data, output)
- }
- /// Auxiliary function to define the alias command handling.
- async fn handle_alias(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct command structure
- if parts.len() < 2 {
- output.push(String::from("Malformed `alias` command"));
- output.push(String::from("Usage: alias (add|show|remove)"));
- return
- }
- // Handle subcommand
- match parts[1] {
- "add" => handle_alias_add(drk, parts, output).await,
- "show" => handle_alias_show(drk, parts, output).await,
- "remove" => handle_alias_remove(drk, parts, output).await,
- _ => {
- output.push(format!("Unrecognized alias subcommand: {}", parts[1]));
- output.push(String::from("Usage: alias (add|show|remove)"));
- }
- }
- }
- /// Auxiliary function to define the alias add subcommand handling.
- async fn handle_alias_add(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 4 {
- output.push(String::from("Malformed `alias add` subcommand"));
- output.push(String::from("Usage: alias add <alias> <token>"));
- return
- }
- if parts[2].len() > 5 {
- output.push(String::from("Error: Alias exceeds 5 characters"));
- return
- }
- let token_id = match TokenId::from_str(parts[3]) {
- Ok(t) => t,
- Err(e) => {
- output.push(format!("Invalid Token ID: {e}"));
- return
- }
- };
- if let Err(e) = drk.read().await.add_alias(String::from(parts[2]), token_id, output).await {
- output.push(format!("Failed to add alias: {e}"));
- }
- }
- /// Auxiliary function to define the alias show subcommand handling.
- async fn handle_alias_show(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct command structure
- if parts.len() != 2 && parts.len() != 4 && parts.len() != 6 {
- output.push(String::from("Malformed `alias show` command"));
- output.push(String::from("Usage: alias show [-a, --alias <alias>] [-t, --token <token>]"));
- return
- }
- let mut alias = None;
- let mut token_id = None;
- if parts.len() > 2 {
- let mut index = 2;
- if parts[index] == "-a" || parts[index] == "--alias" {
- alias = Some(String::from(parts[index + 1]));
- index += 2;
- }
- if index < parts.len() && (parts[index] == "-t" || parts[index] == "--token") {
- match TokenId::from_str(parts[index + 1]) {
- Ok(t) => token_id = Some(t),
- Err(e) => {
- output.push(format!("Invalid Token ID: {e}"));
- return
- }
- };
- index += 2;
- }
- // Check alias again in case it was after token
- if index < parts.len() && (parts[index] == "-a" || parts[index] == "--alias") {
- alias = Some(String::from(parts[index + 1]));
- }
- }
- let map = match drk.read().await.get_aliases(alias, token_id).await {
- Ok(m) => m,
- Err(e) => {
- output.push(format!("Failed to fetch aliases map: {e}"));
- return
- }
- };
- let table = prettytable_aliases(&map);
- if table.is_empty() {
- output.push(String::from("No aliases found"));
- } else {
- output.push(format!("{table}"));
- }
- }
- /// Auxiliary function to define the alias remove subcommand handling.
- async fn handle_alias_remove(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 3 {
- output.push(String::from("Malformed `alias remove` subcommand"));
- output.push(String::from("Usage: alias remove <alias>"));
- return
- }
- if let Err(e) = drk.read().await.remove_alias(String::from(parts[2]), output).await {
- output.push(format!("Failed to remove alias: {e}"));
- }
- }
- /// Auxiliary function to define the token command handling.
- async fn handle_token(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct command structure
- if parts.len() < 2 {
- output.push(String::from("Malformed `token` command"));
- output.push(String::from("Usage: token (import|generate-mint|list|mint|freeze)"));
- return
- }
- // Handle subcommand
- match parts[1] {
- "import" => handle_token_import(drk, parts, output).await,
- "generate-mint" => handle_token_generate_mint(drk, parts, output).await,
- "list" => handle_token_list(drk, parts, output).await,
- "mint" => handle_token_mint(drk, parts, output).await,
- "freeze" => handle_token_freeze(drk, parts, output).await,
- _ => {
- output.push(format!("Unrecognized token subcommand: {}", parts[1]));
- output.push(String::from("Usage: token (import|generate-mint|list|mint|freeze)"));
- }
- }
- }
- /// Auxiliary function to define the token import subcommand handling.
- async fn handle_token_import(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 4 {
- output.push(String::from("Malformed `token import` subcommand"));
- output.push(String::from("Usage: token import <secret-key> <token-blind>"));
- return
- }
- let mint_authority = match SecretKey::from_str(parts[2]) {
- Ok(ma) => ma,
- Err(e) => {
- output.push(format!("Invalid mint authority: {e}"));
- return
- }
- };
- let token_blind = match BaseBlind::from_str(parts[3]) {
- Ok(tb) => tb,
- Err(e) => {
- output.push(format!("Invalid token blind: {e}"));
- return
- }
- };
- match drk.read().await.import_mint_authority(mint_authority, token_blind).await {
- Ok(token_id) => {
- output.push(format!("Successfully imported mint authority for token ID: {token_id}"))
- }
- Err(e) => output.push(format!("Failed to import mint authority: {e}")),
- }
- }
- /// Auxiliary function to define the token generate mint subcommand handling.
- async fn handle_token_generate_mint(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 2 {
- output.push(String::from("Malformed `token generate-mint` subcommand"));
- output.push(String::from("Usage: token generate-mint"));
- return
- }
- let mint_authority = SecretKey::random(&mut OsRng);
- let token_blind = BaseBlind::random(&mut OsRng);
- match drk.read().await.import_mint_authority(mint_authority, token_blind).await {
- Ok(token_id) => {
- output.push(format!("Successfully imported mint authority for token ID: {token_id}"))
- }
- Err(e) => output.push(format!("Failed to import mint authority: {e}")),
- }
- }
- /// Auxiliary function to define the token list subcommand handling.
- async fn handle_token_list(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 2 {
- output.push(String::from("Malformed `token list` subcommand"));
- output.push(String::from("Usage: token list"));
- return
- }
- let lock = drk.read().await;
- let tokens = match lock.get_mint_authorities().await {
- Ok(m) => m,
- Err(e) => {
- output.push(format!("Failed to fetch mint authorities: {e}"));
- return
- }
- };
- let aliases_map = match lock.get_aliases_mapped_by_token().await {
- Ok(m) => m,
- Err(e) => {
- output.push(format!("Failed to fetch aliases map: {e}"));
- return
- }
- };
- let table = prettytable_tokenlist(&tokens, &aliases_map);
- if table.is_empty() {
- output.push(String::from("No tokens found"));
- } else {
- output.push(format!("{table}"));
- }
- }
- /// Auxiliary function to define the token mint subcommand handling.
- async fn handle_token_mint(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct command structure
- if parts.len() < 5 || parts.len() > 7 {
- output.push(String::from("Malformed `token mint` subcommand"));
- output.push(String::from(
- "Usage: token mint <token> <amount> <recipient> [spend-hook] [user-data]",
- ));
- return
- }
- let amount = String::from(parts[3]);
- if let Err(e) = f64::from_str(&amount) {
- output.push(format!("Invalid amount: {e}"));
- return
- }
- let rcpt = match Address::from_str(parts[4]) {
- Ok(r) => r,
- Err(e) => {
- output.push(format!("Invalid recipient: {e}"));
- return
- }
- };
- let lock = drk.read().await;
- if rcpt.network() != lock.network {
- output.push("Recipient address prefix mismatch".to_string());
- return
- }
- let token_id = match lock.get_token(String::from(parts[2])).await {
- Ok(t) => t,
- Err(e) => {
- output.push(format!("Invalid token ID: {e}"));
- return
- }
- };
- // Parse command
- let mut index = 5;
- let spend_hook = if index < parts.len() {
- match FuncId::from_str(parts[index]) {
- Ok(s) => Some(s),
- Err(e) => {
- output.push(format!("Invalid spend hook: {e}"));
- return
- }
- }
- } else {
- None
- };
- index += 1;
- let user_data = if index < parts.len() {
- let bytes = match bs58::decode(&parts[index]).into_vec() {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid user data: {e}"));
- return
- }
- };
- let bytes: [u8; 32] = match bytes.try_into() {
- Ok(b) => b,
- Err(e) => {
- output.push(format!("Invalid user data: {e:?}"));
- return
- }
- };
- let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
- Some(v) => v,
- None => {
- output.push(String::from("Invalid user data"));
- return
- }
- };
- Some(elem)
- } else {
- None
- };
- match lock.mint_token(&amount, *rcpt.public_key(), token_id, spend_hook, user_data).await {
- Ok(t) => output.push(base64::encode(&serialize_async(&t).await)),
- Err(e) => output.push(format!("Failed to create token mint transaction: {e}")),
- }
- }
- /// Auxiliary function to define the token freeze subcommand handling.
- async fn handle_token_freeze(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 3 {
- output.push(String::from("Malformed `token freeze` subcommand"));
- output.push(String::from("Usage: token freeze <token>"));
- return
- }
- let lock = drk.read().await;
- let token_id = match lock.get_token(String::from(parts[2])).await {
- Ok(t) => t,
- Err(e) => {
- output.push(format!("Invalid token ID: {e}"));
- return
- }
- };
- match lock.freeze_token(token_id).await {
- Ok(t) => output.push(base64::encode(&serialize_async(&t).await)),
- Err(e) => output.push(format!("Failed to create token freeze transaction: {e}")),
- }
- }
- /// Auxiliary function to define the contract command handling.
- async fn handle_contract(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct command structure
- if parts.len() < 2 {
- output.push(String::from("Malformed `contract` command"));
- output.push(String::from("Usage: contract (generate-deploy|list|export-data|deploy|lock)"));
- return
- }
- // Handle subcommand
- match parts[1] {
- "generate-deploy" => handle_contract_generate_deploy(drk, parts, output).await,
- "list" => handle_contract_list(drk, parts, output).await,
- "export-data" => handle_contract_export_data(drk, parts, output).await,
- "deploy" => handle_contract_deploy(drk, parts, output).await,
- "lock" => handle_contract_lock(drk, parts, output).await,
- _ => {
- output.push(format!("Unrecognized contract subcommand: {}", parts[1]));
- output.push(String::from(
- "Usage: contract (generate-deploy|list|export-data|deploy|lock)",
- ));
- }
- }
- }
- /// Auxiliary function to define the contract generate deploy subcommand handling.
- async fn handle_contract_generate_deploy(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 2 {
- output.push(String::from("Malformed `contract generate-deploy` subcommand"));
- output.push(String::from("Usage: contract generate-deploy"));
- return
- }
- if let Err(e) = drk.read().await.deploy_auth_keygen(output).await {
- output.push(format!("Error creating deploy auth keypair: {e}"));
- }
- }
- /// Auxiliary function to define the contract list subcommand handling.
- async fn handle_contract_list(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 2 && parts.len() != 3 {
- output.push(String::from("Malformed `contract list` subcommand"));
- output.push(String::from("Usage: contract list [contract-id]"));
- return
- }
- if parts.len() == 3 {
- let deploy_auth = match ContractId::from_str(parts[2]) {
- Ok(d) => d,
- Err(e) => {
- output.push(format!("Invalid deploy authority: {e}"));
- return
- }
- };
- let history = match drk.read().await.get_deploy_auth_history(&deploy_auth).await {
- Ok(a) => a,
- Err(e) => {
- output.push(format!("Failed to fetch deploy authority history records: {e}"));
- return
- }
- };
- let table = prettytable_contract_history(&history);
- if table.is_empty() {
- output.push(String::from("No history records found"));
- } else {
- output.push(format!("{table}"));
- }
- return
- }
- let auths = match drk.read().await.list_deploy_auth().await {
- Ok(a) => a,
- Err(e) => {
- output.push(format!("Failed to fetch deploy authorities: {e}"));
- return
- }
- };
- let table = prettytable_contract_auth(&auths);
- if table.is_empty() {
- output.push(String::from("No deploy authorities found"));
- } else {
- output.push(format!("{table}"));
- }
- }
- /// Auxiliary function to define the contract export data subcommand handling.
- async fn handle_contract_export_data(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 3 {
- output.push(String::from("Malformed `contract export-data` subcommand"));
- output.push(String::from("Usage: contract export-data <tx-hash>"));
- return
- }
- match drk.read().await.get_deploy_history_record_data(parts[2]).await {
- Ok(pair) => output.push(base64::encode(&serialize_async(&pair).await)),
- Err(e) => output.push(format!("Failed to retrieve history record: {e}")),
- }
- }
- /// Auxiliary function to define the contract deploy subcommand handling.
- async fn handle_contract_deploy(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 4 && parts.len() != 5 {
- output.push(String::from("Malformed `contract deploy` subcommand"));
- output.push(String::from("Usage: contract deploy <deploy-auth> <wasm-path> [deploy-ix]"));
- return
- }
- let deploy_auth = match ContractId::from_str(parts[2]) {
- Ok(d) => d,
- Err(e) => {
- output.push(format!("Invalid deploy authority: {e}"));
- return
- }
- };
- // Read the wasm bincode and deploy instruction
- let file_path = match expand_path(parts[3]) {
- Ok(p) => p,
- Err(e) => {
- output.push(format!("Error while expanding wasm bincode file path: {e}"));
- return
- }
- };
- let wasm_bin = match smol::fs::read(file_path).await {
- Ok(w) => w,
- Err(e) => {
- output.push(format!("Error while reading wasm bincode file: {e}"));
- return
- }
- };
- let deploy_ix = if parts.len() == 5 {
- let file_path = match expand_path(parts[4]) {
- Ok(p) => p,
- Err(e) => {
- output.push(format!("Error while expanding deploy instruction file path: {e}"));
- return
- }
- };
- match smol::fs::read(file_path).await {
- Ok(d) => d,
- Err(e) => {
- output.push(format!("Error while reading deploy instruction file: {e}"));
- return
- }
- }
- } else {
- vec![]
- };
- match drk.read().await.deploy_contract(&deploy_auth, wasm_bin, deploy_ix).await {
- Ok(t) => output.push(base64::encode(&serialize_async(&t).await)),
- Err(e) => output.push(format!("Failed to create contract deployment transaction: {e}")),
- }
- }
- /// Auxiliary function to define the contract lock subcommand handling.
- async fn handle_contract_lock(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
- // Check correct subcommand structure
- if parts.len() != 3 {
- output.push(String::from("Malformed `contract lock` subcommand"));
- output.push(String::from("Usage: contract lock <deploy-auth>"));
- return
- }
- let deploy_auth = match ContractId::from_str(parts[2]) {
- Ok(d) => d,
- Err(e) => {
- output.push(format!("Invalid deploy authority: {e}"));
- return
- }
- };
- match drk.read().await.lock_contract(&deploy_auth).await {
- Ok(t) => output.push(base64::encode(&serialize_async(&t).await)),
- Err(e) => output.push(format!("Failed to create contract lock transaction: {e}")),
- }
- }
|