Skip to content

Commit

Permalink
cleaning
Browse files Browse the repository at this point in the history
  • Loading branch information
kent-3 committed Oct 20, 2024
1 parent 5a3ce34 commit c05518e
Show file tree
Hide file tree
Showing 8 changed files with 115 additions and 272 deletions.
123 changes: 30 additions & 93 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
#![allow(unused)]
#![allow(mixed_script_confusables)]
#![allow(confusable_idents)]

// use codee::string::FromToStringCodec;
// use leptos_use::storage::use_local_storage;
Expand All @@ -10,14 +8,10 @@ use leptos::{
html::{Dialog, Input},
logging::log,
prelude::*,
reactive::graph::ReactiveNode,
};
use leptos_router::components::{ParentRoute, Route, Router, Routes, A};
use leptos_router_macro::path;
use rsecret::{
query::{bank::BankQuerier, compute::ComputeQuerier},
secret_client::CreateQuerierOptions,
};
use rsecret::query::{bank::BankQuerier, compute::ComputeQuerier};
use secret_toolkit_snip20::{QueryMsg, TokenInfoResponse};
use secretrs::utils::EnigmaUtils;
use send_wrapper::SendWrapper;
Expand All @@ -41,7 +35,7 @@ use constants::{CHAIN_ID, GRPC_URL};
use error::Error;
use keplr::{Keplr, Key};
use routes::{pool::*, trade::*};
use state::{ChainId, Endpoint, KeplrSignals, ProviderConfig, TokenMap};
use state::{ChainId, Endpoint, KeplrSignals, TokenMap};
use types::Coin;

#[component]
Expand All @@ -50,28 +44,18 @@ pub fn App() -> impl IntoView {

// Global Contexts

// provide_context(RwSignal::new(ProviderConfig::new(GRPC_URL, CHAIN_ID)));
provide_context(Endpoint::default());
provide_context(ChainId::default());
provide_context(KeplrSignals::new());
provide_context(TokenMap::new());

// let provider =
// use_context::<RwSignal<ProviderConfig>>().expect("provider config context missing!");
let endpoint = use_context::<Endpoint>().expect("endpoint context missing!");
let chain_id = use_context::<ChainId>().expect("chain id context missing!");
let keplr = use_context::<KeplrSignals>().expect("keplr signals context missing!");
let token_map = use_context::<TokenMap>().expect("tokens context missing!");

debug!("Loaded {} tokens", token_map.len());

// Effect::new(move |_| {
// let provider = provider.get();
// debug!(
// "Endpoint: {}\nChain ID: {}",
// provider.url, provider.chain_id
// )
// });
Effect::new(move |_| {
let enabled = keplr.enabled.get();
let key = keplr.key.get();
Expand All @@ -90,10 +74,10 @@ pub fn App() -> impl IntoView {
keplr.enabled.set(true);
});

// let update_grpc_url = move |_| {
// debug!("updating client_options.grpc_url");
// wasm_client.set(Client::new("https://foobar.com".to_string()))
// };
on_cleanup(move || {
info!("cleaning up <App/>");
keplr_keystorechange_handle.remove()
});

// Actions

Expand Down Expand Up @@ -127,38 +111,19 @@ pub fn App() -> impl IntoView {

// on:click handlers

let enable_keplr = move |_| {
let enable_keplr = move |_: MouseEvent| {
enable_keplr_action.dispatch(());
};

// let disable_keplr = move |_| {
// keplr_sys::disable(CHAIN_ID);
// keplr.enabled.set(false);
// keplr.key.set(None);
// };
let disable_keplr = move |_: MouseEvent| {
Keplr::disable(CHAIN_ID);
keplr.enabled.set(false);
};

// Node references

let options_dialog_ref = NodeRef::<Dialog>::new();

// Effects

// open the dialog whenever the "enable_keplr_action" is pending
// Effect::new(move |_| match dialog_ref.get() {
// Some(dialog) => match enable_keplr_action.pending().get() {
// true => {
// let _ = dialog.show_modal();
// }
// false => dialog.close(),
// },
// None => (),
// });

Owner::on_cleanup(move || {
info!("cleaning up <Aoo/>");
keplr_keystorechange_handle.remove()
});

// HTML Elements

let toggle_options_menu = move |_| match options_dialog_ref.get() {
Expand All @@ -180,7 +145,6 @@ pub fn App() -> impl IntoView {
<div class="background-image"></div>
<header>
<div class="flex justify-between items-center">
// <span class="italic font-extrabold">ρ</span>
<div class="my-3 font-bold text-3xl line-clamp-1">"Trader Crow 2"</div>
<Show when=move || keplr.key.get().and_then(|key| key.ok()).is_some()>
<p class="hidden sm:block text-sm outline outline-2 outline-offset-8 outline-neutral-500">
Expand Down Expand Up @@ -338,27 +302,6 @@ fn Home() -> impl IntoView {
let keplr = use_context::<KeplrSignals>().expect("keplr signals context missing!");
let token_map = use_context::<TokenMap>().expect("tokens context missing!");

// whenever the key store changes, this will re-set 'is_keplr_enabled' to true, triggering a
// reload of everything subscribed to that signal
let keplr_keystorechange_handle =
window_event_listener_untyped("keplr_keystorechange", move |_| {
keplr.enabled.set(true);
});

on_cleanup(move || {
info!("cleaning up <Home/>");
keplr_keystorechange_handle.remove()
});

// Effect::new(move |_| {
// if keplr.enabled.get() {
// spawn_local(async move {
// let key: Option<Key> = Keplr::get_key(CHAIN_ID).await.ok();
// keplr.key.set(key);
// })
// }
// });

let viewing_keys = Resource::new(
move || keplr.key.track(),
move |_| {
Expand All @@ -380,6 +323,7 @@ fn Home() -> impl IntoView {
));
}
}
debug!("Found {} viewing keys.", keys.len());
keys
} else {
vec![]
Expand Down Expand Up @@ -408,29 +352,25 @@ fn Home() -> impl IntoView {
})
};

let user_balance = AsyncDerived::new_unsync(move || {
let client = Client::new(endpoint.get());
async move {
if let Some(Ok(key)) = keplr.key.get() {
let user_balance = Resource::new(
move || keplr.key.track(),
move |_| {
let client = Client::new(endpoint.get());
SendWrapper::new(async move {
let bank = BankQuerier::new(client);
match bank.balance(key.bech32_address, "uscrt").await {
Ok(balance) => {
let balance: Coin = balance.balance.unwrap().into();
Ok(balance.to_string())
}
// TODO: do better with these Error semantics
Err(error) => {
error!("{error}");
Err(Error::from(error))
}
}
} else {
Err(Error::generic("no wallet key found"))
}
}
});
let key = keplr.key.await?;

let encryption_utils = EnigmaUtils::new(None, "secret-4").unwrap();
bank.balance(key.bech32_address, "uscrt")
.await
.map(|balance| Coin::from(balance.balance.unwrap()))
.map_err(Error::from)
.inspect(|coin| debug!("{coin:?}"))
.inspect_err(|err| error!("{err:?}"))
})
},
);

let enigma_utils = EnigmaUtils::new(None, "secret-4").unwrap();

// TODO: move all static resources like this (query response is always the same) to a separate
// module. Implement caching with local storage. They can all use a random account for the
Expand All @@ -442,7 +382,7 @@ fn Home() -> impl IntoView {
move |_| {
debug!("loading token_info resource");
let compute =
ComputeQuerier::new(Client::new(endpoint.get()), encryption_utils.clone().into());
ComputeQuerier::new(Client::new(endpoint.get()), enigma_utils.clone().into());
SendWrapper::new(async move {
let query = QueryMsg::TokenInfo {};
compute
Expand Down Expand Up @@ -524,9 +464,6 @@ fn Modal() -> impl IntoView {
log!("show modal");
let node = dialog_ref.get().unwrap();
node.show_modal().expect("I don't know what I expected");

// Example using context
// ctx.keplr_enabled.update(|value| *value = !*value);
};
let close_modal = move |_| {
log!("close modal");
Expand Down
31 changes: 6 additions & 25 deletions src/routes/nav.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,12 @@ use leptos_router::components::A;
#[component]
pub fn Nav() -> impl IntoView {
view! {
<header class="header">
<nav class="inner">
<A href="/home">
<strong>"HN"</strong>
</A>
<A href="/new">
<strong>"New"</strong>
</A>
<A href="/show">
<strong>"Show"</strong>
</A>
<A href="/ask">
<strong>"Ask"</strong>
</A>
<A href="/job">
<strong>"Jobs"</strong>
</A>
<a
class="github"
href="http://github.com/leptos-rs/leptos"
target="_blank"
rel="noreferrer"
>
"Built with Leptos"
</a>
<header>
<nav>
<A href="/trader-crow-leptos/">"Home"</A>
<A href="/trader-crow-leptos/pool">"Pool"</A>
<A href="/trader-crow-leptos/trade">"Trade"</A>
<A href="/trader-crow-leptos/analytics">"Analytics"</A>
</nav>
</header>
}
Expand Down
7 changes: 5 additions & 2 deletions src/routes/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ use leptos_router::nested_router::Outlet;
use send_wrapper::SendWrapper;
use tracing::{debug, info};

use crate::liquidity_book::{constants::addrs::LB_FACTORY_CONTRACT, Querier};
use shade_protocol::contract_interfaces::liquidity_book::lb_factory::QueryMsg;
use crate::liquidity_book::{
constants::addrs::LB_FACTORY_CONTRACT, contract_interfaces::lb_factory::QueryMsg, Querier,
};

#[component]
pub fn Pool() -> impl IntoView {
Expand Down Expand Up @@ -45,6 +46,8 @@ pub fn Pool() -> impl IntoView {
}
}

// NOTE: If the Router gets complicated enough, it's possible to split it up like this:

// use leptos_router::{
// components::{ParentRoute, Route},
// MatchNestedRoutes,
Expand Down
4 changes: 3 additions & 1 deletion src/routes/pool/add_liquidity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ pub fn AddLiquidity() -> impl IntoView {
adjusted_value.round() as u32
}

// Might be useful to have this re-run regularly at the top-level and provide a context
// let latest_block = Resource::new(
// move || endpoint.get(),
// move |endpoint| {
Expand Down Expand Up @@ -222,6 +223,7 @@ pub fn AddLiquidity() -> impl IntoView {
};

let add_liquidity_action = Action::new(move |liquidity_parameters: &LiquidityParameters| {
// TODO: Use the dynamic versions instead.
// let url = endpoint.get();
// let chain_id = chain_id.get();
let url = GRPC_URL;
Expand All @@ -238,7 +240,7 @@ pub fn AddLiquidity() -> impl IntoView {
let wallet = Keplr::get_offline_signer_only_amino(&chain_id);
let enigma_utils = Keplr::get_enigma_utils(&chain_id).into();

// TODO: I guess I need to make this type use Strings instead of &str, because the
// TODO: I guess I need to make this type use Strings instead of &'static str, because the
// values are not static in this application (user is able to set them to anything).
let options = CreateTxSenderOptions {
url,
Expand Down
1 change: 1 addition & 0 deletions src/routes/pool/pool_creator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ pub fn PoolCreator() -> impl IntoView {
let (bin_step, set_bin_step) = signal("100".to_string());
let (active_price, set_active_price) = signal("1".to_string());

// TODO:
let create_pool = move |ev: leptos::ev::SubmitEvent| {
ev.prevent_default();
let token_x = token_x.get();
Expand Down
Loading

0 comments on commit c05518e

Please sign in to comment.