Yellowstone gRPC クイックスタート

公開日:・更新日:

空のアカウントから、ターミナルにトランザクションが流れるまでの手順です。USDC を保有する Solana ウォレットと、クライアントを動かすサーバーが必要です。

エンドポイントは fra.machgrpc.xyz:10000。平文の gRPC(TLS なし)で、標準の Yellowstone インターフェースです。API キーもヘッダーも不要です。接続元のアドレスが許可リストに登録されていれば、ストリームが開きます。

クライアントの例:Node.js・Go・Rust

1. チャージして IP を登録する

  1. まず Discord でご連絡ください。利用開始の手続きをご案内します。プランは月額 $300 の定額、USDC 払いです。すでにアクセスをお持ちの場合は、コンソール https://app.machgrpc.xyz/ を開き、ウォレットを接続してチャージします。
  2. 接続するサーバー上で(ノート PC ではなく)、外向きの IPv4 アドレスを確認します。

    curl -4 https://checkip.amazonaws.com
  3. そのアドレスをコンソールに登録します。1 アカウントにつき 1 アドレスです。

2. grpcurl で確認する

grpcurl -plaintext fra.machgrpc.xyz:10000 list

サービスの一覧が表示されれば、ネットワーク経路と許可リストの両方が機能しています。grpcurl で接続できなければ、どのクライアントでも接続できません。トラブルシューティングを参照してください。

3. クライアントを実行する

どのプログラムもそのまま動く完全なものです。vote 以外の成功したトランザクションをすべて購読し、署名、手数料支払者、2 番目のアカウントキーを表示します。いずれか一つを選んでください。

Node.js

mkdir mach-quickstart && cd mach-quickstart
npm init -y
npm i @triton-one/yellowstone-grpc bs58

index.mjs として保存します。

// index.mjs - npm i @triton-one/yellowstone-grpc bs58
import Client, { CommitmentLevel } from '@triton-one/yellowstone-grpc'
import bs58 from 'bs58'

const ENDPOINT = 'http://fra.machgrpc.xyz:10000'

async function main() {
  // The second argument is the x-token. There is none:
  // your registered IP is the credential.
  const client = new Client(ENDPOINT, undefined, {})
  const stream = await client.subscribe()

  stream.on('data', (update) => {
    const info = update.transaction?.transaction
    if (!info) return
    const keys = info.transaction.message.accountKeys
    // Key 0 is the fee payer. On a plain transfer, key 1 is the recipient.
    console.log(
      bs58.encode(info.signature),
      'from', bs58.encode(keys[0]),
      'to', bs58.encode(keys[1]),
    )
  })
  stream.on('error', (err) => {
    console.error(err)
    process.exit(1)
  })

  stream.write({
    transactions: { all: { vote: false, failed: false } },
    commitment: CommitmentLevel.CONFIRMED,
    accounts: {}, slots: {}, blocks: {}, blocksMeta: {}, entry: {},
    accountsDataSlice: [], transactionsStatus: {},
  })
}

main().catch((err) => {
  console.error(err)
  process.exit(1)
})
node index.mjs

Go

mkdir mach-quickstart && cd mach-quickstart
go mod init mach-quickstart
go get github.com/rpcpool/yellowstone-grpc/examples/golang \
       google.golang.org/grpc github.com/mr-tron/base58

main.go として保存します。

// main.go - go get github.com/rpcpool/yellowstone-grpc/examples/golang \
//              google.golang.org/grpc github.com/mr-tron/base58
package main

