bloXroute Documentation
WebsiteBlogTwitterDiscord
  • Welcome to bloXroute
  • Introduction
    • Why Use bloXroute?
    • Products
    • Create An Account
    • Technical Support
  • SOLANA
    • Trader API
      • Introduction
        • Regions
        • Authorization
        • Rate Limits
        • Tip and Tipping Addresses
      • Quick Start
        • Transaction Submission
        • Front-Running Protection & Transaction Bundle
        • Go SDK
        • Python SDK
        • Typescript SDK
        • Rust SDK
      • API Endpoints
        • Core Endpoints
          • submit
          • submit-paladin
          • submit-batch
          • balance
          • rate-limit
          • transaction
          • priority-fee
          • GetPriorityFeeStream
          • GetBundleTipStream
          • submit-snipe
        • Pump.fun
          • quotes
          • swap
          • swap-sol
          • GetPumpFunNewTokensStream
          • GetPumpFunSwapsStream
          • GetPumpFunAMMSwapsStream
        • Raydium
          • quotes
          • pools
          • pool-reserves
          • swap
          • cpmm-swap
          • clmm-swap
          • route-swap
          • GetPoolReservesStream
          • GetSwapsStream
          • GetNewRaydiumPoolsStream
          • GetNewRaydiumPoolsByTransactionStream
        • Jupiter
          • quotes
          • swap
          • swap-instructions
          • route-swap
        • Openbook
          • markets
          • orderbooks/{market}
          • depth/{market}
          • tickers/{market}
          • open-orders/{market}
          • unsettled/{market}
          • place
          • replace
          • cancel
          • settle
          • GetOrderbooksStream
          • GetTickersStream
      • Best Performance for Landing Transactions
      • Support
        • API Health
        • Contact us
        • Suggestions
        • Wiki
          • Terms & Concepts
          • Resources
    • Optimized Feed Relay (OFR)
      • Transaction Streamer
      • Gateway and OFR Requirements
      • Gateway and OFR Setup
      • Gateway Startup Arguments
      • OFR performance
      • Logging
      • Submitting Transaction
      • Upgrading Gateway
      • Troubleshooting
  • BSC & ETH
    • EVM Blockchain Distribution Network (BDN)
      • How to Connect
      • The bloXroute Gateway
        • Local Gateway
          • Installation and Startup
            • Authentication & Certificates
            • Requirements
            • Supported Clients
            • GitHub repository option
            • Docker container option
            • Startup Script
            • Startup Arguments
          • General Connectivity Troubleshooting
          • Logging
          • Upgrading your Gateway
        • Add Your Gateway as a Trusted Peer to Your Execution Layer Client
        • Connecting Your Gateway with the Consensus Layer
      • IPs & Relays
        • Relays IPs
        • Private Relays
        • Cloud-API IPs
          • ⏩Reducing Latencies using the BDN
    • APIs
      • Authorization
      • Check Transaction Quota
      • Submit a Transaction
        • Raw Transaction Construction
        • Tx-Validation
        • Batch Transaction
      • Private Transactions
        • ETH Private Transactions
        • BSC Private Transactions
      • Transaction Bundles
        • Bundle Simulation
        • Bundle Validation
        • Bundle Submission
          • BSC Bundle Submission
            • List of BSC Validators
          • ETH Bundle Submission
          • Bundle Submission with Gateway
        • Bundle Tracking
          • BSC Bundle-Trace
          • ETH Bundle-Trace
          • ETH Bundle Inclusion Status
        • Bundle Refunds
          • Priority Fee Refund
          • Bundle Refund
          • Latest Bundle Refunds
      • Backrun Arbitrage
        • BackRunMe: Bundle Submission
          • BSC submit arbOnly
          • ETH submit arbOnly
            • blxr_info
            • ETH arbOnly Simulation
      • Token Launch Sniping
      • Other Utilities
        • List of bloXroute Builders
        • List of External Builders
        • Tx-Trace
        • Ping
    • Streams
      • Requirements
      • Subscription limits
      • Working With Streams
        • Creating a Subscription
          • Websocket
          • gRPC
        • Handling the Notification
          • Websocket
          • gRPC
        • Cancelling a Subscription
          • Websocket
          • gRPC
        • Local Node Validation
      • newTxs and pendingTxs
        • Filters
        • Raw TX Reconstruction
      • BackRunMe: arbOnlyMEV
        • ETH arbOnlyMEV
        • BSC arbOnlyMEV
      • transactionStatus
      • txReceipts
      • newBlocks
      • bdnBlocks
      • ethOnBlock
      • MEVBlockValue
      • MEVNextProposerInfo
    • Block Builders and Validators
      • Validator Gateway
      • MEV Relay (For Validators)
      • Block Submission
      • Proposer MEV-Protect
      • Compliance Lists
      • Preconfirmations
    • Protect RPCs
      • ETH Protect RPC
      • ETH Gas Protect RPC
      • BSC Protect RPC
      • SOL Protect RPC
  • Base Network
    • Submit Transactions
    • Streams
      • GetBdnBlockStream
  • TON NETWORK
    • TON Trader API
      • Quick Start
      • Fee Schedule
      • Connection
      • Submit Signed Transaction
  • Resources
    • BDN Explorer
    • Block Explorer
    • Guides
      • Algorithmic Trading
      • Setting Up a Local Gateway
      • Gateway as Web3 Bridge
    • Architecture
      • BDN Architecture
        • Network Components
        • Performance Techniques
          • Block Compression
          • Cut-through Routing
          • Optimized Topology
      • bloXroute Protocol
        • Versioning
        • Message Structure
        • Message Types
    • Contact Us
