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
126
127
128
129
130
# 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::Providers::WhatsOnChain.default(network: net_sym)
  utxo_result = woc.call(:get_utxos_all, sender_address)
  return Helpers.error_response("UTXO fetch failed: #{utxo_result.message}") unless utxo_result.success?

  all_utxos = utxo_result.data.map do |entry|
    BSV::Network::UTXO.new(
      tx_hash: entry[:tx_hash], tx_pos: entry[:tx_pos],
      satoshis: entry[:satoshis], height: entry[:height]
    )
  end

  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)
  arc_result = arc.call(:broadcast, tx)
  return Helpers.error_response("Broadcast failed: #{arc_result.message}") unless arc_result.success?

  result = {
    txid: arc_result.data[:txid],
    tx_status: arc_result.data[: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)
end