import (
	"context"
	"log"

	"github.com/mr-tron/base58"
	pb "github.com/rpcpool/yellowstone-grpc/examples/golang/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

const endpoint = "fra.machgrpc.xyz:10000"

func main() {
	// Plaintext, and no per-RPC credentials of any kind: the port speaks gRPC
	// directly, and your registered IP is the whole of the authorisation.
	conn, err := grpc.NewClient(
		endpoint,
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	stream, err := pb.NewGeyserClient(conn).Subscribe(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	vote, failed := false, false
	err = stream.Send(&pb.SubscribeRequest{
		Transactions: map[string]*pb.SubscribeRequestFilterTransactions{
			"all": {Vote: &vote, Failed: &failed},
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	for {
		update, err := stream.Recv()
		if err != nil {
			log.Fatal(err)
		}
		tx := update.GetTransaction()
		if tx == nil {
			continue
		}
		info := tx.GetTransaction()
		keys := info.GetTransaction().GetMessage().GetAccountKeys()
		// Key 0 is the fee payer. On a plain transfer, key 1 is the recipient.
		log.Printf("%s from %s to %s",
			base58.Encode(info.GetSignature()),
			base58.Encode(keys[0]),
			base58.Encode(keys[1]))
	}
}
go run .

Rust

cargo new mach-quickstart && cd mach-quickstart
cargo add yellowstone-grpc-client yellowstone-grpc-proto \
          bs58 anyhow futures tokio --features tokio/full

src/main.rs を次の内容に置き換えます。

// src/main.rs - cargo add yellowstone-grpc-client yellowstone-grpc-proto \
//                          bs58 anyhow futures tokio --features tokio/full
use std::collections::HashMap;

use futures::StreamExt;
use yellowstone_grpc_client::GeyserGrpcClient;
use yellowstone_grpc_proto::prelude::{
    subscribe_update::UpdateOneof, SubscribeRequest, SubscribeRequestFilterTransactions,
};

const ENDPOINT: &str = "http://fra.machgrpc.xyz:10000";

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // No x_token: your registered IP is the credential.
    let mut client = GeyserGrpcClient::build_from_shared(ENDPOINT)?
        .connect()
        .await?;

    let mut transactions = HashMap::new();
    transactions.insert(
        "all".to_owned(),
        SubscribeRequestFilterTransactions {
            vote: Some(false),
            failed: Some(false),
            ..Default::default()
        },
    );

    let request = SubscribeRequest { transactions, ..Default::default() };
    let (_sink, mut stream) = client.subscribe_with_request(Some(request)).await?;

    while let Some(update) = stream.next().await {
        if let Some(UpdateOneof::Transaction(tx)) = update?.update_oneof {
            let Some(info) = tx.transaction else { continue };
            let message = info.transaction.unwrap().message.unwrap();
            let keys = message.account_keys;
            // Key 0 is the fee payer. On a plain transfer, key 1 is the recipient.
            println!(
                "{} from {} to {}",
                bs58::encode(info.signature).into_string(),
                bs58::encode(&keys[0]).into_string(),
                bs58::encode(&keys[1]).into_string()
            );
        }
    }
    Ok(())
}
cargo run --release

表示される内容

トランザクション 1 件につき 1 行が流れ続けます(Go では行頭にタイムスタンプが付きます)。

<signature> from <fee payer> to <second account key>

これはチェーン上の vote 以外の成功したトランザクションすべてです。必要なものに絞るには、同じ SubscribeRequest にサーバー側フィルターを追加します。Yellowstone gRPC のフィルターを参照してください。

トラブルシューティング

症状原因対処
応答がない、タイムアウトする、接続が拒否される登録したものとは別のアドレスから接続している。NAT、クラウドの NAT ゲートウェイ、VPN、プロキシの背後では、サーバーはゲートウェイのアドレスで外に出る。クライアントを動かすマシンで curl -4 https://checkip.amazonaws.com を実行し、表示されたアドレスを登録する。
first record does not look like a TLS handshake などの TLS エラー平文のエンドポイントに TLS で接続している。grpcurl -plaintext、Node と Rust では http:// のエンドポイント、Go では insecure.NewCredentials() を使う。
1 台目のサーバーでは動くが、2 台目では動かない1 アカウントにつき 1 アドレス。2 台目を登録済みのアドレス経由で外に出すか、登録を変更する。
他社の x-token や authorization ヘッダーが設定に残っている以前の構成の名残。削除する。認証情報は許可リストだけ。

Mach gRPC

Mach gRPC は Yellowstone 互換の Geyser gRPC ストリームを提供しています。セルフサービスで月額 $300 の定額、USDC 払い、IP 許可リスト方式です。shred ストリームも提供しており、利用は Discord でご案内します。

  • まず試せます。 契約前に短期間のトライアルをご利用いただけます。詳細はお問い合わせください。
  • 初月の移行サポート。 既存構成の移行をお手伝いします。

Discord でお問い合わせください。