Skip to content

Commit

Permalink
feat: adding events to shielded sync
Browse files Browse the repository at this point in the history
  • Loading branch information
jurevans committed Oct 31, 2024
1 parent 15e94cd commit c318d65
Show file tree
Hide file tree
Showing 7 changed files with 173 additions and 17 deletions.
51 changes: 51 additions & 0 deletions apps/namadillo/src/App/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { useTransactionCallback } from "hooks/useTransactionCallbacks";
import { useTransactionNotifications } from "hooks/useTransactionNotifications";
import { Outlet } from "react-router-dom";

import { SdkEvents } from "@heliaxdev/namada-sdk/web";
import { useEffect } from "react";
import { ChainLoader } from "./Setup/ChainLoader";

export const history = createBrowserHistory({ window });
Expand All @@ -15,6 +17,55 @@ export function App(): JSX.Element {
useTransactionNotifications();
useTransactionCallback();

// TODO: This useEffect should be removed! Just testing here:
useEffect(() => {
// eslint-disable-next-line
const onProgressBarStarted = (e: any): void => {
console.info(SdkEvents.ProgressBarStarted, e);
};

// eslint-disable-next-line
const onProgressBarIncremented = (e: any): void => {
console.info(SdkEvents.ProgressBarIncremented, e);
};

// eslint-disable-next-line
const onProgressBarFinished = (e: any): void => {
console.info(SdkEvents.ProgressBarFinished, e);
};

document.onreadystatechange = function() {
window.addEventListener(
SdkEvents.ProgressBarStarted,
onProgressBarStarted
);

window.addEventListener(
SdkEvents.ProgressBarIncremented,
onProgressBarIncremented
);
window.addEventListener(
SdkEvents.ProgressBarFinished,
onProgressBarFinished
);

return () => {
window.removeEventListener(
SdkEvents.ProgressBarStarted,
onProgressBarStarted
);
window.removeEventListener(
SdkEvents.ProgressBarIncremented,
onProgressBarIncremented
);
window.removeEventListener(
SdkEvents.ProgressBarFinished,
onProgressBarFinished
);
};
};
}, []);

return (
<>
<Toasts />
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export type {
export { TxType, TxTypeLabel } from "./tx";
export type { SupportedTx } from "./tx";

export { Sdk } from "./sdk";
export { Sdk, SdkEvents } from "./sdk";

export { publicKeyToBech32 } from "./keys";

Expand Down
6 changes: 6 additions & 0 deletions packages/sdk/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ import { Rpc } from "./rpc";
import { Signing } from "./signing";
import { Tx } from "./tx";

export enum SdkEvents {
ProgressBarStarted = "namada_sdk::progress_bar::started",
ProgressBarIncremented = "namada_sdk::progress_bar::incremented",
ProgressBarFinished = "namada_sdk::progress_bar::finished",
}

/**
* API for interacting with Namada SDK
*/
Expand Down
5 changes: 5 additions & 0 deletions packages/shared/lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ subtle-encoding = "0.5.1"
version = "0.3.4"
features = [
'console',
'Document',
'Event',
'EventTarget',
'CustomEvent',
'CustomEventInit',
'Headers',
'Request',
'RequestInit',
Expand Down
86 changes: 86 additions & 0 deletions packages/shared/lib/src/sdk/events.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
use crate::utils::to_js_result;
use serde::Serialize;
use wasm_bindgen::prelude::*;
use web_sys::{CustomEvent, CustomEventInit, Document, Event};

#[wasm_bindgen]
#[derive(Debug, Serialize)]
pub struct ProgressIncrement {
current: usize,
total: usize,
}

impl ProgressIncrement {
pub fn to_json(&self) -> JsValue {
let json = serde_json::to_value(&self).unwrap();
JsValue::from_str(&json.to_string())
}
}

/// Event constants for use in Rust
const SDK_EVENT_PROGRESS_BAR_STARTED: &str = "namada_sdk::progress_bar::started";
const SDK_EVENT_PROGRESS_BAR_INCREMENTED: &str = "namada_sdk::progress_bar::incremented";
const SDK_EVENT_PROGRESS_BAR_FINISHED: &str = "namada_sdk::progress_bar::finished";

pub struct EventDispatcher {
document: Document,
}

impl EventDispatcher {
pub fn new() -> Self {
Self {
document: web_sys::window().unwrap().document().unwrap(),
}
}

fn dispatch(&self, event: Event) -> Result<JsValue, JsError> {
to_js_result(
self.document
.dispatch_event(&event)
.map_err(|err| JsError::new(&format!("Error dispatching event: {:?}", err)))?,
)
}

fn dispatch_custom_event(&self, custom_event: CustomEvent) -> Result<JsValue, JsError> {
to_js_result(
self.document
.dispatch_event(&custom_event)
.map_err(|err| JsError::new(&format!("Error dispatching: {:?}", err)))?,
)
}

pub fn progress_bar_started(&self) -> Result<JsValue, JsError> {
// let event = Event::new(SDK_EVENT_PROGRESS_BAR_STARTED).unwrap();
let event = self.document.create_event("Event").unwrap();
event.init_event(SDK_EVENT_PROGRESS_BAR_STARTED);
self.dispatch(event)
}

pub fn progress_bar_incremented(
&self,
current: usize,
total: usize,
) -> Result<JsValue, JsError> {
let increment = ProgressIncrement { current, total };

let data = &increment.to_json();

let mut options = CustomEventInit::new();

options.detail(data);
options.bubbles(true);
options.cancelable(false);
options.composed(true);

let event =
CustomEvent::new_with_event_init_dict(SDK_EVENT_PROGRESS_BAR_INCREMENTED, &options)
.unwrap();

self.dispatch_custom_event(event)
}

pub fn progress_bar_finished(&self) -> Result<JsValue, JsError> {
let event = Event::new(SDK_EVENT_PROGRESS_BAR_FINISHED).unwrap();
self.dispatch(event)
}
}
6 changes: 6 additions & 0 deletions packages/shared/lib/src/sdk/masp/sync.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::sdk::events::EventDispatcher;
use namada_sdk::control_flow::ShutdownSignal;
use namada_sdk::io::ProgressBar;
use namada_sdk::task_env::{TaskEnvironment, TaskSpawner};
Expand Down Expand Up @@ -97,10 +98,14 @@ impl ProgressBar for ProgressBarWeb {

fn set_upper_limit(&mut self, limit: u64) {
self.total = limit as usize;
let _ = EventDispatcher::new().progress_bar_started().is_ok();
}

fn increment_by(&mut self, amount: u64) {
self.current += amount as usize;
let _ = EventDispatcher::new()
.progress_bar_incremented(self.current, self.total)
.is_ok();
web_sys::console::log_1(&format!("Progress: {}/{}", self.current, self.total).into());
}

Expand All @@ -109,6 +114,7 @@ impl ProgressBar for ProgressBarWeb {
}

fn finish(&mut self) {
let _ = EventDispatcher::new().progress_bar_finished().is_ok();
web_sys::console::log_1(&"Finished".into());
}
}
34 changes: 18 additions & 16 deletions packages/shared/lib/src/sdk/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
mod args;
pub mod events;
pub mod io;
pub mod masp;
mod signature;
Expand All @@ -14,37 +15,37 @@ use crate::utils::to_bytes;
use crate::utils::to_js_result;
use gloo_utils::format::JsValueSerdeExt;
use namada_sdk::address::{Address, MASP};
use namada_sdk::args::{GenIbcShieldingTransfer, InputAmount, Query, TxExpiration};
use namada_sdk::borsh::{self, BorshDeserialize};
use namada_sdk::eth_bridge::bridge_pool::build_bridge_pool_tx;
use namada_sdk::hash::Hash;
use namada_sdk::ibc::convert_masp_tx_to_ibc_memo;
use namada_sdk::ibc::core::host::types::identifiers::{ChannelId, PortId};
use namada_sdk::io::NamadaIo;
use namada_sdk::key::{common, ed25519, SigScheme};
use namada_sdk::masp::ShieldedContext;
use namada_sdk::rpc::{query_epoch, InnerTxResult};
use namada_sdk::signing::SigningTxData;
use namada_sdk::string_encoding::Format;
use namada_sdk::tendermint_rpc::Url;
use namada_sdk::token::DenominatedAmount;
use namada_sdk::tx::{
build_batch, build_bond, build_claim_rewards, build_ibc_transfer, build_redelegation,
build_reveal_pk, build_shielded_transfer, build_shielding_transfer, build_transparent_transfer,
build_unbond, build_unshielding_transfer, build_vote_proposal, build_withdraw,
data::compute_inner_tx_hash, either::Either, process_tx, ProcessTxResponse,
Tx, gen_ibc_shielding_transfer
data::compute_inner_tx_hash, either::Either, gen_ibc_shielding_transfer, process_tx,
ProcessTxResponse, Tx,
};
use namada_sdk::wallet::{Store, Wallet};
use namada_sdk::{Namada, NamadaImpl, PaymentAddress, TransferTarget};
use namada_sdk::args::{InputAmount, GenIbcShieldingTransfer, Query, TxExpiration};
use namada_sdk::ibc::core::host::types::identifiers::{ChannelId, PortId};
use namada_sdk::ibc::convert_masp_tx_to_ibc_memo;
use namada_sdk::token::DenominatedAmount;
use namada_sdk::tendermint_rpc::Url;
use std::str::FromStr;
use wasm_bindgen::{prelude::wasm_bindgen, JsError, JsValue};

/// Represents the Sdk public API.
#[wasm_bindgen]
pub struct Sdk {
namada: NamadaImpl<HttpClient, wallet::JSWalletUtils, masp::JSShieldedUtils, WebIo>,
rpc_url: String
rpc_url: String,
}

#[wasm_bindgen]
Expand Down Expand Up @@ -72,7 +73,7 @@ impl Sdk {

Sdk {
namada,
rpc_url: url
rpc_url: url,
}
}

Expand Down Expand Up @@ -490,15 +491,14 @@ impl Sdk {
target: &str,
token: String,
amount: &str,
channel_id: &str
channel_id: &str,
) -> Result<JsValue, JsError> {
let ledger_address = Url::from_str(&self.rpc_url).expect("RPC URL is a valid URL");
let target = TransferTarget::PaymentAddress(
PaymentAddress::from_str(target).expect("target is a valid shielded address")
);
let amount = InputAmount::Unvalidated(
DenominatedAmount::from_str(amount).expect("amount is valid")
PaymentAddress::from_str(target).expect("target is a valid shielded address"),
);
let amount =
InputAmount::Unvalidated(DenominatedAmount::from_str(amount).expect("amount is valid"));
let channel_id = ChannelId::from_str(channel_id).expect("channel ID is valid");

let args = GenIbcShieldingTransfer {
Expand All @@ -509,14 +509,16 @@ impl Sdk {
amount,
port_id: PortId::transfer(),
channel_id,
expiration: TxExpiration::Default
expiration: TxExpiration::Default,
};

if let Some(masp_tx) = gen_ibc_shielding_transfer(&self.namada, args).await? {
let memo = convert_masp_tx_to_ibc_memo(&masp_tx);
to_js_result(memo)
} else {
Err(JsError::new("Generating ibc shielding transfer generated nothing"))
Err(JsError::new(
"Generating ibc shielding transfer generated nothing",
))
}
}

Expand Down

0 comments on commit c318d65

Please sign in to comment.