Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(walletconnect): walletconnect integration #2223

Open
wants to merge 158 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
158 commits
Select commit Hold shift + click to select a range
9100780
init, start walletconnect client impl
borngraced Sep 9, 2024
ca3f558
save dev state - walletconnect client impl
borngraced Sep 9, 2024
c3dc6c6
save dev state - WalletConnect client impl
borngraced Sep 9, 2024
0eea639
rough implementations
borngraced Sep 11, 2024
588316f
commit lock file
borngraced Sep 11, 2024
60a2fc5
save dev state - handle connection close, session improvements, etc
borngraced Sep 12, 2024
fd8797c
minor changes
borngraced Sep 12, 2024
437767b
fix wasm compilation
borngraced Sep 13, 2024
6374da3
minor changes - create metadata mod
borngraced Sep 13, 2024
1c9cfe0
minor changes and code organization
borngraced Sep 14, 2024
f7987dd
minor changes + merge session and session_key mod
borngraced Sep 14, 2024
1f2adb2
minor changes to namespaces
borngraced Sep 15, 2024
658357f
some improvements
borngraced Sep 16, 2024
98026ac
add some session fn doc comments
borngraced Sep 16, 2024
9dddb91
big improvements to session handling
borngraced Sep 16, 2024
52a0f72
implement session delete and cleaup
borngraced Sep 17, 2024
9f5944c
improve code and locking
borngraced Sep 17, 2024
dff1b42
remove unused dep
borngraced Sep 17, 2024
591fbdb
refactorings and cleanupds
borngraced Sep 17, 2024
f6e7864
minor changes
borngraced Sep 18, 2024
f535f0b
make session single
borngraced Sep 19, 2024
3eb8969
minor changes
borngraced Sep 19, 2024
2d68488
save dev state
borngraced Sep 19, 2024
42dd5ba
implement coin activation for tendermint and other minor changes
borngraced Sep 21, 2024
edcb5a7
improve code and minor needed changes
borngraced Sep 22, 2024
e606ca4
improve relayer disconnection, remove unneeded changes, track topic s…
borngraced Sep 23, 2024
d7b5a17
fix tendermint pubkey derivation from walletconnect
borngraced Sep 23, 2024
3a85a17
start persistent session storage implementation
borngraced Sep 23, 2024
be98c40
implement sqlite session storage table and insert session method
borngraced Sep 24, 2024
6453a33
fix cyclic deps and continue storage implementations
borngraced Sep 25, 2024
9f87a9e
implement WASM persistent storage
borngraced Sep 26, 2024
6135665
implement persistent indexed_db session storage
borngraced Sep 26, 2024
5457d80
save dev state - implement wc rpc commands
borngraced Sep 26, 2024
9d12079
move walletconnect rpc to mm2_main rpc
borngraced Sep 26, 2024
03d9978
remove mm2_test_helpers lock file
borngraced Sep 26, 2024
32e46d9
format mm2_net cargo.toml
borngraced Sep 26, 2024
1e352b1
update storage session upon session settle response/request
borngraced Sep 26, 2024
a30511b
add tokio to wc dependency list
borngraced Sep 26, 2024
341b18e
improve tenderming with_pubkey activation params
borngraced Sep 26, 2024
4c8e299
minor changes
borngraced Sep 29, 2024
73d8315
fix proposer mod
borngraced Sep 29, 2024
c1accc9
merge with dev
borngraced Sep 29, 2024
7ab33d5
implement walletconnect sign tx for tendermint - wip
borngraced Oct 2, 2024
0bcd41c
remove chain params from get cosmos account method
borngraced Oct 2, 2024
b2ec309
tx impl - wip
borngraced Oct 2, 2024
2e25bde
save dev state
borngraced Oct 6, 2024
328bc76
handle client connnection/reconnection efficiently and minor renaming
borngraced Oct 6, 2024
9b20d7f
minor changes
borngraced Oct 6, 2024
ca2e19c
implement multi session management
borngraced Oct 8, 2024
481f1c3
remove mm2_test_helpers lock file
borngraced Oct 8, 2024
0c00710
refactoring and unit tests
borngraced Oct 8, 2024
e5e2150
fix session topic generation bug
borngraced Oct 8, 2024
8d749de
tendermint sign tx impl fixes
borngraced Oct 9, 2024
8b1b6c3
improve wc tx_signing codes
borngraced Oct 9, 2024
4202950
minor fix
borngraced Oct 9, 2024
d440ed9
add more session rpc endpoint
borngraced Oct 10, 2024
f3cf28b
update wc deps
borngraced Oct 10, 2024
e56f8d7
update wc_common deps
borngraced Oct 10, 2024
1ab21d7
merge with dev and fix conflicts
borngraced Oct 10, 2024
a498381
use rustls
borngraced Oct 10, 2024
c7b41a8
update bip39 deps
borngraced Oct 11, 2024
8fc7620
fix wasm clippy
borngraced Oct 11, 2024
2d52404
add chains/tendermint test
borngraced Oct 11, 2024
4cbd2fa
minor changes, improve api
borngraced Oct 14, 2024
a57495d
remove subscription on session delete
borngraced Oct 14, 2024
c7e7de6
improve ledger external wallet connection checks
borngraced Oct 14, 2024
cc3c568
wc tx handling for tendermint
borngraced Oct 14, 2024
7683090
merge with dev and fix conflicts
borngraced Oct 14, 2024
5a574a6
complete persistent session storage with unit test for native and wasm
borngraced Oct 15, 2024
81ebee7
minor changes
borngraced Oct 15, 2024
46e3802
fix is ledger connection fn
borngraced Oct 17, 2024
500cb87
module refactorings
borngraced Oct 19, 2024
b2dea85
Merge branch 'dev' of github.com:KomodoPlatform/komodo-defi-framework…
borngraced Oct 20, 2024
1840ca8
introduce WcRequstOps trait, untighten code and more
borngraced Oct 21, 2024
6501134
commit cargo.lock
borngraced Oct 21, 2024
38dadbe
implement cosmos ledger amino sign support
borngraced Oct 21, 2024
301a5b0
fix fmt
borngraced Oct 21, 2024
3cde05b
start eth pubkey mode impl
borngraced Oct 22, 2024
5eb3e4c
save progress - impl wc eth_personal sign
borngraced Oct 22, 2024
b35bd4a
implement eth coin activation using walletconnect
borngraced Oct 23, 2024
337154c
eth walletconnect coin activation and message handler code improvements
borngraced Oct 24, 2024
b358825
improve session message handling process
borngraced Oct 24, 2024
afc4058
further wc improve message handling
borngraced Oct 24, 2024
18eb62f
uncommit mm2_test_helpers lock file
borngraced Oct 24, 2024
9c083ac
eth wc transaction - save dev state
borngraced Oct 25, 2024
7f37fd3
impl eth withdraw for walletconnect policy
borngraced Oct 26, 2024
6e57330
don't support sign_raw_tx rpc in walletconnect mode
borngraced Oct 26, 2024
e45243b
cleanups
borngraced Oct 27, 2024
a8d937e
improvements to session, wc ops, and more
borngraced Oct 28, 2024
1569ede
create connection with custom namespaces
borngraced Oct 28, 2024
4fc5a43
impl eth sign and send tx for WalletConnect
borngraced Oct 31, 2024
3792027
swaps working, impl connection health manager
borngraced Nov 1, 2024
0b1da04
remove debug log
borngraced Nov 1, 2024
f0659a4
connection_handler improvements
borngraced Nov 1, 2024
187bf5e
improve tendermint wc code
borngraced Nov 2, 2024
2a2f167
use const_hex
borngraced Nov 2, 2024
cd368bf
major changes to connection handling and other minor fixes
borngraced Nov 3, 2024
0c61287
add logging to wc storage impl
borngraced Nov 3, 2024
fe0d096
Merge branch 'refs/heads/dev' into wc-integration
borngraced Nov 3, 2024
a0220d7
fix conflict and minor changes + merge with dev branch
borngraced Nov 3, 2024
3468502
minor changes
borngraced Nov 4, 2024
c4a07e4
monitor if relay client is connected
borngraced Nov 4, 2024
1e78257
changes to client impls
borngraced Nov 6, 2024
a43dc60
handle broadcast option for WalletConnect and some minor fixes
borngraced Nov 6, 2024
eea1532
remove unused
borngraced Nov 6, 2024
fb9f8c1
fix: handle unexpected end of file
borngraced Nov 6, 2024
d58b18f
re-enable use_watcher
borngraced Nov 6, 2024
045625b
cleanups
borngraced Nov 6, 2024
65c7f90
fix websocket connection drop
borngraced Nov 12, 2024
2326959
handle conn drop for session creation
borngraced Nov 12, 2024
42eaa29
nits
borngraced Nov 12, 2024
4ad423e
Merge branch 'refs/heads/dev' into wc-integration
borngraced Nov 12, 2024
e82083a
fix conflict after merge
borngraced Nov 12, 2024
ad38241
nits
borngraced Nov 12, 2024
59db165
move storage to session manager and minor improvements
borngraced Nov 13, 2024
f5caa19
fix review notes
borngraced Nov 13, 2024
bb186c2
fix: self review
borngraced Nov 15, 2024
77d7909
fix review notes
borngraced Nov 16, 2024
0d3fdfe
increase rpc timeout and return PublicKey from recover
borngraced Nov 18, 2024
35d0fa4
fix review notes
borngraced Nov 18, 2024
db1e687
fmt
borngraced Nov 18, 2024
11d114d
remove dup session delete rpc
borngraced Nov 19, 2024
af91d47
rename var and remove unnecessary sorting from storage sessions loading
borngraced Nov 19, 2024
10e9e67
refactor wait_for_tx_appears_on_rpc to use secs for time
borngraced Nov 19, 2024
b9075ce
batch subscribe to topics
borngraced Nov 26, 2024
1ff17cd
rename ctx.session to ctx.session_manager
borngraced Nov 26, 2024
5e89b9f
use weak spawner to spawn wc related task/event loops
borngraced Nov 27, 2024
1fec24f
validate table name only during initialization
borngraced Nov 27, 2024
bdf9636
make required_namespaces required for wc activation and remove defaults
borngraced Nov 27, 2024
31c9594
use sync mutex for active topic
borngraced Nov 27, 2024
37a36f7
fix review notes
borngraced Nov 28, 2024
0351d67
Merge branch 'dev' into wc-integration
borngraced Nov 28, 2024
21f42f0
nits
borngraced Dec 3, 2024
c743464
bump wc libs
borngraced Dec 3, 2024
cab1b36
remove todo comment, replace remove const-hex crate
borngraced Dec 5, 2024
4e82c4f
remove dashmap
borngraced Dec 6, 2024
b96881e
revert mm2-parity-eth lib ver
borngraced Dec 6, 2024
738f941
review deps, add todo for WC ctx initialization
borngraced Dec 8, 2024
19b1d8a
reverse lock_api deps
borngraced Dec 8, 2024
9f73688
remove session request timestamp and add doc comments to message hand…
borngraced Dec 9, 2024
b874221
fix fmt
borngraced Dec 9, 2024
26ea297
review deps
borngraced Dec 9, 2024
371af58
use exponential backoff in spawn_connection_initializations reconnection
borngraced Dec 9, 2024
fdc18d7
remove redundancy and fix nits
borngraced Dec 9, 2024
e3d9a9f
Merge branch 'dev' into wc-integration
borngraced Dec 9, 2024
5f47368
fix notes and graceful shutdown on init failure
borngraced Dec 10, 2024
1860776
nits
borngraced Dec 10, 2024
27cf3fb
track message via message_id
borngraced Dec 11, 2024
06e4dc7
impl correlated message handling for inbound messages
borngraced Dec 11, 2024
25275e9
remove println
borngraced Dec 12, 2024
89756db
revert session property deserializing
borngraced Dec 12, 2024
a2c7c71
nits
borngraced Dec 12, 2024
bbddec5
Merge branch 'dev' into wc-integration
borngraced Dec 13, 2024
9db99ac
fix merge conflict
borngraced Dec 13, 2024
4739ec3
self review fixes
borngraced Dec 24, 2024
414fda5
nits
borngraced Dec 25, 2024
f95e385
bump WalletConnectRust lib
borngraced Dec 26, 2024
dd1a842
save dev state - implement dynamic session management for activated c…
borngraced Dec 31, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 0 additions & 15 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions mm2src/coins/eth/wallet_connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ impl WalletConnectOps for EthCoin {
wc.send_session_request_and_wait(&chain_id, WcRequestMethods::EthSendTransaction, tx_json, Ok)
.await?
};

