Skip to content

Commit

Permalink
improve code and minor needed changes
Browse files Browse the repository at this point in the history
  • Loading branch information
borngraced committed Sep 22, 2024
1 parent 42dd5ba commit edcb5a7
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 74 deletions.
43 changes: 7 additions & 36 deletions mm2src/kdf_walletconnect/src/chain/mod.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,13 @@
pub mod cosmos;

use relay_rpc::rpc::params::session::{ProposeNamespace, ProposeNamespaces};
use std::collections::{BTreeMap, BTreeSet};

pub(crate) const SUPPORTED_EVENTS: &[&str] = &["chainChanged", "accountsChanged"];

pub(crate) const ETH_SUPPORTED_METHODS: &[&str] = &[
"eth_sendTransaction",
"eth_signTransaction",
"eth_sign",
"personal_sign",
"eth_signTypedData",
];
pub(crate) const ETH_SUPPORTED_CHAINS: &[&str] = &["eip155:1", "eip155:5"];
use std::collections::BTreeMap;

pub(crate) const COSMOS_SUPPORTED_METHODS: &[&str] = &["cosmos_getAccounts", "cosmos_signDirect", "cosmos_signAmino"];
pub(crate) const COSMOS_SUPPORTED_CHAINS: &[&str] = &["cosmos:cosmoshub-4"];
pub(crate) const SUPPORTED_EVENTS: &[&str] = &[];
pub(crate) const SUPPORTED_METHODS: &[&str] = &["cosmos_getAccounts", "cosmos_signDirect", "cosmos_signAmino"];
pub(crate) const SUPPORTED_CHAINS: &[&str] = &["cosmos:cosmoshub-4"];

#[derive(Debug, Clone)]
pub enum WcRequestMethods {
EthSendTransaction,
EthSignTransaction,
EthSign,
EthPersonalSign,
EthSignTypedData,
CosmosSignDirect,
CosmosSignAmino,
CosmosGetAccounts,
Expand All @@ -32,11 +16,6 @@ pub enum WcRequestMethods {
impl AsRef<str> for WcRequestMethods {
fn as_ref(&self) -> &str {
match self {
Self::EthSignTransaction => "eth_signTransaction",
Self::EthSendTransaction => "eth_sendTransaction",
Self::EthSign => "eth_sign",
Self::EthPersonalSign => "personal_sign",
Self::EthSignTypedData => "eth_signTypedData",
Self::CosmosSignDirect => "cosmos_signDirect",
Self::CosmosSignAmino => "cosmos_signAmino",
Self::CosmosGetAccounts => "cosmos_getAccounts",
Expand All @@ -46,18 +25,10 @@ impl AsRef<str> for WcRequestMethods {

pub(crate) fn build_required_namespaces() -> ProposeNamespaces {
let mut required = BTreeMap::new();

// build eth
required.insert("eip155".to_string(), ProposeNamespace {
chains: ETH_SUPPORTED_CHAINS.iter().map(|c| c.to_string()).collect(),
methods: ETH_SUPPORTED_METHODS.iter().map(|m| m.to_string()).collect(),
events: SUPPORTED_EVENTS.iter().map(|e| e.to_string()).collect(),
});

required.insert("cosmos".to_string(), ProposeNamespace {
chains: COSMOS_SUPPORTED_CHAINS.iter().map(|c| c.to_string()).collect(),
methods: COSMOS_SUPPORTED_METHODS.iter().map(|m| m.to_string()).collect(),
events: BTreeSet::new(),
chains: SUPPORTED_CHAINS.iter().map(|c| c.to_string()).collect(),
methods: SUPPORTED_METHODS.iter().map(|m| m.to_string()).collect(),
events: SUPPORTED_EVENTS.iter().map(|m| m.to_string()).collect(),
});

ProposeNamespaces(required)
Expand Down
5 changes: 4 additions & 1 deletion mm2src/kdf_walletconnect/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ mod session;

use async_trait::async_trait;
use chain::{build_required_namespaces,
cosmos::{cosmos_get_accounts_impl, CosmosAccount}};
cosmos::{cosmos_get_accounts_impl, CosmosAccount},
SUPPORTED_CHAINS};
use common::{executor::Timer, log::info};
use error::WalletConnectCtxError;
use futures::{channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
Expand Down Expand Up @@ -117,6 +118,8 @@ impl WalletConnectCtx {
Ok(topic)
}

pub fn is_chain_supported(&self, chain_id: &str) -> bool { SUPPORTED_CHAINS.iter().any(|chain| chain == &chain_id) }

/// Set active chain.
pub async fn set_active_chain(&self, chain_id: &str) {
let mut active_chain = self.active_chain_id.lock().await;
Expand Down
2 changes: 1 addition & 1 deletion mm2src/kdf_walletconnect/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub(crate) fn generate_metadata() -> Metadata {
Metadata {
description: APP_DESCRIPTION.to_owned(),
url: AUTH_TOKEN_SUB.to_owned(),
icons: vec![],
icons: vec!["https://avatars.githubusercontent.com/u/21276113?s=200&v=4".to_owned()],
name: APP_NAME.to_owned(),
}
}
53 changes: 20 additions & 33 deletions mm2src/kdf_walletconnect/src/session/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,42 +59,29 @@ impl SessionEvents {
topic: &Topic,
message_id: &MessageId,
) -> MmResult<(), WalletConnectCtxError> {
{
*ctx.active_chain_id.lock().await = chain_id.clone().to_owned();

// TODO: validate session expiration.
//
if let Some((namespace, _chain)) = parse_chain_and_chain_id(chain_id) {
if ctx.namespaces.get(&namespace).is_none() {
let error_data = ErrorData {
code: UNSUPPORTED_CHAINS,
message: "Chain_Id was changed to an unsupported chain".to_string(),
data: None,
};

ctx.publish_response_err(topic, ResponseParamsError::SessionEvent(error_data), message_id)
.await?;

return MmError::err(WalletConnectCtxError::SessionError(format!(
"Unsupported chainChanged chain_id from session request: {chain_id}",
)));
}

let mut session = ctx.session.lock().await;
if let Some(session) = session.as_mut() {
if let Some(ns) = session.namespaces.get_mut(&namespace) {
if let Some(chains) = ns.chains.as_mut() {
chains.insert(chain_id.to_owned());
}
if ctx.is_chain_supported(chain_id) {
if let Some((key, chain)) = parse_chain_and_chain_id(chain_id) {
if let Some(namespace) = ctx.namespaces.get(&key) {
if namespace.chains.contains(&chain) {
// TODO: Notify GUI about chain changed.
// Update active chain_id
*ctx.active_chain_id.lock().await = chain_id.clone().to_owned();
let params = ResponseParamsSuccess::SessionEvent(true);
ctx.publish_response_ok(topic, params, message_id).await?;

return Ok(());
}
}
}
}

//TODO: Notify about chain changed.
};

let params = ResponseParamsSuccess::SessionEvent(true);
ctx.publish_response_ok(topic, params, message_id).await?;
let error_data = ErrorData {
code: UNSUPPORTED_CHAINS,
message: "Chain_Id was changed to an unsupported chain".to_string(),
data: None,
};
ctx.publish_response_err(topic, ResponseParamsError::SessionEvent(error_data), message_id)
.await?;

Ok(())
}
Expand All @@ -118,7 +105,7 @@ impl SessionEvents {

fn parse_chain_and_chain_id(chain: &str) -> Option<(String, String)> {
let sp = chain.split(':').collect::<Vec<_>>();
if sp.len() == 2 {
if sp.len() != 2 {
return None;
};

Expand Down
6 changes: 3 additions & 3 deletions mm2src/kdf_walletconnect/src/session/settle.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::{Session, THIRTY_DAYS};
use crate::chain::{ETH_SUPPORTED_CHAINS, ETH_SUPPORTED_METHODS, SUPPORTED_EVENTS};
use crate::chain::{SUPPORTED_CHAINS, SUPPORTED_EVENTS, SUPPORTED_METHODS};
use crate::{error::WalletConnectCtxError, WalletConnectCtx};

use chrono::Utc;
Expand All @@ -17,8 +17,8 @@ pub(crate) async fn send_session_settle_request(
) -> MmResult<(), WalletConnectCtxError> {
let mut settled_namespaces = BTreeMap::<String, Namespace>::new();
settled_namespaces.insert("eip155".to_string(), Namespace {
chains: Some(ETH_SUPPORTED_CHAINS.iter().map(|c| c.to_string()).collect()),
methods: ETH_SUPPORTED_METHODS.iter().map(|m| m.to_string()).collect(),
chains: Some(SUPPORTED_CHAINS.iter().map(|c| c.to_string()).collect()),
methods: SUPPORTED_METHODS.iter().map(|m| m.to_string()).collect(),
events: SUPPORTED_EVENTS.iter().map(|e| e.to_string()).collect(),
accounts: None,
});
Expand Down

0 comments on commit edcb5a7

Please sign in to comment.