subscribe gRPC Method - Solana gRPC
Solana gRPC est inclus dans les plans Scale et Business. Pour les plans Build et Accelerate, il reste disponible via l'extension Solana gRPC.
Paramètres
Cette méthode n'accepte aucun paramètre
Renvoie
résultat
objet
Chargement...
Requête
1package main23import (4"context"5"crypto/tls"6"fmt"7"log"8"time"9"github.com/mr-tron/base58"10"encoding/json"1112pb "yellowstone/proto"1314"google.golang.org/grpc"15"google.golang.org/grpc/credentials"16"google.golang.org/grpc/encoding/gzip"17"google.golang.org/grpc/keepalive"18)1920// Quicknode endpoints consist of two crucial components: the endpoint name and the corresponding token21// For eg: QN Endpoint: https://docs-demo.solana-mainnet.quiknode.pro/abcde12345678922// endpoint will be: docs-demo.solana-mainnet.quiknode.pro:10000 {10000 is the port number for gRPC}23// token will be : abcde1234567892425var (26endpoint = "YOUR_QN_ENDPOINT:10000"27token = "YOUR_TOKEN_NUMBER"28)2930func main() {31opts := []grpc.DialOption{32grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})),33grpc.WithKeepaliveParams(kacp),34grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1024*1024*1024), grpc.UseCompressor(gzip.Name)),35grpc.WithPerRPCCredentials(tokenAuth{token: token}),36}3738conn, err := grpc.NewClient(endpoint, opts...)39if err != nil {40log.Fatalf("Échec de la connexion : %v", err)41}42defer conn.Close()4344client := pb.NewGeyserClient(conn)4546commitment := pb.CommitmentLevel_FINALIZED47subReq := &pb.SubscribeRequest{48Commitment: &commitment,49BlocksMeta: map[string]*pb.SubscribeRequestFilterBlocksMeta{50"blocks": {},51},52Slots: map[string]*pb.SubscribeRequestFilterSlots{53"slots": {},54},55}5657d, _ := json.Marshal(subReq)58fmt.Printf("Subscription request: %s\n", string(d))5960stream, err := client.Subscribe(context.Background())61if err != nil {62fmt.Printf("Failed to subscribe to yellowstone: %v\n", err)63return64}6566if err = stream.Send(subReq); err != nil {67fmt.Printf("Failed to send subscription request: %v\n", err)68return69}7071for {72m, err := stream.Recv()73if err != nil {74fmt.Printf("Failed to receive yellowstone message: %v\n", err)75return76}7778switch {79case m.GetBlock() != nil:80fmt.Printf("Block: %d\n", m.GetBlock().GetBlockHeight())81case m.GetBlockMeta() != nil:82fmt.Printf("BlockMeta: %d\n", m.GetBlockMeta().GetBlockHeight())83case m.GetTransaction() != nil:84fmt.Printf("Transaction: %s\n", base58.Encode(m.GetTransaction().GetTransaction().GetSignature()))85case m.GetSlot() != nil:86fmt.Printf("Slot: %d\n", m.GetSlot().GetSlot())87}88}89}
1package main23import (4"context"5"crypto/tls"6"fmt"7"log"8"time"9"github.com/mr-tron/base58"10"encoding/json"1112pb "yellowstone/proto"1314"google.golang.org/grpc"15"google.golang.org/grpc/credentials"16"google.golang.org/grpc/encoding/gzip"17"google.golang.org/grpc/keepalive"18)1920// Quicknode endpoints consist of two crucial components: the endpoint name and the corresponding token21// For eg: QN Endpoint: https://docs-demo.solana-mainnet.quiknode.pro/abcde12345678922// endpoint will be: docs-demo.solana-mainnet.quiknode.pro:10000 {10000 is the port number for gRPC}23// token will be : abcde1234567892425var (26endpoint = "YOUR_QN_ENDPOINT:10000"27token = "YOUR_TOKEN_NUMBER"28)2930func main() {31opts := []grpc.DialOption{32grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})),33grpc.WithKeepaliveParams(kacp),34grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1024*1024*1024), grpc.UseCompressor(gzip.Name)),35grpc.WithPerRPCCredentials(tokenAuth{token: token}),36}3738conn, err := grpc.NewClient(endpoint, opts...)39if err != nil {40log.Fatalf("Échec de la connexion : %v", err)41}42defer conn.Close()4344client := pb.NewGeyserClient(conn)4546commitment := pb.CommitmentLevel_FINALIZED47subReq := &pb.SubscribeRequest{48Commitment: &commitment,49BlocksMeta: map[string]*pb.SubscribeRequestFilterBlocksMeta{50"blocks": {},51},52Slots: map[string]*pb.SubscribeRequestFilterSlots{53"slots": {},54},55}5657d, _ := json.Marshal(subReq)58fmt.Printf("Subscription request: %s\n", string(d))5960stream, err := client.Subscribe(context.Background())61if err != nil {62fmt.Printf("Failed to subscribe to yellowstone: %v\n", err)63return64}6566if err = stream.Send(subReq); err != nil {67fmt.Printf("Failed to send subscription request: %v\n", err)68return69}7071for {72m, err := stream.Recv()73if err != nil {74fmt.Printf("Failed to receive yellowstone message: %v\n", err)75return76}7778switch {79case m.GetBlock() != nil:80fmt.Printf("Block: %d\n", m.GetBlock().GetBlockHeight())81case m.GetBlockMeta() != nil:82fmt.Printf("BlockMeta: %d\n", m.GetBlockMeta().GetBlockHeight())83case m.GetTransaction() != nil:84fmt.Printf("Transaction: %s\n", base58.Encode(m.GetTransaction().GetTransaction().GetSignature()))85case m.GetSlot() != nil:86fmt.Printf("Slot: %d\n", m.GetSlot().GetSlot())87}88}89}
1import Client, { CommitmentLevel, SubscribeRequest, SubscribeUpdate, SubscribeUpdateTransaction } from "@triton-one/yellowstone-grpc";23// Quicknode endpoints consist of two crucial components: the endpoint name and the corresponding token4// For eg: QN Endpoint: https://docs-demo.solana-mainnet.quiknode.pro/abcde1234567895// endpoint will be: docs-demo.solana-mainnet.quiknode.pro:10000 {10000 is the port number for gRPC}6// token will be : abcde12345678978const POINT D'EXTRÉMITÉ = "VOTRE_POINT_D'ACCÈS_QN:10000";9const TOKEN = "VOTRE_NUMÉRO_DE_TOKEN";1011async function main() {12const client = new Client(ENDPOINT, TOKEN, {});1314const engagement = Niveau d'engagement.CONFIRMÉ;1516essayer {17const stream = await client.subscribe();1819// Set up error and end handlers20stream.on("error", (error) => {21console.error("Stream error:", error);22stream.end();23});2425stream.on("end", () => {26console.log("Stream ended");27});2829// Handle incoming data30stream.on("data", (data: SubscribeUpdate) => {31handleSubscribeUpdate(data);32});3334// Create subscription request35const request: SubscribeRequest = {36slots: { client: { filterByCommitment: true } },37transactions: {38client: {39vote: false,40failed: false,41signature: undefined,42accountInclude: [],43accountExclude: [],44accountRequired: [],45},46},47commitment: commitment,48accounts: {},49transactionsStatus: {},50entry: {},51blocks: {},52blocksMeta: {},53accountsDataSlice: [],54ping: undefined,55};5657// Send subscription request58await new Promise<void>((resolve, reject) => {59stream.write(request, (err: Error | null | undefined) => {60if (err) {61reject(err);62} else {63resolve();64}65});66});6768console.log("Subscription started. Waiting for events...");6970// Keep the script running71await new Promise(() => {});7273} catch (error) {74console.error("Error in subscription process:", error);75}76}7778function handleSubscribeUpdate(data: SubscribeUpdate) {79if ("slot" in data) {80console.log("Slot update:", data.slot);81} else if ("transaction" in data) {82const transaction = data.transaction as SubscribeUpdateTransaction;83if (transaction && transaction.transaction) {84console.log("Transaction update:", {85signature: Buffer.from(transaction.transaction.signature).toString('base64'),86slot: transaction.slot,87});88}89} else {90console.log("Other update:", data);91}92}9394main()95.catch((err) => {96console.error("Erreur non gérée :", err);97process.exit(1);98});
1import Client, { CommitmentLevel, SubscribeRequest, SubscribeUpdate, SubscribeUpdateTransaction } from "@triton-one/yellowstone-grpc";23// Quicknode endpoints consist of two crucial components: the endpoint name and the corresponding token4// For eg: QN Endpoint: https://docs-demo.solana-mainnet.quiknode.pro/abcde1234567895// endpoint will be: docs-demo.solana-mainnet.quiknode.pro:10000 {10000 is the port number for gRPC}6// token will be : abcde12345678978const POINT D'EXTRÉMITÉ = "VOTRE_POINT_D'ACCÈS_QN:10000";9const TOKEN = "VOTRE_NUMÉRO_DE_TOKEN";1011async function main() {12const client = new Client(ENDPOINT, TOKEN, {});1314const engagement = Niveau d'engagement.CONFIRMÉ;1516essayer {17const stream = await client.subscribe();1819// Set up error and end handlers20stream.on("error", (error) => {21console.error("Stream error:", error);22stream.end();23});2425stream.on("end", () => {26console.log("Stream ended");27});2829// Handle incoming data30stream.on("data", (data: SubscribeUpdate) => {31handleSubscribeUpdate(data);32});3334// Create subscription request35const request: SubscribeRequest = {36slots: { client: { filterByCommitment: true } },37transactions: {38client: {39vote: false,40failed: false,41signature: undefined,42accountInclude: [],43accountExclude: [],44accountRequired: [],45},46},47commitment: commitment,48accounts: {},49transactionsStatus: {},50entry: {},51blocks: {},52blocksMeta: {},53accountsDataSlice: [],54ping: undefined,55};5657// Send subscription request58await new Promise<void>((resolve, reject) => {59stream.write(request, (err: Error | null | undefined) => {60if (err) {61reject(err);62} else {63resolve();64}65});66});6768console.log("Subscription started. Waiting for events...");6970// Keep the script running71await new Promise(() => {});7273} catch (error) {74console.error("Error in subscription process:", error);75}76}7778function handleSubscribeUpdate(data: SubscribeUpdate) {79if ("slot" in data) {80console.log("Slot update:", data.slot);81} else if ("transaction" in data) {82const transaction = data.transaction as SubscribeUpdateTransaction;83if (transaction && transaction.transaction) {84console.log("Transaction update:", {85signature: Buffer.from(transaction.transaction.signature).toString('base64'),86slot: transaction.slot,87});88}89} else {90console.log("Other update:", data);91}92}9394main()95.catch((err) => {96console.error("Erreur non gérée :", err);97process.exit(1);98});
Vous n'avez pas encore de compte ?
Créez votre endpoint Quicknode en quelques secondes et commencez à développer
Commencez gratuitement