Skip to content

Instantly share code, notes, and snippets.

@0xJohnnyGault
Created November 20, 2024 02:48
Show Gist options
  • Save 0xJohnnyGault/d16a067f6e1a051f55ce45cb3a0a6a97 to your computer and use it in GitHub Desktop.
Save 0xJohnnyGault/d16a067f6e1a051f55ce45cb3a0a6a97 to your computer and use it in GitHub Desktop.
Easier way to curl a JSON-RPC endpoint
#!/usr/bin/env ruby
require 'json'
# Check if 'jo' command exists
unless system('which jo > /dev/null 2>&1')
puts "Error: 'jo' command not found. Please install it using:"
puts " brew install jo"
exit 1
end
def usage
puts <<~USAGE
Usage: ggurl <url> <method> [params...]
Makes JSON-RPC calls to Avalanche nodes
Arguments:
url - API endpoint (if starts with /, NODE_URL env var will be prepended)
method - JSON-RPC method name
params - Optional key=value parameters for the method (processed using 'jo')
Environment:
NODE_URL - Base URL of the node (e.g. https://api.avax.network)
Examples:
ggurl /ext/info info.getNetworkID
ggurl /ext/bc/C/rpc eth_chainId
ggurl /ext/bc/P platform.getCurrentValidators subnetID=abc123
Use -s before a key to force a string type
ggurl /ext/bc/C/rpc eth_getBalance "-s params[]=0x09167154e444884B06d6608CE842Ddc3a768b22a params[]=latest"
USAGE
exit 1
end
# Show usage if not enough arguments
usage if ARGV.length < 2
url = ARGV.shift
# If url starts with /, prepend NODE_URL (or mainnet) from env
if url.start_with?('/')
url = "#{ENV['NODE_URL'] || 'https://api.avax.network'}#{url}"
end
method = ARGV.shift
params = {id: '0', jsonrpc: '2.0', method: method}
# Process params using 'jo'
# https://github.com/jpmens/jo/blob/master/jo.md
args = ARGV.empty? ? "" : `jo -- #{ARGV.join(' ').to_s}`
# Parse args as JSON and merge with params if not empty
params.merge!(JSON.parse(args)) unless args.strip.empty?
cmd = "curl --silent --json '#{params.to_json}' '#{url}'"
puts `#{cmd} 2>&1`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment