From f39068c20b4be2cb0166fa9aa3e8ec608bc66346 Mon Sep 17 00:00:00 2001 From: lunar-mining Date: Wed, 29 Sep 2021 09:33:07 +0200 Subject: [PATCH] src/util: completed f64 to u64 conversion in parse_param --- src/bin/darkfid.rs | 4 +++- src/util.rs | 28 +++++++++++++++++++++------- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/bin/darkfid.rs b/src/bin/darkfid.rs index cd29b870d..7a9b1cb21 100644 --- a/src/bin/darkfid.rs +++ b/src/bin/darkfid.rs @@ -17,7 +17,9 @@ use drk::{ rpcserver::{listen_and_serve, RequestHandler, RpcServerConfig}, }, serial::{deserialize, serialize}, - util::{expand_path, join_config_path, parse_network, parse_wrapped_token, search_id}, + util::{ + expand_path, join_config_path, parse_network, parse_params, parse_wrapped_token, search_id, + }, wallet::WalletDb, Result, }; diff --git a/src/util.rs b/src/util.rs index 08ceb460d..106905181 100644 --- a/src/util.rs +++ b/src/util.rs @@ -39,7 +39,6 @@ pub fn join_config_path(file: &Path) -> Result { Ok(path) } - #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub enum NetworkName { Solana, @@ -151,21 +150,19 @@ pub fn parse_network(network: &str, token: &str) -> Result { } } -// BTC has 8 decimals -// SOL uses conversion function soltolamport() -// or there are decimals in the token info -// TODO: how to organize these functions more logically w less repetition? pub fn parse_params(network: &str, token: &str, amount: u64) -> Result<(String, u64)> { match NetworkName::from_str(network)? { NetworkName::Solana => match token { "solana" | "sol" => { let token_id = "So11111111111111111111111111111111111111112"; - let amount_in_apo: u64 = amount * 10 ^ 8; + let decimals = 9; + let amount_in_apo: u64 = amount * 10 ^ decimals; Ok((token_id.to_string(), amount_in_apo)) } tkn => { let token_id = symbol_to_id(tkn)?; - let amount_in_apo: u64 = amount * 10 ^ 8; + let decimals = search_decimal(tkn)?; + let amount_in_apo: u64 = amount * 10 ^ decimals; Ok((token_id.to_string(), amount_in_apo)) } }, @@ -205,6 +202,23 @@ pub fn search_id(symbol: &str) -> Result { unreachable!(); } +pub fn search_decimal(symbol: &str) -> Result { + // TODO: FIXME + let file_contents = std::fs::read_to_string("token/solanatokenlist.json")?; + let tokenlist: serde_json::Value = serde_json::from_str(&file_contents)?; + let tokens = tokenlist["tokens"] + .as_array() + .ok_or_else(|| Error::TokenParseError)?; + for item in tokens { + if item["symbol"] == symbol.to_uppercase() { + let decimals = item["decimals"].clone(); + let decimals = decimals.as_u64().ok_or_else(|| Error::TokenParseError)?; + return Ok(decimals); + } + } + unreachable!(); +} + #[cfg(test)] mod tests { use crate::serial::{deserialize, serialize};