jito-ts TypeScript SDK

repository·master·Indexed 42 days ago

https://github.com/jito-labs/jito-ts

A TypeScript SDK (v4.2.1) for interacting with Jito APIs, including the block-engine and relayer. It provides tools for managing bundles of VersionedTransactions, authenticating via AuthProvider and JWT, and connecting to Jito Geyser gRPC endpoints. Key features include the SearcherClient for submitting bundles, tip account retrieval, and automated gRPC authentication interceptors.

Tokens
7.9K
Snippets
30
Records
37
Agent score
52%

What's inside jito-ts

  1. Regenerate protobuf files

    master

    While generated proto files are committed, you may need to regenerate them if the underlying .proto definitions change.

    Prerequisites:

    • protoc must be installed on your system.
    • If new .proto files are added, update the corresponding ./scripts/gen-*-protos script.

    Steps:

    1. Run the appropriate generation command: yarn gen-* ${PATH_TO_PROTOS}.
    2. Commit the newly generated files.
  2. Understand the SimulatedBundleResponse structure

    master

    The simulateBundle method returns a SimulatedBundleResponse wrapped in an RpcResponseAndContext.

    Response Structure:

    • summary: Either 'succeeded' or an object containing a failed property. If failed, it includes the error (as a BundleError or string) and the tx_signature of the failing transaction.
    • transactionResults: An array of SimulatedBundleTransactionResult objects (one per transaction in the bundle).

    Per-Transaction Result (SimulatedBundleTransactionResult):

    • err: The error for that specific transaction (TransactionError, string, or null).
    • logs: An array of execution logs (or null).
    • preExecutionAccounts: (Optional) Array of SimulatedTransactionAccountInfo representing account states before execution.
    • postExecutionAccounts: (Optional) Array of SimulatedTransactionAccountInfo representing account states after execution.
    • unitsConsumed: (Optional) The number of compute units consumed.
    • returnData: (Optional) Data returned by the program, containing programId and data (base64 encoded).
  3. Initialize a GeyserClient instance

    master

    To connect to a Jito Geyser gRPC server, use the geyserClient factory function. It requires the server URL and an access token for authentication. You can optionally provide gRPC ChannelOptions for advanced configuration.

    Returns a GeyserClient instance used to subscribe to various Solana network streams.

    import { geyserClient } from 'jito-ts/sdk/geyser';
    
    const client = geyserClient(
      'https://your-geyser-endpoint.jito.com',
      'YOUR_ACCESS_TOKEN'
    );
  4. Fix protoc-gen-js errors on macOS

    master

    If you encounter the error protoc-gen-js: program not found or is not executable on macOS, follow these steps to install the necessary protobuf dependencies via Homebrew:

    1. brew install protobuf@3
    2. brew link --overwrite protobuf@3
    3. Regenerate block engine protos: yarn gen-block-engine ${PATH_TO_BLOCK_ENGINE_PROTOS}
    4. Regenerate geyser protos: yarn gen-geyser ${PATH_TO_GEYSER_PROTOS}
    brew install protobuf@3
    brew link --overwrite protobuf@3
    yarn gen-block-engine ${PATH_TO_BLOCK_ENGINE_PROTOS}
    yarn gen-geyser ${PATH_TO_GEYSER_PROTOS}
  5. Run a simple bundle example

    master

    To run the simple_bundle example, you must set the following environment variables to point to your RPC, the Jito Block Engine, and your authentication keypair. You can then execute the command via yarn.

    Required Environment Variables:

    • RPC_URL: Your Solana RPC endpoint.
    • BLOCK_ENGINE_URL: The Jito block engine URL (e.g., mainnet.block-engine.jito.wtf).
    • AUTH_KEYPAIR_PATH: Path to your JSON authentication keypair file.
    • BUNDLE_TRANSACTION_LIMIT: The limit for transactions in a bundle.
    export RPC_URL="https://MY_RPC_URL"
    export BLOCK_ENGINE_URL=mainnet.block-engine.jito.wtf
    export AUTH_KEYPAIR_PATH=MY_AUTH_KEYPAIR.json
    export BUNDLE_TRANSACTION_LIMIT=5
    
    yarn run:simple_bundle
  6. Configure SimulateBundleConfig for bundle simulation

    master

    When calling simulateBundle, you can pass a SimulateBundleConfig object to fine-tune the simulation.

    Key Configuration Options:

    • preExecutionAccountsConfigs: An array of account configurations to return the state of before transaction execution. The array length must match the number of transactions in the bundle.
    • postExecutionAccountsConfigs: An array of account configurations to return the state of after transaction execution. The array length must match the number of transactions in the bundle.
    • simulationBank: (Optional) Specifies the bank to run the simulation against. Can be a Commitment level, a specific Slot (number), or the string 'tip'.
    • skipSigVerify: (Optional) Boolean to skip signature verification before simulation.
    • replaceRecentBlockhash: (Optional) Boolean to replace the simulated transaction's recent blockhash with the latest blockhash.
  7. Serialize VersionedTransactions into Packets

    master

    Use serializeTransactions to convert an array of Solana VersionedTransaction objects into an array of Packet objects suitable for transmission to the Jito Block Engine. This function automatically populates the Meta field for each packet, including the serialized data length and default network metadata (port: 0, addr: '0.0.0.0').

    import { VersionedTransaction } from '@solana/web3.js';
    import { serializeTransactions } from './path-to-utils';
    
    const txs: VersionedTransaction[] = [...];
    const packets = serializeTransactions(txs);
  8. Get the next scheduled leader using getNextScheduledLeader

    master

    The getNextScheduledLeader method returns information about the next scheduled leader connected to the block engine. It returns an object containing:

    • currentSlot: The current slot number the backend is on.
    • nextLeaderSlot: The slot number of the next scheduled leader.
    • nextLeaderIdentity: The identity (public key) of the next scheduled leader.
    const result = await client.getNextScheduledLeader();
    
    if (result.isOk()) {
      const { currentSlot, nextLeaderSlot, nextLeaderIdentity } = result.value;
      console.log(`Current Slot: ${currentSlot}, Next Leader: ${nextLeaderIdentity} at slot ${nextLeaderSlot}`);
    } else {
      console.error('Error fetching next leader:', result.error.message);
    }
  9. Get connected leaders using getConnectedLeaders

    master

    The getConnectedLeaders method returns a map of connected validators. The keys are validator identity public keys, and the values are SlotList objects representing their scheduled slots.

    const result = await client.getConnectedLeaders();
    
    if (result.isOk()) {
      const leaders = result.value;
      // leaders is a Record<string, SlotList>
      console.log('Connected leaders:', leaders);
    } else {
      console.error('Error fetching leaders:', result.error.message);
    }
  10. Create and manage a Bundle

    master

    The Bundle class represents a collection of VersionedTransaction objects intended to be executed atomically and sequentially. You can initialize a bundle with an existing set of transactions and a maximum transaction limit, then extend it using addTransactions or addTipTx.

    import { Bundle } from 'jito-ts';
    import { Keypair, PublicKey } from '@solana/web3.js';
    
    // Initialize a bundle with a transaction limit
    const bundle = new Bundle(initialTransactions, 10);
    
    // Add more transactions
    const result = bundle.addTransactions(...moreTransactions);
    if (result instanceof Error) {
      console.error(result.message);
    }
    
    // Add a tip transaction to the bundle
    const tipResult = bundle.addTipTx(
      keypair,           // Keypair to pay the tip
      1000000,           // Tip amount in lamports
      tipAccount,        // The Jito tip account address
      recentBlockhash    // Recent blockhash
    );
  11. Get the server heartbeat interval

    master

    Use getHeartbeatIntervalMillis() to retrieve the heartbeat interval from the Geyser server in milliseconds. This is useful for monitoring connection health or timing heartbeats.

    Returns a Promise<number> representing the interval in milliseconds. Throws a ServiceError if the request fails.

    const interval = await client.getHeartbeatIntervalMillis();
    console.log(`Heartbeat interval: ${interval}ms`);