Class: BSV::MCP::Tools::BroadcastP2pkh

Inherits:
MCP::Tool
  • Object
show all
Defined in:
lib/bsv/mcp/tools/broadcast_p2pkh.rb

Overview

Builds, signs, and broadcasts a simple P2PKH payment transaction.

Fetches UTXOs for the sender’s address, constructs a transaction with one payment output and one change output, signs all inputs with the provided private key, and submits to ARC in Extended Format (EF/BRC-30).

This is the most complex MCP tool: it orchestrates WIF → PrivateKey → PublicKey → address → UTXO fetch → tx build → sign → broadcast.

Constant Summary collapse

DUST_THRESHOLD =

Minimum output value to avoid dust rejection.

546

Class Method Summary collapse

Class Method Details

.call(wif:, to_address:, satoshis:, network: nil, server_context: nil) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/bsv/mcp/tools/broadcast_p2pkh.rb', line 88

def self.call(wif:, to_address:, satoshis:, network: nil, server_context: nil)
  net_sym = Helpers.resolve_network_sym(network, server_context)

  private_key = BSV::Primitives::PrivateKey.from_wif(wif)
  sender_address = private_key.public_key.address(network: net_sym)

  woc = BSV::Network::WhatsOnChain.new(network: net_sym)
  all_utxos = woc.fetch_utxos(sender_address)

  return Helpers.error_response('No UTXOs found for sender address — the address may have no funds') if all_utxos.empty?

  # Greedy UTXO selection: sort descending, take until sufficient
  sorted = all_utxos.sort_by { |u| -u.satoshis }
  selected = select_utxos(sorted, satoshis)
  return Helpers.error_response("Insufficient funds — available: #{all_utxos.sum(&:satoshis)} satoshis") if selected.nil?

  tx = build_transaction(selected, satoshis, to_address, sender_address, private_key)

  arc = build_arc(net_sym, server_context)
  broadcast_result = arc.broadcast(tx)

  result = {
    txid: broadcast_result.txid,
    tx_status: broadcast_result.tx_status,
    hex: tx.to_hex
  }

  ::MCP::Tool::Response.new(
    [::MCP::Content::Text.new(result.to_json)],
    structured_content: result
  )
rescue ArgumentError => e
  Helpers.error_response(e.message)
rescue BSV::Network::ChainProviderError => e
  Helpers.error_response("UTXO fetch failed: #{e.message}")
rescue BSV::Network::BroadcastError => e
  Helpers.error_response("Broadcast failed: #{e.message}")
end