subscribe gRPC Method - Solana gRPC
Solana gRPC is included with Scale plans and up. Learn more on our pricing page.
Paramètres
Cette méthode n'accepte aucun paramètre
Retours
résultat
objet
Chargement en cours...
Demande
1paquet principal23import (4« contexte »5« crypto/tls »6« fmt »7« journal »8« temps »9"github.com/mr-tron/base58"10« encoding/json »1112pb "yellowstone/proto"1314« google.golang.grpc »15« google.golang.grpc »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:443 {443 is the port number for gRPC}23// token will be : abcde1234567892425var (26endpoint = "YOUR_QN_ENDPOINT:443"27token = "YOUR_TOKEN_NUMBER"28)2930var kacp = keepalive.ClientParameters{31Time: 10 * time.Second,32Timeout: time.Second,33PermitWithoutStream: true,34}3536type tokenAuth struct {37jeton chaîne de caractères38}3940func (t tokenAuth) GetRequestMetadata(ctx context.Context, in ...string) (map[string]string, error) {41retour carte[chaîne]chaîne{42"x-token": t.token,43}, nil44}4546func (tokenAuth) RequireTransportSecurity() bool {47return true48}4950func main() {51opts := []grpc.DialOption{52grpc.WithTransportCredentials(informations d'authentification.NewTLS(&tls.Config{})),53grpc.WithKeepaliveParams(kacp),54grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1024*1024*1024), grpc.UseCompressor(gzip.Name)),55grpc.WithPerRPCCredentials(tokenAuth{token: token}),56}5758conn, err := grpc.NewClient(endpoint, opts...)59si err != nil {60log.Fatalf("Failed to connect: %v", err)61}62reporter conn.Fermer()6364client := pb.NewGeyserClient(conn)6566commitment := pb.CommitmentLevel_FINALIZED67subReq := &pb.SubscribeRequest{68Commitment: &commitment,69BlocksMeta: map[string]*pb.SubscribeRequestFilterBlocksMeta{70"blocks": {},71},72Slots: map[string]*pb.SubscribeRequestFilterSlots{73"slots": {},74},75}7677d, _ := json.Marshal(subReq)78fmt.Printf("Subscription request: %s\n", string(d))7980stream, err := client.Subscribe(context.Background())81if err != nil {82fmt.Printf("Failed to subscribe to yellowstone: %v\n", err)83retour84}8586if err = stream.Send(subReq); err != nil {87fmt.Printf("Failed to send subscription request: %v\n", err)88retour89}9091for {92m, err := stream.Recv()93if err != nil {94fmt.Printf("Failed to receive yellowstone message: %v\n", err)95retour96}9798switch {99case m.GetBlock() != nil:100fmt.Printf("Block: %d\n", m.GetBlock().GetBlockHeight().GetBlockHeight())101case m.GetBlockMeta() != nil:102fmt.Printf("BlockMeta: %d\n", m.GetBlockMeta().GetBlockHeight().GetBlockHeight())103case m.GetTransaction() != nil:104fmt.Printf("Transaction: %s\n", base58.Encode(m.GetTransaction().GetTransaction().GetSignature()))105case m.GetSlot() != nil:106fmt.Printf("Slot: %d\n", m.GetSlot().GetSlot())107}108}109}110
1paquet principal23import (4« contexte »5« crypto/tls »6« fmt »7« journal »8« temps »9"github.com/mr-tron/base58"10« encoding/json »1112pb "yellowstone/proto"1314« google.golang.grpc »15« google.golang.grpc »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:443 {443 is the port number for gRPC}23// token will be : abcde1234567892425var (26endpoint = "YOUR_QN_ENDPOINT:443"27token = "YOUR_TOKEN_NUMBER"28)2930var kacp = keepalive.ClientParameters{31Time: 10 * time.Second,32Timeout: time.Second,33PermitWithoutStream: true,34}3536type tokenAuth struct {37jeton chaîne de caractères38}3940func (t tokenAuth) GetRequestMetadata(ctx context.Context, in ...string) (map[string]string, error) {41retour carte[chaîne]chaîne{42"x-token": t.token,43}, nil44}4546func (tokenAuth) RequireTransportSecurity() bool {47return true48}4950func main() {51opts := []grpc.DialOption{52grpc.WithTransportCredentials(informations d'authentification.NewTLS(&tls.Config{})),53grpc.WithKeepaliveParams(kacp),54grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1024*1024*1024), grpc.UseCompressor(gzip.Name)),55grpc.WithPerRPCCredentials(tokenAuth{token: token}),56}5758conn, err := grpc.NewClient(endpoint, opts...)59si err != nil {60log.Fatalf("Failed to connect: %v", err)61}62reporter conn.Fermer()6364client := pb.NewGeyserClient(conn)6566commitment := pb.CommitmentLevel_FINALIZED67subReq := &pb.SubscribeRequest{68Commitment: &commitment,69BlocksMeta: map[string]*pb.SubscribeRequestFilterBlocksMeta{70"blocks": {},71},72Slots: map[string]*pb.SubscribeRequestFilterSlots{73"slots": {},74},75}7677d, _ := json.Marshal(subReq)78fmt.Printf("Subscription request: %s\n", string(d))7980stream, err := client.Subscribe(context.Background())81if err != nil {82fmt.Printf("Failed to subscribe to yellowstone: %v\n", err)83retour84}8586if err = stream.Send(subReq); err != nil {87fmt.Printf("Failed to send subscription request: %v\n", err)88retour89}9091for {92m, err := stream.Recv()93if err != nil {94fmt.Printf("Failed to receive yellowstone message: %v\n", err)95retour96}9798switch {99case m.GetBlock() != nil:100fmt.Printf("Block: %d\n", m.GetBlock().GetBlockHeight().GetBlockHeight())101case m.GetBlockMeta() != nil:102fmt.Printf("BlockMeta: %d\n", m.GetBlockMeta().GetBlockHeight().GetBlockHeight())103case m.GetTransaction() != nil:104fmt.Printf("Transaction: %s\n", base58.Encode(m.GetTransaction().GetTransaction().GetSignature()))105case m.GetSlot() != nil:106fmt.Printf("Slot: %d\n", m.GetSlot().GetSlot())107}108}109}110
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: https://docs-demo.solana-mainnet.quiknode.pro:443 {443 is the port number for gRPC}6// token will be : abcde12345678978const ENDPOINT = "https://YOUR_QN_ENDPOINT:443";9const TOKEN = "YOUR_TOKEN_NUMBER";1011async fonction main() {12const client = new Client(ENDPOINT, TOKEN, {13grpcDefaultCompressionAlgorithm: 0, // 0 = gzip, 1 = zstd14});15await client.connect();1617const commitment = CommitmentLevel.CONFIRMED;1819try {20const stream = await client.subscribe();2122// Set up error and end handlers23stream.on("error", (error) => {24console.error("Stream error:", error);25stream.end();26});2728stream.on("end", () => {29console.log("Stream ended");30});3132// Handle incoming data33stream.on("data", (data: SubscribeUpdate) => {34handleSubscribeUpdate(data);35});3637// Create subscription request38const request: SubscribeRequest = {39slots: { client: { filterByCommitment: true } },40transactions: {41client: {42vote: false,43failed: false,44signature: undefined,45accountInclude: [],46accountExclude: [],47accountRequired: [],48},49},50commitment: commitment,51accounts: {},52transactionsStatus: {},53entry: {},54blocks: {},55blocksMeta: {},56accountsDataSlice: [],57ping: undefined,58};5960// Send subscription request61await new Promise<void>((resolve, reject) => {62stream.write(request, (err: Error | null | undefined) => {63if (err) {64reject(err);65} else {66resolve();67}68});69});7071console.log("Subscription started. Waiting for events...");7273// Keep the script running74await new Promise(() => {});7576} catch (error) {77console.error("Error in subscription process:", error);78}79}8081function handleSubscribeUpdate(data: SubscribeUpdate) {82if (data.slot) {83console.log("Slot update:", data.slot);84} else if (data.transaction) {85const transaction = data.transaction as SubscribeUpdateTransaction;86if (transaction && transaction.transaction) {87console.log("Transaction update:", {88signature: Buffer.from(transaction.transaction.signature).toString('base64'),89slot: transaction.slot,90});91}92} else {93console.log("Other update:", data);94}95}9697main()98.catch((err) => {99console.error("Unhandled error:", err);100process.exit(1);101});102
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: https://docs-demo.solana-mainnet.quiknode.pro:443 {443 is the port number for gRPC}6// token will be : abcde12345678978const ENDPOINT = "https://YOUR_QN_ENDPOINT:443";9const TOKEN = "YOUR_TOKEN_NUMBER";1011async fonction main() {12const client = new Client(ENDPOINT, TOKEN, {13grpcDefaultCompressionAlgorithm: 0, // 0 = gzip, 1 = zstd14});15await client.connect();1617const commitment = CommitmentLevel.CONFIRMED;1819try {20const stream = await client.subscribe();2122// Set up error and end handlers23stream.on("error", (error) => {24console.error("Stream error:", error);25stream.end();26});2728stream.on("end", () => {29console.log("Stream ended");30});3132// Handle incoming data33stream.on("data", (data: SubscribeUpdate) => {34handleSubscribeUpdate(data);35});3637// Create subscription request38const request: SubscribeRequest = {39slots: { client: { filterByCommitment: true } },40transactions: {41client: {42vote: false,43failed: false,44signature: undefined,45accountInclude: [],46accountExclude: [],47accountRequired: [],48},49},50commitment: commitment,51accounts: {},52transactionsStatus: {},53entry: {},54blocks: {},55blocksMeta: {},56accountsDataSlice: [],57ping: undefined,58};5960// Send subscription request61await new Promise<void>((resolve, reject) => {62stream.write(request, (err: Error | null | undefined) => {63if (err) {64reject(err);65} else {66resolve();67}68});69});7071console.log("Subscription started. Waiting for events...");7273// Keep the script running74await new Promise(() => {});7576} catch (error) {77console.error("Error in subscription process:", error);78}79}8081function handleSubscribeUpdate(data: SubscribeUpdate) {82if (data.slot) {83console.log("Slot update:", data.slot);84} else if (data.transaction) {85const transaction = data.transaction as SubscribeUpdateTransaction;86if (transaction && transaction.transaction) {87console.log("Transaction update:", {88signature: Buffer.from(transaction.transaction.signature).toString('base64'),89slot: transaction.slot,90});91}92} else {93console.log("Other update:", data);94}95}9697main()98.catch((err) => {99console.error("Unhandled error:", err);100process.exit(1);101});102
Vous n'avez pas encore de compte ?
Créez votreendpoint Quicknode endpoint quelques secondes et commencez à développer
Commencez gratuitement