Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
surinder83singh committed Mar 14, 2024
1 parent a4937eb commit b4da55f
Show file tree
Hide file tree
Showing 8 changed files with 149 additions and 47 deletions.
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 21 additions & 3 deletions core/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -654,6 +654,9 @@ impl Core {
) -> Result<()> {
// println!("event: {:?}", event);
match event {
Events::WebMessage(msg)=>{
log_info!("Events::WebMessage msg: {msg}");
}
Events::NetworkChange(network) => {
self.modules.clone().values().for_each(|module| {
module.network_change(self, network);
Expand Down Expand Up @@ -757,8 +760,8 @@ impl Core {
// println!("event: {:?}", event);
match *event {
CoreWallet::WalletPing => {
// log_info!("KASPA NG RECEIVED WALLET START EVENT");
crate::runtime::runtime().notify(UserNotification::info("Wallet ping"));
log_info!("KASPA NG RECEIVED WALLET START EVENT");
// crate::runtime::runtime().notify(UserNotification::info("Wallet ping"));
}
CoreWallet::Error { message } => {
// runtime().notify(UserNotification::error(message.as_str()));
Expand Down Expand Up @@ -910,7 +913,22 @@ impl Core {

self.purge_secure_stack();
}
CoreWallet::AccountSelection { id: _ } => {}
CoreWallet::AccountSelection { id } => {
if let Some(id) = id{
log_info!("AccountSelection id: {id}");
self.account_collection
.as_ref()
.and_then(|account_collection| {
account_collection.get(&id).map(|account| {
let balance = account.balance();
let address = account.receive_address();
log_info!("AccountSelection address: {address}");
let res = self.sender().try_send(Events::WebMessage(format!("address: {}, balance: {balance:?}", address)));
log_info!("AccountSelection res: {res:?}");
})
});
}
}
CoreWallet::DaaScoreChange { current_daa_score } => {
self.state.current_daa_score.replace(current_daa_score);
}
Expand Down
1 change: 1 addition & 0 deletions core/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub type ApplicationEventsChannel = crate::runtime::channel::Channel<Events>;

#[derive(Clone, Debug)]
pub enum Events {
WebMessage(String),
NetworkChange(Network),
UpdateStorage(StorageUpdateOptions),
VisibilityChange(VisibilityState),
Expand Down
7 changes: 6 additions & 1 deletion core/src/modules/account_manager/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,10 @@ impl AccountManager {
}
}).render(ui);
} else if account_collection.len() == 1 {
self.select(Some(account_collection.first().unwrap().clone()), core.device().clone());
let account = account_collection.first().unwrap();
self.select(Some(account.clone()), core.device().clone());
let id = account.id();
let _ = core.sender().try_send(Events::Wallet { event: Box::new(kaspa_wallet_core::events::Events::AccountSelection{id: Some(id)}) });
} else {
Panel::new(self)
.with_caption(i18n("Select Account"))
Expand Down Expand Up @@ -362,6 +365,8 @@ impl AccountManager {
account_collection.iter().for_each(|account_select| {
if ui.account_selector_button(account_select, &network_type, false, core.balance_padding()).clicked() {
this.select(Some(account_select.clone()), core.device().clone());
let id = account_select.id();
let _ = core.sender().try_send(Events::Wallet { event: Box::new(kaspa_wallet_core::events::Events::AccountSelection{id: Some(id)}) });
if core.device().single_pane() {
this.section = AccountManagerSection::Overview;
} else {
Expand Down
6 changes: 6 additions & 0 deletions core/src/modules/account_manager/overview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ impl<'manager> Overview<'manager> {
Action::None => {

Qr::render(ui, rc);
// let address = rc.account.receive_address();
// let balance = rc.account.balance();
// log_info!("#### address: {address:?}");
// log_info!("#### balance: {balance:?}");



ui.vertical_centered(|ui|{

Expand Down
9 changes: 8 additions & 1 deletion extensions/chrome/src/ipc.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use workflow_wasm::extensions::ObjectExtension;

use crate::imports::*;

// const SUCCESS: u8 = 0;
Expand Down Expand Up @@ -113,7 +115,12 @@ pub fn req_to_jsv(target: Target, op: u64, src: &[u8]) -> JsValue {
// );
// mask(&mut data[10..], src, &mut index, mask_data);
// let data =
JsValue::from(data.to_hex())

let obj = js_sys::Object::new();
obj.set("type", &"Internal".into()).unwrap();
obj.set("data", &data.to_hex().into()).unwrap();

obj.into()
}

pub fn jsv_to_req(src: JsValue) -> Result<(Target, u64, Vec<u8>)> {
Expand Down
10 changes: 10 additions & 0 deletions extensions/chrome/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,16 @@ pub async fn kaspa_ng_main() {
let application_events = ApplicationEventsChannel::unbounded();

let client_transport = Arc::new(client::ClientTransport::new(application_events.clone()));
for event in application_events.iter(){
match event{
kaspa_ng_core::events::Events::WebMessage(msg)=>{
log_info!("kaspa_ng_core::events::Events::WebMessage msg: {msg:?}");
}
_=>{

}
}
}
let borsh_transport = Codec::Borsh(client_transport.clone());
let wallet_client: Arc<dyn WalletApi> = Arc::new(WalletClient::new(borsh_transport));

Expand Down
136 changes: 94 additions & 42 deletions extensions/chrome/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub type PortListenerClosure = Closure<dyn FnMut(chrome_runtime_port::Port) -> J
pub type PortEventClosure = Closure<dyn FnMut(JsValue) -> JsValue>;
use std::collections::HashMap;
use workflow_wasm::extensions::ObjectExtension;
use workflow_core::enums::Describe;
use rand::Rng;

#[wasm_bindgen]
Expand All @@ -33,30 +34,71 @@ pub struct Server {
unsafe impl Send for Server {}
unsafe impl Sync for Server {}

#[derive(Debug, Describe)]
enum WebActions{
InjectPageScript,
Connect,
}


#[derive(Debug)]
struct WEBMessage{
action: String,
struct WebMessage{
action: WebActions,
rid: Option<String>,
data: JsValue
}

fn port_msg_to_req(msg: js_sys::Object)->Result<WEBMessage> {
#[derive(Debug)]
struct InternalMessage{
target: Target,
op: u64,
data: Vec<u8>
}

#[derive(Debug)]
enum Message{
Web(WebMessage),
Internal(InternalMessage)
}

impl From<WebMessage> for Message{
fn from(value: WebMessage) -> Self {
Self::Web(value)
}
}
impl From<InternalMessage> for Message{
fn from(value: InternalMessage) -> Self {
Self::Internal(value)
}
}

fn msg_to_req(msg: js_sys::Object)->Result<Message> {
let msg_type = msg.get_string("type")?;

if msg_type == "WEBAPI" {
if msg_type == "WebAPI" {
let info = msg.get_object("data")?;
let action = info.get_string("action")?;
let action = WebActions::from_str(&info.get_string("action")?).expect("`action` is required for WEBAPI message.");
let data = info.get_value("data")?;
let rid = info.try_get_string("rid")?;

return Ok(WEBMessage{
return Ok(WebMessage{
action,
data,
rid
});
}.into());
}

if msg_type == "Internal"{
let info = msg.get_value("data")?;
let (target, op, data) = jsv_to_req(info)?;
return Ok(InternalMessage{
target,
op,
data
}.into());
}

Err("TODO: port_msg_to_req: {msg_type}".to_string().into())
Err("Invalid msg: {msg_type}".to_string().into())


// let src = Vec::<u8>::from_hex(
Expand Down Expand Up @@ -135,13 +177,13 @@ impl Server {
}

pub async fn start(self: &Arc<Self>) {
log_info!("Server starting...");
log_info!("chrome/src/Server starting...");
// self.runtime.start();
self.register_listener();
self.register_port_listener();
self.wallet_server.start();

log_info!("Starting wallet...");
log_info!("chrome/src/Starting wallet...");
self.wallet
.start()
.await
Expand Down Expand Up @@ -193,25 +235,29 @@ impl Server {
*self.port_closure.lock().unwrap() = Some(closure);
}

async fn handle_port_event(self: &Arc<Self>, msg: js_sys::Object, port:Rc<chrome_runtime_port::Port>)->JsValue{

let req = port_msg_to_req(msg.clone()).unwrap();
workflow_log::log_info!("handle_port_event: req {:?}", req);
async fn handle_port_event(self: &Arc<Self>, msg_jsv: js_sys::Object, port:Rc<chrome_runtime_port::Port>)->JsValue{

match req.action.as_str(){
"inject-page-script" => {
let tab_id = port.sender().tab().id();
init_page_script(tab_id, req.data);
let msg = msg_to_req(msg_jsv.clone()).unwrap();
workflow_log::log_info!("handle_port_event: msg {:?}", msg);
match msg {
Message::Web(msg)=>{
match msg.action{
WebActions::InjectPageScript => {
let tab_id = port.sender().tab().id();
init_page_script(tab_id, msg.data);
},
WebActions::Connect => {
open_popup_window()
}
}
},
"connect" =>{
open_popup_window()
}
_ =>{

Message::Internal(_)=>{
//
}
}


format!("handle_port_event: got msg: {msg:?}").into()
format!("handle_port_event: got msg: {msg_jsv:?}").into()
}

fn register_listener(self: &Arc<Self>) {
Expand Down Expand Up @@ -242,7 +288,7 @@ impl Server {

fn handle_message(
self: Arc<Self>,
msg: JsValue,
msg_jsv: JsValue,
sender: Sender,
callback: Function,
) -> Result<()> {
Expand All @@ -258,27 +304,33 @@ impl Server {

log_info!(
"[WASM] msg: {:?}, sender id:{:?}, {:?}",
msg,
msg_jsv,
sender.id(),
callback
);

let (target, op, data) = jsv_to_req(msg)?;

match target {
Target::Wallet => {
spawn_local(async move {
let resp = resp_to_jsv(
Target::Wallet,
self.wallet_server.call_with_borsh(op, &data).await,
);
if let Err(err) = callback.call1(&JsValue::UNDEFINED, &resp) {
log_error!("onMessage callback error: {:?}", err);
let msg = msg_to_req(js_sys::Object::from(msg_jsv)).unwrap();
match msg{
Message::Internal(msg)=>{
match msg.target {
Target::Wallet => {
spawn_local(async move {
let resp = resp_to_jsv(
Target::Wallet,
self.wallet_server.call_with_borsh(msg.op, &msg.data).await,
);
if let Err(err) = callback.call1(&JsValue::UNDEFINED, &resp) {
log_error!("onMessage callback error: {:?}", err);
}
});
}
});
}
Target::Runtime => {
todo!()
Target::Runtime => {
todo!()
}
}
},
Message::Web(_msg)=>{

}
}

Expand Down Expand Up @@ -307,7 +359,7 @@ struct ServerEventHandler {}
#[async_trait]
impl EventHandler for ServerEventHandler {
async fn handle_event(&self, event: &Events) {
log_info!("EVENT HANDLER - POSTING NOTIFICATION!");
log_info!("EVENT HANDLER - POSTING NOTIFICATION! {event:?}");

let data = event.try_to_vec().unwrap();
spawn_local(async move {
Expand Down

0 comments on commit b4da55f

Please sign in to comment.