subscribe gRPC Method - Solana gRPC
Solana gRPC is included with Scale plans and up. Learn more on our pricing page.
参数
该方法不接受任何参数
退货
结果
对象
正在加载...
请求
1包 main23import (4"上下文"5"crypto/tls"6"fmt"7“日志”8“时间”9"github.com/mr-tron/base58"10"encoding/json"1112pb "yellowstone"1314"google.golang.grpc"15"google.golang.grpc"16"google.golang.grpc"17"google.golang.grpc"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 = "您的令牌编号"28)2930var kacp = keepalive.ClientParameters{31Time: 10 * time.Second,32Timeout: time.Second,33PermitWithoutStream: true,34}3536type tokenAuth struct {37token 字符串38}3940func (t tokenAuth) GetRequestMetadata(ctx context.Context, in ...string) (map[string]string, error) {41返回 map[字符串]字符串{42"x-token": t.token,43}, nil44}4546func (tokenAuth) RequireTransportSecurity() bool {47返回 true48}4950func main() {51opts := []grpc.DialOption{52grpc.WithTransportCredentials(凭证.NewTLS(&tls.配置{})),53grpc.WithKeepaliveParams(kacp),54grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1024*1024*1024), grpc.UseCompressor(gzip.名称)),55grpc.WithPerRPCCredentials(tokenAuth{token: token}),56}5758conn, err := grpc.NewClient(endpoint, opts...)59如果 err != nil {60log.Fatalf("连接失败:%v", err)61}62推迟 conn.关闭()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())81如果 err != nil {82fmt.Printf("Failed to subscribe to yellowstone: %v\n", err)83返回84}8586if err = stream.Send(subReq); err != nil {87fmt.Printf("Failed to send subscription request: %v\n", err)88返回89}9091for {92m, err := stream.Recv()93if err != nil {94fmt.Printf("Failed to receive yellowstone message: %v\n", err)95返回96}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
1包 main23import (4"上下文"5"crypto/tls"6"fmt"7“日志”8“时间”9"github.com/mr-tron/base58"10"encoding/json"1112pb "yellowstone"1314"google.golang.grpc"15"google.golang.grpc"16"google.golang.grpc"17"google.golang.grpc"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 = "您的令牌编号"28)2930var kacp = keepalive.ClientParameters{31Time: 10 * time.Second,32Timeout: time.Second,33PermitWithoutStream: true,34}3536type tokenAuth struct {37token 字符串38}3940func (t tokenAuth) GetRequestMetadata(ctx context.Context, in ...string) (map[string]string, error) {41返回 map[字符串]字符串{42"x-token": t.token,43}, nil44}4546func (tokenAuth) RequireTransportSecurity() bool {47返回 true48}4950func main() {51opts := []grpc.DialOption{52grpc.WithTransportCredentials(凭证.NewTLS(&tls.配置{})),53grpc.WithKeepaliveParams(kacp),54grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1024*1024*1024), grpc.UseCompressor(gzip.名称)),55grpc.WithPerRPCCredentials(tokenAuth{token: token}),56}5758conn, err := grpc.NewClient(endpoint, opts...)59如果 err != nil {60log.Fatalf("连接失败:%v", err)61}62推迟 conn.关闭()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())81如果 err != nil {82fmt.Printf("Failed to subscribe to yellowstone: %v\n", err)83返回84}8586if err = stream.Send(subReq); err != nil {87fmt.Printf("Failed to send subscription request: %v\n", err)88返回89}9091for {92m, err := stream.Recv()93if err != nil {94fmt.Printf("Failed to receive yellowstone message: %v\n", err)95返回96}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 = "您的令牌编号";1011async 函数 main() {12const client = new Client(ENDPOINT, TOKEN, {13grpcDefaultCompressionAlgorithm: 0, // 0 = gzip, 1 = zstd14});15await client.connect();1617const 承诺 = 承诺级别.已确认;1819试一试 {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}9697主()98.catch((err) => {99控制台.错误("未处理的错误:", err);100流程.退出(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 = "您的令牌编号";1011async 函数 main() {12const client = new Client(ENDPOINT, TOKEN, {13grpcDefaultCompressionAlgorithm: 0, // 0 = gzip, 1 = zstd14});15await client.connect();1617const 承诺 = 承诺级别.已确认;1819试一试 {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}9697主()98.catch((err) => {99控制台.错误("未处理的错误:", err);100流程.退出(1);101});102