Skip to content

Instantly share code, notes, and snippets.

@ditto-b
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ditto-b/9360868 to your computer and use it in GitHub Desktop.
Save ditto-b/9360868 to your computer and use it in GitHub Desktop.
Basic coin control for Bitcoin/Altcoin wallets in Ruby
require 'rpcjson'
require 'bigdecimal'
require 'bigdecimal/util'
class Wallet
class InsufficientFundsError < StandardError; end
def initialize(user, pass, host = '127.0.0.1:22555', fee = '0.1'.to_d)
@rpc = RPC::JSON::Client.new "http://#{user}:#{pass}@#{host}", 1.1
@fee = fee
end
def address_balance(address, confs = 0)
unspent_outputs = list_unspent confs, 9999999, [address]
unspent_outputs.inject(0){|sum,o| sum + o['amount']}
end
def send_from_address(from, to, amount)
total_amount = (amount + @fee).round(8)
unspent_outputs = list_unspent 0, 9999999, [from]
amount_to_spend = BigDecimal('0')
txs_to_spend = []
unspent_outputs.each do |o|
break if amount_to_spend >= total_amount
amount_to_spend += o['amount'].to_s.to_d
txs_to_spend << {'txid' => o['txid'], 'vout' => o['vout']}
end
raise InsufficientFundsError if amount_to_spend < total_amount
new_outputs = {}
new_outputs[to] = amount.round(8).to_f
new_outputs[from] = (amount_to_spend - send_amount - @fee).round(8).to_f
raw_tx = create_raw_transaction txs_to_spend, new_outputs
signed_tx = sign_raw_transaction raw_tx
send_raw_transaction signed_tx['hex']
end
def method_missing(method, *args)
@rpc.send method.to_s.gsub('_','').to_sym, *args
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment