Class: BSV::Network::WhatsOnChain

Inherits:
Object
  • Object
show all
Defined in:
lib/bsv/network/whats_on_chain.rb

Overview

WhatsOnChain chain data provider for reading transactions and UTXOs from the BSV network.

Any object responding to #fetch_utxos(address) and #fetch_transaction(txid) can serve as a chain data provider; this class implements that contract using the WhatsOnChain API.

The HTTP client is injectable for testability. It must respond to #request(uri, request) and return an object with #code and #body.

Constant Summary collapse

BASE_URL =
'https://api.whatsonchain.com'

Instance Method Summary collapse

Constructor Details

#initialize(network: :mainnet, http_client: nil) ⇒ WhatsOnChain

Returns a new instance of WhatsOnChain.



21
22
23
24
# File 'lib/bsv/network/whats_on_chain.rb', line 21

def initialize(network: :mainnet, http_client: nil)
  @network = network == :mainnet ? 'main' : 'test'
  @http_client = http_client
end

Instance Method Details

#fetch_transaction(txid) ⇒ BSV::Transaction::Transaction

Fetch a raw transaction by its txid and parse it.

Parameters:

  • txid (String)

    transaction ID (hex)

Returns:



46
47
48
49
# File 'lib/bsv/network/whats_on_chain.rb', line 46

def fetch_transaction(txid)
  response = get("/v1/bsv/#{@network}/tx/#{txid}/hex")
  BSV::Transaction::Transaction.from_hex(response.body)
end

#fetch_utxos(address) ⇒ Array<UTXO>

Fetch unspent transaction outputs for an address.

Parameters:

  • address (String)

    BSV address

Returns:



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/bsv/network/whats_on_chain.rb', line 29

def fetch_utxos(address)
  response = get("/v1/bsv/#{@network}/address/#{address}/unspent")
  body = JSON.parse(response.body)

  body.map do |entry|
    UTXO.new(
      tx_hash: entry['tx_hash'],
      tx_pos: entry['tx_pos'],
      satoshis: entry['value'],
      height: entry['height']
    )
  end
end