### Install Rust and WebAssembly Toolchain Source: https://docs.hyperbridge.network/developers/network/node Setup the Rust compiler and the required WebAssembly target for the Hyperbridge runtime. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` ```bash rustup update nightly rustup target add wasm32-unknown-unknown rustup target add wasm32-unknown-unknown --toolchain nightly rustup component add rust-src ``` -------------------------------- ### Install Prebuilt Binaries Source: https://docs.hyperbridge.network/developers/network/node Commands to download and install the latest Hyperbridge binary or use the automated installer script. ```bash LATEST_TAG=$(curl -s https://hub.docker.com/v2/repositories/polytopelabs/hyperbridge/tags\?page_size\=1\&page\=2 | jq -r '.results[0].name') wget -q --show-progress https://github.com/polytope-labs/hyperbridge/releases/download/hyperbridge-$LATEST_TAG/hyperbridge-x86_64-unknown-linux-gnu.tar.gz tar -xvzf hyperbridge-x86_64-unknown-linux-gnu.tar.gz # copy to $PATH cp hyperbridge-x86_64-unknown-linux-gnu/hyperbridge $HOME/.local/bin/ ``` ```bash LATEST_TAG=$(curl -s https://hub.docker.com/v2/repositories/polytopelabs/hyperbridge/tags\?page_size\=1\&page\=2 | jq -r '.results[0].name') curl --proto '=https' --tlsv1.2 -LsSf https://github.com/polytope-labs/hyperbridge/releases/download/hyperbridge-$LATEST_TAG/hyperbridge-installer.sh | sh ``` -------------------------------- ### Run Simplex Docker Container Source: https://docs.hyperbridge.network/developers/intent-gateway/simplex Pull the latest Simplex Docker image and run it with the --help flag to see available options. This is the recommended way to get started with Simplex. ```bash docker pull polytopelabs/simplex:latest docker run --rm -it simplex --help ``` -------------------------------- ### Tesseract Configuration Example Source: https://docs.hyperbridge.network/developers/network/messaging-relayer Example configuration file settings for a substrate node connection. ```toml rpc_ws = "ws://127.0.0.1:9944" # example endpoint # The consensus state identifier for this chain on hyperbridge. # "DOT0" for parachains on mainnet and "PAS0" on Paseo testnet consensus_state_id = "PAS0" # (Optional) # Configures the maximum size of an rpc request/response in bytes # max_rpc_payload_size = 150000000 # Hex-encoded private key for the relayer account on this chain signer = "" # (Optional) Frequency in seconds to poll the chain # for new state machine update events # poll_interval = 10 # (Optional) initial height # This sets the height at which to start querying messages, # This exists for testing and development, # misuse can cause the rpc to be overloaded with queries # initial_height = 1000 # (Optional) # This provides the relayer with the precision for the fee token on this substrate chain # Needed for ensuring correct delivery fee estimation # It defaults to 6 which is the decimal for USDC and USDT on Polkadot parachains # fee_token_decimals = 6 ``` -------------------------------- ### Install Rust Compiler Source: https://docs.hyperbridge.network/developers/network/messaging-relayer Installs the Rust compiler and build tools using the official rustup script. Follow the on-screen prompts for a default installation. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Install Hyperbridge SDK with pnpm Source: https://docs.hyperbridge.network/developers/sdk/getting-started Install the Hyperbridge SDK using pnpm. Ensure Node.js 22+ is installed. ```bash pnpm add @hyperbridge/sdk ``` -------------------------------- ### Usage Example Source: https://docs.hyperbridge.network/developers/sdk/api/substrate-chain A comprehensive example demonstrating how to connect to Hyperbridge, query data, and disconnect. ```APIDOC ## Usage Example ```javascript import { SubstrateChain } from "@hyperbridge/sdk" // Create and connect to Hyperbridge const hyperbridge = await SubstrateChain.connect({ stateMachineId: "POLKADOT-3367", wsUrl: "wss://hyperbridge-rpc.polkadot.io", consensusStateId: "DOT0", hasher: "Keccak" }) try { // Query current timestamp const time = await hyperbridge.timestamp() console.log(`Current time: ${time}`) // Check if a request was delivered const receipt = await hyperbridge.queryRequestReceipt(commitmentHash) if (receipt) { console.log(`Delivered by: ${receipt}`) } // Get latest state machine height const height = await hyperbridge.latestStateMachineHeight({ stateId: { Ethereum: 1 } }) console.log(`Latest Ethereum height: ${height}`) } finally { // Always disconnect when done await hyperbridge.disconnect() } ``` ``` -------------------------------- ### Install Build Dependencies Source: https://docs.hyperbridge.network/developers/network/node System-specific commands to install required dependencies for building from source. ```bash sudo apt update sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler ``` ```bash pacman -Syu --needed --noconfirm curl git clang make protobuf ``` ```bash sudo dnf update sudo dnf install clang curl git openssl-devel make protobuf-compiler ``` ```bash sudo zypper install clang curl git openssl-devel llvm-devel libudev-devel make protobuf ``` -------------------------------- ### Install Subkey Tool Source: https://docs.hyperbridge.network/developers/network/collator Installs the Subkey utility for managing Substrate-based cryptographic keys. ```bash cargo install subkey ``` -------------------------------- ### Install Hyperbridge SDK with yarn Source: https://docs.hyperbridge.network/developers/sdk/getting-started Install the Hyperbridge SDK using yarn. Ensure Node.js 22+ is installed. ```bash yarn add @hyperbridge/sdk ``` -------------------------------- ### Setup SNARK and Commit Validator Set Source: https://docs.hyperbridge.network/protocol/consensus/casper-ffg Performs the SNARK setup and computes the commitment to the validator set. Outputs setup keys and the initial commitment. ```pseudocode Setup(s,t,V): ⟨srspk​,srsvk​⟩→APK.Setup(t,s) C=APK.Commit(srspk​,V) srsuk​=gL(s) Output ⟨srsuk​,srspk​,srsvk​⟩ ``` -------------------------------- ### Install Tesseract Relayer with One-Liner Script Source: https://docs.hyperbridge.network/developers/network/messaging-relayer Installs the Tesseract relayer using a single bash command. This script downloads and executes an installer script from GitHub. ```bash LATEST_TAG=$(curl -s https://hub.docker.com/v2/repositories/polytopelabs/tesseract/tags?page_size=1&page=2 | jq -r '.results[0].name') curl --proto '=https' --tlsv1.2 -LsSf https://github.com/polytope-labs/hyperbridge/releases/download/tesseract-$LATEST_TAG/tesseract-installer.sh | sh ``` -------------------------------- ### Install Dependencies on OpenSUSE Source: https://docs.hyperbridge.network/developers/network/messaging-relayer Installs necessary build dependencies for the Tesseract relayer on OpenSUSE using zypper. ```bash sudo zypper install clang curl git openssl-devel llvm-devel libudev-devel make protobuf ``` -------------------------------- ### Dispatching a GET Request to Read Remote Balance Source: https://docs.hyperbridge.network/developers/evm/dispatching/get-requests Example function to dispatch a GET request for reading an account's token balance on a remote chain. It constructs the necessary storage keys and populates the `DispatchGet` struct. ```solidity function readRemoteBalance( address token, address account, bytes memory dest ) public payable returns (bytes32) { // Calculate the storage slot for balanceOf[account] bytes32 slot = keccak256(abi.encode(account, uint256(0))); // Assuming balances at slot 0 // Construct the storage key (20 bytes address + 32 bytes slot) bytes[] memory keys = new bytes[](1); keys[0] = bytes.concat(bytes20(token), slot); // Encode context to track this request bytes memory context = abi.encode(token, account); DispatchGet memory request = DispatchGet({ dest: dest, height: 0, // Latest finalized block keys: keys, timeout: 3600, // 1 hour fee: msg.value, context: new bytes(0) // empty for this use-case }); return IDispatcher(_host).dispatch{value: msg.value}(request); } ``` -------------------------------- ### Install Hyperbridge SDK Source: https://docs.hyperbridge.network/developers/sdk/vite-integration Install the Hyperbridge SDK package using npm. This includes the Vite plugin. ```bash npm install @hyperbridge/sdk ``` -------------------------------- ### Install Dependencies on Debian/Ubuntu Source: https://docs.hyperbridge.network/developers/network/messaging-relayer Installs necessary build dependencies for the Tesseract relayer on Debian-based systems using apt. ```bash sudo apt update sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler ``` -------------------------------- ### Install Dependencies on Fedora Source: https://docs.hyperbridge.network/developers/network/messaging-relayer Installs necessary build dependencies for the Tesseract relayer on Fedora using dnf. ```bash sudo dnf update sudo dnf install clang curl git openssl-devel make protobuf-compiler ``` -------------------------------- ### Install Dependencies on Arch Linux Source: https://docs.hyperbridge.network/developers/network/messaging-relayer Installs necessary build dependencies for the Tesseract relayer on Arch Linux using pacman. ```bash pacman -Syu --needed --noconfirm curl git clang make protobuf ``` -------------------------------- ### Download and Install Tesseract Relayer (Bash) Source: https://docs.hyperbridge.network/developers/network/messaging-relayer Installs the Tesseract relayer using prebuilt binaries. It fetches the latest release, extracts it, and copies the executable to your PATH. ```bash LATEST_TAG=$(curl -s https://hub.docker.com/v2/repositories/polytopelabs/tesseract/tags?page_size=1&page=2 | jq -r '.results[0].name') wget -q --show-progress https://github.com/polytope-labs/hyperbridge/releases/download/tesseract-$LATEST_TAG/tesseract-x86_64-unknown-linux-gnu.tar.gz tar -xvzf tesseract-x86_64-unknown-linux-gnu.tar.gz # copy to $PATH cp tesseract-x86_64-unknown-linux-gnu/tesseract $HOME/.local/bin/ ``` -------------------------------- ### Full usage example Source: https://docs.hyperbridge.network/developers/sdk/api/substrate-chain Demonstrates connecting to Hyperbridge, querying data, and handling cleanup. ```typescript import { SubstrateChain } from "@hyperbridge/sdk" // Create and connect to Hyperbridge const hyperbridge = await SubstrateChain.connect({ stateMachineId: "POLKADOT-3367", wsUrl: "wss://hyperbridge-rpc.polkadot.io", consensusStateId: "DOT0", hasher: "Keccak" }) try { // Query current timestamp const time = await hyperbridge.timestamp() console.log(`Current time: ${time}`) // Check if a request was delivered const receipt = await hyperbridge.queryRequestReceipt(commitmentHash) if (receipt) { console.log(`Delivered by: ${receipt}`) } // Get latest state machine height const height = await hyperbridge.latestStateMachineHeight({ stateId: { Ethereum: 1 } }) console.log(`Latest Ethereum height: ${height}`) } finally { // Always disconnect when done await hyperbridge.disconnect() } ``` -------------------------------- ### Install Tesseract via Bash Script Source: https://docs.hyperbridge.network/developers/network/consensus-relayer Use these scripts to download and install the latest Tesseract consensus relayer binary on x86 Linux systems. ```bash LATEST_TAG=$(curl -s https://hub.docker.com/v2/repositories/polytopelabs/tesseract-consensus/tags\?page_size\=1\&page\=2 | jq -r '.results[0].name') wget -q --show-progress https://github.com/polytope-labs/hyperbridge/releases/download/tesseract-consensus-$LATEST_TAG/tesseract-x86_64-unknown-linux-gnu.tar.gz tar -xvzf tesseract-x86_64-unknown-linux-gnu.tar.gz # copy to $PATH cp tesseract-x86_64-unknown-linux-gnu/tesseract $HOME/.local/bin/ ``` ```bash LATEST_TAG=$(curl -s https://hub.docker.com/v2/repositories/polytopelabs/tesseract-consensus/tags\?page_size\=1\&page\=2 | jq -r '.results[0].name') curl --proto '=https' --tlsv1.2 -LsSf https://github.com/polytope-labs/hyperbridge/releases/download/tesseract-consensus-$LATEST_TAG/tesseract-installer.sh | sh ``` -------------------------------- ### Install @hyperbridge/core with pnpm Source: https://docs.hyperbridge.network/developers/evm/overview Install the Hyperbridge core package using pnpm. This package provides the necessary interfaces and SDKs for cross-chain communication. ```bash pnpm add @hyperbridge/core ``` -------------------------------- ### Install @hyperbridge/core with npm Source: https://docs.hyperbridge.network/developers/evm/overview Install the Hyperbridge core package using npm. This package provides the necessary interfaces and SDKs for cross-chain communication. ```bash npm install @hyperbridge/core ``` -------------------------------- ### Install @hyperbridge/core with yarn Source: https://docs.hyperbridge.network/developers/evm/overview Install the Hyperbridge core package using yarn. This package provides the necessary interfaces and SDKs for cross-chain communication. ```bash yarn add @hyperbridge/core ``` -------------------------------- ### Calculate GET Request Protocol Fee with Context (Solidity) Source: https://docs.hyperbridge.network/developers/evm/dispatching/get-requests Calculates the protocol fee for a GET request in Solidity, assuming `get.fee` is set to 0. Demonstrates fee calculation based on context length and minimum fee. ```solidity // Query the per-byte fee for Hyperbridge (the host) bytes memory host = IDispatcher(hostAddr).host(); uint256 perByteFee = IDispatcher(hostAddr).perByteFee(host); // Calculate minimum fee (32 bytes) uint256 minimumFee = 32 * perByteFee; // Calculate total fee based on context uint256 totalFee = 0 + (perByteFee * context.length); // get.fee = 0 // Actual fee is the maximum uint256 actualFee = minimumFee > totalFee ? minimumFee : totalFee; ``` -------------------------------- ### Tesseract Relayer Configuration Example Source: https://docs.hyperbridge.network/developers/network/messaging-relayer Example TOML configuration for the Tesseract relayer. Specifies the state machine, hashing algorithm, RPC endpoint, and signer private key. ```toml # Hyperbridge config, required [hyperbridge] # For mainnet "POLKADOT-3367" state_machine = "KUSAMA-4009" hashing = "Keccak" # Hyperbridge node ws rpc endpoint. rpc_ws = "ws://127.0.0.1:9944" # example endpoint # hex-encoded private key for the relayer account on Hyperbridge. # This is the private key to the Hyperbridge account where you earn BRIDGE token rewards signer = "" # Sets the maximum size of an rpc request or response # in bytes defaults to 150mb # max_rpc_payload_size = 150000000 # (Optional) initial height ``` -------------------------------- ### Complete SDK Initialization and Request Tracking Source: https://docs.hyperbridge.network/developers/sdk/getting-started A full implementation example showing chain instance creation, client initialization, and monitoring a request status stream. ```typescript import { IndexerClient, createQueryClient, EvmChain, SubstrateChain } from "@hyperbridge/sdk" async function main() { // 1. Create query client const queryClient = createQueryClient({ url: "https://gargantua.indexer.polytope.technology" }) // 2. Create chain instances — auto-detects chain ID and IsmpHost address const sourceChain = await EvmChain.create("https://data-seed-prebsc-1-s1.binance.org:8545") const destChain = await EvmChain.create("https://rpc.chiadochain.net") const hyperbridgeChain = await SubstrateChain.connect({ stateMachineId: "KUSAMA-4009", wsUrl: "wss://gargantua.polytope.technology", hasher: "Keccak", consensusStateId: "PAS0" }) // 3. Initialize IndexerClient const indexer = new IndexerClient({ queryClient, pollInterval: 1_000, source: sourceChain, dest: destChain, hyperbridge: hyperbridgeChain }) console.log("✓ SDK initialized successfully!") // 4. Track a request (example) const requestHash = "0xYourRequestHashHere" for await (const status of indexer.postRequestStatusStream(requestHash)) { console.log(`Status: ${status.status}`) if (status.status === "DESTINATION" || status.status === "PENDING_TIMEOUT") { break } } // Clean up await hyperbridgeChain.disconnect() } main().catch(console.error) ``` -------------------------------- ### Get Host State Machine Identifier Source: https://docs.hyperbridge.network/developers/evm/api/idispatcher Returns the state machine identifier for the current host chain. Example: "EVM-1" for Ethereum. ```solidity function host() external view returns (bytes memory) ``` -------------------------------- ### Setup Hyperbridge SDK environment Source: https://docs.hyperbridge.network/developers/intent-gateway/cancelling-orders Initializes the necessary clients and wallet configurations required to interact with the Hyperbridge SDK. ```typescript import { EvmChain, IntentsCoprocessor, IntentGateway, IndexerClient, createQueryClient } from "@hyperbridge/sdk" import { createWalletClient, http } from "viem" import { privateKeyToAccount } from "viem/accounts" const sourceChain = await EvmChain.create("https://eth-mainnet.g.alchemy.com/v2/demo") const destChain = await EvmChain.create("https://arbitrum-one.public.blastapi.io") const coprocessor = await IntentsCoprocessor.connect("wss://nexus.ibp.network") const intentGateway = await IntentGateway.create(sourceChain, destChain, coprocessor) const queryClient = createQueryClient({ url: "https://nexus.indexer.polytope.technology" }) const indexerClient = new IndexerClient({ queryClient, source: sourceChain, dest: destChain }) const account = privateKeyToAccount("0xYOUR_PRIVATE_KEY") const sourceWallet = createWalletClient({ account, transport: http("https://eth-mainnet.g.alchemy.com/v2/demo") }) const destWallet = createWalletClient({ account, transport: http("https://arbitrum-one.public.blastapi.io") }) ``` -------------------------------- ### Configure Path and Install Binary Source: https://docs.hyperbridge.network/developers/network/node Update shell configuration to include the binary directory and move the compiled node. ```bash export RC_PATH=${HOME}/.bashrc echo 'export PATH="${HOME}/.local/bin:${PATH}"' >> ${RC_PATH} source ${RC_PATH} ``` ```bash mkdir -p $HOME/.local/bin/ mv target/release/hyperbridge $HOME/.local/bin/ ``` -------------------------------- ### Get Request Event Source: https://docs.hyperbridge.network/developers/evm/api/idispatcher Emitted when a new GET request is dispatched. ```solidity event GetRequestEvent( string source, string dest, address indexed from, bytes[] keys, uint256 height, uint256 nonce, uint256 timeoutTimestamp, bytes context, uint256 fee ) ``` -------------------------------- ### EVM Account State Key Example Source: https://docs.hyperbridge.network/developers/evm/dispatching/get-requests Shows how to create a storage key to read account-level information for an EVM address. This key is simply the 20-byte address itself. ```solidity // Reading account state for an address address account = 0x1234...; bytes memory key = bytes20(account); ``` -------------------------------- ### Handle GET request timeout Source: https://docs.hyperbridge.network/developers/evm/api/hyperapp Override to handle cases where a sent GET request times out. ```solidity function onGetTimeout(GetRequest memory request) external virtual onlyHost ``` -------------------------------- ### latestStateMachineHeight() - Get Latest State Machine Height Source: https://docs.hyperbridge.network/developers/sdk/api/substrate-chain Gets the latest known height for a state machine. ```APIDOC ## POST /latestStateMachineHeight ### Description Gets the latest known height for a state machine. ### Method POST ### Endpoint /latestStateMachineHeight ### Parameters #### Request Body - **stateMachineId** (StateMachineIdParams) - Required - The state machine identifier ### Request Example ```json { "stateMachineId": { "stateId": { "Ethereum": 1 } } } ``` ### Response #### Success Response (200) - **height** (bigint) - Latest state machine height #### Response Example ```json { "height": 123456789n } ``` ``` -------------------------------- ### Instantiate EvmChain via create Source: https://docs.hyperbridge.network/developers/sdk/api/evm-chain Recommended method for initializing an EvmChain by auto-detecting parameters from an RPC URL. ```typescript static async create(rpcUrl: string, bundlerUrl?: string): Promise ``` ```typescript import { EvmChain } from "@hyperbridge/sdk" // Auto-detect chain from RPC const chain = await EvmChain.create("https://mainnet.base.org") // With ERC-4337 bundler for IntentGateway const destChain = await EvmChain.create( "https://arb-mainnet.g.alchemy.com/v2/YOUR_KEY", "https://bundler.example.com" ) ``` -------------------------------- ### Query GET Request Directly Source: https://docs.hyperbridge.network/developers/sdk/tracking/get-requests Perform a direct query for a GET request status without initializing an IndexerClient. ```typescript import { createQueryClient, queryGetRequest } from "@hyperbridge/sdk" const queryClient = createQueryClient({ url: "https://hyperbridge-indexer-url", }) const commitmentHash = "0x..." const request = await queryGetRequest({ commitmentHash, queryClient }) if (request) { console.log("Request statuses:", request.statuses) console.log("Request details:", request) console.log("Storage keys queried:", request.keys) } ``` -------------------------------- ### SubstrateChain Configuration and Connection Source: https://docs.hyperbridge.network/developers/sdk/api/substrate-chain Details on configuring and connecting to a Substrate chain using ISubstrateConfig. ```APIDOC ## SubstrateChain.connect(params) ### Description Establishes a connection to a Substrate chain using the provided configuration. ### Method `connect()` ### Parameters #### Request Body - **params** (ISubstrateConfig) - Required - Configuration object for the Substrate chain. ### Request Example ```json { "wsUrl": "wss://rpc.polkadot.io", "consensusStateId": "0x1234abcd...", "hasher": "Keccak", "stateMachineId": "POLKADOT-3367" } ``` ### Response #### Success Response (200) Indicates a successful connection. #### Response Example ```json { "status": "connected" } ``` ``` -------------------------------- ### dispatchWithFeeToken (GET Request) Source: https://docs.hyperbridge.network/developers/evm/api/hyperapp Dispatches a GET request using the fee token for payment, handling approvals automatically. ```APIDOC ## dispatchWithFeeToken(DispatchGet) ### Description Dispatches a GET request using the fee token for payment, handling approvals automatically. ### Parameters #### Request Body - **request** (DispatchGet) - Required - The GET request to dispatch - **payer** (address) - Required - Address that will pay the fee token ### Response - **bytes32** - Commitment hash identifying the dispatched request ``` -------------------------------- ### Handle incoming GET response Source: https://docs.hyperbridge.network/developers/evm/api/hyperapp Override to process state data from a GET response. Response values are RLP-encoded. ```solidity function onGetResponse(IncomingGetResponse memory incoming) external virtual onlyHost ``` -------------------------------- ### SubstrateChain.connect Source: https://docs.hyperbridge.network/developers/sdk/api/substrate-chain Static factory method to create and connect a new SubstrateChain instance. ```APIDOC ## Static Method: SubstrateChain.connect ### Description Creates a new SubstrateChain instance and establishes a WebSocket connection to the specified node. ### Parameters #### Request Body - **params.stateMachineId** (string) - Required - State machine identifier (e.g., "POLKADOT-3367") - **params.wsUrl** (string) - Required - WebSocket URL for the Substrate node (must be an archive node) - **params.consensusStateId** (string) - Required - Consensus state identifier on Hyperbridge - **params.hasher** ("Blake2" | "Keccak") - Required - Hashing algorithm used by the chain ### Response #### Success Response (200) - **SubstrateChain** (Object) - A connected chain instance. ``` -------------------------------- ### GET /queryGetRequest Source: https://docs.hyperbridge.network/developers/sdk/tracking/get-requests Queries the status of a GET request directly using a commitment hash without requiring an IndexerClient instance. ```APIDOC ## GET /queryGetRequest ### Description Queries the current status and details of a GET request using its commitment hash. ### Method GET ### Parameters #### Request Body - **commitmentHash** (string) - Required - The unique hash identifying the GET request. - **queryClient** (object) - Required - The initialized query client instance. ### Request Example { "commitmentHash": "0x...", "queryClient": "queryClientInstance" } ### Response #### Success Response (200) - **statuses** (Array) - List of status updates for the request. - **keys** (Array) - Storage keys queried during the request. #### Response Example { "statuses": [], "keys": [], "blockHash": "0x...", "blockNumber": 12345 } ``` -------------------------------- ### Register Native Token with EVM Deployments Source: https://docs.hyperbridge.network/developers/polkadot/token-gateway Use `utility.batchAll` to combine `createAssetMapping` and `registerStandaloneChainNativeAssets` for tokens natively minted on a Substrate chain with EVM deployments. Ensure correct chain IDs and addresses are provided. ```rust use sp_io::hashing::keccak_256; // The token gateway asset ID is keccak256 of the symbol let asset_id: H256 = keccak_256(b"MYTOKEN").into(); let call = RuntimeCall::Utility(pallet_utility::Call::batch_all { calls: vec![ // 1. Register the token contract addresses on EVM chains RuntimeCall::TokenGovernor( pallet_token_governor::Call::create_asset_mapping { asset: ERC20AssetRegistration { name: b"My Token".to_vec().try_into().unwrap(), symbol: b"MYTOKEN".to_vec().try_into().unwrap(), chains: vec![ AssetRegistration { chain: StateMachine::Evm(1), // Ethereum erc20: Some(H160::from_str("0x...").unwrap()), erc6160: Some(H160::from_str("0x0000000000000000000000000000000000000001")), }, AssetRegistration { chain: StateMachine::Evm(42161), // Arbitrum erc20: Some(H160::from_str("0x...").unwrap()), erc6160: Some(H160::from_str("0x0000000000000000000000000000000000000001")), }, ], }, }, ), // 2. Register the asset as native to the substrate chain RuntimeCall::TokenGovernor( pallet_token_governor::Call::register_standalone_chain_native_assets { assets: BTreeMap::from([( StateMachine::Polkadot(2000), // The chain where the token is natively minted BTreeSet::from([asset_id]), )]), }, ), ], }); ``` -------------------------------- ### Dispatch GET request with fee token Source: https://docs.hyperbridge.network/developers/evm/api/hyperapp Dispatches a GET request using the fee token for payment, automatically handling approvals. ```solidity function dispatchWithFeeToken(DispatchGet memory request, address payer) internal returns (bytes32) ``` -------------------------------- ### SubstrateChain Static Methods Source: https://docs.hyperbridge.network/developers/sdk/api/substrate-chain Reference for static methods available on the SubstrateChain class. ```APIDOC ## SubstrateChain Static Methods ### connect(params) Connects to a Substrate chain. ### disconnect() Disconnects from the Substrate chain. ### requestReceiptKey() Requests the receipt key. ### requestCommitmentKey() Requests the commitment key. ### queryRequestCommitment(commitmentKey) Queries for a request commitment. ### queryRequestReceipt(receiptKey) Queries for a request receipt. ### timestamp() Gets the current chain timestamp. ### queryProof(commitmentKey) Queries for a proof. ### submitUnsigned(message) Submits an unsigned message. ### queryStateProof(stateMachineId, blockHeight) Queries for a state proof. ### latestStateMachineHeight() Retrieves the latest state machine height. ``` -------------------------------- ### Verify Substrate Proof Algorithm Source: https://docs.hyperbridge.network/protocol/cryptography/merkle-trees/patricia-trie Procedural logic for verifying a Substrate storage proof by traversing the trie structure. ```pseudocode 1:procedure VerifySubstrateProof(root,proof,keys) 2:values←array of StorageValue of length length(keys) 3:nodes←array of TrieNode of length length(proof) 4:for i=0 to length(proof)−1 do 5:nodes[i]←TrieNode(keccak256(proof[i]),proof[i]) 6:end for 7:for i=0 to length(keys)−1 do 8:values[i].key←keys[i] 9:keyNibbles←NibbleSlice(keys[i],0) 10:node←SubstrateTrieDB.decodeNodeKind(TrieDB.get(nodes,root)) 11:for j=1 to ∞ do 12:nextNode←undefined 13:if TrieDB.isLeaf(node) then 14:leaf←SubstrateTrieDB.decodeLeaf(node) 15:if NibbleSliceOps.eq(leaf.key,keyNibbles) then 16:values[i].value←TrieDB.load(nodes,leaf.value) 17:end if 18:break 19:else if TrieDB.isNibbledBranch(node) then 20:nibbled←SubstrateTrieDB.decodeNibbledBranch(node) 21:nibbledBranchKeyLength←NibbleSliceOps.len(nibbled.key) 22:if not NibbleSliceOps.startsWith(keyNibbles,nibbled.key) then 23:break 24:end if 25:if NibbleSliceOps.len(keyNibbles)=nibbledBranchKeyLength then 26:if Option.isSome(nibbled.value) then 27:values[i].value←TrieDB.load(nodes,nibbled.value.value) 28:end if 29:break 30:else 31:index←NibbleSliceOps.at(keyNibbles,nibbledBranchKeyLength) 32:handle←nibbled.children[index] 33:if Option.isSome(handle) then 34:keyNibbles←NibbleSliceOps.mid(keyNibbles,nibbledBranchKeyLength+1) 35:nextNode←handle.value 36:else 37:break 38:end if 39:end if 40:else if TrieDB.isEmpty(node) then 41:break 42:end if 43:node←SubstrateTrieDB.decodeNodeKind(TrieDB.load(nodes,nextNode)) 44:end for 45:end for 46: 47:return values 48:end procedure ``` -------------------------------- ### Initialize IndexerClient Source: https://docs.hyperbridge.network/developers/sdk/getting-started Initializes the IndexerClient with the required query client, polling interval, and chain instances. ```APIDOC ## Constructor: IndexerClient ### Description Initializes a new instance of the IndexerClient to track cross-chain messages. ### Parameters #### Request Body - **queryClient** (QueryClient) - Required - Query client for the Hyperbridge indexer. - **pollInterval** (number) - Optional - Polling interval in milliseconds (default: 1000). - **source** (IChain) - Required - Source chain instance (e.g., EvmChain, SubstrateChain). - **dest** (IChain) - Required - Destination chain instance. - **hyperbridge** (IChain) - Required - Hyperbridge chain instance. ### Request Example { "queryClient": "QueryClientInstance", "pollInterval": 1000, "source": "EvmChainInstance", "dest": "EvmChainInstance", "hyperbridge": "SubstrateChainInstance" } ``` -------------------------------- ### Dispatch Incoming GET Response Source: https://docs.hyperbridge.network/developers/evm/api/ihost Dispatches an incoming GET response to the source application's `onGetResponse()` callback. Access is restricted to the handler. ```APIDOC ## dispatchIncoming(GetResponse) ### Description Dispatches an incoming GET response to the source application's `onGetResponse()` callback. ### Method EXTERNAL ### Endpoint `dispatchIncoming(GetResponse memory response, address relayer)` ### Parameters #### Path Parameters - **response** (GetResponse memory) - Required - The GET response - **relayer** (address) - Required - The relayer who delivered the response ### Access Restricted to handler ``` -------------------------------- ### Setup Same-Chain Order with Hyperbridge SDK Source: https://docs.hyperbridge.network/developers/intent-gateway/placing-orders Configure the Hyperbridge SDK for same-chain orders. The source and destination chains are the same instance. A bundler URL is still required for the destination chain, as solvers submit UserOperations on the same chain. ```typescript import { EvmChain, IntentsCoprocessor, IntentGateway } from "@hyperbridge/sdk" import { createWalletClient, http } from "viem" import { privateKeyToAccount } from "viem/accounts" const RPC_URL = "https://base-mainnet.g.alchemy.com/v2/YOUR_ALCHEMY_KEY" const BUNDLER_URL = "https://base-mainnet.g.alchemy.com/v2/YOUR_ALCHEMY_KEY" // Source and destination are the same chain for same-chain swaps const chain = await EvmChain.create(RPC_URL, BUNDLER_URL) // Hyperbridge coprocessor — hosts the auction even for same-chain orders const coprocessor = await IntentsCoprocessor.connect("wss://nexus.ibp.network") // Pass the same chain instance for both source and dest const intentGateway = await IntentGateway.create(chain, chain, coprocessor) const account = privateKeyToAccount("0xYOUR_PRIVATE_KEY") const walletClient = createWalletClient({ account, transport: http(RPC_URL), }) ``` -------------------------------- ### EvmChain Creation and Configuration Source: https://docs.hyperbridge.network/developers/sdk/api/evm-chain Methods for creating and configuring EVM chain instances, including static methods and properties. ```APIDOC ## EvmChain Static Methods and Properties ### `EvmChain.create(rpcUrl, bundlerUrl?)` Creates a new EvmChain instance. ### `EvmChain.fromParams(params)` Creates a new EvmChain instance from provided parameters. ### Properties - `client`: The underlying client for interacting with the chain. - `host`: The address of the IsmpHost contract. - `bundlerUrl`: The ERC-4337 bundler URL, if configured. - `config`: The configuration object for the EvmChain. - `configService`: Service for managing chain configurations. ### Functions - `requestReceiptKey()`: Retrieves the key for a transaction receipt. - `queryRequestReceipt()`: Queries for a transaction receipt. - `queryProof()`: Queries for a storage proof. - `queryStateProof()`: Queries for a state proof. - `timestamp()`: Gets the current timestamp of the chain. - `latestStateMachineHeight()`: Retrieves the latest state machine height. - `getFeeTokenWithDecimals()`: Gets fee token information with decimals. - `getHostNonce()`: Retrieves the nonce for the IsmpHost contract. - `broadcastTransaction()`: Broadcasts a transaction to the chain. - `getTransactionReceipt()`: Retrieves the receipt of a broadcasted transaction. ``` -------------------------------- ### Handle GET Request Timeouts Source: https://docs.hyperbridge.network/developers/evm/api/ihandler Processes timed-out GET requests using non-membership proofs. Primarily used for cleanup and state management. ```solidity function handleGetRequestTimeouts( IHost host, GetTimeoutMessage calldata message ) external ``` -------------------------------- ### Handle GET Responses Source: https://docs.hyperbridge.network/developers/evm/api/ihandler Processes and delivers GET responses with state data to source applications. Validates storage proofs and RLP-decodes values. ```solidity function handleGetResponses( IHost host, GetResponseMessage calldata message ) external ``` -------------------------------- ### Implement onGetTimeout Callback Source: https://docs.hyperbridge.network/developers/evm/api/iapp Called when a GET request you sent has timed out. Primarily for cleanup and state management as GET requests have no relayer fees. ```solidity function onGetTimeout(GetRequest memory request) external ``` -------------------------------- ### Run Hyperbridge Node on Paseo Source: https://docs.hyperbridge.network/developers/network/node Command to start a Hyperbridge node on the Paseo testnet. ```bash export PUBLIC_IP_ADDRESS= hyperbridge \ --base-path=$HOME/.hyperbridge \ --pruning=archive \ --name="Your node name here" \ --rpc-cors=all \ --rpc-port=9944 \ --unsafe-rpc-external \ --rpc-methods=unsafe \ --chain=gargantua \ --no-mdns \ --listen-addr=/ip4/0.0.0.0/tcp/30333 \ --listen-addr=/ip6/::/tcp/30333 \ --public-addr=/ip4/$PUBLIC_IP_ADDRESS/tcp/30333 \ --out-peers=32 \ -- \ --sync=fast-unsafe ``` -------------------------------- ### Simplex Core Configuration Source: https://docs.hyperbridge.network/developers/intent-gateway/simplex Basic Simplex configuration including order limits, logging level, and Hyperbridge connection details. The `substratePrivateKey` is required for Hyperbridge extrinsics. ```toml [simplex] maxConcurrentOrders = 5 logging = "info" # trace | debug | info | warn | error # Required for HyperFX / solver selection substratePrivateKey = "0x.." # Hex seed or mnemonic for Hyperbridge extrinsics hyperbridgeWsUrl = "wss://nexus.ibp.network" # Hyperbridge WebSocket endpoint [simplex.queue] maxRechecks = 10 recheckDelayMs = 30000 ``` -------------------------------- ### Query current GET request status snapshot Source: https://docs.hyperbridge.network/developers/sdk/tracking/get-requests Retrieves a single snapshot of a GET request's status without initiating a continuous stream. ```typescript // Query current status const request = await indexer.queryGetRequestWithStatus(commitment) if (request) { console.log("Current statuses:", request.statuses) console.log("Request data:", request) console.log("Queried keys:", request.keys) console.log("Query height:", request.height) // Check the latest status const latestStatus = request.statuses[request.statuses.length - 1] console.log(`Latest status: ${latestStatus.status}`) } else { console.log("GET request not found in indexer") } ``` -------------------------------- ### Launch Hyperbridge Node Source: https://docs.hyperbridge.network/developers/network/node Starts the Hyperbridge node with specific network and RPC configurations. Ensure the PUBLIC_IP_ADDRESS environment variable is set before execution. ```bash export PUBLIC_IP_ADDRESS= hyperbridge \ --base-path=$HOME/.hyperbridge \ --pruning=archive \ --name="Your node name here" \ --rpc-cors=all \ --rpc-port=9944 \ --unsafe-rpc-external \ --rpc-methods=unsafe \ --chain=nexus \ --no-mdns \ --listen-addr=/ip4/0.0.0.0/tcp/30333 \ --listen-addr=/ip6/::/tcp/30333 \ --public-addr=/ip4/$PUBLIC_IP_ADDRESS/tcp/30333 \ --out-peers=32 ``` -------------------------------- ### Tracking GET Requests with Hyperbridge SDK Source: https://docs.hyperbridge.network/developers/sdk/tracking/get-requests This section details how to track GET requests, understand their lifecycle, and calculate commitment hashes using the Hyperbridge SDK. ```APIDOC ## Request Lifecycle Every GET request goes through these stages: ``` SOURCE_FINALIZED → HYPERBRIDGE_DELIVERED → HYPERBRIDGE_FINALIZED → DESTINATION ``` Stage| Description ---|--- **SOURCE_FINALIZED**| GET request transaction finalized on source chain **HYPERBRIDGE_DELIVERED**| Request delivered to Hyperbridge **HYPERBRIDGE_FINALIZED**| Request finalized on Hyperbridge **DESTINATION**| Response delivered and executed on source chain - Complete! ## Calculate Commitment Hash First, calculate the commitment hash for your GET request: ### GET Request Parameters Parameter| Type| Description ---|---|--- `source`| `string`| Source chain state machine ID (e.g., "EVM-97") `dest`| `string`| Destination chain state machine ID `nonce`| `bigint`| Request nonce `from`| `HexString`| Requester address `keys`| `HexString[]`| Array of storage keys to query `height`| `bigint`| Block height to query at `timeoutTimestamp`| `bigint`| Unix timestamp when request times out `context`| `HexString`| Optional context data ### Example Usage (TypeScript) ```typescript import { getRequestCommitment } from "@hyperbridge/sdk" // Your GET request object const getRequest = { source: "EVM-97", dest: "EVM-10200", nonce: 1n, from: "0x...", keys: ["0x...", "0x..."], height: 12345n, timeoutTimestamp: 1234567890n, context: "0x" } const commitment = getRequestCommitment(getRequest) console.log(`GET Request Commitment: ${commitment}`) ``` ``` -------------------------------- ### Clone and Build Hyperbridge Source: https://docs.hyperbridge.network/developers/network/node Steps to download the source code and compile the node binary. ```bash # fetch the latest tag from docker hub LATEST_TAG=$(curl -s https://hub.docker.com/v2/repositories/polytopelabs/hyperbridge/tags\?page_size\=1\&page\=2 | jq -r '.results[0].name') git clone https://github.com/polytope-labs/hyperbridge.git cd ./hyperbridge git checkout ${LATEST_TAG} ``` ```bash cargo build --release -p hyperbridge ``` -------------------------------- ### EVM Contract Storage Key Example Source: https://docs.hyperbridge.network/developers/evm/dispatching/get-requests Demonstrates how to construct a storage key for reading a specific storage slot within an EVM contract. This involves concatenating the contract address and the storage slot hash. ```solidity // Reading balances[account] from an ERC20 at slot 0 address token = 0x1234...; address account = 0x5678...; bytes32 slot = keccak256(abi.encode(account, uint256(0))); bytes memory key = bytes.concat(bytes20(token), slot); ``` -------------------------------- ### IncomingGetResponse Structure Source: https://docs.hyperbridge.network/developers/evm/api/iapp Encapsulates an incoming GET response, including the response payload and the relayer's address. Use this to process GET responses received from the network. ```solidity struct IncomingGetResponse { GetResponse response; address relayer; } ``` -------------------------------- ### Dispatch a POST Response Source: https://docs.hyperbridge.network/developers/evm/dispatching/post-responses Example implementation of the onAccept callback to process a request and dispatch a corresponding response. ```solidity // Receive and handle POST request function onAccept(PostRequest memory request) external override onlyHost { // Process the request // ... your business logic here ... // Prepare response data bytes memory responseData = abi.encode( true, // success block.timestamp, amount ); // Dispatch response DispatchPostResponse memory postResponse = DispatchPostResponse({ request: request, response: responseData, timeout: 3600, // 1 hour fee: 0, // self-relay payer: msg.sender }); IDispatcher(_host).dispatch(postResponse); } ``` -------------------------------- ### onGetTimeout() Source: https://docs.hyperbridge.network/developers/evm/api/iapp Callback function invoked when a GET request sent by the application times out. This is primarily for cleanup and state management as GET requests do not involve relayer fees. ```APIDOC ## Function onGetTimeout() Called when a GET request you sent has timed out. ### Signature ```solidity function onGetTimeout(GetRequest memory request) external ``` ### Parameters #### Path Parameters - **request** (`GetRequest`) - Required - The timed-out GET request ### Access Only callable by the Host contract ### Important * GET requests have no relayer fees, so no refunds occur * Primarily for cleanup and state management ``` -------------------------------- ### Calculate GET Request Protocol Fee (Solidity) Source: https://docs.hyperbridge.network/developers/evm/dispatching/get-requests Calculates the protocol fee for a GET request in Solidity. Fees are based on a minimum charge and a per-byte component of the context. ```solidity uint256 perByteFee = perByteFee(host()); // Hyperbridge per-byte fee uint256 minimumFee = 32 * perByteFee; // Minimum charge (one word) uint256 totalFee = get.fee + (perByteFee * context.length); uint256 actualFee = minimumFee > totalFee ? minimumFee : totalFee; ``` -------------------------------- ### Create IntentGateway Instance Source: https://docs.hyperbridge.network/developers/sdk/api/intent-gateway Use `IntentGateway.create` to initialize an instance. It fetches fee tokens and optionally caches solver account bytecode. Requires source and destination chain configurations. ```typescript import { EvmChain, IntentsCoprocessor, IntentGateway } from "@hyperbridge/sdk" const source = await EvmChain.create("https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY") const dest = await EvmChain.create( "https://arb-mainnet.g.alchemy.com/v2/YOUR_KEY", "https://bundler.example.com", ) const coprocessor = await IntentsCoprocessor.connect("wss://coprocessor.hyperbridge.network") const gateway = await IntentGateway.create(source, dest, coprocessor) ``` -------------------------------- ### GetResponse Structure Source: https://docs.hyperbridge.network/developers/evm/api/iapp Represents a GET response containing state data. It includes the original request and the retrieved values. Use this to return data queried via a GET request. ```solidity struct GetResponse { GetRequest request; bytes[] values; } ``` -------------------------------- ### Initialize IndexerClient Source: https://docs.hyperbridge.network/developers/sdk/getting-started Instantiate the IndexerClient with required query client, polling interval, and chain instances. ```typescript import { IndexerClient } from "@hyperbridge/sdk" const indexer = new IndexerClient({ queryClient, pollInterval: 1_000, // Poll every 1 second source: sourceChain, dest: destChain, hyperbridge: hyperbridge }) ``` -------------------------------- ### Instantiate EvmChain via fromParams Source: https://docs.hyperbridge.network/developers/sdk/api/evm-chain Manual initialization for when chain ID and host address are already known. ```typescript static fromParams(params: EvmChainParams): EvmChain ``` ```typescript import { EvmChain } from "@hyperbridge/sdk" const ethereumChain = EvmChain.fromParams({ chainId: 1, rpcUrl: "https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY", host: "0x87ea459...", consensusStateId: "ETH0" // Optional, auto-detected for known chains }) const arbitrumChain = EvmChain.fromParams({ chainId: 42161, rpcUrl: "https://arb-mainnet.g.alchemy.com/v2/YOUR_KEY", host: "0x42fa123...", bundlerUrl: "https://bundler.example.com" // Optional, for ERC-4337 support }) ``` -------------------------------- ### Quote Fee for GET Request (Fee Token) Source: https://docs.hyperbridge.network/developers/evm/api/hyperapp Calculates the fee in the fee token for dispatching a GET request. A minimum fee equivalent to 32 bytes of data is enforced. ```solidity function quote(DispatchGet memory request) public view returns (uint256) ```