subscribe gRPC Method - Solana gRPC
Solana gRPC está incluido en los planes Scale y Business. En los planes Build y Accelerate, sigue estando disponible a través del complemento Solana gRPC.
Parámetros
Este método no admite ningún parámetro
Devoluciones
resultado
objeto
Cargando...
Solicitud
1paquete principal23import (4«contexto»5«crypto/tls»6«fmt»7«registro»8«tiempo»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 (26punto final = "TU_QN_ENDPOINT:10000"27token = "TU_NÚMERO_DE_TOKEN"28)2930func main() {31opts := []grpc.DialOption{32grpc.WithTransportCredentials(credenciales.NewTLS(&tls.Config{})),33grpc.WithKeepaliveParams(kacp),34grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1024*1024*1024), grpc.UseCompressor(gzip.Nombre)),35grpc.WithPerRPCCredentials(tokenAuth{token: token}),36}3738conn, err := grpc.NewClient(punto de conexión, opts...)39si err != nil {40registro.Fatalf(«Error al conectarse: %v», err)41}42aplazar conn.Cerrar()4344cliente := 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)63volver64}6566if err = stream.Send(subReq); err != nil {67fmt.Printf("Failed to send subscription request: %v\n", err)68volver69}7071for {72m, err := stream.Recv()73if err != nil {74fmt.Printf("Failed to receive yellowstone message: %v\n", err)75volver76}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}
1paquete principal23import (4«contexto»5«crypto/tls»6«fmt»7«registro»8«tiempo»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 (26punto final = "TU_QN_ENDPOINT:10000"27token = "TU_NÚMERO_DE_TOKEN"28)2930func main() {31opts := []grpc.DialOption{32grpc.WithTransportCredentials(credenciales.NewTLS(&tls.Config{})),33grpc.WithKeepaliveParams(kacp),34grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1024*1024*1024), grpc.UseCompressor(gzip.Nombre)),35grpc.WithPerRPCCredentials(tokenAuth{token: token}),36}3738conn, err := grpc.NewClient(punto de conexión, opts...)39si err != nil {40registro.Fatalf(«Error al conectarse: %v», err)41}42aplazar conn.Cerrar()4344cliente := 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)63volver64}6566if err = stream.Send(subReq); err != nil {67fmt.Printf("Failed to send subscription request: %v\n", err)68volver69}7071for {72m, err := stream.Recv()73if err != nil {74fmt.Printf("Failed to receive yellowstone message: %v\n", err)75volver76}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 PUNTO FINAL = "TU_QN_ENDPOINT:10000";9const TOKEN = "TU_NÚMERO_DE_TOKEN";1011asíncrono función main() {12const client = new Client(ENDPOINT, TOKEN, {});1314const compromiso = NivelDeCompromiso.CONFIRMADO;1516prueba {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}9394principal()95.captura((err) => {96consola.error(«Error no gestionado:», err);97proceso.salir(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 PUNTO FINAL = "TU_QN_ENDPOINT:10000";9const TOKEN = "TU_NÚMERO_DE_TOKEN";1011asíncrono función main() {12const client = new Client(ENDPOINT, TOKEN, {});1314const compromiso = NivelDeCompromiso.CONFIRMADO;1516prueba {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}9394principal()95.captura((err) => {96consola.error(«Error no gestionado:», err);97proceso.salir(1);98});
¿Aún no tienes una cuenta?
Crea tu punto de conexión de Quicknode en cuestión de segundos y empieza a desarrollar
Empieza gratis