Note on Naming: Despite the repository name, this project is a backend service, not a UI component. It simulates the architectural logic of a decentralized bridge oracle.
This repository contains a Python-based simulation of a critical backend component for a cross-chain bridge: the Event Listener and Validator Node. This script monitors a source blockchain for specific events (e.g., TokensLocked), validates them, and then prepares and signs a corresponding message for the destination chain.
Cross-chain bridges allow users to transfer assets or data from one blockchain to another. A common architectural pattern is the "lock-and-mint" or "burn-and-release" mechanism. This script simulates the off-chain oracle or validator's role in this system.
- Listen: The service continuously monitors a
Bridgesmart contract on the source chain (e.g., Ethereum). - Detect: It looks for a specific event, such as
TokensLocked, which is emitted when a user deposits assets into the bridge contract, specifying a destination chain and recipient address. - Confirm: To mitigate the risk of block reorganizations (re-orgs)—where a block is temporarily orphaned and replaced—the service waits for a predefined number of
confirmation_blocksto pass before considering an event as final. - Validate & Attest: Once confirmed, the service (acting as a validator) processes the event data. It creates a standardized payload containing the details of the transfer (amount, recipient, etc.) and signs it with its private key. This signature is an attestation, a verifiable proof that the event occurred on the source chain.
- Dispatch: The signed attestation is then dispatched to the destination chain. In a real system, this could be sent to a relayer network or submitted directly to a smart contract on the destination chain, which would then mint the equivalent tokens for the user.
The script is designed with a modular, object-oriented approach to separate concerns and enhance maintainability.
+-----------------------+
| BridgeOrchestrator | (Main loop, coordinates all components)
+-----------+-----------+
|
| 1. Starts and manages
v
+-----------------------+
| EventScanner | (Scans source chain for events)
+-----------+-----------+
| |
| | 2. Uses connector to get block data
| v
| +-----------------------+
| | BlockchainConnector | (Manages Web3 connection)
| +-----------------------+
|
| 3. Passes confirmed events to
v
+-----------------------+
| TransactionProcessor | (Validates event data, creates payload)
+-----------+-----------+
|
| 4. Passes payload to
v
+-----------------------+
| CrossChainDispatcher | (Signs payload with validator key, sends to dest)
+-----------------------+
-
BlockchainConnector: A wrapper aroundweb3.pythat manages the connection to a blockchain's RPC endpoint. -
EventScanner: The heart of the listening process. It polls the source chain for new blocks, queries for specific contract events within a block range, and waits for confirmations before flagging an event as final. -
TransactionProcessor: A stateless logic class that takes a raw event log, validates its data (e.g., checking if it's intended for the correct destination chain), and transforms it into a structured, standardized payload.Conceptual Example:
def process_event(event_log): # Simplified logic args = event_log['args'] if args['destinationChainId'] != SUPPORTED_DEST_CHAIN_ID: return None return { "source_tx_hash": event_log['transactionHash'].hex(), "recipient": args['recipientAddress'], "amount": str(args['amount']), # ... and other fields }
-
CrossChainDispatcher: Simulates the validator's role. It takes the processed payload, signs it using a private key, and dispatches the signed message. In this simulation, it sends the signed data to a mock API endpoint. -
BridgeOrchestrator: The top-level class that initializes and integrates all other components. It runs the main asynchronous loop, controlling the flow from scanning to dispatching.
-
Configuration: The script loads its configuration from environment variables (via a
.envfile for secrets like RPC URLs and private keys) and supplements it with static settings from theCONFIGdictionary inscript.py. -
Initialization: The
BridgeOrchestratoris instantiated. It creates instances of theBlockchainConnector,EventScanner,TransactionProcessor, andCrossChainDispatcherusing the loaded configuration. -
Scanning Loop: The orchestrator starts its
run()method.- The
EventScannerdetermines the range of blocks to scan, from the last scanned block up to the latest block minus the required number of confirmations. - It uses
web3.pyto filter forTokensLockedevents within that block range.
- The
-
Processing: If any confirmed events are found:
- Each event is passed to the
TransactionProcessor. - The processor checks if the event's
destinationChainIdmatches the configured destination. If so, it creates a structured payload.
- Each event is passed to the
-
Dispatching:
- The valid payload is passed to the
CrossChainDispatcher. - The dispatcher serializes the payload into a standard format, hashes it (using Keccak-256), and signs the resulting hash with the validator's private key.
- The signed message is then sent to a mock API endpoint to simulate the completion of the cross-chain communication leg.
- The valid payload is passed to the
-
Repeat: The orchestrator pauses for a configured interval (
poll_interval_seconds) and then repeats the loop.
The listener is configured to watch for a specific event signature on the source bridge contract. For this simulation, it targets a TokensLocked event, which might be defined in a Solidity smart contract like this:
// Example Solidity event in the source Bridge.sol contract
event TokensLocked(
address indexed user,
address indexed token,
uint256 amount,
uint256 destinationChainId,
bytes recipientAddress
);When a user locks tokens, this event is emitted, and its data becomes the input for the cross-chain validation and dispatch process.
- Python 3.8+
- An RPC URL for an EVM-compatible source chain (e.g., from Infura or Alchemy for Sepolia testnet).
- A private key for the account that will act as the validator. Use a burner account with no real funds.
Clone the repository and install the required dependencies.
# 1. Clone this repository
git clone https://github.com/your-username/react-query-builder.git
cd react-query-builder
# 2. Create and activate a virtual environment (optional but recommended)
python -m venv venv
source venv/bin/activate # On Windows, use: venv\Scripts\activate
# 3. Install dependencies
pip install -r requirements.txtCreate a .env file in the root of the project directory and add your configuration details. This file is ignored by Git to protect your secrets.
# .env file
# RPC URL for the blockchain you want to listen to (e.g., Ethereum Sepolia)
SOURCE_CHAIN_RPC_URL="https://sepolia.infura.io/v3/YOUR_INFURA_PROJECT_ID"
# Address of the bridge contract to monitor on the source chain.
# If not set, the script uses a default address on Sepolia for demonstration.
SOURCE_BRIDGE_CONTRACT="0x_your_bridge_contract_address_here"
# Private key of the account that will sign the attestations.
# MUST start with 0x. USE A BURNER ACCOUNT WITH NO REAL FUNDS.
VALIDATOR_PRIVATE_KEY="0x_your_burner_private_key_here"Execute the script from your terminal.
python script.pyThe script will start, connect to the source chain, and begin scanning for events. The console will show detailed log output of its operations.
# Example Output
2023-10-27 15:30:00 - BridgeOrchestrator - [INFO] - Initializing Bridge Orchestrator...
2023-10-27 15:30:01 - BlockchainConnector - [INFO] - Successfully connected to Ethereum-Sepolia (Chain ID: 11155111).
2023-10-27 15:30:01 - EventScanner - [INFO] - Initializing bridge contract on Ethereum-Sepolia at 0x...
2023-10-27 15:30:01 - TransactionProcessor - [INFO] - TransactionProcessor initialized for source 11155111 -> dest Polygon-Mumbai
2023-10-27 15:30:01 - CrossChainDispatcher - [INFO] - Dispatcher initialized with validator address: 0x...
2023-10-27 15:30:01 - BridgeOrchestrator - [INFO] - Bridge Event Listener service starting.
2023-10-27 15:30:02 - EventScanner - [INFO] - Scanning Ethereum-Sepolia from block 4851200 to 4851210...
2023-10-27 15:30:04 - BridgeOrchestrator - [INFO] - No new confirmed events found. Waiting for 10 seconds.
...