forked from Sfippa/api-client-v1-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
96 lines (83 loc) · 2.36 KB
/
Copy pathindex.js
File metadata and controls
96 lines (83 loc) · 2.36 KB
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
89
90
91
92
93
94
95
96
var EventEmitter = require('events')
var util = require('util')
var WebSocket
try {
WebSocket = require('ws')
module.exports = Socket
} catch (e) {
var wsErrMsg = 'Cannot create Socket object, module `ws` was not installed correctly'
module.exports = function () { throw new Error(wsErrMsg) }
}
util.inherits(Socket, EventEmitter)
function Socket (options) {
EventEmitter.call(this)
options = options || { network: 0 }
var wsUrl = Socket.wsUrlForNetwork(options.network)
var socket = new WebSocket(wsUrl)
this.close = socket.close.bind(socket)
this.getReadyState = function () { return socket.readyState }
this.op = function (op, data) {
var message = JSON.stringify(extend({ op: op }, data || {}))
var send = socket.send.bind(socket, message)
if (socket.readyState === WebSocket.CONNECTING) socket.on('open', send)
else if (socket.readyState === WebSocket.OPEN) send()
}
socket.on('message', function (message) {
message = JSON.parse(message)
this.emit(message.op, message.x)
}.bind(this))
socket.on('open', this.emit.bind(this, 'open'))
socket.on('close', this.emit.bind(this, 'close'))
socket.on('error', this.emit.bind(this, 'error'))
}
Socket.prototype.subscribe = function (sub, options) {
this.op(sub, options)
return this
}
Socket.prototype.onOpen = function (callback) {
this.on('open', callback)
return this
}
Socket.prototype.onClose = function (callback) {
this.on('close', callback)
return this
}
Socket.prototype.onTransaction = function (callback, options) {
options = options || {}
if (options.addresses instanceof Array) {
options.addresses.forEach(function (addr) {
this.op('addr_sub', { addr: addr })
}, this)
} else {
this.op('unconfirmed_sub')
}
if (options.setTxMini) {
this.op('set_tx_mini')
}
this.on('utx', callback)
this.on('minitx', callback)
return this
}
Socket.prototype.onBlock = function (callback) {
this.op('blocks_sub')
this.on('block', callback)
return this
}
Socket.wsUrlForNetwork = function (network) {
switch (network) {
case 0:
return 'wss://ws.blockchain.info/inv'
case 3:
return 'wss://ws.blockchain.info/testnet3/inv'
default:
throw new Error('Invalid network: ' + network)
}
}
function extend (o, p) {
for (var prop in p) {
if (!o.hasOwnProperty(prop)) {
o[prop] = p[prop]
}
}
return o
}