Here was my code for free use:
* Take the entire Balance of Address A and send it to Address B
*
* @param jsonRPCClient $jsonrpc A valid jsonRPCClient connected to bitcoind
* @param string $addrA Address to sweep
* @param string $addrB Address to receive swept funds
* @param int $fee Fee to be applied (satoshis), is computed as ($perkb * size in kb) if $fee == -1
* else it is applied directly
* @param int $perkb Fee (satoshis) to be applied per kb of transaction size
* @param int $minconf Minimum number of confirmations required to be swept
* @return array Result contains 2 elements, success and either message or txid.
* If success == true then txid contains the transaction id else message contains the error
*/
function sweepBTC($jsonrpc, $addrA, $addrB, $fee = -1, $perkb = 10000, $minconf = 0) {
$unspent = $jsonrpc->listunspent($minconf);
$txinputs = array();
$addrbalance = 0;
foreach ($unspent as $value) {
if ($value["address"] == $addrA) {
$txinputs[] = array("txid" => $value["txid"],
"vout" => $value["vout"]);
$addrbalance += (int) round($value["amount"] * 1e8);
}
}
if (count($txinputs) < 1) {
return array("success" => false, "message" => "No unspent outputs available");
}
// fee calculate by ($perkb * size in kb) following the formula at:
// http://bitcoin.stackexchange.com/questions/1195/how-to-calculate-transaction-size-before-sending
if ($fee == -1)
$fee = (int) max($perkb * floor((count($txinputs) * 148 + 44) / 1024), $perkb);
else if ($fee < 0) {
return array("succes" => false, "message" => "Fee must be non-negative");
}
$btcToSend = ($addrbalance - $fee);
if ($btcToSend < 0) {
return array("success" => false, "message" => "Not enough funds to cover fee");
}
$rawtx = $jsonrpc->createrawtransaction(
$txinputs, array(
$addrB => ($btcToSend / 1e8)));
$signedtx = $jsonrpc->signrawtransaction($rawtx);
if ($signedtx["Complete"] == 1) {
$txid = $jsonrpc->sendrawtransaction($signedtx["hex"]);
} else {
return array("success" => false, "message" => "Oddly the transaction did not sign completely...");
}
return array("success" => true, "txid" => $txid);
}