### Ruby Demo Scripts for Solana RPC and Websockets Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/README.md The Solana RPC Ruby gem includes demo scripts for testing its API and Websockets functionality. Users can clone the repository, set up the gemset, and run scripts like 'demo.rb' or 'demo_ws_METHOD.rb' to see example outputs. These scripts serve as a guide for method usage and testing. ```ruby # Example usage within a demo script (conceptual) # require 'solana_rpc_ruby' # client = SolanaRpcRuby::Client.new # client.get_block_height ``` -------------------------------- ### Get Blocks with Limit (Ruby) Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves a list of confirmed blocks starting from a specified slot up to a given limit. This method requires solana-core v1.7 or newer. It takes the starting slot, a limit for the number of blocks, and an optional commitment level as parameters. It returns a Response object on success or an ApiError on failure. ```ruby def get_blocks_with_limit(start_slot, limit, commitment: nil) http_method = :post method = create_method_name(__method__) params = [] params_hash = {} params_hash['commitment'] = commitment unless blank?(commitment) params << start_slot params << limit params << params_hash unless params_hash.empty? body = create_json_body(method, method_params: params) send_request(body, http_method) end ``` -------------------------------- ### Get Blocks With Limit Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves a list of confirmed blocks starting from a specified slot. This method requires solana-core v1.7 or newer. For older versions, use getConfirmedBlocks. ```APIDOC ## POST /getBlocksWithLimit ### Description Returns a list of confirmed blocks starting at the given slot. This method is only available in solana-core v1.7 or newer. ### Method POST ### Endpoint /getBlocksWithLimit ### Parameters #### Query Parameters - **start_slot** (Integer) - Required - The starting slot number. - **limit** (Integer) - Required - The maximum number of blocks to return. - **commitment** (String) - Optional - The commitment level for the block data. ### Request Example ```json { "jsonrpc": "2.0", "id": "some-id", "method": "getBlocksWithLimit", "params": [ 123456789, 100, { "commitment": "confirmed" } ] } ``` ### Response #### Success Response (200) - **result** (Array) - A list of confirmed block slots. - **error** (ApiError) - An error object if the request fails. #### Response Example ```json { "jsonrpc": "2.0", "result": [ 123456790, 123456791, 123456792 ], "id": "some-id" } ``` ``` -------------------------------- ### Get Version Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves the current Solana versions running on the node. ```APIDOC ## GET /getVersion ### Description Returns the current solana versions running on the node. ### Method GET ### Endpoint /getVersion ### Parameters None ### Response #### Success Response (200) - **value** (object) - Solana version information. - **solanaCore** (string) - The version of Solana Core. - **featureIds** (array of strings) - List of enabled feature IDs. #### Response Example ```json { "jsonrpc": "2.0", "result": { "solanaCore": "1.16.0", "featureIds": [ "..." ] }, "id": 1 } ``` ``` -------------------------------- ### Get SPL Token Account Balance in Ruby Source: https://context7.com/block-logic/solana-rpc-ruby/llms.txt This example retrieves the balance of an SPL Token account. It provides the token amount, the number of decimals for the token, and a UI-formatted amount string. ```ruby token_account_pubkey = '7zio4a4zAQz5cBS2Ah4WsHVCexQ2bt76ByiEjL3h8m1p' response = client.get_token_account_balance(token_account_pubkey, commitment: 'confirmed') balance_info = response.result['value'] puts "Token Amount: #{balance_info['uiAmountString']}" puts "Raw Amount: #{balance_info['amount']}" puts "Decimals: #{balance_info['decimals']}" ``` -------------------------------- ### Get Stake Activation Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves epoch activation information for a stake account. ```APIDOC ## GET /getStakeActivation ### Description Returns epoch activation information for a stake account. ### Method GET ### Endpoint /getStakeActivation ### Parameters #### Query Parameters - **pubkey** (string) - Required - The public key of the stake account. - **commitment** (object) - Optional - Commitment level for the query. - **epoch** (integer) - Optional - The epoch to retrieve activation information for. ### Response #### Success Response (200) - **value** (object) - Stake activation details. - **state** (string) - The activation state (active, deactivating, or inactive). - **active** (integer) - The amount of stake that is active. - **inactive** (integer) - The amount of stake that is inactive. #### Response Example ```json { "jsonrpc": "2.0", "result": { "state": "active", "active": 1000000000, "inactive": 0 }, "id": 1 } ``` ``` -------------------------------- ### GET MULTIPLE ACCOUNTS Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves account information for a list of provided public keys. Supports commitment, encoding, and data slicing. ```APIDOC ## GET MULTIPLE ACCOUNTS ### Description Returns the account information for a list of Pubkeys. This method allows fetching data for multiple accounts in a single request, which can be more efficient than individual requests. ### Method POST ### Endpoint `/` (Assuming a default RPC endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **pubkeys** (Array) - Required - An array of account public keys (strings) to fetch information for. - **commitment** (String) - Optional - The commitment level to use for the query (e.g., 'processed', 'confirmed', 'finalized'). Defaults to nil. - **encoding** (String) - Optional - The encoding for the account data (e.g., 'base64', 'base58', 'jsonParsed'). Defaults to ''. - **data_slice** (Hash) - Optional - An object to specify a slice of the account data to return. Defaults to an empty hash. - **offset** (Integer) - The starting byte offset of the data slice. Required if `data_slice` is provided. - **length** (Integer) - The number of bytes to include in the data slice. Required if `data_slice` is provided. ### Request Example ```json { "jsonrpc": "2.0", "id": "some-id", "method": "getMultipleAccounts", "params": [ ["Pubkey1", "Pubkey2"], { "commitment": "confirmed", "encoding": "base64", "dataSlice": { "offset": 0, "length": 100 } } ] } ``` ### Response #### Success Response (200) - **value** (Array) - An array of account information objects. - **lamports** (Integer) - The number of lamports in the account. - **owner** (String) - The program ID that owns the account. - **executable** (Boolean) - Whether the account is executable. - **rentEpoch** (Integer) - The epoch when the next rent payment is due. - **data** (Object) - The account data. - **program** (String) - The program ID. - **space** (Integer) - The size of the account data in bytes. - **parsed** (Object) - Parsed account data (if `encoding` is 'jsonParsed'). - **data** (String) - Account data in the specified encoding. - **`context`** (Object) - Contextual information about the state of the ledger when the data was fetched. - **`apiVersion`** (String) - The RPC API version. - **`slot`** (Integer) - The slot number. #### Response Example ```json { "jsonrpc": "2.0", "result": { "context": { "apiVersion": "1.18.0", "slot": 248743340 }, "value": [ { "account": { "data": { "program": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "space": 165, "data": "base64_encoded_data" }, "executable": false, "lamports": 1234567890, "owner": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "rentEpoch": 350 }, "pubkey": "AccountPubkey1" }, { "account": { "data": { "program": "11111111111111111111111111111111", "space": 123, "data": "base64_encoded_data" }, "executable": false, "lamports": 987654321, "owner": "11111111111111111111111111111111", "rentEpoch": 350 }, "pubkey": "AccountPubkey2" } ] }, "id": "some-id" } ``` ``` -------------------------------- ### Get Account Info API Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves all information associated with an account for a given public key. Supports encoding, data slicing, and commitment levels. ```APIDOC ## POST /getAccountInfo ### Description Returns all information associated with the account of provided Pubkey. ### Method POST ### Endpoint /getAccountInfo ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **account_pubkey** (String) - Required - The public key of the account. - **encoding** (String) - Optional - The encoding format for the account data (e.g., 'base64', 'jsonParsed'). Defaults to empty string. - **data_slice** (Hash) - Optional - Specifies a slice of the account data to retrieve. - **offset** (Integer) - The starting offset for the data slice. - **length** (Integer) - The length of the data slice to retrieve. - **commitment** (String) - Optional - The commitment level for the query (e.g., 'confirmed', 'processed'). Defaults to empty string. ### Request Example ```json { "account_pubkey": "YOUR_ACCOUNT_PUBKEY", "encoding": "base64", "data_slice": { "offset": 0, "length": 100 }, "commitment": "confirmed" } ``` ### Response #### Success Response (200) - **value** (Object) - Contains the account information. - **lamports** (Integer) - The number of lamports in the account. - **owner** (String) - The public key of the program that owns the account. - **executable** (Boolean) - Indicates if the account is executable. - **rentEpoch** (Integer) - The epoch when the next rent payment is due. - **data** (Object|Array) - The account data, format depends on encoding. - **pubkey** (String) - The public key of the account. #### Response Example ```json { "jsonrpc": "2.0", "result": { "context": { "slot": 123456789 }, "value": { "lamports": 1000000, "owner": "OWNER_PROGRAM_PUBKEY", "executable": false, "rentEpoch": 287, "data": { "program": "spl-token", "parsed": { "type": "account", "info": { "mint": "MINT_PUBKEY", "owner": "ACCOUNT_OWNER_PUBKEY", "amount": "1000", "delegate": null, "delegatedAmount": "0", "closeAuthority": null } }, "space": 165 } } }, "id": "YOUR_REQUEST_ID" } ``` ``` -------------------------------- ### Get Supply Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves information about the current total supply of SOL. ```APIDOC ## GET /getSupply ### Description Returns information about the current supply. ### Method GET ### Endpoint /getSupply ### Parameters #### Query Parameters - **commitment** (object) - Optional - Commitment level for the query. - **excludeNonCirculatingAccountsList** (boolean) - Optional - Whether to exclude non-circulating accounts from the supply calculation. ### Response #### Success Response (200) - **value** (object) - Supply details. - **total** (integer) - The total supply of SOL. - **circulating** (integer) - The circulating supply of SOL. - **nonCirculating** (integer) - The non-circulating supply of SOL. - **** (object) - Details for specific account types (e.g., `totalUpdates`, `totalLamports`). #### Response Example ```json { "jsonrpc": "2.0", "result": { "total": 5000000000, "circulating": 4000000000, "nonCirculating": 1000000000 }, "id": 1 } ``` ``` -------------------------------- ### Ruby: Get ApiClient Instance Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Returns the initialized ApiClient instance. This client is used to establish communication with the Solana cluster for making RPC calls. ```ruby def api_client @api_client end ``` -------------------------------- ### Get Balance API Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves the balance of an account for a given public key, with support for commitment levels. ```APIDOC ## POST /getBalance ### Description Returns the balance of the account of provided Pubkey. ### Method POST ### Endpoint /getBalance ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **account_pubkey** (String) - Required - The public key of the account. - **commitment** (String) - Optional - The commitment level for the query (e.g., 'confirmed', 'processed'). Defaults to nil. ### Request Example ```json { "account_pubkey": "YOUR_ACCOUNT_PUBKEY", "commitment": "confirmed" } ``` ### Response #### Success Response (200) - **value** (Integer) - The balance of the account in lamports. #### Response Example ```json { "jsonrpc": "2.0", "result": { "context": { "slot": 123456789 }, "value": 1000000 }, "id": "YOUR_REQUEST_ID" } ``` ``` -------------------------------- ### Get Token Accounts By Delegate Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves all SPL Token accounts associated with a specific delegate. This method requires either a 'mint' or 'program_id' to be provided, but not both. ```APIDOC ## POST /get_token_accounts_by_delegate ### Description Returns all SPL Token accounts by approved Delegate. IMPORTANT: According to docs there should be mint or program_id passed in, not both. ### Method POST ### Endpoint /get_token_accounts_by_delegate ### Parameters #### Path Parameters - **token_account_pubkey** (String) - Required - The public key of the token account. #### Query Parameters - **mint** (String) - Optional - Defaults to ''. The mint ID of the token. - **program_id** (String) - Optional - Defaults to ''. The program ID. - **commitment** (String) - Optional - Defaults to nil. The commitment level. - **encoding** (String) - Optional - Defaults to ''. The encoding format. - **data_slice** (Hash) - Optional - Defaults to {}. - **offset** (Integer) - The offset for the data slice. - **length** (Integer) - The length for the data slice. ### Request Example ```json { "method": "getTokenAccountsByDelegate", "params": [ "YOUR_TOKEN_ACCOUNT_PUBKEY", { "mint": "YOUR_MINT_ID" }, { "encoding": "jsonParsed", "commitment": "confirmed" } ] } ``` ### Response #### Success Response (200) - **result** (Array) - An array of token account objects. - **error** (null) - Null if the request was successful. #### Response Example ```json { "result": [ { "context": { "apiVersion": "1.15.2", "slot": 195818119 }, "value": [ { "executable": false, "owner": "3j9Lq6z4N273jM4y39QhFf8B5m1y9d9w9d9w9d9w9d9w9d9w9d9w9d", "lamports": 2039280, "rentEpoch": 350, "space": 165, "tokenAmount": { "amount": "1", "decimals": 6, "uiAmount": 1.0 } } ] } ], "error": null } ``` ``` -------------------------------- ### Get Leader Schedule - Ruby Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Returns the leader schedule for a given epoch. This method accepts epoch, commitment, and identity as optional parameters. ```ruby def get_leader_schedule(epoch: nil, commitment: nil, identity: '') http_method = :post method = create_method_name(__method__) params = [] params_hash = {} params_hash['epoch'] = epoch unless epoch.nil? params_hash['identity'] = identity unless identity.empty? params_hash['commitment'] = commitment unless blank?(commitment) params << params_hash unless params_hash.empty? body = create_json_body(method, method_params: params) send_request(body, http_method) end ``` -------------------------------- ### Get Inflation Rate (Ruby) Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Fetches the specific inflation values for the current epoch. This method provides detailed insights into how inflation is currently distributed. It does not require any parameters. ```ruby def get_inflation_rate http_method = :post method = create_method_name(__method__) body = create_json_body(method) send_request(body, http_method) end ``` -------------------------------- ### GET /getBalance Source: https://context7.com/block-logic/solana-rpc-ruby/llms.txt Query the SOL balance (in lamports) for any account on the Solana blockchain. Allows specifying commitment level. ```APIDOC ## GET /getBalance ### Description Query the SOL balance (in lamports) for any account on the Solana blockchain. ### Method GET ### Endpoint `/getBalance` ### Parameters #### Path Parameters None #### Query Parameters - **account_pubkey** (string) - Required - The public key of the account to query. - **commitment** (string) - Optional - The commitment level for the query (e.g., 'finalized', 'confirmed'). ### Request Example ```ruby account_pubkey = '71bhKKL89U3dNHzuZVZ7KarqV6XtHEgjXjvJTsguD11B' response = client.get_balance(account_pubkey, commitment: 'finalized') lamports = response.result['value'] sol_balance = lamports / 1_000_000_000.0 puts "Balance: #{sol_balance} SOL (#{lamports} lamports)" ``` ### Response #### Success Response (200) - **value** (number) - The SOL balance of the account in lamports. - **context** (object) - Context information about the request. - **slot** (number) - The slot at which the data was fetched. - **jsonrpc** (string) - The JSON RPC version. - **id** (number) - The request ID. #### Response Example ```json { "jsonrpc": "2.0", "result": { "context": { "slot": 150000000 }, "value": 1000000000 }, "id": 1 } ``` ``` -------------------------------- ### Interact with Solana RPC API using Ruby Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/README.md This example demonstrates how to use the `MethodsWrapper` class from the `solana_rpc_ruby` gem to call Solana RPC methods. It shows initialization with an optional cluster and ID, and how to make a `get_account_info` call. ```ruby # If you set default cluster you don't need to pass it every time. method_wrapper = SolanaRpcRuby::MethodsWrapper.new( # optional, if not passed, default cluster from config will be used cluster: 'https://api.testnet.solana.com', # optional, if not passed, default random number # from range 1 to 99_999 will be used id: 123 ) response = method_wrapper.get_account_info(account_pubkey) puts response # You can check cluster and id that are used. method_wrapper.cluster method_wrapper.id ``` -------------------------------- ### Subscribe to Solana Blockchain via WebSocket in Ruby Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/README.md This snippet illustrates how to establish a WebSocket connection to the Solana network using `WebsocketsMethodsWrapper`. It covers initializing the wrapper, subscribing to the root, and handling incoming messages with a provided block for real-time data processing. ```ruby ws_method_wrapper = SolanaRpcRuby::WebsocketsMethodsWrapper.new( # optional, if not passed, default ws_cluster from config will be used cluster: 'ws://api.testnet.solana.com', # optional, if not passed, default random number # from range 1 to 99_999 will be used id: 123 ) # You should see stream of messages in your console. ws_method_wrapper.root_subscribe # You can pass a block to do something with websocket's messages, ie: block = Proc.new do |message| json = JSON.parse(message) puts json['params'] end ws_method_wrapper.root_subscribe(&block) # You can check cluster and id that are used. ws_method_wrapper.cluster ws_method_wrapper.id ``` -------------------------------- ### Initialize WebsocketClient for Solana RPC Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/WebsocketClient.html Initializes the WebsocketClient with a Faye::WebSocket instance and an optional cluster. It sets up the client and determines the cluster address, raising an error if the cluster is not configured. ```ruby def initialize(websocket_client: Faye::WebSocket, cluster: nil) @client = websocket_client @cluster = cluster || [SolanaRpcRuby].ws_cluster @retries = 0 message = 'Websocket cluster is missing. Please provide default cluster in config or pass it to the client directly.' raise ArgumentError, message unless @cluster end ``` -------------------------------- ### Get Slot Leaders in Ruby Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves a list of slot leaders for a specified range of slots. This method requires a start slot and a limit as integer parameters. It returns a SolanaRpcRuby::Response object on success or an ApiError on failure. Ensure the Solana RPC endpoint is accessible. ```ruby def get_slot_leaders(start_slot, limit) http_method = :post method = create_method_name(__method__) params = [start_slot, limit] body = create_json_body(method, method_params: params) send_request(body, http_method) end ``` -------------------------------- ### Initialize Client Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Initializes the API client with the cluster address for requests. ```APIDOC ## POST /initialize ### Description Initialize object with cluster address where requests will be sent. ### Method POST ### Endpoint /initialize ### Parameters #### Request Body - **apiClient** (object) - Required - An instance of ApiClient. - **cluster** (string) - Required - The cluster address (e.g., "https://api.mainnet-beta.solana.com"). - **id** (integer) - Optional - A unique identifier for the request (defaults to a random integer). ### Request Example ```json { "apiClient": "", "cluster": "https://api.mainnet-beta.solana.com", "id": 12345 } ``` ### Response #### Success Response (200) - **MethodsWrapper** (object) - An object containing methods to interact with the Solana RPC. #### Response Example (This method typically returns an object that allows further calls, rather than a direct JSON response in this context.) ``` -------------------------------- ### Get Confirmed Blocks (Ruby) - Deprecated Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves a list of confirmed blocks between two specified slots. This method is deprecated and will be removed in solana-core v1.8; use getBlocks instead. It takes a starting slot and an optional ending slot. It returns a Response object on success or an ApiError on failure. ```ruby def get_confirmed_blocks(start_slot, end_slot: nil) warn 'DEPRECATED: Please use getBlocks instead. This method is expected to be removed in solana-core v1.8' http_method = :post method = create_method_name(__method__) params = [] params << start_slot params << end_slot unless end_slot.nil? # optional body = create_json_body(method, method_params: params) send_request(body, http_method) end ``` -------------------------------- ### Get Blocks Between Slots (Ruby) Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Returns a list of confirmed blocks within a specified range of slots (start_slot to end_slot). This method is available in solana-core v1.7 or newer. Parameters include start and end slots, and an optional commitment level. The output is either a successful response or an API error. ```ruby def get_blocks(start_slot, end_slot: nil, commitment: nil) http_method = :post method = create_method_name(__method__) params = [] params_hash = {} params << start_slot params << end_slot unless end_slot.nil? params_hash['commitment'] = commitment unless blank?(commitment) params << params_hash unless params_hash.empty? body = create_json_body(method, method_params: params) send_request(body, http_method) end ``` -------------------------------- ### Initialize WebSocket Client (Ruby) Source: https://context7.com/block-logic/solana-rpc-ruby/llms.txt Sets up a WebSocket client for real-time blockchain event subscriptions. Allows configuration of the WebSocket cluster URL and JSON RPC version. ```ruby require 'solana_rpc_ruby' # Configure WebSocket cluster SolanaRpcRuby.config do |c| c.ws_cluster = 'ws://api.mainnet-beta.solana.com' c.json_rpc_version = '2.0' end # Create WebSocket wrapper ws_client = SolanaRpcRuby::WebsocketsMethodsWrapper.new # Or with custom cluster ws_client = SolanaRpcRuby::WebsocketsMethodsWrapper.new( cluster: 'ws://api.testnet.solana.com', id: 456 ) ``` -------------------------------- ### Configure ActionCable for Development Environment Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/file.README.html Set the ActionCable URL and allowed origins for the development environment in `config/environments/development.rb`. This ensures proper websocket connection establishment. ```ruby config.action_cable.url = "ws://localhost:3000/cable" config.action_cable.allowed_request_origins = [/http:\/*/, /https:\/*/] ``` -------------------------------- ### Initialize JSON RPC Client Source: https://context7.com/block-logic/solana-rpc-ruby/llms.txt Demonstrates how to initialize a client instance to interact with the Solana blockchain via HTTP JSON RPC. It covers default cluster configuration and programmatic configuration with custom endpoints. ```APIDOC ## Initialize JSON RPC Client ### Description Create a client instance to interact with Solana blockchain via HTTP JSON RPC. The client supports configuration through initializers or direct instantiation with custom cluster endpoints. ### Method Instance creation ### Endpoint N/A (Library Initialization) ### Parameters None ### Request Example ```ruby require 'solana_rpc_ruby' # Configure default cluster SolanaRpcRuby.config do |c| c.cluster = 'https://api.mainnet-beta.solana.com' c.json_rpc_version = '2.0' end # Create method wrapper with default cluster client = SolanaRpcRuby::MethodsWrapper.new # Or specify custom cluster and ID testnet_client = SolanaRpcRuby::MethodsWrapper.new( cluster: 'https://api.testnet.solana.com', id: 123 ) # Check configuration puts client.cluster # => "https://api.mainnet-beta.solana.com" puts client.id # => random number 1-99999 ``` ### Response #### Success Response N/A (Initialization) #### Response Example N/A ``` -------------------------------- ### GET BLOCK COMMITMENT Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Returns the commitment for a particular block. ```APIDOC ## GET /block-commitment ### Description Returns commitment for a particular block. ### Method POST ### Endpoint /block-commitment ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **block** (Integer) - Required - The block number for which to retrieve commitment. ### Request Example ```json { "method": "getBlockCommitment", "params": [ 12345 ] } ``` ### Response #### Success Response (200) - **commitment** (String) - The commitment level of the block. #### Response Example ```json { "jsonrpc": "2.0", "result": "confirmed", "id": "1" } ``` ``` -------------------------------- ### Get Slot Leader Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves the leader for the current slot. ```APIDOC ## GET /getSlotLeader ### Description Returns the current slot leader. ### Method GET ### Endpoint /getSlotLeader ### Parameters #### Query Parameters - **commitment** (object) - Optional - Commitment level for the query. ### Response #### Success Response (200) - **value** (string) - The public key of the current slot leader. #### Response Example ```json { "jsonrpc": "2.0", "result": "", "id": 1 } ``` ``` -------------------------------- ### Redis Adapter Configuration for ActionCable Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/index.html Sets up the Redis adapter for ActionCable in the development environment. This configuration specifies the Redis URL, allowing ActionCable to use Redis for managing websocket connections. ```ruby development: adapter: redis url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> ``` -------------------------------- ### Generate Solana RPC Ruby Configuration Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/Generators/InstallGenerator.html This method generates a configuration file for the Solana RPC Ruby gem. It copies a template file to the application's initializers directory. This is essential for setting up the Solana RPC client within a Rails application. ```ruby def copy_config template 'solana_rpc_ruby_config.rb', "#{Rails.root}/config/initializers/solana_rpc_ruby.rb" end ``` -------------------------------- ### Get Slot Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves the current slot that the node is processing. ```APIDOC ## GET /getSlot ### Description Returns the current slot the node is processing. ### Method GET ### Endpoint /getSlot ### Parameters #### Query Parameters - **commitment** (object) - Optional - Commitment level for the query. ### Response #### Success Response (200) - **value** (integer) - The current slot number. #### Response Example ```json { "jsonrpc": "2.0", "result": 100, "id": 1 } ``` ``` -------------------------------- ### GET BLOCK HEIGHT Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Returns the current block height of the node. ```APIDOC ## GET /block-height ### Description Returns the current block height of the node. ### Method POST ### Endpoint /block-height ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **commitment** (String) - Optional - The level of commitment desired for the block height. ### Request Example ```json { "method": "getBlockHeight", "params": [ "confirmed" ] } ``` ### Response #### Success Response (200) - **blockHeight** (Integer) - The current block height. #### Response Example ```json { "jsonrpc": "2.0", "result": 12345, "id": "1" } ``` ``` -------------------------------- ### Implement Client-Side Channel Subscription and Message Handling (JavaScript) Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/file.README.html Create a JavaScript file to subscribe to the ActionCable channel and handle incoming messages. This code connects to the specified channel and updates the UI when new data is received. ```javascript import consumer from "./consumer" consumer.subscriptions.create("WallChannel", { connected() { console.log("Connected to WallChannel"); // Called when the subscription is ready for use on the server }, disconnected() { // Called when the subscription has been terminated by the server }, received(data) { let wall = document.getElementById('wall'); wall.innerHTML += "