println!("TX_JSON: {tx_hash:?}");
let tx_hash = tx_hash.strip_prefix("0x").unwrap_or(&tx_hash);
let maybe_signed_tx = {
self.wait_for_tx_appears_on_rpc(H256::from_slice(&hex::decode(tx_hash)?), WAIT_RPC_TIMEOUT_SECS, 1.)
Expand Down
1 change: 0 additions & 1 deletion mm2src/kdf_walletconnect/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ futures = { version = "0.3", package = "futures", features = [
"async-await",
] }
hkdf = "0.12.4"
dashmap = "6.1.0"
mariocynicys marked this conversation as resolved.
Show resolved Hide resolved
mm2_core = { path = "../mm2_core" }
mm2_db = { path = "../mm2_db" }
mm2_err_handle = { path = "../mm2_err_handle" }
Expand Down
17 changes: 14 additions & 3 deletions mm2src/kdf_walletconnect/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ use std::ops::Deref;
use std::{sync::Arc, time::Duration};
use storage::SessionStorageDb;
use storage::WalletConnectStorageOps;
use tokio::time::timeout;
use wc_common::{decode_and_decrypt_type0, encrypt_and_encode, EnvelopeType, SymKey};

const PUBLISH_TIMEOUT_SECS: f64 = 6.;
Expand Down Expand Up @@ -286,8 +287,14 @@ impl WalletConnectCtxImpl {
pairing_topics.push(pairing_topic);
}

let all_topics: Vec<_> = valid_topics.into_iter().chain(pairing_topics.into_iter()).collect();
self.client.batch_subscribe(all_topics).await?;
let all_topics = valid_topics
.into_iter()
.chain(pairing_topics.into_iter())
.collect::<Vec<_>>();

if !all_topics.is_empty() {
self.client.batch_subscribe(all_topics).await?;
}

Ok(())
}
Expand Down Expand Up @@ -535,7 +542,11 @@ impl WalletConnectCtxImpl {
let ttl = request.irn_metadata().ttl;
self.publish_request(&active_topic, request).await?;

if let Ok(Some(resp)) = self.message_rx.lock().await.next().timeout_secs(ttl as f64).await {
if let Ok(Some(resp)) = timeout(Duration::from_secs(ttl), async {
self.message_rx.lock().await.next().await
})
.await
{
let result = resp.mm_err(WalletConnectError::InternalError)?;
if let ResponseParamsSuccess::Arbitrary(data) = result.data {
let data = serde_json::from_value::<T>(data)?;
Expand Down
36 changes: 18 additions & 18 deletions mm2src/kdf_walletconnect/src/session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@ use crate::{error::WalletConnectError, WalletConnectCtxImpl};

use chrono::Utc;
use common::log::info;
use dashmap::mapref::multiple::RefMulti;
use dashmap::mapref::one::RefMut;
use dashmap::DashMap;
use derive_more::Display;
use key::SessionKey;
use mm2_err_handle::prelude::{MmError, MmResult};
Expand All @@ -21,9 +18,9 @@ use relay_rpc::{domain::SubscriptionId,
rpc::params::{session::ProposeNamespaces, session_settle::Controller, Metadata, Relay}};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashMap};
use std::fmt::Debug;
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
use wc_common::SymKey;

pub(crate) const FIVE_MINUTES: u64 = 5 * 60;
Expand Down Expand Up @@ -182,7 +179,7 @@ struct SessionManagerImpl {
/// The currently active session topic.
active_topic: Mutex<Option<Topic>>,
mariocynicys marked this conversation as resolved.
Show resolved Hide resolved
/// A thread-safe map of sessions indexed by topic.
sessions: DashMap<Topic, Session>,
sessions: Arc<RwLock<HashMap<Topic, Session>>>,
pub(crate) storage: SessionStorageDb,
}

Expand Down Expand Up @@ -216,6 +213,14 @@ impl SessionManager {
)
}

pub(crate) fn read(&self) -> RwLockReadGuard<HashMap<Topic, Session>> {
self.0.sessions.read().expect("read shouldn't fail")
}

pub(crate) fn write(&self) -> RwLockWriteGuard<HashMap<Topic, Session>> {
self.0.sessions.write().expect("read shouldn't fail")
}

pub(crate) fn storage(&self) -> &SessionStorageDb { &self.0.storage }

/// Get active session topic or return error if no session has been activated.
Expand All @@ -236,7 +241,7 @@ impl SessionManager {
// set active session topic.
*self.0.active_topic.lock().unwrap() = Some(session.topic.clone());
// insert session
self.0.sessions.insert(session.topic.clone(), session);
self.write().insert(session.topic.clone(), session);
}

/// Removes session corresponding to the specified topic from the session store.
Expand All @@ -246,12 +251,12 @@ impl SessionManager {
let mut active_topic = self.0.active_topic.lock().unwrap();

// Remove the session and get the removed session (if any)
let removed_session = self.0.sessions.remove(topic).map(|(_, session)| session);
let removed_session = self.write().remove(topic);

// Update active topic if necessary
if active_topic.as_ref() == Some(topic) {
// If the deleted session was the active one, find a new active session
*active_topic = self.0.sessions.iter().next().map(|session| session.topic.clone());
*active_topic = self.read().iter().next().map(|(topic, session)| topic.clone());

if let Some(new_active_topic) = active_topic.as_ref() {
info!("[{new_active_topic}] New session with topic activated!");
Expand All @@ -275,12 +280,7 @@ impl SessionManager {
}

/// Retrieves a cloned session associated with a given topic.
pub fn get_session(&self, topic: &Topic) -> Option<Session> { self.0.sessions.get(topic).map(|s| s.clone()) }

/// Retrieves a mutable reference to the session associated with a given topic.
pub(crate) fn get_session_mut(&self, topic: &Topic) -> Option<RefMut<'_, Topic, Session>> {
self.0.sessions.get_mut(topic)
}
pub fn get_session(&self, topic: &Topic) -> Option<Session> { self.read().get(topic).cloned() }

/// returns an `option<session>` containing the active session if it exists; otherwise, returns `none`.
pub fn get_session_active(&self) -> Option<Session> {
Expand All @@ -294,16 +294,16 @@ impl SessionManager {

/// Retrieves all sessions(active and inactive)
pub fn get_sessions(&self) -> impl Iterator<Item = SessionRpcInfo> {
self.0.sessions.clone().into_iter().map(|(_, session)| session.into())
self.read().clone().into_values().map(|session| session.into())
}

pub(crate) fn get_sessions_full(&self) -> impl Iterator<Item = RefMulti<Topic, Session>> { self.0.sessions.iter() }
pub(crate) fn get_sessions_full(&self) -> impl Iterator<Item = Session> { self.read().clone().into_values() }

/// Updates the expiry time of the session associated with the given topic to the specified timestamp.
/// If the session does not exist, this method does nothing.
pub(crate) fn extend_session(&self, topic: &Topic, till: u64) {
info!("[{topic}] Extending session with topic");
if let Some(mut session) = self.0.sessions.get_mut(topic) {
if let Some(mut session) = self.write().get_mut(topic) {
session.extend(till);
}
}
Expand Down
3 changes: 2 additions & 1 deletion mm2src/kdf_walletconnect/src/session/rpc/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ pub async fn handle_session_event(
} else {
{
ctx.session_manager
.get_session_mut(topic)
.write()
.get_mut(topic)
.ok_or(MmError::new(WalletConnectError::SessionError(
"No active WalletConnect session found".to_string(),
)))?
Expand Down
48 changes: 28 additions & 20 deletions mm2src/kdf_walletconnect/src/session/rpc/settle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::storage::WalletConnectStorageOps;
use crate::{error::WalletConnectError, WalletConnectCtxImpl};

use common::log::{debug, info};
use mm2_err_handle::prelude::{MapMmError, MmResult};
use mm2_err_handle::prelude::{MapMmError, MmError, MmResult};
use relay_rpc::domain::Topic;
use relay_rpc::rpc::params::session_settle::SessionSettleRequest;

Expand Down Expand Up @@ -40,27 +40,35 @@ pub(crate) async fn reply_session_settle_request(
settle: SessionSettleRequest,
) -> MmResult<(), WalletConnectError> {
{
let session = ctx.session_manager.get_session_mut(topic);
if let Some(mut session) = session {
session.namespaces = settle.namespaces.0;
session.controller = settle.controller.clone();
session.relay = settle.relay;
session.expiry = settle.expiry;

if let Some(value) = settle.session_properties {
let session_properties = serde_json::from_str::<SessionProperties>(&value.to_string())?;
session.session_properties = Some(session_properties);
}
let mut session = ctx.session_manager.write();
let Some(session) = session.get_mut(topic) else {
return MmError::err(WalletConnectError::SessionError(format!("No session found for topic: {topic}")));
};
session.namespaces = settle.namespaces.0;
session.controller = settle.controller.clone();
session.relay = settle.relay;
session.expiry = settle.expiry;

// Update storage session.
ctx.session_manager
.storage()
.update_session(&session)
.await
.mm_err(|err| WalletConnectError::StorageError(err.to_string()))?;
if let Some(value) = settle.session_properties {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any reason why not let settle.session_properties be of type Option<SessionProperties> instead of Option<Value>?

Copy link
Member Author

@borngraced borngraced Dec 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

session_properties field varies depending on the wallet and is currently used primarily by certain wallets like Keplr. Its fields can differ across wallets, as it isn’t standardized.

We can extend this using any enum once more wallets are discovered. For now, only Keplr sends this field during session initialization afaik.

pub session_properties: Option<SessionProperties>,

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you mean we want to be able to discard this field if we were not able to deserialize it?
i think then the serde_json::from_str::<SessionProperties>(&value.to_string())? should be optional, i.e. we shouldn't fail (?) the whole function if we fail deserializing the arbitrary value.

p.s. we can also use serde_json::from_value instead of from_str and ditch .to_string()

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any reason why not let settle.session_properties be of type Option<SessionProperties> instead of Option<Value>?

settle.session_properties is generic I mean it can be any arbitrary data depending on the wallet of course.

Copy link
Collaborator

@mariocynicys mariocynicys Dec 25, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so,

  • if session_properties isn't sent, it's fine since it's optional,
  • if session_properties is sent along in the request, we MUST succeed in parsing it (that means we must have an enumration of all the possible shapes it could be)
    • if we fail to de-serialize session_properties we will fail the request (the MUST part).

why do we need it as Option<Value> (instead of Option<SessionProperties>) if we will fail the request if we fail to deserialize it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not all wallet will send this payload e.g metamask doesn't send but Kelpr does and maybe TrustWallet

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if it's not sent we will deserialize it as None (because session_properties: Option<SessionProps>) so it's fine and exactly the same as using Option<Value>. the only diff is we let serde deser the value instead of we desering it ourselves.

Copy link
Member Author

@borngraced borngraced Dec 25, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

another thing, WalletConnect lib shouldn't handle this data since it can't know what type it is so that's why I delegate the data deserialization to the lib user, which I assume is the right way.

LIBRARY: doesn't have any idea what data it is, so session_properties: Option<Value>
USER: have an idea of what the data type is, so Option<SessionProps>

let session_properties = serde_json::from_str::<SessionProperties>(&value.to_string())?;
session.session_properties = Some(session_properties);
};
}
info!("Session successfully settled for topic: {:?}", topic);
};

// Update storage session.
let session = ctx
.session_manager
.get_session(topic)
.ok_or(MmError::new(WalletConnectError::SessionError(format!(
"session not foun topic: {topic}"
mariocynicys marked this conversation as resolved.
Show resolved Hide resolved
))))?;
ctx.session_manager
.storage()
.update_session(&session)
.await
.mm_err(|err| WalletConnectError::StorageError(err.to_string()))?;

info!("[{topic}] Session successfully settled for topic");

// Delete other sessions with same controller
// TODO: we might not want to do this!
Expand Down
39 changes: 24 additions & 15 deletions mm2src/kdf_walletconnect/src/session/rpc/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,33 @@ pub(crate) async fn reply_session_update_request(
update: SessionUpdateRequest,
) -> MmResult<(), WalletConnectError> {
{
if let Some(mut session) = ctx.session_manager.get_session_mut(topic) {
update
.namespaces
.caip2_validate()
.map_to_mm(|err| WalletConnectError::InternalError(err.to_string()))?;
//TODO: session.namespaces.supported(update.namespaces.0)
session.namespaces = update.namespaces.0;
// Update storage session.
ctx.session_manager
.storage()
.update_session(&session)
.await
.mm_err(|err| WalletConnectError::StorageError(err.to_string()))?;

info!("Updated extended, info: {:?}", session.topic);
let mut session = ctx.session_manager.write();
let Some(session) = session.get_mut(topic) else {
return MmError::err(WalletConnectError::SessionError(format!("No session found for topic: {topic}")));
};
update
.namespaces
.caip2_validate()
.map_to_mm(|err| WalletConnectError::InternalError(err.to_string()))?;
//TODO: session.namespaces.supported(update.namespaces.0)
session.namespaces = update.namespaces.0;
let session = session;
info!("Updated extended, info: {:?}", session.topic);
}

// Update storage session.
let session = ctx
.session_manager
.get_session(topic)
.ok_or(MmError::new(WalletConnectError::SessionError(format!(
"session not foun topic: {topic}"
))))?;
ctx.session_manager
.storage()
.update_session(&session)
.await
.mm_err(|err| WalletConnectError::StorageError(err.to_string()))?;

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

Expand Down
Loading