Skip to content

Commit fe74aa9

Browse files
Problem: missing support for defi-wallet (fix #469) (#470)
defiwallet fix fix signing for defiwallet fix clippy remove test_fetch function remove legacy code run cargo test use runtime env fix warning change log
1 parent c4bdafa commit fe74aa9

9 files changed

Lines changed: 55 additions & 50 deletions

File tree

.github/workflows/ci.yml

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -49,15 +49,9 @@ jobs:
4949
~/.cargo/git/db/
5050
target/
5151
key: ${{ runner.os }}-cargo-stable-${{ hashFiles('**/Cargo.lock') }}
52-
- name: Install cargo-llvm-cov
53-
uses: taiki-e/install-action@cargo-llvm-cov
54-
- name: Generate code coverage
55-
run: cargo llvm-cov --all-features --all --lcov --output-path lcov.info
56-
- name: Upload coverage to Codecov
57-
uses: codecov/codecov-action@v3
58-
with:
59-
files: ./lcov.info
60-
fail_ci_if_error: true
52+
- name: Run tests
53+
run: cargo test --all-features --all
54+
6155
fmt:
6256
name: cargo fmt
6357
runs-on: ubuntu-latest

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
# Changelog
22
## [Unreleased]
33

4+
## [v0.0.25-alpha] - 2024-4-23
5+
- support defi-wallet
6+
47
## [v0.0.24-alpha] - 2023-12-4
58
- fix walletconnect 2.0 send_tx
69
- add from_address for walletconnect 2.0 sendtx

extra-cpp-bindings/src/wallectconnectregistry.rs

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -198,26 +198,6 @@ mod test {
198198
assert_eq!(wallets.len(), 20);
199199
}
200200

201-
#[test]
202-
fn test_fetch_new_no_cache() {
203-
let reg = Registry::fetch_new(None);
204-
assert!(reg.is_ok());
205-
}
206-
207-
#[test]
208-
fn test_fetch_new_with_cache() {
209-
let mut dir = std::env::temp_dir();
210-
let tmpfile = format!("{}.json", uuid::Uuid::new_v4());
211-
dir.push(tmpfile);
212-
println!("{:?}", dir);
213-
214-
let reg = Registry::fetch_new(Some(dir.clone()));
215-
assert!(reg.is_ok());
216-
217-
let reg = Registry::load_cached(Some(dir));
218-
assert!(reg.is_ok());
219-
}
220-
221201
#[test]
222202
fn test_load_cached() {
223203
let reg = Registry::load_cached(Some(PathBuf::from("./not_exists.json")));

integration_test.sh

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,5 @@ $PWD/demo/build/examples/get_tokens_blocking
3939
$PWD/demo/build/examples/get_token_transfers_blocking
4040
$PWD/demo/build/examples/create_payment
4141
$PWD/demo/build/examples/wallet_connect
42-
$PWD/demo/build/examples/get_token_holders
4342
$PWD/demo/build/examples/new_wallet
4443
$PWD/demo/build/examples/restore_wallet
45-
$PWD/demo/build/examples/get_wallet

wallet-connect/examples/web3_v2.rs

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,20 @@
1+
use defi_wallet_connect::v2::WCMiddleware;
12
use ethers::abi::Address;
23
use ethers::core::types::transaction::eip2718::TypedTransaction;
4+
use ethers::prelude::*;
35
use eyre::Result;
46
use image::Luma;
57
use qrcode::QrCode;
68
use std::fs;
79
use std::io;
810
use std::io::Write;
9-
//use ethers::ethers_providers::Middleware;
10-
use defi_wallet_connect::v2::WCMiddleware;
11-
use ethers::prelude::*;
1211

1312
use std::str::FromStr;
1413

1514
use defi_wallet_connect::v2::{Client, ClientOptions, Metadata, RequiredNamespaces, SessionInfo};
1615
use std::error::Error;
1716
use std::io::BufRead;
1817

19-
const RPC_URL: &str = env!("MY_RPC_URL");
20-
const CHAIN_ID: &str = env!("MY_CHAIN_ID");
21-
const FROM_ADDRESS: &str = env!("MY_FROM_ADDRESS");
22-
const TO_ADDRESS: &str = env!("MY_TO_ADDRESS");
23-
2418
#[derive(Debug, Default)]
2519
pub struct WalletConnectTxCommon {
2620
pub gas_limit: String, // decimal string, "1"
@@ -43,7 +37,9 @@ pub struct WalletConnectTxEip155 {
4337
async fn make_client(
4438
callback_sender: Option<tokio::sync::mpsc::UnboundedSender<String>>,
4539
) -> Result<Client, relay_client::Error> {
46-
let mychain = format!("eip155:{}", CHAIN_ID);
40+
let chain_id = std::env::var("MY_CHAIN_ID").expect("MY_CHAIN_ID not set");
41+
let mychain = format!("eip155:{}", chain_id);
42+
4743
let opts = ClientOptions {
4844
relay_server: "wss://relay.walletconnect.com".parse().expect("url"),
4945
project_id: std::env::args().skip(1).next().expect("project_id"),
@@ -200,7 +196,6 @@ pub async fn send_eip155_transaction_blocking(
200196
.await
201197
.map_err(|e| eyre::eyre!("send_typed_transaction error {}", e.to_string()))?;
202198

203-
//Ok(tx_bytes.0.to_vec())
204199
Ok(tx_bytes.0.to_vec())
205200
}
206201

@@ -225,7 +220,8 @@ async fn send_ethereum_transaction(
225220
let from_address = Address::from_str(from)?;
226221
let to_address = Address::from_str(to)?;
227222

228-
let provider = Provider::<Http>::try_from(RPC_URL)?;
223+
let rpc_url = std::env::var("MY_RPC_URL").expect("MY_RPC_URL not set");
224+
let provider = Provider::<Http>::try_from(rpc_url.as_str())?;
229225
let chain_id = provider.get_chainid().await?;
230226
let nonce = provider.get_transaction_count(from_address, None).await?;
231227
// Construct the transaction
@@ -296,18 +292,23 @@ async fn main() -> Result<(), Box<dyn Error>> {
296292
}
297293

298294
if test_sign_tx {
295+
let from_address = std::env::var("MY_FROM_ADDRESS").expect("MY_FROM_ADDRESS not set");
296+
let to_address = std::env::var("MY_TO_ADDRESS").expect("MY_TO_ADDRESS not set");
297+
299298
// convert fromaddress to 20 fixed byte array
300-
let fromaddress = Address::from_str(&FROM_ADDRESS)?;
299+
let fromaddress = Address::from_str(&from_address)?;
301300

302301
let txinfo = WalletConnectTxEip155 {
303302
common: WalletConnectTxCommon {
304-
chainid: CHAIN_ID.parse::<u64>()?,
303+
chainid: std::env::var("MY_CHAIN_ID")
304+
.expect("MY_CHAIN_ID not set")
305+
.parse::<u64>()?,
305306
gas_limit: "21000".into(),
306307
gas_price: "1000000000".into(),
307-
nonce: "0".into(),
308+
nonce: "".into(),
308309
web3api_url: "".into(),
309310
},
310-
to: TO_ADDRESS.into(),
311+
to: to_address.into(),
311312
data: vec![],
312313
value: "1000".into(),
313314
};
@@ -331,10 +332,13 @@ async fn main() -> Result<(), Box<dyn Error>> {
331332
}
332333

333334
if test_send_tx {
335+
let from_address = std::env::var("MY_FROM_ADDRESS").expect("MY_FROM_ADDRESS not set");
336+
let to_address = std::env::var("MY_TO_ADDRESS").expect("MY_TO_ADDRESS not set");
337+
334338
let amount = U256::from_dec_str("1000012345678912")?; // 1 ETH for example
335339

336340
let tx_hash =
337-
send_ethereum_transaction(&mut client, FROM_ADDRESS, TO_ADDRESS, amount).await?;
341+
send_ethereum_transaction(&mut client, &from_address, &to_address, amount).await?;
338342

339343
println!("Transaction sent with hash: {:?}", tx_hash);
340344
}

wallet-connect/src/crypto.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,4 @@ mod aead;
33
/// wrapper around the symmetric key
44
mod key;
55

6-
pub use aead::*;
76
pub use key::*;

wallet-connect/src/v2/client.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use async_trait::async_trait;
22
use ethers::prelude::PendingTransaction;
33
use ethers::types::transaction::eip2718::TypedTransaction;
44
use ethers::types::BlockId;
5+
use ethers::types::U256;
56
use ethers::{
67
prelude::{
78
Address, Bytes, JsonRpcClient, Middleware, MiddlewareError, NameOrAddress, Provider,
@@ -242,6 +243,21 @@ fn append_hex(s: String) -> String {
242243
}
243244
}
244245

246+
// tx_bytes is 32 bytes, for defi-wallet , it's txhash
247+
fn make_defiwallet_signature(tx_bytes: &[u8]) -> Option<Signature> {
248+
// print hex of tx_bytes
249+
if tx_bytes.len() == 32 {
250+
let r = U256::from_big_endian(tx_bytes);
251+
let s = U256::zero();
252+
let v = 0;
253+
// r: 32 bytes, s: 32bytes, v: 1 bytes
254+
let sig = Signature { r, s, v };
255+
Some(sig)
256+
} else {
257+
None
258+
}
259+
}
260+
245261
#[async_trait]
246262
impl Middleware for WCMiddleware<Provider<Client>> {
247263
type Error = WCError<Provider<Client>>;
@@ -268,6 +284,9 @@ impl Middleware for WCMiddleware<Provider<Client>> {
268284
}
269285
if let Some(data) = tx.data() {
270286
tx_obj.insert("data", format!("0x{}", hex::encode(data)));
287+
} else {
288+
// need for defi wallet, otherwise user rejection error
289+
tx_obj.insert("data", "0x".to_string());
271290
}
272291
if let Some(gas) = tx.gas() {
273292
// gas not working for webwallet
@@ -299,6 +318,14 @@ impl Middleware for WCMiddleware<Provider<Client>> {
299318
))));
300319
}
301320

321+
if tx_rlp.as_raw().len() == 32 {
322+
// It's not RLP-encoded
323+
return make_defiwallet_signature(tx_rlp.as_raw()).ok_or_else(|| {
324+
WCError::ClientError(ClientError::Eyre(eyre!(
325+
"failed to decode defiwallet tx-hash signature"
326+
)))
327+
});
328+
}
302329
let first_byte = tx_rlp.as_raw()[0];
303330
// TODO: check that the decoded request matches the typed transaction content here? or a new `sign_transaction` function that returns both request+signature?
304331
if first_byte <= 0x7f {

wallet-connect/src/v2/core.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -619,7 +619,7 @@ impl JsonRpcClient for Connector {
619619
.required_namespaces
620620
.eip155
621621
.chains
622-
.get(0)
622+
.first()
623623
.map(ToOwned::to_owned)
624624
.unwrap_or_else(|| "eip155:25".to_owned());
625625
// release the lock

wallet-connect/src/v2/protocol.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ pub struct WcSessionProposeResponse {
9292
pub struct WcSessionSettle {
9393
relay: Relay,
9494
pub namespaces: Namespaces,
95-
#[serde(rename = "requiredNamespaces")]
95+
#[serde(rename = "requiredNamespaces", default)]
9696
required_namespaces: RequiredNamespaces,
9797
pub controller: Peer,
9898
expiry: i64,

0 commit comments

Comments
 (0)