-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathmove_balance_to_change_addresses.js
88 lines (80 loc) · 2.64 KB
/
move_balance_to_change_addresses.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*jslint node: true */
/*
To be used by exchanges in order to move balance away from deposit addresses
*/
"use strict";
var headlessWallet = require('../start.js');
var eventBus = require('ocore/event_bus.js');
var db = require('ocore/db.js');
var conf = require('ocore/conf.js');
const MAX_FEES = 5000;
var wallet;
function onError(err){
throw Error(err);
}
function readNextChangeAddress(handleChangeAddress){
if (conf.bStaticChangeAddress)
headlessWallet.issueOrSelectStaticChangeAddress(handleChangeAddress);
else{
var walletDefinedByKeys = require('ocore/wallet_defined_by_keys.js');
walletDefinedByKeys.issueNextAddress(wallet, 1, function(objAddr){
handleChangeAddress(objAddr.address);
});
}
}
function moveBalance(){
var composer = require('ocore/composer.js');
var network = require('ocore/network.js');
db.query(
"SELECT address, SUM(amount) AS amount FROM my_addresses JOIN outputs USING(address) JOIN units USING(unit) \n\
WHERE wallet=? AND is_change=0 AND is_spent=0 AND asset IS NULL AND sequence='good' AND is_stable=1 \n\
GROUP BY address \n\
ORDER BY EXISTS ( \n\
SELECT * FROM unit_authors JOIN units USING(unit) \n\
WHERE is_stable=0 AND unit_authors.address=outputs.address AND definition_chash IS NOT NULL \n\
) \n\
LIMIT 10",
[wallet],
function(rows){
let arrPayingAddresses = rows.map(row => row.address);
let amount = rows.reduce((acc, row) => { return acc+row.amount; }, 0);
let pay_amount = Math.round(amount/2);
if (rows.length === 0 || pay_amount <= MAX_FEES){
console.error('done');
return setTimeout(() => { process.exit(0); }, 1000);
}
console.error('will move '+pay_amount+' bytes from', arrPayingAddresses);
readNextChangeAddress(function(to_address){
readNextChangeAddress(function(change_address){
var arrOutputs = [
{address: change_address, amount: 0}, // the change
{address: to_address, amount: pay_amount} // the receiver
];
composer.composeAndSaveMinimalJoint({
available_paying_addresses: arrPayingAddresses,
outputs: arrOutputs,
signer: headlessWallet.signer,
callbacks: {
ifNotEnoughFunds: function(err){
console.error(err+', will retry in 1 min');
setTimeout(moveBalance, 60*1000);
},
ifError: onError,
ifOk: function(objJoint){
network.broadcastJoint(objJoint);
console.error("moved "+pay_amount+" bytes, unit "+objJoint.unit.unit);
moveBalance();
}
}
});
});
});
}
);
}
eventBus.on('headless_wallet_ready', function(){
headlessWallet.readSingleWallet(function(_wallet){
wallet = _wallet;
moveBalance();
});
});