| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342 |
- /* This file is part of DarkFi (https://dark.fi)
- *
- * Copyright (C) 2020-2024 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::{
- io::{stdin, Read},
- process::exit,
- str::FromStr,
- sync::Arc,
- };
- use prettytable::{format, row, Table};
- use rand::rngs::OsRng;
- use smol::{fs::read_to_string, stream::StreamExt};
- use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
- use url::Url;
- use darkfi::{
- async_daemonize, cli_desc,
- util::{
- encoding::base64,
- parse::{decode_base10, encode_base10},
- path::{expand_path, get_config_path},
- },
- zk::halo2::Field,
- Error, Result,
- };
- use darkfi_dao_contract::{blockwindow, model::DaoProposalBulla, DaoFunction};
- use darkfi_money_contract::model::{Coin, CoinAttributes, TokenId};
- use darkfi_sdk::{
- crypto::{
- note::AeadEncryptedNote, BaseBlind, FuncId, FuncRef, PublicKey, SecretKey, DAO_CONTRACT_ID,
- },
- pasta::{group::ff::PrimeField, pallas},
- tx::TransactionHash,
- };
- use darkfi_serial::{deserialize_async, serialize_async};
- use drk::{
- cli_util::{
- generate_completions, kaching, parse_token_pair, parse_tx_from_stdin, parse_value_pair,
- },
- dao::{DaoParams, ProposalRecord},
- money::BALANCE_BASE10_DECIMALS,
- swap::PartialSwapData,
- Drk,
- };
- const CONFIG_FILE: &str = "drk_config.toml";
- const CONFIG_FILE_CONTENTS: &str = include_str!("../drk_config.toml");
- // Dev Note: when adding/modifying args here,
- // don't forget to update cli_util::generate_completions()
- #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
- #[serde(default)]
- #[structopt(name = "drk", about = cli_desc!())]
- struct Args {
- #[structopt(short, long)]
- /// Configuration file to use
- config: Option<String>,
- #[structopt(short, long, default_value = "testnet")]
- /// Blockchain network to use
- network: String,
- #[structopt(subcommand)]
- /// Sub command to execute
- command: Subcmd,
- #[structopt(short, long)]
- /// Flag indicating whether you want some fun in your life
- fun: bool,
- #[structopt(short, long)]
- /// Set log file to ouput into
- log: Option<String>,
- #[structopt(short, parse(from_occurrences))]
- /// Increase verbosity (-vvv supported)
- verbose: u8,
- }
- // Dev Note: when adding/modifying commands here,
- // don't forget to update cli_util::generate_completions()
- #[derive(Clone, Debug, Deserialize, StructOpt)]
- enum Subcmd {
- /// Fun
- Kaching,
- /// Send a ping request to the darkfid RPC endpoint
- Ping,
- /// Generate a SHELL completion script and print to stdout
- Completions {
- /// The Shell you want to generate script for
- shell: String,
- },
- /// Wallet operations
- Wallet {
- #[structopt(long)]
- /// Initialize wallet database
- initialize: bool,
- #[structopt(long)]
- /// Generate a new keypair in the wallet
- keygen: bool,
- #[structopt(long)]
- /// Query the wallet for known balances
- balance: bool,
- #[structopt(long)]
- /// Get the default address in the wallet
- address: bool,
- #[structopt(long)]
- /// Print all the addresses in the wallet
- addresses: bool,
- #[structopt(long)]
- /// Set the default address in the wallet
- default_address: Option<usize>,
- #[structopt(long)]
- /// Print all the secret keys from the wallet
- secrets: bool,
- #[structopt(long)]
- /// Import secret keys from stdin into the wallet, separated by newlines
- import_secrets: bool,
- #[structopt(long)]
- /// Print the Merkle tree in the wallet
- tree: bool,
- #[structopt(long)]
- /// Print all the coins in the wallet
- coins: bool,
- },
- /// Read a transaction from stdin and mark its input coins as spent
- Spend,
- /// Unspend a coin
- Unspend {
- /// base58-encoded coin to mark as unspent
- coin: String,
- },
- /// Create a payment transaction
- Transfer {
- /// Amount to send
- amount: String,
- /// Token ID to send
- token: String,
- /// Recipient address
- recipient: String,
- /// Optional contract spend hook to use
- spend_hook: Option<String>,
- /// Optional user data to use
- user_data: Option<String>,
- #[structopt(long)]
- /// Split the output coin into two equal halves
- half_split: bool,
- },
- /// OTC atomic swap
- Otc {
- #[structopt(subcommand)]
- /// Sub command to execute
- command: OtcSubcmd,
- },
- /// Attach the fee call to a transaction given from stdin
- AttachFee,
- /// Inspect a transaction from stdin
- Inspect,
- /// Read a transaction from stdin and broadcast it
- Broadcast,
- /// This subscription will listen for incoming blocks from darkfid and look
- /// through their transactions to see if there's any that interest us.
- /// With `drk` we look at transactions calling the money contract so we can
- /// find coins sent to us and fill our wallet with the necessary metadata.
- Subscribe,
- /// DAO functionalities
- Dao {
- #[structopt(subcommand)]
- /// Sub command to execute
- command: DaoSubcmd,
- },
- /// Scan the blockchain and parse relevant transactions
- Scan {
- #[structopt(long)]
- /// Reset Merkle tree and start scanning from first block
- reset: bool,
- },
- /// Explorer related subcommands
- Explorer {
- #[structopt(subcommand)]
- /// Sub command to execute
- command: ExplorerSubcmd,
- },
- /// Manage Token aliases
- Alias {
- #[structopt(subcommand)]
- /// Sub command to execute
- command: AliasSubcmd,
- },
- /// Token functionalities
- Token {
- #[structopt(subcommand)]
- /// Sub command to execute
- command: TokenSubcmd,
- },
- /// Contract functionalities
- Contract {
- #[structopt(subcommand)]
- /// Sub command to execute
- command: ContractSubcmd,
- },
- }
- #[derive(Clone, Debug, Deserialize, StructOpt)]
- enum OtcSubcmd {
- /// Initialize the first half of the atomic swap
- Init {
- /// Value pair to send:recv (11.55:99.42)
- #[structopt(short, long)]
- value_pair: String,
- /// Token pair to send:recv (f00:b4r)
- #[structopt(short, long)]
- token_pair: String,
- },
- /// Build entire swap tx given the first half from stdin
- Join,
- /// Inspect a swap half or the full swap tx from stdin
- Inspect,
- /// Sign a swap transaction given from stdin
- Sign,
- }
- #[derive(Clone, Debug, Deserialize, StructOpt)]
- enum DaoSubcmd {
- /// Create DAO parameters
- Create {
- /// The minimum amount of governance tokens needed to open a proposal for this DAO
- proposer_limit: String,
- /// Minimal threshold of participating total tokens needed for a proposal to pass
- quorum: String,
- /// The ratio of winning votes/total votes needed for a proposal to pass (2 decimals)
- approval_ratio: f64,
- /// DAO's governance token ID
- gov_token_id: String,
- },
- /// View DAO data from stdin
- View,
- /// Import DAO data from stdin
- Import {
- /// Name identifier for the DAO
- name: String,
- },
- /// List imported DAOs (or info about a specific one)
- List {
- /// Name identifier for the DAO (optional)
- name: Option<String>,
- },
- /// Show the balance of a DAO
- Balance {
- /// Name identifier for the DAO
- name: String,
- },
- /// Mint an imported DAO on-chain
- Mint {
- /// Name identifier for the DAO
- name: String,
- },
- /// Create a transfer proposal for a DAO
- ProposeTransfer {
- /// Name identifier for the DAO
- name: String,
- /// Duration of the proposal, in block windows
- duration: u64,
- /// Amount to send
- amount: String,
- /// Token ID to send
- token: String,
- /// Recipient address
- recipient: String,
- /// Optional contract spend hook to use
- spend_hook: Option<String>,
- /// Optional user data to use
- user_data: Option<String>,
- },
- /// List DAO proposals
- Proposals {
- /// Name identifier for the DAO
- name: String,
- },
- /// View a DAO proposal data
- Proposal {
- /// Bulla identifier for the proposal
- bulla: String,
- #[structopt(long)]
- /// Encrypt the proposal and encode it to base64
- export: bool,
- #[structopt(long)]
- /// Create the proposal transaction
- mint_proposal: bool,
- },
- /// Import a base64 encoded and encrypted proposal from stdin
- ProposalImport,
- /// Vote on a given proposal
- Vote {
- /// Bulla identifier for the proposal
- bulla: String,
- /// Vote (0 for NO, 1 for YES)
- vote: u8,
- /// Optional vote weight (amount of governance tokens)
- vote_weight: Option<String>,
- },
- /// Execute a DAO proposal
- Exec {
- /// Bulla identifier for the proposal
- bulla: String,
- },
- /// Print the DAO contract base58-encoded spend hook
- SpendHook,
- }
- #[derive(Clone, Debug, Deserialize, StructOpt)]
- enum ExplorerSubcmd {
- /// Fetch a blockchain transaction by hash
- FetchTx {
- /// Transaction hash
- tx_hash: String,
- #[structopt(long)]
- /// Print the full transaction information
- full: bool,
- #[structopt(long)]
- /// Encode transaction to base58
- encode: bool,
- },
- /// Read a transaction from stdin and simulate it
- SimulateTx,
- /// Fetch broadcasted transactions history
- TxsHistory {
- /// Fetch specific history record (optional)
- tx_hash: Option<String>,
- #[structopt(long)]
- /// Encode specific history record transaction to base58
- encode: bool,
- },
- }
- #[derive(Clone, Debug, Deserialize, StructOpt)]
- enum AliasSubcmd {
- /// Create a Token alias
- Add {
- /// Token alias
- alias: String,
- /// Token to create alias for
- token: String,
- },
- /// Print alias info of optional arguments.
- /// If no argument is provided, list all the aliases in the wallet.
- Show {
- /// Token alias to search for
- #[structopt(short, long)]
- alias: Option<String>,
- /// Token to search alias for
- #[structopt(short, long)]
- token: Option<String>,
- },
- /// Remove a Token alias
- Remove {
- /// Token alias to remove
- alias: String,
- },
- }
- #[derive(Clone, Debug, Deserialize, StructOpt)]
- enum TokenSubcmd {
- /// Import a mint authority
- Import {
- /// Mint authority secret key
- secret_key: String,
- /// Mint authority token blind
- token_blind: String,
- },
- /// Generate a new mint authority
- GenerateMint,
- /// List token IDs with available mint authorities
- List,
- /// Mint tokens
- Mint {
- /// Token ID to mint
- token: String,
- /// Amount to mint
- amount: String,
- /// Recipient of the minted tokens
- recipient: String,
- /// Optional contract spend hook to use
- spend_hook: Option<String>,
- /// Optional user data to use
- user_data: Option<String>,
- },
- /// Freeze a token mint
- Freeze {
- /// Token ID to freeze
- token: String,
- },
- }
- #[derive(Clone, Debug, Deserialize, StructOpt)]
- enum ContractSubcmd {
- /// Generate a new deploy authority
- GenerateDeploy,
- /// List deploy authorities in the wallet
- List,
- /// Deploy a smart contract
- Deploy {
- /// Contract ID (deploy authority)
- deploy_auth: u64,
- /// Path to contract wasm bincode
- wasm_path: String,
- /// Path to serialized deploy instruction
- deploy_ix: String,
- },
- /// Lock a smart contract
- Lock {
- /// Contract ID (deploy authority)
- deploy_auth: u64,
- },
- }
- /// Defines a blockchain network configuration.
- /// Default values correspond to a local network.
- #[derive(Clone, Debug, serde::Deserialize, structopt::StructOpt, structopt_toml::StructOptToml)]
- #[structopt()]
- struct BlockchainNetwork {
- #[structopt(long, default_value = "~/.local/darkfi/drk/localnet/wallet.db")]
- /// Path to wallet database
- wallet_path: String,
- #[structopt(long, default_value = "changeme")]
- /// Password for the wallet database
- wallet_pass: String,
- #[structopt(short, long, default_value = "tcp://127.0.0.1:8240")]
- /// darkfid JSON-RPC endpoint
- endpoint: Url,
- }
- /// Auxiliary function to parse darkfid configuration file and extract requested
- /// blockchain network config.
- async fn parse_blockchain_config(
- config: Option<String>,
- network: &str,
- ) -> Result<BlockchainNetwork> {
- // Grab config path
- let config_path = get_config_path(config, CONFIG_FILE)?;
- // Parse TOML file contents
- let contents = read_to_string(&config_path).await?;
- let contents: toml::Value = match toml::from_str(&contents) {
- Ok(v) => v,
- Err(e) => {
- eprintln!("Failed parsing TOML config: {e}");
- return Err(Error::ParseFailed("Failed parsing TOML config"))
- }
- };
- // Grab requested network config
- let Some(table) = contents.as_table() else { return Err(Error::ParseFailed("TOML not a map")) };
- let Some(network_configs) = table.get("network_config") else {
- return Err(Error::ParseFailed("TOML does not contain network configurations"))
- };
- let Some(network_configs) = network_configs.as_table() else {
- return Err(Error::ParseFailed("`network_config` not a map"))
- };
- let Some(network_config) = network_configs.get(network) else {
- return Err(Error::ParseFailed("TOML does not contain requested network configuration"))
- };
- let network_config = toml::to_string(&network_config).unwrap();
- let network_config =
- match BlockchainNetwork::from_iter_with_toml::<Vec<String>>(&network_config, vec![]) {
- Ok(v) => v,
- Err(e) => {
- eprintln!("Failed parsing requested network configuration: {e}");
- return Err(Error::ParseFailed("Failed parsing requested network configuration"))
- }
- };
- Ok(network_config)
- }
- async_daemonize!(realmain);
- async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
- // Grab blockchain network configuration
- let blockchain_config = match args.network.as_str() {
- "localnet" => parse_blockchain_config(args.config, "localnet").await?,
- "testnet" => parse_blockchain_config(args.config, "testnet").await?,
- "mainnet" => parse_blockchain_config(args.config, "mainnet").await?,
- _ => {
- eprintln!("Unsupported chain `{}`", args.network);
- return Err(Error::UnsupportedChain)
- }
- };
- match args.command {
- Subcmd::Kaching => {
- if !args.fun {
- println!("Apparently you don't like fun...");
- return Ok(())
- }
- kaching().await;
- Ok(())
- }
- Subcmd::Ping => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- drk.ping().await?;
- drk.stop_rpc_client().await
- }
- Subcmd::Completions { shell } => generate_completions(&shell),
- Subcmd::Wallet {
- initialize,
- keygen,
- balance,
- address,
- addresses,
- default_address,
- secrets,
- import_secrets,
- tree,
- coins,
- } => {
- if !initialize &&
- !keygen &&
- !balance &&
- !address &&
- !addresses &&
- default_address.is_none() &&
- !secrets &&
- !tree &&
- !coins &&
- !import_secrets
- {
- eprintln!("Error: You must use at least one flag for this subcommand");
- eprintln!("Run with \"wallet -h\" to see the subcommand usage.");
- exit(2);
- }
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- if initialize {
- drk.initialize_wallet()?;
- if let Err(e) = drk.initialize_money().await {
- eprintln!("Failed to initialize Money: {e:?}");
- exit(2);
- }
- if let Err(e) = drk.initialize_dao().await {
- eprintln!("Failed to initialize DAO: {e:?}");
- exit(2);
- }
- if let Err(e) = drk.initialize_deployooor() {
- eprintln!("Failed to initialize Deployooor: {e:?}");
- exit(2);
- }
- return Ok(())
- }
- if keygen {
- if let Err(e) = drk.money_keygen().await {
- eprintln!("Failed to generate keypair: {e:?}");
- exit(2);
- }
- return Ok(())
- }
- if balance {
- let balmap = drk.money_balance().await?;
- let aliases_map = drk.get_aliases_mapped_by_token().await?;
- // 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!["Token ID", "Aliases", "Balance"]);
- for (token_id, balance) in balmap.iter() {
- let aliases = match aliases_map.get(token_id) {
- Some(a) => a,
- None => "-",
- };
- table.add_row(row![
- token_id,
- aliases,
- encode_base10(*balance, BALANCE_BASE10_DECIMALS)
- ]);
- }
- if table.is_empty() {
- println!("No unspent balances found");
- } else {
- println!("{table}");
- }
- return Ok(())
- }
- if address {
- let address = match drk.default_address().await {
- Ok(a) => a,
- Err(e) => {
- eprintln!("Failed to fetch default address: {e:?}");
- exit(2);
- }
- };
- println!("{address}");
- return Ok(())
- }
- if addresses {
- let addresses = drk.addresses().await?;
- // 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!["Key ID", "Public Key", "Secret Key", "Is Default"]);
- for (key_id, public_key, secret_key, is_default) in addresses {
- let is_default = match is_default {
- 1 => "*",
- _ => "",
- };
- table.add_row(row![key_id, public_key, secret_key, is_default]);
- }
- if table.is_empty() {
- println!("No addresses found");
- } else {
- println!("{table}");
- }
- return Ok(())
- }
- if let Some(idx) = default_address {
- if let Err(e) = drk.set_default_address(idx) {
- eprintln!("Failed to set default address: {e:?}");
- exit(2);
- }
- return Ok(())
- }
- if secrets {
- let v = drk.get_money_secrets().await?;
- for i in v {
- println!("{i}");
- }
- return Ok(())
- }
- if import_secrets {
- let mut secrets = vec![];
- let lines = stdin().lines();
- for (i, line) in lines.enumerate() {
- if let Ok(line) = line {
- let bytes = bs58::decode(&line.trim()).into_vec()?;
- let Ok(secret) = deserialize_async(&bytes).await else {
- println!("Warning: Failed to deserialize secret on line {i}");
- continue
- };
- secrets.push(secret);
- }
- }
- let pubkeys = match drk.import_money_secrets(secrets).await {
- Ok(p) => p,
- Err(e) => {
- eprintln!("Failed to import secret keys into wallet: {e:?}");
- exit(2);
- }
- };
- for key in pubkeys {
- println!("{key}");
- }
- return Ok(())
- }
- if tree {
- let tree = drk.get_money_tree().await?;
- println!("{tree:#?}");
- return Ok(())
- }
- if coins {
- let coins = drk.get_coins(true).await?;
- let aliases_map = drk.get_aliases_mapped_by_token().await?;
- if coins.is_empty() {
- return Ok(())
- }
- let mut table = Table::new();
- table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
- table.set_titles(row![
- "Coin",
- "Spent",
- "Token ID",
- "Aliases",
- "Value",
- "Spend Hook",
- "User Data",
- "Spent TX"
- ]);
- for coin in coins {
- let aliases = match aliases_map.get(&coin.0.note.token_id.to_string()) {
- Some(a) => a,
- None => "-",
- };
- let spend_hook = if coin.0.note.spend_hook != FuncId::none() {
- format!("{}", coin.0.note.spend_hook)
- } else {
- String::from("-")
- };
- let user_data = if coin.0.note.user_data != pallas::Base::ZERO {
- bs58::encode(&serialize_async(&coin.0.note.user_data).await)
- .into_string()
- .to_string()
- } else {
- String::from("-")
- };
- table.add_row(row![
- bs58::encode(&serialize_async(&coin.0.coin.inner()).await)
- .into_string()
- .to_string(),
- coin.1,
- coin.0.note.token_id,
- aliases,
- format!(
- "{} ({})",
- coin.0.note.value,
- encode_base10(coin.0.note.value, BALANCE_BASE10_DECIMALS)
- ),
- spend_hook,
- user_data,
- coin.2
- ]);
- }
- println!("{table}");
- return Ok(())
- }
- unreachable!()
- }
- Subcmd::Spend => {
- let tx = parse_tx_from_stdin().await?;
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- if let Err(e) = drk.mark_tx_spend(&tx).await {
- eprintln!("Failed to mark transaction coins as spent: {e:?}");
- exit(2);
- };
- Ok(())
- }
- Subcmd::Unspend { coin } => {
- let bytes: [u8; 32] = match bs58::decode(&coin).into_vec()?.try_into() {
- Ok(b) => b,
- Err(e) => {
- eprintln!("Invalid coin: {e:?}");
- exit(2);
- }
- };
- let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
- Some(v) => v,
- None => {
- eprintln!("Invalid coin");
- exit(2);
- }
- };
- let coin = Coin::from(elem);
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- if let Err(e) = drk.unspend_coin(&coin).await {
- eprintln!("Failed to mark coin as unspent: {e:?}");
- exit(2);
- }
- Ok(())
- }
- Subcmd::Transfer { amount, token, recipient, spend_hook, user_data, half_split } => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- if let Err(e) = f64::from_str(&amount) {
- eprintln!("Invalid amount: {e:?}");
- exit(2);
- }
- let rcpt = match PublicKey::from_str(&recipient) {
- Ok(r) => r,
- Err(e) => {
- eprintln!("Invalid recipient: {e:?}");
- exit(2);
- }
- };
- let token_id = match drk.get_token(token).await {
- Ok(t) => t,
- Err(e) => {
- eprintln!("Invalid token alias: {e:?}");
- exit(2);
- }
- };
- let spend_hook = match spend_hook {
- Some(s) => match FuncId::from_str(&s) {
- Ok(s) => Some(s),
- Err(e) => {
- eprintln!("Invalid spend hook: {e:?}");
- exit(2);
- }
- },
- None => None,
- };
- let user_data = match user_data {
- Some(u) => {
- let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
- Ok(b) => b,
- Err(e) => {
- eprintln!("Invalid user data: {e:?}");
- exit(2);
- }
- };
- match pallas::Base::from_repr(bytes).into() {
- Some(v) => Some(v),
- None => {
- eprintln!("Invalid user data");
- exit(2);
- }
- }
- }
- None => None,
- };
- let tx = match drk
- .transfer(&amount, token_id, rcpt, spend_hook, user_data, half_split)
- .await
- {
- Ok(t) => t,
- Err(e) => {
- eprintln!("Failed to create payment transaction: {e:?}");
- exit(2);
- }
- };
- println!("{}", base64::encode(&serialize_async(&tx).await));
- drk.stop_rpc_client().await
- }
- Subcmd::Otc { command } => match command {
- OtcSubcmd::Init { value_pair, token_pair } => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- let value_pair = parse_value_pair(&value_pair)?;
- let token_pair = parse_token_pair(&drk, &token_pair).await?;
- let half = match drk.init_swap(value_pair, token_pair, None, None, None).await {
- Ok(h) => h,
- Err(e) => {
- eprintln!("Failed to create swap transaction half: {e:?}");
- exit(2);
- }
- };
- println!("{}", base64::encode(&serialize_async(&half).await));
- drk.stop_rpc_client().await
- }
- OtcSubcmd::Join => {
- let mut buf = String::new();
- stdin().read_to_string(&mut buf)?;
- let Some(bytes) = base64::decode(buf.trim()) else {
- eprintln!("Failed to decode partial swap data");
- exit(2);
- };
- let partial: PartialSwapData = deserialize_async(&bytes).await?;
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- let tx = match drk.join_swap(partial, None, None, None).await {
- Ok(tx) => tx,
- Err(e) => {
- eprintln!("Failed to create a join swap transaction: {e:?}");
- exit(2);
- }
- };
- println!("{}", base64::encode(&serialize_async(&tx).await));
- drk.stop_rpc_client().await
- }
- OtcSubcmd::Inspect => {
- let mut buf = String::new();
- stdin().read_to_string(&mut buf)?;
- let Some(bytes) = base64::decode(buf.trim()) else {
- eprintln!("Failed to decode swap transaction");
- exit(2);
- };
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- if let Err(e) = drk.inspect_swap(bytes).await {
- eprintln!("Failed to inspect swap: {e:?}");
- exit(2);
- };
- Ok(())
- }
- OtcSubcmd::Sign => {
- let mut tx = parse_tx_from_stdin().await?;
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- if let Err(e) = drk.sign_swap(&mut tx).await {
- eprintln!("Failed to sign joined swap transaction: {e:?}");
- exit(2);
- };
- println!("{}", base64::encode(&serialize_async(&tx).await));
- Ok(())
- }
- },
- Subcmd::Dao { command } => match command {
- DaoSubcmd::Create { proposer_limit, quorum, approval_ratio, gov_token_id } => {
- if let Err(e) = f64::from_str(&proposer_limit) {
- eprintln!("Invalid proposer limit: {e:?}");
- exit(2);
- }
- if let Err(e) = f64::from_str(&quorum) {
- eprintln!("Invalid quorum: {e:?}");
- exit(2);
- }
- let proposer_limit = decode_base10(&proposer_limit, BALANCE_BASE10_DECIMALS, true)?;
- let quorum = decode_base10(&quorum, BALANCE_BASE10_DECIMALS, true)?;
- if approval_ratio > 1.0 {
- eprintln!("Error: Approval ratio cannot be >1.0");
- exit(2);
- }
- let approval_ratio_base = 100_u64;
- let approval_ratio_quot = (approval_ratio * approval_ratio_base as f64) as u64;
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- let gov_token_id = match drk.get_token(gov_token_id).await {
- Ok(g) => g,
- Err(e) => {
- eprintln!("Invalid Token ID: {e:?}");
- exit(2);
- }
- };
- let secret_key = SecretKey::random(&mut OsRng);
- let bulla_blind = BaseBlind::random(&mut OsRng);
- let params = DaoParams::new(
- proposer_limit,
- quorum,
- approval_ratio_base,
- approval_ratio_quot,
- gov_token_id,
- secret_key,
- bulla_blind,
- );
- let encoded = bs58::encode(&serialize_async(¶ms).await).into_string();
- println!("{encoded}");
- Ok(())
- }
- DaoSubcmd::View => {
- let mut buf = String::new();
- stdin().read_to_string(&mut buf)?;
- let bytes = bs58::decode(&buf.trim()).into_vec()?;
- let dao_params: DaoParams = deserialize_async(&bytes).await?;
- println!("{dao_params}");
- Ok(())
- }
- DaoSubcmd::Import { name } => {
- let mut buf = String::new();
- stdin().read_to_string(&mut buf)?;
- let bytes = bs58::decode(&buf.trim()).into_vec()?;
- let params: DaoParams = deserialize_async(&bytes).await?;
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- if let Err(e) = drk.import_dao(&name, params).await {
- eprintln!("Failed to import DAO: {e:?}");
- exit(2);
- }
- Ok(())
- }
- DaoSubcmd::List { name } => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- if let Err(e) = drk.dao_list(&name).await {
- eprintln!("Failed to list DAO: {e:?}");
- exit(2);
- }
- Ok(())
- }
- DaoSubcmd::Balance { name } => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- let balmap = match drk.dao_balance(&name).await {
- Ok(b) => b,
- Err(e) => {
- eprintln!("Failed to fetch DAO balance: {e:?}");
- exit(2);
- }
- };
- let aliases_map = match drk.get_aliases_mapped_by_token().await {
- Ok(a) => a,
- Err(e) => {
- eprintln!("Failed to fetch wallet aliases: {e:?}");
- exit(2);
- }
- };
- // 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!["Token ID", "Aliases", "Balance"]);
- for (token_id, balance) in balmap.iter() {
- let aliases = match aliases_map.get(token_id) {
- Some(a) => a,
- None => "-",
- };
- table.add_row(row![
- token_id,
- aliases,
- encode_base10(*balance, BALANCE_BASE10_DECIMALS)
- ]);
- }
- if table.is_empty() {
- println!("No unspent balances found");
- } else {
- println!("{table}");
- }
- Ok(())
- }
- DaoSubcmd::Mint { name } => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- let tx = match drk.dao_mint(&name).await {
- Ok(tx) => tx,
- Err(e) => {
- eprintln!("Failed to mint DAO: {e:?}");
- exit(2);
- }
- };
- println!("{}", base64::encode(&serialize_async(&tx).await));
- drk.stop_rpc_client().await
- }
- DaoSubcmd::ProposeTransfer {
- name,
- duration,
- amount,
- token,
- recipient,
- spend_hook,
- user_data,
- } => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- if let Err(e) = f64::from_str(&amount) {
- eprintln!("Invalid amount: {e:?}");
- exit(2);
- }
- let rcpt = match PublicKey::from_str(&recipient) {
- Ok(r) => r,
- Err(e) => {
- eprintln!("Invalid recipient: {e:?}");
- exit(2);
- }
- };
- let token_id = match drk.get_token(token).await {
- Ok(t) => t,
- Err(e) => {
- eprintln!("Invalid token alias: {e:?}");
- exit(2);
- }
- };
- let spend_hook = match spend_hook {
- Some(s) => match FuncId::from_str(&s) {
- Ok(s) => Some(s),
- Err(e) => {
- eprintln!("Invalid spend hook: {e:?}");
- exit(2);
- }
- },
- None => None,
- };
- let user_data = match user_data {
- Some(u) => {
- let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
- Ok(b) => b,
- Err(e) => {
- eprintln!("Invalid user data: {e:?}");
- exit(2);
- }
- };
- match pallas::Base::from_repr(bytes).into() {
- Some(v) => Some(v),
- None => {
- eprintln!("Invalid user data");
- exit(2);
- }
- }
- }
- None => None,
- };
- let proposal = match drk
- .dao_propose_transfer(
- &name, duration, &amount, token_id, rcpt, spend_hook, user_data,
- )
- .await
- {
- Ok(p) => p,
- Err(e) => {
- eprintln!("Failed to create DAO transfer proposal: {e:?}");
- exit(2);
- }
- };
- println!("Generated proposal: {}", proposal.bulla());
- drk.stop_rpc_client().await
- }
- DaoSubcmd::Proposals { name } => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- let proposals = drk.get_dao_proposals(&name).await?;
- for (i, proposal) in proposals.iter().enumerate() {
- println!("{i}. {}", proposal.bulla());
- }
- Ok(())
- }
- DaoSubcmd::Proposal { bulla, export, mint_proposal } => {
- let bulla = match DaoProposalBulla::from_str(&bulla) {
- Ok(b) => b,
- Err(e) => {
- eprintln!("Invalid proposal bulla: {e:?}");
- exit(2);
- }
- };
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- let proposal = drk.get_dao_proposal_by_bulla(&bulla).await?;
- if export {
- // Retrieve the DAO
- let dao = drk.get_dao_by_bulla(&proposal.proposal.dao_bulla).await?;
- // Encypt the proposal
- let enc_note = AeadEncryptedNote::encrypt(
- &proposal,
- &dao.params.dao.public_key,
- &mut OsRng,
- )
- .unwrap();
- // Export it to base64
- println!("{}", base64::encode(&serialize_async(&enc_note).await));
- return drk.stop_rpc_client().await
- }
- if mint_proposal {
- for call in &proposal.proposal.auth_calls {
- if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
- let tx = match drk.dao_transfer_proposal_tx(&proposal).await {
- Ok(tx) => tx,
- Err(e) => {
- eprintln!("Failed to create DAO transfer proposal: {e:?}");
- exit(2);
- }
- };
- println!("{}", base64::encode(&serialize_async(&tx).await));
- return drk.stop_rpc_client().await
- }
- }
- eprintln!("Unsuported DAO proposal");
- exit(2);
- }
- println!("{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 =
- deserialize_async(proposal.data.as_ref().unwrap()).await?;
- 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",
- coin.public_key,
- "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));
- }
- }
- println!("{contract_calls}");
- let votes = drk.get_dao_proposal_votes(&bulla).await?;
- 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() {
- println!("Votes: No votes found");
- "Rejected"
- } else {
- println!("Votes:");
- println!("{table}");
- println!(
- "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;
- println!(
- "Total tokens Yes votes: {} ({approval_ratio:.2}%)",
- encode_base10(total_yes_vote_value, BALANCE_BASE10_DECIMALS)
- );
- println!(
- "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 = drk.get_dao_by_bulla(&proposal.proposal.dao_bulla).await?;
- 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 {
- println!("Proposal was executed on transaction: {exec_tx_hash}");
- return drk.stop_rpc_client().await
- }
- // Retrieve next block height and current block time target,
- // to compute their window.
- let next_block_height = drk.get_next_block_height().await?;
- let block_target = drk.get_block_target().await?;
- 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}"))
- };
- println!("Voting status: {voting_status}");
- println!("{proposal_status_message}");
- drk.stop_rpc_client().await
- }
- DaoSubcmd::ProposalImport {} => {
- let mut buf = String::new();
- stdin().read_to_string(&mut buf)?;
- let Some(bytes) = base64::decode(buf.trim()) else {
- eprintln!("Failed to decode encrypted proposal data");
- exit(2);
- };
- let encrypted_proposal: AeadEncryptedNote = deserialize_async(&bytes).await?;
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- // Retrieve all DAOs to try to decrypt the proposal
- let daos = drk.get_daos().await?;
- for dao in &daos {
- if let Ok(proposal) =
- encrypted_proposal.decrypt::<ProposalRecord>(&dao.params.secret_key)
- {
- let proposal = match drk.get_dao_proposal_by_bulla(&proposal.bulla()).await
- {
- Ok(p) => {
- let mut our_proposal = p;
- our_proposal.data = proposal.data;
- our_proposal
- }
- Err(_) => proposal,
- };
- return drk.put_dao_proposal(&proposal).await
- }
- }
- eprintln!("Couldn't decrypt the proposal with out DAO keys");
- exit(2);
- }
- DaoSubcmd::Vote { bulla, vote, vote_weight } => {
- let bulla = match DaoProposalBulla::from_str(&bulla) {
- Ok(b) => b,
- Err(e) => {
- eprintln!("Invalid proposal bulla: {e:?}");
- exit(2);
- }
- };
- if vote > 1 {
- eprintln!("Vote can be either 0 (NO) or 1 (YES)");
- exit(2);
- }
- let vote = vote != 0;
- let weight = match vote_weight {
- Some(w) => {
- if let Err(e) = f64::from_str(&w) {
- eprintln!("Invalid vote weight: {e:?}");
- exit(2);
- }
- Some(decode_base10(&w, BALANCE_BASE10_DECIMALS, true)?)
- }
- None => None,
- };
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- let tx = match drk.dao_vote(&bulla, vote, weight).await {
- Ok(tx) => tx,
- Err(e) => {
- eprintln!("Failed to create DAO Vote transaction: {e:?}");
- exit(2);
- }
- };
- println!("{}", base64::encode(&serialize_async(&tx).await));
- drk.stop_rpc_client().await
- }
- DaoSubcmd::Exec { bulla } => {
- let bulla = match DaoProposalBulla::from_str(&bulla) {
- Ok(b) => b,
- Err(e) => {
- eprintln!("Invalid proposal bulla: {e:?}");
- exit(2);
- }
- };
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- let proposal = drk.get_dao_proposal_by_bulla(&bulla).await?;
- for call in &proposal.proposal.auth_calls {
- if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
- let tx = match drk.dao_exec_transfer(&proposal).await {
- Ok(tx) => tx,
- Err(e) => {
- eprintln!("Failed to execute DAO transfer proposal: {e:?}");
- exit(2);
- }
- };
- println!("{}", base64::encode(&serialize_async(&tx).await));
- return drk.stop_rpc_client().await
- }
- }
- eprintln!("Unsuported DAO proposal");
- exit(2);
- }
- DaoSubcmd::SpendHook => {
- let spend_hook =
- FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
- .to_func_id();
- println!("{spend_hook}");
- Ok(())
- }
- },
- Subcmd::AttachFee => {
- let mut tx = parse_tx_from_stdin().await?;
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- if let Err(e) = drk.attach_fee(&mut tx).await {
- eprintln!("Failed to attach the fee call to the transaction: {e:?}");
- exit(2);
- };
- println!("{}", base64::encode(&serialize_async(&tx).await));
- drk.stop_rpc_client().await
- }
- Subcmd::Inspect => {
- let tx = parse_tx_from_stdin().await?;
- println!("{tx:#?}");
- Ok(())
- }
- Subcmd::Broadcast => {
- let tx = parse_tx_from_stdin().await?;
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- if let Err(e) = drk.simulate_tx(&tx).await {
- eprintln!("Failed to simulate tx: {e:?}");
- exit(2);
- };
- if let Err(e) = drk.mark_tx_spend(&tx).await {
- eprintln!("Failed to mark transaction coins as spent: {e:?}");
- exit(2);
- };
- let txid = match drk.broadcast_tx(&tx).await {
- Ok(t) => t,
- Err(e) => {
- eprintln!("Failed to broadcast transaction: {e:?}");
- exit(2);
- }
- };
- println!("Transaction ID: {txid}");
- drk.stop_rpc_client().await
- }
- Subcmd::Subscribe => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint.clone()),
- ex.clone(),
- args.fun,
- )
- .await?;
- if let Err(e) = drk.subscribe_blocks(blockchain_config.endpoint, ex).await {
- eprintln!("Block subscription failed: {e:?}");
- exit(2);
- }
- drk.stop_rpc_client().await
- }
- Subcmd::Scan { reset } => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- if reset {
- println!("Reset requested.");
- if let Err(e) = drk.scan_blocks(true).await {
- eprintln!("Failed during scanning: {e:?}");
- exit(2);
- }
- println!("Finished scanning blockchain");
- return drk.stop_rpc_client().await
- }
- if let Err(e) = drk.scan_blocks(false).await {
- eprintln!("Failed during scanning: {e:?}");
- exit(2);
- }
- println!("Finished scanning blockchain");
- drk.stop_rpc_client().await
- }
- Subcmd::Explorer { command } => match command {
- ExplorerSubcmd::FetchTx { tx_hash, full, encode } => {
- let tx_hash = TransactionHash(*blake3::Hash::from_hex(&tx_hash)?.as_bytes());
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- let tx = match drk.get_tx(&tx_hash).await {
- Ok(tx) => tx,
- Err(e) => {
- eprintln!("Failed to fetch transaction: {e:?}");
- exit(2);
- }
- };
- let Some(tx) = tx else {
- println!("Transaction was not found");
- exit(1);
- };
- // Make sure the tx is correct
- assert_eq!(tx.hash(), tx_hash);
- if encode {
- println!("{}", base64::encode(&serialize_async(&tx).await));
- exit(1)
- }
- println!("Transaction ID: {tx_hash}");
- if full {
- println!("{tx:?}");
- }
- drk.stop_rpc_client().await
- }
- ExplorerSubcmd::SimulateTx => {
- let tx = parse_tx_from_stdin().await?;
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- let is_valid = match drk.simulate_tx(&tx).await {
- Ok(b) => b,
- Err(e) => {
- eprintln!("Failed to simulate tx: {e:?}");
- exit(2);
- }
- };
- println!("Transaction ID: {}", tx.hash());
- println!("State: {}", if is_valid { "valid" } else { "invalid" });
- drk.stop_rpc_client().await
- }
- ExplorerSubcmd::TxsHistory { tx_hash, encode } => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- if let Some(c) = tx_hash {
- let (tx_hash, status, tx) = drk.get_tx_history_record(&c).await?;
- if encode {
- println!("{}", base64::encode(&serialize_async(&tx).await));
- exit(1)
- }
- println!("Transaction ID: {tx_hash}");
- println!("Status: {status}");
- println!("{tx:?}");
- return Ok(())
- }
- let map = match drk.get_txs_history() {
- Ok(m) => m,
- Err(e) => {
- eprintln!("Failed to retrieve transactions history records: {e:?}");
- exit(2);
- }
- };
- // 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"]);
- for (txs_hash, status) in map.iter() {
- table.add_row(row![txs_hash, status]);
- }
- if table.is_empty() {
- println!("No transactions found");
- } else {
- println!("{table}");
- }
- Ok(())
- }
- },
- Subcmd::Alias { command } => match command {
- AliasSubcmd::Add { alias, token } => {
- if alias.chars().count() > 5 {
- eprintln!("Error: Alias exceeds 5 characters");
- exit(2);
- }
- let token_id = match TokenId::from_str(token.as_str()) {
- Ok(t) => t,
- Err(e) => {
- eprintln!("Invalid Token ID: {e:?}");
- exit(2);
- }
- };
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- if let Err(e) = drk.add_alias(alias, token_id).await {
- eprintln!("Failed to add alias: {e:?}");
- exit(2);
- }
- Ok(())
- }
- AliasSubcmd::Show { alias, token } => {
- let token_id = match token {
- Some(t) => match TokenId::from_str(t.as_str()) {
- Ok(t) => Some(t),
- Err(e) => {
- eprintln!("Invalid Token ID: {e:?}");
- exit(2);
- }
- },
- None => None,
- };
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- let map = drk.get_aliases(alias, token_id).await?;
- // 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!["Alias", "Token ID"]);
- for (alias, token_id) in map.iter() {
- table.add_row(row![alias, token_id]);
- }
- if table.is_empty() {
- println!("No aliases found");
- } else {
- println!("{table}");
- }
- Ok(())
- }
- AliasSubcmd::Remove { alias } => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- if let Err(e) = drk.remove_alias(alias).await {
- eprintln!("Failed to remove alias: {e:?}");
- exit(2);
- }
- Ok(())
- }
- },
- Subcmd::Token { command } => match command {
- TokenSubcmd::Import { secret_key, token_blind } => {
- let mint_authority = match SecretKey::from_str(&secret_key) {
- Ok(ma) => ma,
- Err(e) => {
- eprintln!("Invalid mint authority: {e:?}");
- exit(2);
- }
- };
- let token_blind = match BaseBlind::from_str(&token_blind) {
- Ok(tb) => tb,
- Err(e) => {
- eprintln!("Invalid token blind: {e:?}");
- exit(2);
- }
- };
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- let token_id = drk.import_mint_authority(mint_authority, token_blind).await?;
- println!("Successfully imported mint authority for token ID: {token_id}");
- Ok(())
- }
- TokenSubcmd::GenerateMint => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- let mint_authority = SecretKey::random(&mut OsRng);
- let token_blind = BaseBlind::random(&mut OsRng);
- let token_id = drk.import_mint_authority(mint_authority, token_blind).await?;
- println!("Successfully imported mint authority for token ID: {token_id}");
- Ok(())
- }
- TokenSubcmd::List => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- let tokens = drk.get_mint_authorities().await?;
- let aliases_map = match drk.get_aliases_mapped_by_token().await {
- Ok(map) => map,
- Err(e) => {
- eprintln!("Failed to fetch wallet aliases: {e:?}");
- exit(2);
- }
- };
- let mut table = Table::new();
- table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
- table.set_titles(row![
- "Token ID",
- "Aliases",
- "Mint Authority",
- "Token Blind",
- "Frozen"
- ]);
- for (token_id, authority, blind, frozen) in tokens {
- let aliases = match aliases_map.get(&token_id.to_string()) {
- Some(a) => a,
- None => "-",
- };
- table.add_row(row![token_id, aliases, authority, blind, frozen]);
- }
- if table.is_empty() {
- println!("No tokens found");
- } else {
- println!("{table}");
- }
- Ok(())
- }
- TokenSubcmd::Mint { token, amount, recipient, spend_hook, user_data } => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- if let Err(e) = f64::from_str(&amount) {
- eprintln!("Invalid amount: {e:?}");
- exit(2);
- }
- let rcpt = match PublicKey::from_str(&recipient) {
- Ok(r) => r,
- Err(e) => {
- eprintln!("Invalid recipient: {e:?}");
- exit(2);
- }
- };
- let token_id = match drk.get_token(token).await {
- Ok(t) => t,
- Err(e) => {
- eprintln!("Invalid Token ID: {e:?}");
- exit(2);
- }
- };
- let spend_hook = match spend_hook {
- Some(s) => match FuncId::from_str(&s) {
- Ok(s) => Some(s),
- Err(e) => {
- eprintln!("Invalid spend hook: {e:?}");
- exit(2);
- }
- },
- None => None,
- };
- let user_data = match user_data {
- Some(u) => {
- let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
- Ok(b) => b,
- Err(e) => {
- eprintln!("Invalid user data: {e:?}");
- exit(2);
- }
- };
- match pallas::Base::from_repr(bytes).into() {
- Some(v) => Some(v),
- None => {
- eprintln!("Invalid user data");
- exit(2);
- }
- }
- }
- None => None,
- };
- let tx = match drk.mint_token(&amount, rcpt, token_id, spend_hook, user_data).await
- {
- Ok(tx) => tx,
- Err(e) => {
- eprintln!("Failed to create token mint transaction: {e:?}");
- exit(2);
- }
- };
- println!("{}", base64::encode(&serialize_async(&tx).await));
- drk.stop_rpc_client().await
- }
- TokenSubcmd::Freeze { token } => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- let token_id = match drk.get_token(token).await {
- Ok(t) => t,
- Err(e) => {
- eprintln!("Invalid Token ID: {e:?}");
- exit(2);
- }
- };
- let tx = match drk.freeze_token(token_id).await {
- Ok(tx) => tx,
- Err(e) => {
- eprintln!("Failed to create token freeze transaction: {e:?}");
- exit(2);
- }
- };
- println!("{}", base64::encode(&serialize_async(&tx).await));
- drk.stop_rpc_client().await
- }
- },
- Subcmd::Contract { command } => match command {
- ContractSubcmd::GenerateDeploy => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- if let Err(e) = drk.deploy_auth_keygen().await {
- eprintln!("Error creating deploy auth keypair: {:?}", e);
- exit(2);
- }
- Ok(())
- }
- ContractSubcmd::List => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- None,
- ex,
- args.fun,
- )
- .await?;
- let auths = drk.list_deploy_auth().await?;
- let mut table = Table::new();
- table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
- table.set_titles(row!["Index", "Contract ID", "Frozen"]);
- for (idx, contract_id, frozen) in auths {
- table.add_row(row![idx, contract_id, frozen]);
- }
- if table.is_empty() {
- println!("No deploy authorities found");
- } else {
- println!("{table}");
- }
- Ok(())
- }
- ContractSubcmd::Deploy { deploy_auth, wasm_path, deploy_ix } => {
- // Read the wasm bincode and deploy instruction
- let wasm_bin = smol::fs::read(expand_path(&wasm_path)?).await?;
- let deploy_ix = smol::fs::read(expand_path(&deploy_ix)?).await?;
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- let mut tx = match drk.deploy_contract(deploy_auth, wasm_bin, deploy_ix).await {
- Ok(v) => v,
- Err(e) => {
- eprintln!("Error creating contract deployment tx: {}", e);
- exit(2);
- }
- };
- if let Err(e) = drk.attach_fee(&mut tx).await {
- eprintln!("Failed to attach the fee call to the transaction: {e:?}");
- exit(2);
- };
- println!("{}", base64::encode(&serialize_async(&tx).await));
- drk.stop_rpc_client().await
- }
- ContractSubcmd::Lock { deploy_auth } => {
- let drk = Drk::new(
- blockchain_config.wallet_path,
- blockchain_config.wallet_pass,
- Some(blockchain_config.endpoint),
- ex,
- args.fun,
- )
- .await?;
- let mut tx = match drk.lock_contract(deploy_auth).await {
- Ok(v) => v,
- Err(e) => {
- eprintln!("Error creating contract lock tx: {}", e);
- exit(2);
- }
- };
- if let Err(e) = drk.attach_fee(&mut tx).await {
- eprintln!("Failed to attach the fee call to the transaction: {e:?}");
- exit(2);
- };
- println!("{}", base64::encode(&serialize_async(&tx).await));
- drk.stop_rpc_client().await
- }
- },
- }
- }
|