Created
November 28, 2012 13:16
-
-
Save abrkn/4161213 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var config = require('../config') | |
, bitcoin = new (require('bitcoin').Client)(config('BTC')) | |
, debug = require('debug')('snow:btc-edge:sender') | |
, db = require('./db') | |
, num = require('num') | |
, util = require('util') | |
, Q = require('q') | |
, client | |
function getBatch() { | |
debug('getting batch') | |
var query = ['SELECT * FROM pop_btc_withdraw_requests() AS', | |
'(request_id int, amount bigint, scale int, address varchar(34));'].join('\n') | |
return Q.ninvoke(client, 'query', query).get('rows') | |
} | |
function executeBatch(jobs) { | |
var r = _.reduce(jobs, function(r, i) { r[i.address] = +num(i.amount, i.scale); return r; }, { }) | |
debug('will send ' + jobs.length + ' transactions') | |
debug('sends to perform: ' + JSON.stringify(r, null, 4)) | |
return Q.ninvoke(bitcoin, 'sendMany', 'credited', r) | |
} | |
function markItemDone(job) { | |
debug('marking item done ' + job.request_id) | |
return Q.ninvoke(client, 'query', { | |
text: 'SELECT confirm_withdraw($1)', | |
values: [row.request_id] | |
}) | |
} | |
function markBatchDone(jobs) { | |
debug('marking ' + jobs.length + ' jobs done') | |
var ids = _.pluck(jobs, 'request_id') | |
return Q.ninvoke(client, 'query', { | |
text: ['UPDATE withdraw_request SET state = "completed", completed = current_timestamp', | |
'WHERE request_id IN (' + ids.join(', ') + ')'].join('\n') | |
}) | |
} | |
function send() { | |
var d = Q.defer() | |
, jobs = getBatch() | |
.then(function(jobs) { | |
if (!jobs.length) { debug('nothing to do'); return d.resolve() } | |
executeBatch(jobs).then(function() { | |
debug('batch is done, spreading on ' + util.inspect(jobs)) | |
Q.spread(jobs, markItemDone).then(function() { | |
debug('item marking done') | |
d.resolve() | |
}) | |
}) | |
}) | |
return d | |
} | |
function loop() { | |
client = db() | |
return send() | |
promise | |
.fin(function() { | |
client.end() | |
client = null | |
}) | |
.fail(function(err) { | |
console.error(err) | |
console.error(err.stack) | |
}) | |
} | |
module.exports = function() { | |
var timer | |
loop().promise.then(function() { | |
debug('scheduling next loop') | |
timer = setTimeout(loop, 10 * 1000) | |
}) | |
process.on('exit', function() { | |
timer && clearTimeout(timer) | |
}) | |
} | |
if (~process.argv[1].indexOf('bitcoinedge.sender.js')) { | |
module.exports() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment