diff --git a/copay.js b/copay.js index 5b2a2951c..8da76ebc7 100644 --- a/copay.js +++ b/copay.js @@ -1,5 +1,6 @@ module.exports.Storage = require('./js/models/Storage'); module.exports.PublicKeyRing = require('./js/models/PublicKeyRing'); +module.exports.Wallet = require('./js/models/Wallet'); module.exports.CopayPeer = require('./js/models/CopayPeer'); module.exports.FakeStorage = require('./test/FakeStorage'); diff --git a/index.html b/index.html index b5942f087..9a6bddac8 100644 --- a/index.html +++ b/index.html @@ -281,7 +281,7 @@ - + diff --git a/js/models/Wallet.js b/js/models/Wallet.js new file mode 100644 index 000000000..559d87b5f --- /dev/null +++ b/js/models/Wallet.js @@ -0,0 +1,115 @@ +'use strict'; + +var imports = require('soop').imports(); +var bitcore = require('bitcore'); +var http = require('http'); + +function Wallet(opts) { + opts = opts || {}; + this.host = 'localhost'; + this.port = '3001'; +} + +function asyncForEach(array, fn, callback) { + array = array.slice(0); + function processOne() { + var item = array.pop(); + fn(item, function(result) { + if(array.length > 0) { + setTimeout(processOne, 0); // schedule immediately + } else { + callback(); // Done! + } + }); + } + if(array.length > 0) { + setTimeout(processOne, 0); // schedule immediately + } else { + callback(); // Done! + } +}; + +Wallet.prototype.getBalance = function(unspent) { + var balance = 0; + for(var i=0;i 0) { + all = all.concat(res); + } + callback(); + }); + }, function() { + return cb(all); + }); +}; + +Wallet.prototype.sendRawTransaction = function(rawtx, cb) { + if (!rawtx) return callback(); + + var options = { + host: this.host, + port: this.port, + method: 'POST', + path: '/api/tx/send', + data: 'rawtx='+rawtx, + headers: { 'content-type' : 'application/x-www-form-urlencoded' } + }; + + this.request(options, function(err,res) { + if (err) return cb(); + return cb(res.txid); + }); +}; + +Wallet.prototype.request = function(options, callback) { + var req = http.request(options, function(response) { + var ret; + if (response.statusCode == 200) { + response.on('data', function(chunk) { + try { + ret = JSON.parse(chunk); + } catch (e) { + callback({message: "Wrong response from insight"}); + return; + } + }); + response.on('end', function () { + callback(undefined, ret); + return; + }); + } + else { + callback({message: 'Error ' + response.statusCode}); + return; + } + }); + if (options.data) { + req.write(options.data); + } + req.end(); +} + + +module.exports = require('soop')(Wallet); + diff --git a/test/index.html b/test/index.html index d84916368..a6139d84f 100644 --- a/test/index.html +++ b/test/index.html @@ -12,13 +12,14 @@ - + - + +