newBlocks provides a stream of all new blocks as they propagate through the BDN. It is intended for use cases that are not latency-sensitive and require fully validated blocks. For lower-latency use cases, use bdnBlocks.
Service available via Gateway and Cloud API.
Note: Gateway must have a node connection to both Consensus Layer and Execution Layer as well as be using the eth-ws-uristartup argument (seeHow to connect Go-Gateway to consensus layer).
[Default: all]
future_validator_infocontains validator addresses for future blocks and indicates whether the validators are connected to the BDN (currently only supported in BSC)
withdrawals
contains withdrawals for ETH block
parsedTxs
Controls whether transactions in each block are returned as fully parsed JSON objects (true) or as raw, unparsed RLP payloads (false). Disabling parsing reduces server work and improves delivery latency.
Type: boolean
[Default: false]
Examples (Websocket)
Cloud-API
## ETH Examplewscat-cwss://virginia.eth.blxrbdn.com/ws--header"Authorization: <YOUR-AUTHORIZATION-HEADER>">{"jsonrpc":"2.0","id":1,"method":"subscribe","params": ["newBlocks", {"include": [""]}]}< ......
varfs=require('fs');constWebSocket=require('ws');// Enterprise users can follow line 5-16constws=newWebSocket('wss://virginia.eth.blxrbdn.com/ws',// for ETH // use 'wss://virginia.bsc.blxrbdn.com/ws', //for BSC{headers:{"Authorization":<YOUR-AUTHORIZATION-HEADER> }, // Add the following line if you work with IP instead of DNS // rejectUnauthorized: false, });// const ws = new WebSocket(// "wss://api.blxrbdn.com/ws", // {// headers: { // "Authorization" : <YOUR-AUTHORIZATION-HEADER> // },// rejectUnauthorized: false,// }// );functionproceed() { // ETH Examplews.send(`{"jsonrpc": "2.0", "id": 1, "method": "subscribe", "params": ["newBlocks", {"include": ["hash"]}]}`);}functionhandle(nextNotification) {console.log(nextNotification.toString()); // or process it generally}ws.on('open', proceed);ws.on('message', handle);
Gateway-API (gRPC)
Response (Block Event)
This response is for when parsedTxs is set to true in the stream subscription
# Python version 3.7 or higher required
import asyncio, json, websockets
async def main():
try:
uri = "wss://virginia.eth.blxrbdn.com/ws"
auth_key = "YOUR_AUTHORIZATION_HEADER"
async with websockets.connect(
uri,
header=["Authorization:{}".format(auth_key)],
# Add the following line if you work with IP instead of DNS
# sslopt={"cert_reqs": ssl.CERT_NONE}
) as websocket:
# ETH Example
subscription_request = json.dumps({
"jsonrpc": "2.0",
"method": "subscribe",
"params": ["newBlocks", {"include": ["hash"]}],
"id": 1,
})
await websocket.send(subscription_request)
while True:
response = await websocket.recv()
print(response) # or process it generally
except Exception as e:
print(f'Connection failed, Reason: {e}')
if __name__ == '__main__':
asyncio.run(main())
package main
import (
"crypto/tls"
"fmt"
"github.com/gorilla/websocket"
"net/http"
)
func main() {
dialer := websocket.DefaultDialer
// Add the following lines if you work with IP instead of DNS
// tlsConfig := &tls.Config{
// Certificates: []tls.Certificate{cert},
// InsecureSkipVerify: true,
// }
// dialer.TLSClientConfig = tlsConfig
wsSubscriber, _, err := dialer.Dial("wss://virginia.eth.blxrbdn.com/ws", http.Header{"Authorization": []string{<YOUR-AUTHORIZATION-HEADER>}})
if err != nil {
fmt.Println(err)
return
}
// ETH Example
subRequest := `{"id": 1, "method": "subscribe", "params": ["newBlocks", {"include": ["hash"]}]}`
err = wsSubscriber.WriteMessage(websocket.TextMessage, []byte(subRequest))
if err != nil {
fmt.Println(err)
return
}
for {
_, nextNotification, err := wsSubscriber.ReadMessage()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(nextNotification)) // or process it generally
}
}
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.NewBlocks(callContext, &pb.BlocksRequest{})
for {
subscriptionNotification, err := stream.Recv()
if err == nil {
fmt.Println(subscriptionNotification) // or process it generally
}
}
}