> For the complete documentation index, see [llms.txt](https://docs.circular.fi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.circular.fi/api/fast/grpc-integration.md). Agents can also search and read this documentation through its [MCP server](https://docs.circular.fi/~gitbook/mcp).

# gRPC Integration

{% tabs %}
{% tab title="Javascript" %}

```javascript
import grpc from "@grpc/grpc-js";
import protoLoader from "@grpc/proto-loader";

import {
  mkdtempSync,
  writeFileSync,
  rmSync,
} from "node:fs";

import { join } from "node:path";
import { tmpdir } from "node:os";

const FAST_GRPC_ENDPOINT = "fra.fast.circular.fi:8081";
const API_KEY = "your-api-key";

const TRANSACTION_BASE64 =
  "<base64-bincode-versioned-transaction>";

const FORWARD = false;
const CASHBACK_ADDRESS = "your-cashback-solana-address";
const MEMO = null;

const REQUEST_TIMEOUT_MS = 10_000;

const PROTO_CONTENT = `
syntax = "proto3";

package fast_tx;

service FastTx {
  rpc SendTransaction(SendTransactionRequest)
      returns (SendTransactionResponse);
}

message SendTransactionRequest {
  bytes transaction = 1;
  optional string memo = 3;
  optional bool forward = 4;
  optional string cashback_address = 5;
}

message SendTransactionResponse {
  string signature = 1;
  optional string bundle_id = 2;
  string request_id = 3;
}
`;

const temporaryDirectory = mkdtempSync(
  join(tmpdir(), "circular-fast-tx-")
);

const temporaryProtoPath = join(
  temporaryDirectory,
  "fast_tx.proto"
);

writeFileSync(
  temporaryProtoPath,
  PROTO_CONTENT,
  "utf8"
);

let packageDefinition;

try {
  packageDefinition = protoLoader.loadSync(
    temporaryProtoPath,
    {
      keepCase: true,
      longs: String,
      enums: String,
      defaults: true,
      oneofs: true,
    }
  );
} finally {
  rmSync(temporaryDirectory, {
    recursive: true,
    force: true,
  });
}

const proto = grpc.loadPackageDefinition(
  packageDefinition
);

const FastTx = proto.fast_tx.FastTx;

const client = new FastTx(
  FAST_GRPC_ENDPOINT,
  grpc.credentials.createInsecure(),
  {
    "grpc.max_send_message_length":
      4 * 1024 * 1024,

    "grpc.max_receive_message_length":
      4 * 1024 * 1024,

    "grpc.keepalive_time_ms": 20_000,
    "grpc.keepalive_timeout_ms": 5_000,

    "grpc.keepalive_permit_without_calls": 1,
  }
);

async function sendFastTx(
  transactionBase64,
  {
    forward = FORWARD,
    cashbackAddress = CASHBACK_ADDRESS,
    memo = MEMO,
  } = {}
) {
  const transactionBytes = Buffer.from(
    transactionBase64,
    "base64"
  );

  const metadata = new grpc.Metadata();

  metadata.set(
    "x-api-key",
    API_KEY
  );

  const request = {
    transaction: transactionBytes,
    forward,
  };

  if (cashbackAddress) {
    request.cashback_address = cashbackAddress;
  }

  if (memo) {
    request.memo = memo;
  }

  const options = {
    deadline: Date.now() + REQUEST_TIMEOUT_MS,
  };

  return new Promise((resolve, reject) => {
    client.SendTransaction(
      request,
      metadata,
      options,
      (error, response) => {
        if (error) {
          reject(error);
          return;
        }

        resolve(response);
      }
    );
  });
}

try {
  const response = await sendFastTx(
    TRANSACTION_BASE64
  );

  console.log(
    "Signature:",
    response.signature
  );

  console.log(
    "Bundle ID:",
    response.bundle_id || null
  );

  console.log(
    "Request ID:",
    response.request_id
  );
} catch (error) {
  console.error(
    "gRPC error:",
    error.details || error.message
  );
}
```

{% endtab %}

{% tab title="Typescript" %}

```typescript
import grpc from "@grpc/grpc-js";
import protoLoader from "@grpc/proto-loader";

import {
  mkdtempSync,
  writeFileSync,
  rmSync,
} from "node:fs";

import { join } from "node:path";
import { tmpdir } from "node:os";

const FAST_GRPC_ENDPOINT =
  "fra.fast.circular.fi:8081";

const API_KEY =
  "your-api-key";

const TRANSACTION_BASE64 =
  "<base64-bincode-versioned-transaction>";

const FORWARD = false;

const CASHBACK_ADDRESS =
  "your-cashback-solana-address";

const MEMO: string | null = null;

const REQUEST_TIMEOUT_MS = 10_000;

interface SendTransactionRequest {
  transaction: Buffer;
  memo?: string;
  forward?: boolean;
  cashback_address?: string;
}

interface SendTransactionResponse {
  signature: string;
  bundle_id?: string;
  request_id: string;
}

const PROTO_CONTENT = `
syntax = "proto3";

package fast_tx;

service FastTx {
  rpc SendTransaction(SendTransactionRequest)
      returns (SendTransactionResponse);
}

message SendTransactionRequest {
  bytes transaction = 1;
  optional string memo = 3;
  optional bool forward = 4;
  optional string cashback_address = 5;
}

message SendTransactionResponse {
  string signature = 1;
  optional string bundle_id = 2;
  string request_id = 3;
}
`;

const temporaryDirectory = mkdtempSync(
  join(tmpdir(), "circular-fast-tx-")
);

const temporaryProtoPath = join(
  temporaryDirectory,
  "fast_tx.proto"
);

writeFileSync(
  temporaryProtoPath,
  PROTO_CONTENT,
  "utf8"
);

let packageDefinition;

try {
  packageDefinition = protoLoader.loadSync(
    temporaryProtoPath,
    {
      keepCase: true,
      longs: String,
      enums: String,
      defaults: true,
      oneofs: true,
    }
  );
} finally {
  rmSync(temporaryDirectory, {
    recursive: true,
    force: true,
  });
}

const proto = grpc.loadPackageDefinition(
  packageDefinition
) as any;

const FastTx = proto.fast_tx.FastTx;

const client = new FastTx(
  FAST_GRPC_ENDPOINT,
  grpc.credentials.createInsecure(),
  {
    "grpc.max_send_message_length":
      4 * 1024 * 1024,

    "grpc.max_receive_message_length":
      4 * 1024 * 1024,

    "grpc.keepalive_time_ms":
      20_000,

    "grpc.keepalive_timeout_ms":
      5_000,

    "grpc.keepalive_permit_without_calls":
      1,
  }
);

async function sendFastTx(
  transactionBase64: string,
  forward: boolean = FORWARD,
  cashbackAddress: string | null =
    CASHBACK_ADDRESS,
  memo: string | null = MEMO
): Promise<SendTransactionResponse> {
  const transactionBytes = Buffer.from(
    transactionBase64,
    "base64"
  );

  const metadata = new grpc.Metadata();

  metadata.set(
    "x-api-key",
    API_KEY
  );

  const request: SendTransactionRequest = {
    transaction: transactionBytes,
    forward,
  };

  if (cashbackAddress) {
    request.cashback_address =
      cashbackAddress;
  }

  if (memo) {
    request.memo = memo;
  }

  const options = {
    deadline:
      Date.now() + REQUEST_TIMEOUT_MS,
  };

  return new Promise(
    (resolve, reject) => {
      client.SendTransaction(
        request,
        metadata,
        options,
        (
          error: grpc.ServiceError | null,
          response: SendTransactionResponse
        ) => {
          if (error) {
            reject(error);
            return;
          }

          resolve(response);
        }
      );
    }
  );
}

try {
  const response = await sendFastTx(
    TRANSACTION_BASE64
  );

  console.log(
    "Signature:",
    response.signature
  );

  console.log(
    "Bundle ID:",
    response.bundle_id ?? null
  );

  console.log(
    "Request ID:",
    response.request_id
  );
} catch (error) {
  const grpcError =
    error as grpc.ServiceError;

  console.error(
    "gRPC error:",
    grpcError.details ||
      grpcError.message
  );
}
```

{% endtab %}

{% tab title="Python" %}

```python
import base64
import importlib
import sys
import tempfile
from pathlib import Path

import grpc
from grpc_tools import protoc


FAST_GRPC_ENDPOINT = "fra.fast.circular.fi:8081"

API_KEY = "your-api-key"

TRANSACTION_BASE64 = (
    "<base64-bincode-versioned-transaction>"
)

FORWARD = False

CASHBACK_ADDRESS = (
    "your-cashback-solana-address"
)

MEMO = None

REQUEST_TIMEOUT_SECONDS = 10


PROTO_CONTENT = """
syntax = "proto3";

package fast_tx;

service FastTx {
  rpc SendTransaction(SendTransactionRequest)
      returns (SendTransactionResponse);
}

message SendTransactionRequest {
  bytes transaction = 1;
  optional string memo = 3;
  optional bool forward = 4;
  optional string cashback_address = 5;
}

message SendTransactionResponse {
  string signature = 1;
  optional string bundle_id = 2;
  string request_id = 3;
}
"""


def load_fast_proto():
    temporary_directory = tempfile.TemporaryDirectory()

    directory = Path(
        temporary_directory.name
    )

    proto_path = directory / "fast_tx.proto"

    proto_path.write_text(
        PROTO_CONTENT,
        encoding="utf-8",
    )

    result = protoc.main(
        [
            "grpc_tools.protoc",
            f"-I{directory}",
            f"--python_out={directory}",
            f"--grpc_python_out={directory}",
            str(proto_path),
        ]
    )

    if result != 0:
        temporary_directory.cleanup()

        raise RuntimeError(
            "Unable to compile Fast protobuf definition"
        )

    sys.path.insert(
        0,
        str(directory),
    )

    fast_tx_pb2 = importlib.import_module(
        "fast_tx_pb2"
    )

    fast_tx_pb2_grpc = importlib.import_module(
        "fast_tx_pb2_grpc"
    )

    return (
        temporary_directory,
        fast_tx_pb2,
        fast_tx_pb2_grpc,
    )


(
    temporary_directory,
    fast_tx_pb2,
    fast_tx_pb2_grpc,
) = load_fast_proto()


channel = grpc.insecure_channel(
    FAST_GRPC_ENDPOINT,
    options=[
        (
            "grpc.max_send_message_length",
            4 * 1024 * 1024,
        ),
        (
            "grpc.max_receive_message_length",
            4 * 1024 * 1024,
        ),
        (
            "grpc.keepalive_time_ms",
            20_000,
        ),
        (
            "grpc.keepalive_timeout_ms",
            5_000,
        ),
        (
            "grpc.keepalive_permit_without_calls",
            1,
        ),
    ],
)

stub = fast_tx_pb2_grpc.FastTxStub(
    channel
)


def send_fast_tx(
    transaction_base64,
    forward=FORWARD,
    cashback_address=CASHBACK_ADDRESS,
    memo=MEMO,
):
    transaction_bytes = base64.b64decode(
        transaction_base64
    )

    request = fast_tx_pb2.SendTransactionRequest(
        transaction=transaction_bytes,
        forward=forward,
    )

    if cashback_address:
        request.cashback_address = (
            cashback_address
        )

    if memo:
        request.memo = memo

    metadata = (
        (
            "x-api-key",
            API_KEY,
        ),
    )

    return stub.SendTransaction(
        request,
        metadata=metadata,
        timeout=REQUEST_TIMEOUT_SECONDS,
    )


try:
    response = send_fast_tx(
        TRANSACTION_BASE64
    )

    print(
        "Signature:",
        response.signature,
    )

    print(
        "Bundle ID:",
        (
            response.bundle_id
            if response.HasField("bundle_id")
            else None
        ),
    )

    print(
        "Request ID:",
        response.request_id,
    )

except grpc.RpcError as error:
    print(
        "gRPC code:",
        error.code(),
    )

    print(
        "gRPC error:",
        error.details(),
    )
```

{% endtab %}

{% tab title="Rust" %}

```rust
use std::{
    error::Error,
    time::Duration,
};

use base64::{
    engine::general_purpose::STANDARD,
    Engine,
};

use http::uri::PathAndQuery;
use prost::Message;
use tonic::{
    client::Grpc,
    metadata::MetadataValue,
    transport::{
        Channel,
        Endpoint,
    },
    Request,
};
use tonic_prost::ProstCodec;


// ============================================================
// CONFIGURATION
// ============================================================

const FAST_GRPC_ENDPOINT: &str =
    "http://fra.fast.circular.fi:8081";

const API_KEY: &str =
    "your-api-key";

const TRANSACTION_BASE64: &str =
    "<base64-bincode-versioned-transaction>";

// false = ARB stream only
const FORWARD: bool =
    false;

// Address receiving the cashback
const CASHBACK_ADDRESS: &str =
    "your-cashback-solana-address";

// Optional memo
const MEMO: Option<&str> =
    None;

const REQUEST_TIMEOUT_SECONDS: u64 =
    10;


// ============================================================
// PROTO MESSAGES
// ============================================================

#[derive(Clone, PartialEq, Message)]
pub struct SendTransactionRequest {
    #[prost(bytes = "vec", tag = "1")]
    pub transaction: Vec<u8>,

    #[prost(string, optional, tag = "3")]
    pub memo: Option<String>,

    #[prost(bool, optional, tag = "4")]
    pub forward: Option<bool>,

    #[prost(string, optional, tag = "5")]
    pub cashback_address: Option<String>,
}

#[derive(Clone, PartialEq, Message)]
pub struct SendTransactionResponse {
    #[prost(string, tag = "1")]
    pub signature: String,

    #[prost(string, optional, tag = "2")]
    pub bundle_id: Option<String>,

    #[prost(string, tag = "3")]
    pub request_id: String,
}


// ============================================================
// FAST GRPC CLIENT
// ============================================================

async fn send_fast_tx(
    client: &mut Grpc<Channel>,
    transaction_base64: &str,
) -> Result<SendTransactionResponse, Box<dyn Error>> {
    // Decode the Base64 transaction into the raw bytes
    // expected by the protobuf bytes field.
    let transaction_bytes =
        STANDARD.decode(transaction_base64)?;

    let message =
        SendTransactionRequest {
            transaction: transaction_bytes,

            memo:
                MEMO.map(str::to_owned),

            forward:
                Some(FORWARD),

            cashback_address:
                Some(
                    CASHBACK_ADDRESS.to_owned(),
                ),
        };

    let mut request =
        Request::new(message);

    // Same API key as the Fast HTTP API.
    request
        .metadata_mut()
        .insert(
            "x-api-key",
            MetadataValue::try_from(API_KEY)?,
        );

    request.set_timeout(
        Duration::from_secs(
            REQUEST_TIMEOUT_SECONDS,
        ),
    );

    // Final gRPC route:
    // /fast_tx.FastTx/SendTransaction
    let path =
        PathAndQuery::from_static(
            "/fast_tx.FastTx/SendTransaction",
        );

    let codec =
        ProstCodec::<
            SendTransactionRequest,
            SendTransactionResponse,
        >::default();

    client.ready().await?;

    let response =
        client
            .unary(
                request,
                path,
                codec,
            )
            .await?
            .into_inner();

    Ok(response)
}


// ============================================================
// MAIN
// ============================================================

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // The regional :8081 endpoints are gRPC over h2c,
    // therefore Tonic uses an http:// URI.
    let channel =
        Endpoint::from_static(
            FAST_GRPC_ENDPOINT,
        )
        .connect_timeout(
            Duration::from_secs(10),
        )
        .http2_keep_alive_interval(
            Duration::from_secs(20),
        )
        .keep_alive_timeout(
            Duration::from_secs(5),
        )
        .keep_alive_while_idle(true)
        .connect()
        .await?;

    // Keep this client alive and reuse it for multiple
    // transaction submissions in production.
    let mut client =
        Grpc::new(channel)
            .max_encoding_message_size(
                4 * 1024 * 1024,
            )
            .max_decoding_message_size(
                4 * 1024 * 1024,
            );

    match send_fast_tx(
        &mut client,
        TRANSACTION_BASE64,
    )
    .await
    {
        Ok(response) => {
            println!(
                "Signature  : {}",
                response.signature,
            );

            println!(
                "Bundle ID  : {}",
                response
                    .bundle_id
                    .as_deref()
                    .unwrap_or("(not returned)"),
            );

            println!(
                "Request ID : {}",
                response.request_id,
            );
        }

        Err(error) => {
            eprintln!(
                "Fast gRPC error: {}",
                error,
            );
        }
    }

    Ok(())
}
```

{% endtab %}
{% endtabs %}