Result: "+ data['message']['result'] + "

"; // Called when there's incoming data on the websocket for this channel } }); ``` -------------------------------- ### Initialize SolanaRpcRuby ApiClient Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/ApiClient.html Initializes the ApiClient with a cluster address. It sets up the connection details for sending RPC requests to a specified Solana cluster. If no cluster is provided, it attempts to use a default cluster configured elsewhere. Raises an ArgumentError if the cluster is not specified. ```ruby def initialize(cluster = nil) @cluster = cluster || SolanaRpcRuby.cluster message = 'Cluster is missing. Please provide default cluster in config or pass it to the client directly.' raise ArgumentError, message unless @cluster end ``` -------------------------------- ### Get Transaction Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves details for a confirmed transaction using its signature. ```APIDOC ## GET /getTransaction ### Description Returns transaction details for a confirmed transaction. ### Method GET ### Endpoint /getTransaction ### Parameters #### Query Parameters - **transactionSignature** (string) - Required - The signature of the transaction. - **encoding** (string) - Optional - Encoding for the transaction data (e.g., "base64", "jsonParsed"). - **commitment** (object) - Optional - Commitment level for the query. ### Response #### Success Response (200) - **value** (object) - Transaction details. - ** காஷ் (string)** - The transaction signature. - **blockTime** (integer) - The block time of the transaction. - **confirmationStatus** (string) - The confirmation status of the transaction. - **meta** (object) - Metadata about the transaction (e.g., logs, pre/post balances). - **transaction** (object) - The transaction details (instructions, recent blockhash, fee payer). - **rewards** (array of objects) - Rewards associated with the transaction. - **slot** (integer) - The slot in which the transaction was processed. #### Response Example ```json { "jsonrpc": "2.0", "result": { " காஷ்": "...", "blockTime": 1678886400, "confirmationStatus": "confirmed", "meta": { "logMessages": [], "postTokenBalances": [], "preTokenBalances": [], "status": {"Ok": null}, "loadedAddresses": {} }, "transaction": { "message": { "accountKeys": [], "recentBlockhash": "...", "instructions": [], "header": {} }, "signatures": [] }, "rewards": [], "slot": 100 }, "id": 1 } ``` ``` -------------------------------- ### Configure Solana RPC Client (Ruby) Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby.html Allows configuration of the Solana RPC client. This class method takes a block, yielding the client instance to the block for setting various configurations. It's useful for customizing default settings like cluster addresses. ```ruby # File 'lib/solana_rpc_ruby.rb', line 25 def config yield self end ``` -------------------------------- ### Initialize WebsocketsMethodsWrapper in Ruby Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/WebsocketsMethodsWrapper.html Initializes the WebsocketsMethodsWrapper with a websocket client, cluster address, and a unique ID. It sets up the websocket client to connect to the specified cluster. ```ruby def initialize( websocket_client: WebsocketClient, cluster: SolanaRpcRuby.ws_cluster, id: rand(1...99_999) ) @websocket_client = websocket_client.new(cluster: cluster) @id = id end ``` -------------------------------- ### Get Snapshot Slot Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves the highest slot that has a snapshot available. ```APIDOC ## GET /getSnapshotSlot ### Description Deprecated. Please use getHighestSnapshotSlot instead. This method is expected to be removed in solana-core v2.0. ### Method GET ### Endpoint /getSnapshotSlot ### Parameters None ### Response #### Success Response (200) - **value** (integer) - The highest slot with a snapshot. #### Response Example ```json { "jsonrpc": "2.0", "result": 100, "id": 1 } ``` ``` -------------------------------- ### Get Vote Accounts Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves information about all voting accounts and their associated stake. ```APIDOC ## GET /getVoteAccounts ### Description Returns the account info and associated stake for all the voting accounts in the current bank. ### Method GET ### Endpoint /getVoteAccounts ### Parameters #### Query Parameters - **commitment** (object) - Optional - Commitment level for the query. - **votePubkey** (string) - Optional - Filter by a specific vote account public key. - **keepUnqualifiedDelinquents** (boolean) - Optional - Whether to include unqualified delinquent vote accounts. - **delinquentSlotDistance** (integer) - Optional - The number of slots to consider for delinquency. ### Response #### Success Response (200) - **value** (object) - Vote account information. - **current** (array of objects) - Currently active vote accounts. - **delinquent** (array of objects) - Delinquent vote accounts. - **VotePubkey** (string) - The public key of the vote account. - **commission** (integer) - The commission of the validator. - **lastTimestamp** (integer) - The last timestamp the vote account was active. - **epochVoteAccount** (boolean) - Whether this is an epoch vote account. - **activatedStake** (integer) - The amount of stake activated for this vote account. - **stakedNodes** (array of objects) - List of nodes staked to this vote account. #### Response Example ```json { "jsonrpc": "2.0", "result": { "current": [ { "votePubkey": "", "commission": 5, "lastTimestamp": 1678886400, "epochVoteAccount": true, "activatedStake": 1000000000, "stakedNodes": [] } ], "delinquent": [] }, "id": 1 } ``` ``` -------------------------------- ### get_multiple_accounts Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Returns account information for a list of public keys. ```APIDOC ## POST /getMultipleAccounts ### Description Returns account information for a list of public keys. ### Method POST ### Endpoint /getMultipleAccounts ### Parameters #### Request Body - **pubkeys** (array of strings) - Required - A list of account public keys. - **commitment** (object) - Optional - The commitment level for the query. - **encoding** (string) - Optional - The encoding for the account data (e.g., 'base64', 'base58', 'jsonParsed'). - **dataSlice** (object) - Optional - Specifies a slice of the account data to return. - **offset** (number) - The starting offset. - **length** (number) - The length of the slice. ### Request Example ```json { "jsonrpc": "2.0", "id": "some-id", "method": "getMultipleAccounts", "params": [ ["AccountPk11111111111111111111111111111111111", "AccountPk22222222222222222222222222222222222"], { "commitment": "confirmed", "encoding": "jsonParsed", "dataSlice": { "offset": 0, "length": 100 } } ] } ``` ### Response #### Success Response (200) - **result** (object) - Contains account information. - **context** (object) - Context information. - **value** (array of objects) - A list of account information objects. - **account** (object) - Account details. - **executable** (boolean) - Whether the account is executable. - **lamports** (number) - The lamport balance. - **owner** (string) - The owner program ID. - **rentEpoch** (number) - The rent epoch. - **data** (any) - The account data, formatted according to encoding. - **pubkey** (string) - The public key of the account. #### Response Example ```json { "jsonrpc": "2.0", "result": { "context": {"apiVersion":"1.16.0","slot":123456789}, "value": [ { "account": { "executable": false, "lamports": 1000000000000, "owner": "11111111111111111111111111111111", "rentEpoch": 100, "data": { "program":"some_program", "parsed":"some_parsed_data", "space": 100 } }, "pubkey": "AccountPk11111111111111111111111111111111111" } ] }, "id": "some-id" } ``` ``` -------------------------------- ### Get Program Accounts in Ruby Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Fetches all accounts owned by a given program public key. Allows for customization of commitment, encoding, data slicing, filters, and context inclusion. It prepares and sends a JSON RPC request. ```ruby def get_program_accounts( pubkey, commitment: nil, encoding: '', data_slice: {}, filters: [], with_context: false ) http_method = :post method = create_method_name(__method__) params = [] params_hash = {} params_hash['commitment'] = commitment unless blank?(commitment) params_hash['encoding'] = encoding unless blank?(encoding) params_hash['dataSlice'] = data_slice unless data_slice.empty? params_hash['filters'] = filters unless filters.empty? params_hash['withContext'] = with_context params << pubkey params << params_hash unless params_hash.empty? body = create_json_body(method, method_params: params) send_request(body, http_method) end ``` -------------------------------- ### Get Slot Leaders Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/SolanaRpcRuby/MethodsWrapper.html Retrieves the slot leaders for a given slot range. ```APIDOC ## GET /getSlotLeaders ### Description Returns the slot leaders for a given slot range. ### Method GET ### Endpoint /getSlotLeaders ### Parameters #### Query Parameters - **startSlot** (integer) - Required - The starting slot of the range. - **limit** (integer) - Required - The number of slots to retrieve leaders for. ### Response #### Success Response (200) - **value** (array of objects) - An array of slot leader objects. - **slot** (integer) - The slot number. - **leader** (string) - The public key of the slot leader. #### Response Example ```json { "jsonrpc": "2.0", "result": [ { "slot": 100, "leader": "" } ], "id": 1 } ``` ``` -------------------------------- ### Rails ActionCable Configuration for Development Source: https://github.com/block-logic/solana-rpc-ruby/blob/main/doc/index.html Configures ActionCable settings for the development environment, specifying the websocket URL and allowed request origins. Ensures proper websocket connectivity during development. ```ruby config.action_cable.url = "ws://localhost:3000/cable" config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/] ```