Powered by GitBook
On this page
  • Examples - Websocket
  • Examples - gRPC
  1. BSC & ETH
  2. Streams

ethOnBlock

Name: ethOnBlock

ethOnBlock is a stream of changes in the EVM state when a new block is mined. The stream includes the results of eth_call and other RPC requests provided by users and is restricted based on the number of calls. This is a Gateway-API only stream.

Options

Key

Description

Values

include

Fields to include in the on block event stream

name, response, blockHeight, tag [Default: all]

call-params

Fields used to build an RPC call request

method- see chart below for available methods and additional fields required for each method

tag- latest, 0, or negative number. [Default: 0]

name- unique string identifier for call. [Default: integer counter]

Method

Call Documentation

Additional Fields

eth_call

from, to, gas, value, data

eth_getBalance

address

eth_getTransactionCount

address

eth_getCode

address

eth_getStorageAt

address, pos

eth_blockNumber

None

Examples - Websocket

Subscribing to the ethOnBlock stream via the Gateway-API in Python (Line 6 creates the subscription):

import asyncio, jason, websockets

async def main():
    async with websockets.connect(ws_uri) as websocket:
        payload = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "subscribe",
            "params": [
                "ethOnBlock",
                {
                    "include": ["name", "response", "block_height", "tag"],
                    "call-params": [
                        {
                            "name": "my_call_name",
                            "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
                            "gas": "0x76c0",
                            "value": "0x9184e72a",
                            "data": "0x00"
                        },
                        {
                            "name": "number",
                            "method": "eth_blockNumber"
                        }
                    ]
                }
            ]
        }
        await websocket.send(json.dumps(payload))
        subscription_id = await websocket.recv()
        while True:
            next_notification = await websocket.recv()
            print(next_notification)  # or process it generally
        await websocket.send(json.dumps({"jsonrpc": "2.0", "id": 2, "method": "unsubscribe", "params": [subscription_id]}))
        
if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(main())

The ethOnBlock stream is not available via Cloud-API.

TaskCompletedEventis received after all calls have been executed upon receipt of a block.TaskDisabledEvent is received if there is an error response to a call, indicating that the call has been disabled.

Python Gateway:

<<< {'name': 'balance', 'response': {'result': '0x1'}, 'blockHeight': 11654331, 'tag': 11654331}
{'name': 'height', 'response': {'result': '0xb1d4bb'}, 'blockHeight': 11654331, 'tag': 11654331}
{'name': 'TaskDisabledEvent', 'response': {'commandMethod': 'eth_getBalance', 'blockOffset': 0, 'callName': 'balance', 'callPayload': {'address': '0x0000000000000000000000000000000000000000'}, 'active': False}, 'blockHeight': 11654331, 'tag': 11654331}
{'name': 'number', 'response': {'result': '0x0'}, 'blockHeight': 11654331, 'tag': 11654331}
{'name': 'TaskCompletedEvent', 'response': {}, 'blockHeight': 11654331, 'tag': 11654331}}

Go Gateway:

<<< {'name': 'balance', 'response': '0x1', 'block_height': 11654331, 'tag': 11654331}
{'name': 'height', 'response': '0xb1d4bb', 'block_height': 11654331, 'tag': 11654331}
{'name': 'TaskDisabledEvent', 'response': '{commandMethod:eth_call blockOffset:0 callName:my_call callPayload:{"data":"0x00","to":"0x0000000000000000000000000000000000000000"} active:false}', 'block_height': '13462626', 'tag': '0xcd6c62'}
{'name': 'number', 'response': '0x0', 'block_height': 11654331, 'tag': 11654331}
{'name': 'TaskCompletedEvent', 'response': '', 'block_height': 11654331, 'tag': 11654331}}

Examples - gRPC

Subscribing to Gateway ethOnBlock Stream in Go using gRPC.

package main

import (
	"context"
	"fmt"
	pb "github.com/bloXroute-Labs/gateway/v2/protobuf"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"time"
)

type blxrCredentials struct {
	authorization string
}

func (bc blxrCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{
		"authorization": bc.authorization,
	}, nil
}

func (bc blxrCredentials) RequireTransportSecurity() bool {
	return false
}

func main() {
	// gRPC server default values
	gatewayHostIP := "localhost"
	gatewayGRPCPort := 5001
	
	// this will use localhost CA to verify the certificate
	creds := credentials.NewClientTLSFromCert(nil, "")

	// Open gRPC connection to Gateway.
	conn, _ := grpc.Dial(
		fmt.Sprintf("%v:%v", gatewayHostIP, gatewayGRPCPort),
		grpc.WithTransportCredentials(creds),
		grpc.WithPerRPCCredentials(blxrCredentials{authorization: "<YOUR-AUTHORIZATION-HEADER>"}),
	)

	// Use the Gateway client connection interface.
	client := pb.NewGatewayClient(conn)

	// create context and defer cancel of context
	callContext, cancel := context.WithTimeout(context.Background(), 24*time.Hour)
	defer cancel()

	// Create a subscription using the stream-specific method and request.
	stream, _ := client.EthOnBlock(callContext,
		&pb.EthOnBlockRequest{
			CallParams: []*pb.CallParams{
				{
					Params: map[string]string{
						"name":    "balance",
						"method":  "eth_getBalance",
						"address": "0x178B2A...d8E2F4",
					},
				},
				{
					Params: map[string]string{
						"name":   "number",
						"method": "eth_blockNumber",
					},
				},
			},
		},
	)

	for {
		subscriptionNotification, err := stream.Recv()
		if err == nil {
			fmt.Println(subscriptionNotification) // or process it generally
		}
	}	
}

Response (ethOnBlock Event)

TaskCompletedEventis received after all calls have been executed upon receipt of a block.TaskDisabledEvent is received if there is an error response to a call, indicating that the call has been disabled.

<<< name:"number"
response:"0x1cec877"
blockHeight:"0x1cec877"
tag:"0x1cec877"

name:"balance"
response:"0x10febdd5766d5b"
blockHeight:"0x1cec877"
tag:"0x1cec877"

name:"TaskCompletedEvent"
blockHeight:"0x1cec877"
tag:"0x1cec877"
...
PreviousbdnBlocksNextMEVBlockValue

https://eth.wiki/json-rpc/API#eth_call
https://eth.wiki/json-rpc/API#eth_getbalance
https://eth.wiki/json-rpc/API#eth_gettransactioncount
https://eth.wiki/json-rpc/API#eth_getcode
https://eth.wiki/json-rpc/API#eth_getstorageat
https://eth.wiki/json-rpc/API#eth_blocknumber