Class: Remitmd::X402Client

Inherits:
Object
  • Object
show all
Defined in:
lib/remitmd/x402_client.rb

Overview

x402 client - fetch wrapper that auto-pays HTTP 402 Payment Required responses.

On receiving a 402, the client:

  1. Decodes the PAYMENT-REQUIRED header (base64 JSON)
  2. Checks the amount is within max_auto_pay_usdc
  3. Calls /x402/prepare to get hash + authorization fields
  4. Signs the hash
  5. Base64-encodes the PAYMENT-SIGNATURE header
  6. Retries the original request with payment attached

Examples:

signer = Remitmd::PrivateKeySigner.new("0x...")
client = Remitmd::X402Client.new(wallet: signer, api_transport: transport)
response = client.fetch("https://api.provider.com/v1/data")

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(wallet:, api_transport: nil, max_auto_pay_usdc: 0.10) ⇒ X402Client

Returns a new instance of X402Client.

Parameters:

  • wallet (#sign_hash, #address)

    a signer that can sign raw hashes

  • api_transport (#post) (defaults to: nil)

    authenticated HTTP transport for calling /x402/prepare

  • max_auto_pay_usdc (Float) (defaults to: 0.10)

    maximum USDC amount to auto-pay per request (default: 0.10)



45
46
47
48
49
50
# File 'lib/remitmd/x402_client.rb', line 45

def initialize(wallet:, api_transport: nil, max_auto_pay_usdc: 0.10)
  @wallet            = wallet
  @api_transport     = api_transport
  @max_auto_pay_usdc = max_auto_pay_usdc
  @last_payment      = nil
end

Instance Attribute Details

#last_paymentObject (readonly)

Returns the value of attribute last_payment.



40
41
42
# File 'lib/remitmd/x402_client.rb', line 40

def last_payment
  @last_payment
end

Instance Method Details

#fetch(url, method: :get, headers: {}, body: nil) ⇒ Net::HTTPResponse

Make an HTTP request, auto-paying any 402 responses within the configured limit.

Parameters:

  • url (String)

    the URL to fetch

  • method (Symbol) (defaults to: :get)

    HTTP method (:get, :post, etc.)

  • headers (Hash) (defaults to: {})

    additional request headers

  • body (String, nil) (defaults to: nil)

    request body (for POST/PUT)

Returns:

  • (Net::HTTPResponse)


59
60
61
62
63
64
65
66
67
68
# File 'lib/remitmd/x402_client.rb', line 59

def fetch(url, method: :get, headers: {}, body: nil)
  uri  = URI(url)
  resp = make_request(uri, method, headers, body)

  if resp.code.to_i == 402
    handle402(uri, resp, method, headers, body)
  else
    resp
  end
end