Skip to content

Commit

Permalink
save dev state - implement wc rpc commands
Browse files Browse the repository at this point in the history
  • Loading branch information
borngraced committed Sep 26, 2024
1 parent 6135665 commit 5457d80
Show file tree
Hide file tree
Showing 19 changed files with 202 additions and 130 deletions.
2 changes: 2 additions & 0 deletions mm2src/kdf_walletconnect/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ pub(crate) const UNSUPPORTED_EVENTS: i32 = 5102;
pub(crate) const UNSUPPORTED_ACCOUNTS: i32 = 5103;
pub(crate) const UNSUPPORTED_NAMESPACE_KEY: i32 = 5104;

pub(crate) const USER_REQUESTED: i64 = 6000;

#[derive(Debug, Serialize, Deserialize, EnumFromStringify, thiserror::Error)]
pub enum WalletConnectCtxError {
#[error("Pairing Error: {0}")]
Expand Down
36 changes: 17 additions & 19 deletions mm2src/kdf_walletconnect/src/inbound_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{error::WalletConnectCtxError,
pairing::{process_pairing_delete_response, process_pairing_extend_response, process_pairing_ping_response},
session::{delete::process_session_delete_request,
pairing::{reply_pairing_delete_response, reply_pairing_extend_response, reply_pairing_ping_response},
session::{delete::reply_session_delete_request,
event::SessionEvents,
extend::process_session_extend_request,
ping::process_session_ping_request,
propose::{process_proposal_request, process_session_propose_response},
settle::process_session_settle_request,
update::process_session_update_request},
extend::reply_session_extend_request,
ping::reply_session_ping_request,
propose::{process_session_propose_response, reply_session_proposal_request},
settle::reply_session_settle_request,
update::reply_session_update_request},
WalletConnectCtx};

#[derive(Debug, Serialize, Deserialize)]
Expand All @@ -31,26 +31,25 @@ pub(crate) async fn process_inbound_request(
) -> MmResult<(), WalletConnectCtxError> {
let message_id = request.id;
match request.params {
Params::SessionPropose(proposal) => process_proposal_request(ctx, proposal, topic, &message_id).await?,
Params::SessionExtend(param) => process_session_extend_request(ctx, topic, &message_id, param).await?,
Params::SessionDelete(param) => process_session_delete_request(ctx, topic, &message_id, param).await?,
Params::SessionPing(()) => process_session_ping_request(ctx, topic, &message_id).await?,
Params::SessionSettle(param) => process_session_settle_request(ctx, topic, &message_id, param).await?,
Params::SessionUpdate(param) => process_session_update_request(ctx, topic, &message_id, param).await?,
Params::SessionPropose(proposal) => reply_session_proposal_request(ctx, proposal, topic, &message_id).await?,
Params::SessionExtend(param) => reply_session_extend_request(ctx, topic, &message_id, param).await?,
Params::SessionDelete(param) => reply_session_delete_request(ctx, topic, &message_id, param).await?,
Params::SessionPing(()) => reply_session_ping_request(ctx, topic, &message_id).await?,
Params::SessionSettle(param) => reply_session_settle_request(ctx, topic, &message_id, param).await?,
Params::SessionUpdate(param) => reply_session_update_request(ctx, topic, &message_id, param).await?,
Params::SessionEvent(param) => {
SessionEvents::from_events(param)?
.handle_session_event(ctx, topic, &message_id)
.await?
},
Params::SessionRequest(_param) => {
// TODO: send back a success response.
info!("SessionRequest is not yet implemented.");
// TODO: Implement when integrating KDF as a wallet.
return MmError::err(WalletConnectCtxError::NotImplemented);
},

Params::PairingPing(_param) => process_pairing_ping_response(ctx, topic, &message_id).await?,
Params::PairingDelete(param) => process_pairing_delete_response(ctx, topic, &message_id, param).await?,
Params::PairingExtend(param) => process_pairing_extend_response(ctx, topic, &message_id, param).await?,
Params::PairingPing(_param) => reply_pairing_ping_response(ctx, topic, &message_id).await?,
Params::PairingDelete(param) => reply_pairing_delete_response(ctx, topic, &message_id, param).await?,
Params::PairingExtend(param) => reply_pairing_extend_response(ctx, topic, &message_id, param).await?,
_ => {
info!("Unknown request params received.");
return MmError::err(WalletConnectCtxError::InvalidRequest);
Expand All @@ -72,7 +71,6 @@ pub(crate) async fn process_inbound_response(
let success_response = serde_json::from_value::<SuccessResponses>(value.result)?;
match success_response {
SuccessResponses::ResponseParamsSuccess(params) => match params {
// Handle known success responses match success_response {
ResponseParamsSuccess::SessionPropose(param) => {
process_session_propose_response(ctx, topic, param).await
},
Expand Down
13 changes: 6 additions & 7 deletions mm2src/kdf_walletconnect/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ mod handler;
mod inbound_message;
mod metadata;
#[allow(unused)] mod pairing;
pub mod rpc_commands;

mod session;
mod storage;

Expand Down Expand Up @@ -33,7 +35,7 @@ use relay_rpc::{auth::{ed25519_dalek::SigningKey, AuthToken},
ResponseParamsSuccess},
ErrorResponse, Payload, Request, Response, SuccessfulResponse}};
use serde_json::Value;
use session::{propose::send_proposal, Session, SymKeyPair};
use session::{propose::send_proposal_request, Session, SymKeyPair};
use std::{sync::Arc, time::Duration};
use storage::{SessionStorageDb, WalletConnectStorageOps};
use wc_common::{decode_and_decrypt_type0, encrypt_and_encode, EnvelopeType};
Expand Down Expand Up @@ -124,7 +126,7 @@ impl WalletConnectCtx {
}

/// Create a WalletConnect pairing connection url.
pub async fn create_pairing(
pub async fn new_connection(
&self,
required_namespaces: Option<ProposeNamespaces>,
) -> MmResult<String, WalletConnectCtxError> {
Expand All @@ -136,7 +138,7 @@ impl WalletConnectCtx {

info!("Subscribed to topic: {topic:?}");

send_proposal(self, topic.clone(), required_namespaces).await?;
send_proposal_request(self, topic.clone(), required_namespaces).await?;

{
let mut subs = self.subscriptions.lock().await;
Expand Down Expand Up @@ -173,10 +175,7 @@ impl WalletConnectCtx {
/// Get current active chain id.
pub async fn get_active_chain_id(&self) -> String { self.active_chain_id.lock().await.clone() }

pub async fn get_session(&self) -> Option<Session> {
let session = self.session.lock().await;
session.clone()
}
pub async fn get_session(&self) -> Option<Session> { self.session.lock().await.clone() }

/// Get available accounts for a given chain_id.
pub async fn get_account_for_chain_id(&self, chain_id: &str) -> MmResult<String, WalletConnectCtxError> {
Expand Down
35 changes: 3 additions & 32 deletions mm2src/kdf_walletconnect/src/pairing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use relay_rpc::{domain::Topic,
rpc::params::{pairing_delete::PairingDeleteRequest, pairing_extend::PairingExtendRequest,
ResponseParamsSuccess}};

pub(crate) async fn process_pairing_ping_response(
pub(crate) async fn reply_pairing_ping_response(
ctx: &WalletConnectCtx,
topic: &Topic,
message_id: &MessageId,
Expand All @@ -21,7 +21,7 @@ pub(crate) async fn process_pairing_ping_response(
Ok(())
}

pub(crate) async fn process_pairing_extend_response(
pub(crate) async fn reply_pairing_extend_response(
ctx: &WalletConnectCtx,
topic: &Topic,
message_id: &MessageId,
Expand All @@ -41,7 +41,7 @@ pub(crate) async fn process_pairing_extend_response(
Ok(())
}

pub(crate) async fn process_pairing_delete_response(
pub(crate) async fn reply_pairing_delete_response(
ctx: &WalletConnectCtx,
topic: &Topic,
message_id: &MessageId,
Expand All @@ -56,32 +56,3 @@ pub(crate) async fn process_pairing_delete_response(

Ok(())
}

pub(crate) async fn pairing_ping_request() -> WcRequestResponseResult {
let request = RequestParams::PairingPing(PairingPingRequest {});
let irn_metadata = request.irn_metadata();
let value = serde_json::to_value(request)?;

Ok((value, irn_metadata))
}

pub(crate) async fn pairing_delete_request() -> WcRequestResponseResult {
let request = RequestParams::PairingDelete(PairingDeleteRequest {
code: 6000,
message: "Delete my pairing".to_string(),
});
let irn_metadata = request.irn_metadata();
let value = serde_json::to_value(request)?;

Ok((value, irn_metadata))
}

pub(crate) async fn pairing_extend_request() -> WcRequestResponseResult {
let request = RequestParams::PairingExtend(PairingExtendRequest {
expiry: Utc::now().timestamp() as u64 + THIRTY_DAYS,
});
let irn_metadata = request.irn_metadata();
let value = serde_json::to_value(request)?;

Ok((value, irn_metadata))
}
27 changes: 27 additions & 0 deletions mm2src/kdf_walletconnect/src/rpc_commands/delete_connection.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::prelude::MmResult;
use relay_rpc::domain::Topic;
use serde::{Deserialize, Serialize};

use crate::{error::WalletConnectCtxError, session::delete::send_session_delete_request, WalletConnectCtx};

#[derive(Debug, PartialEq, Serialize)]
pub struct DeleteConnectionResponse {
pub successful: bool,
}

#[derive(Deserialize)]
pub struct DeleteConnectionRequest {
topic: Topic,
}

/// `delete connection` RPC command implementation.
pub async fn delete_connection(
ctx: MmArc,
req: DeleteConnectionRequest,
) -> MmResult<DeleteConnectionResponse, WalletConnectCtxError> {
let ctx = WalletConnectCtx::try_from_ctx_or_initialize(&ctx)?;
send_session_delete_request(&ctx, &req.topic).await?;

Ok(DeleteConnectionResponse { successful: true })
}
20 changes: 20 additions & 0 deletions mm2src/kdf_walletconnect/src/rpc_commands/get_chain_id.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::prelude::MmResult;
use serde::Serialize;

use crate::{error::WalletConnectCtxError, WalletConnectCtx};

use super::EmptyRpcRequst;

#[derive(Debug, PartialEq, Serialize)]
pub struct GetChainIdResponse {
pub chain_id: String,
}

/// `delete connection` RPC command implementation.
pub async fn get_chain_id(ctx: MmArc, _req: EmptyRpcRequst) -> MmResult<GetChainIdResponse, WalletConnectCtxError> {
let ctx = WalletConnectCtx::try_from_ctx_or_initialize(&ctx)?;
let chain_id = ctx.get_active_chain_id().await;

Ok(GetChainIdResponse { chain_id })
}
19 changes: 19 additions & 0 deletions mm2src/kdf_walletconnect/src/rpc_commands/get_session.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::prelude::MmResult;
use serde::Serialize;

use super::EmptyRpcRequst;
use crate::{error::WalletConnectCtxError, session::Session, WalletConnectCtx};

#[derive(Debug, PartialEq, Serialize)]
pub struct GetSessionResponse {
pub session: Option<Session>,
}

/// `delete connection` RPC command implementation.
pub async fn get_session(ctx: MmArc, _req: EmptyRpcRequst) -> MmResult<GetSessionResponse, WalletConnectCtxError> {
let ctx = WalletConnectCtx::try_from_ctx_or_initialize(&ctx)?;
let session = ctx.get_session().await;

Ok(GetSessionResponse { session })
}
15 changes: 15 additions & 0 deletions mm2src/kdf_walletconnect/src/rpc_commands/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
mod delete_connection;
mod get_chain_id;
mod get_session;
mod new_connection;
mod ping;

pub use delete_connection::delete_connection;
pub use get_chain_id::get_chain_id;
pub use get_session::get_session;
pub use new_connection::new_connection;
pub use ping::ping_session;
use serde::Deserialize;

#[derive(Deserialize)]
pub struct EmptyRpcRequst {}
22 changes: 22 additions & 0 deletions mm2src/kdf_walletconnect/src/rpc_commands/new_connection.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::prelude::MmResult;
use serde::Serialize;

use super::EmptyRpcRequst;
use crate::{error::WalletConnectCtxError, WalletConnectCtx};

#[derive(Debug, PartialEq, Serialize)]
pub struct CreateConnectionResponse {
pub url: String,
}

/// `new_connection` RPC command implementation.
pub async fn new_connection(
ctx: MmArc,
_req: EmptyRpcRequst,
) -> MmResult<CreateConnectionResponse, WalletConnectCtxError> {
let ctx = WalletConnectCtx::try_from_ctx_or_initialize(&ctx)?;
let url = ctx.new_connection(None).await?;

Ok(CreateConnectionResponse { url })
}
24 changes: 24 additions & 0 deletions mm2src/kdf_walletconnect/src/rpc_commands/ping.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::prelude::MmResult;
use relay_rpc::domain::Topic;
use serde::{Deserialize, Serialize};

use crate::{error::WalletConnectCtxError, session::ping::send_session_ping_request, WalletConnectCtx};

#[derive(Debug, PartialEq, Serialize)]
pub struct SessionPingResponse {
pub successful: bool,
}

#[derive(Deserialize)]
pub struct SessionPingRequest {
topic: Topic,
}

/// `ping session` RPC command implementation.
pub async fn ping_session(ctx: MmArc, req: SessionPingRequest) -> MmResult<SessionPingResponse, WalletConnectCtxError> {
let ctx = WalletConnectCtx::try_from_ctx_or_initialize(&ctx)?;
send_session_ping_request(&ctx, &req.topic).await?;

Ok(SessionPingResponse { successful: true })
}
24 changes: 19 additions & 5 deletions mm2src/kdf_walletconnect/src/session/delete.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use crate::{error::WalletConnectCtxError, WalletConnectCtx};
use crate::{error::{WalletConnectCtxError, USER_REQUESTED},
WalletConnectCtx};

use common::log::debug;
use mm2_err_handle::prelude::MmResult;
use relay_rpc::{domain::{MessageId, Topic},
rpc::params::{session_delete::SessionDeleteRequest, ResponseParamsSuccess}};
rpc::params::{session_delete::SessionDeleteRequest, RequestParams, ResponseParamsSuccess}};

pub(crate) async fn process_session_delete_request(
pub(crate) async fn reply_session_delete_request(
ctx: &WalletConnectCtx,
topic: &Topic,
message_id: &MessageId,
Expand All @@ -14,9 +15,22 @@ pub(crate) async fn process_session_delete_request(
let param = ResponseParamsSuccess::SessionDelete(true);
ctx.publish_response_ok(topic, param, message_id).await?;

session_delete_cleanup(ctx, topic).await?;
session_delete_cleanup(ctx, topic).await
}

Ok(())
pub(crate) async fn send_session_delete_request(
ctx: &WalletConnectCtx,
session_topic: &Topic,
) -> MmResult<(), WalletConnectCtxError> {
let delete_request = SessionDeleteRequest {
code: USER_REQUESTED,
message: "User Disconnected".to_owned(),
};
let param = RequestParams::SessionDelete(delete_request);

ctx.publish_request(session_topic, param).await?;

session_delete_cleanup(ctx, session_topic).await
}

async fn session_delete_cleanup(ctx: &WalletConnectCtx, topic: &Topic) -> MmResult<(), WalletConnectCtxError> {
Expand Down
3 changes: 2 additions & 1 deletion mm2src/kdf_walletconnect/src/session/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ impl SessionEvents {
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();
ctx.set_active_chain(chain_id.clone()).await;

let params = ResponseParamsSuccess::SessionEvent(true);
ctx.publish_response_ok(topic, params, message_id).await?;

Expand Down
2 changes: 1 addition & 1 deletion mm2src/kdf_walletconnect/src/session/extend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use relay_rpc::{domain::{MessageId, Topic},
rpc::params::{session_extend::SessionExtendRequest, ResponseParamsSuccess}};

/// Process session extend request.
pub(crate) async fn process_session_extend_request(
pub(crate) async fn reply_session_extend_request(
ctx: &WalletConnectCtx,
topic: &Topic,
message_id: &MessageId,
Expand Down
Loading

0 comments on commit 5457d80

Please sign in to comment.