pyWalletConnect: A Python Library for WalletConnect Integration

Β·

Integrating decentralized applications (dApps) with crypto wallets has become a cornerstone of the Web3 experience. With pyWalletConnect, developers can seamlessly connect Python-based wallets to dApps using the WalletConnect protocol β€” all within a clean, automated stack. Whether you're building a command-line tool or a full GUI wallet in Python, this library simplifies secure remote communication between users and blockchain applications.

Built for Python 3.7+, pyWalletConnect handles the entire WalletConnect lifecycle: from session initiation and encrypted messaging to request processing and secure closure. It abstracts complex layers like WebSocket management, TLS encryption, JSON-RPC parsing, and relay coordination, allowing developers to focus on user interaction and transaction logic.


How pyWalletConnect Works

pyWalletConnect operates as the wallet-side client in the WalletConnect ecosystem. When a dApp generates a WalletConnect URI (via QR code or deep link), your Python wallet uses this library to establish a secure, bidirectional communication channel through an online relay server.

The architecture is layered and fully managed by the library:

WalletConnect
 |
Topics mgmt
 |
 JSON-RPC
 |
EncryptedTunnel
 |
 WebSocket
 |
 HTTP
 |
 TLS
 |
 Socket

This means developers don’t need to manually handle encryption keys, session persistence, or message queuing β€” pyWalletConnect does it all automatically.

Once connected, the dApp can send JSON-RPC requests such as eth_sign, eth_sendTransaction, or eth_signTypedData. These are securely relayed to your wallet, where they can be presented to the user for approval before signing and responding.

πŸ‘‰ Discover how easy it is to integrate secure wallet connectivity into your next project.


Installation and Setup

Getting started with pyWalletConnect is straightforward.

Prerequisites

Install via pip

python3 -m pip install pyWalletConnect

Install from Source

If you prefer installing directly from the repository:

git clone https://github.com/bitlogik/pywalletconnect.git
cd pywalletconnect
python3 -m pip install .

Basic Usage Example

Here’s a minimal working example that demonstrates how to initiate a WalletConnect session, handle connection requests, and respond to RPC calls.

from pywalletconnect import WCClient, WCClientInvalidOption

# Optional: Set wallet metadata (v2)
WALLET_METADATA = {
    "name": "My Python Wallet",
    "description": "A secure wallet built with Python",
    "url": "https://mypythonwallet.app",
    "icons": ["https://mypythonwallet.app/icon.png"]
}
WCClient.set_wallet_metadata(WALLET_METADATA)

# Required for v2
WCClient.set_project_id("your_walletconnect_project_id")

# Optional origin domain
WCClient.set_origin("https://example-dapp.com")

# Input WalletConnect URI from dApp
string_uri = input("Input the WalletConnect URI: ")

try:
    wallet_dapp = WCClient.from_wc_uri(string_uri)
except WCClientInvalidOption as exc:
    if hasattr(wallet_dapp, "wc_client"):
        wallet_dapp.close()
    raise ValueError(f"Invalid URI: {exc}")

# Wait for session request
try:
    req_id, chain_ids, request_info = wallet_dapp.open_session()
except Exception as e:
    wallet_dapp.close()
    raise TimeoutError("Session request timed out after 8 seconds.")

# Validate chain compatibility
if str(account.chainID) not in chain_ids:
    wallet_dapp.close()
    raise ValueError("Unsupported blockchain network.")

# Prompt user for approval
user_ok = input(f"Connect to {request_info['name']}? [y/N] ")
if user_ok.lower() == "y":
    wallet_dapp.reply_session_request(req_id, account.chainID, account.address)
    print("Session approved. Ready to receive requests.")
else:
    wallet_dapp.reject_session_request(req_id)
    wallet_dapp.close()
    print("Connection rejected by user.")

After approval, your wallet enters an active listening state. You’ll need to periodically check for incoming messages using .get_message().


Handling Incoming Requests

To keep the connection alive and responsive, implement a polling mechanism β€” either via a background thread or timer.

def process_sendtransaction(call_id, tx_params):
    # Present transaction details to user
    approve = input("Approve transaction? (y/N): ").lower()
    if approve == 'y':
        # Sign and broadcast transaction
        tx_hash = sign_and_broadcast(tx_params)
        return tx_hash
    else:
        return None

def watch_messages():
    while True:
        wc_message = wallet_dapp.get_message()
        while wc_message[0] is not None:
            req_id, method, params = wc_message

            if method == "eth_sendTransaction":
                result = process_sendtransaction(req_id, params[0])
                if result:
                    wallet_dapp.reply(req_id, result)
                else:
                    wallet_dapp.reply_error(req_id, "User rejected transaction", 4001)
            elif method == "eth_sign":
                # Handle signature request
                signed_data = sign_data(params[1])
                wallet_dapp.reply(req_id, signed_data)
            elif method in ["wc_sessionDelete", "wc_sessionUpdate"]:
                print("Session ended by dApp.")
                return

            wc_message = wallet_dapp.get_message()

Use a daemon thread or timer (every 3–6 seconds) to call watch_messages() regularly.

πŸ‘‰ Build smarter wallets faster with powerful integration tools.


Key Features and Methods

Class-Level Configuration

MethodPurpose
WCClient.set_wallet_metadata()Define wallet identity (name, icon, URL) for display in dApps (v2 only).
WCClient.set_project_id()Required for v2 connections using official relays. Obtain from WalletConnect Cloud.
WCClient.set_origin()Optional; sets HTTP origin header for WebSocket handshake (v2).

Instance Methods


Core Keywords

For optimal SEO performance and discoverability, these core keywords are naturally integrated throughout the content:

These terms reflect common search intents around developer tools for decentralized finance (DeFi), NFT platforms, and self-custodial wallets.


Frequently Asked Questions

What is pyWalletConnect used for?

pyWalletConnect enables Python-based cryptocurrency wallets to connect securely with Web3 dApps using the WalletConnect protocol. It allows remote signing of transactions and messages via encrypted relay channels.

Is pyWalletConnect compatible with WalletConnect v2?

Yes. The library supports both v1 and v2 of the WalletConnect protocol. For v2, you must set a project ID using set_project_id().

Do I need a backend server to use pyWalletConnect?

No. pyWalletConnect manages the WebSocket connection directly from your Python application to the public WalletConnect relay service. No custom backend is required.

Can I use pyWalletConnect in a GUI wallet?

Absolutely. While the examples are CLI-based, the library works perfectly in GUI environments using threading or async loops to poll for messages without blocking the UI.

How does session security work?

All communications are end-to-end encrypted using shared keys derived during pairing. Messages travel through a public relay but remain unreadable to third parties due to symmetric encryption.

What happens when the connection drops?

pyWalletConnect automatically attempts reconnection when .get_message() is called and detects a broken WebSocket. This ensures robustness even under unstable network conditions.


License and Support

pyWalletConnect is open-source software licensed under the GNU General Public License v3.0. It was developed by BitLogiK SAS and is freely available for use, modification, and distribution under the terms of GPLv3.

For support or bug reports, visit the GitHub repository and open an issue.

πŸ‘‰ Explore advanced integration options for your Web3 projects today.