-
Notifications
You must be signed in to change notification settings - Fork 15
/
apis.js
197 lines (147 loc) · 5.45 KB
/
apis.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
const shortid = require('shortid');
const { isValidTelegramUserIdFormat, getUserAccount } = require('./utils');
const { BalanceWouldBecomeNegativeError } = require('./errors');
const assert = require('assert');
const superagent = require('superagent');
const pMemoize = require('p-memoize');
const { n, formatBch, formatUsd, hasTooManyDecimalsForSats } = require('./utils');
const MIN_WITHDRAW_AMOUNT = 0.0001;
const fetchCoinmarketcap = async coin => {
const { body } = await superagent('https://api.coinmarketcap.com/v1/ticker/?limit=10');
const [item] = body.filter(_ => _.id === coin);
assert(item, `${coin} not found`);
return item;
};
const memFetchCoinmarketcap = pMemoize(fetchCoinmarketcap, { maxAge: 10e3 });
exports.fetchBchAddressBalance = async address => {
const { body } = await superagent(
`https://blockdozer.com/insight-api/addr/${address}/?noTxList=1`
);
const { balance } = body;
return balance;
};
const bchToUsd = async amount => {
const usdRate = (await memFetchCoinmarketcap('bitcoin-cash')).price_usd;
const asUsd = n(amount)
.times(usdRate)
.toNumber();
return asUsd;
};
const usdToBch = async amount => {
const usdRate = (await memFetchCoinmarketcap('bitcoin-cash')).price_usd;
return +parseFloat(n(amount).div(usdRate)).toFixed(8);
};
const formatBchWithUsd = async amount => {
const amountAsUsd = await bchToUsd(amount);
return `${formatBch(amount)} (${formatUsd(amountAsUsd)})`;
};
exports.formatConfirmedAndUnconfirmedBalances = async (confirmed, withUnconfirmed) => {
const pending = n(withUnconfirmed)
.minus(confirmed)
.toNumber();
const confirmedText = await formatBchWithUsd(confirmed);
const parts = [confirmedText];
if (pending > 0) {
const formatted = await formatBchWithUsd(pending);
parts.push(`. Pending deposits: ${formatted}`);
}
return parts.join('');
};
exports.parseBchOrUsdAmount = async value => {
assert.equal(typeof value, 'string');
const match = value.match(/^(\$?)([0-9\.]+)$/);
if (!match) {
return null;
}
const [, symbol, amount] = match;
let bchAmount;
if (symbol === '$') {
bchAmount = await usdToBch(amount);
} else {
bchAmount = +amount;
}
if (n(bchAmount).decimalPlaces() > 8) {
throw new Error(`Too many decimals in ${bchAmount}`);
}
return bchAmount;
};
const getBalanceForAccount = async (accountId, { fetchRpc, minConf } = {}) => {
return await fetchRpc('getbalance', [accountId, ...(minConf !== undefined ? [minConf] : [])]);
};
const getBalanceForUser = (userId, { minConf, fetchRpc } = {}) => {
assert(isValidTelegramUserIdFormat(userId), `Invalid user id format, ${userId}`);
return getBalanceForAccount(getUserAccount(userId), { minConf, fetchRpc });
};
const transfer = async (fromUserId, toUserId, amount, { fetchRpc, lockBitcoind, redisClient }) => {
assert.equal(typeof toUserId, 'string');
assert.equal(typeof fromUserId, 'string');
assert.notEqual(fromUserId, toUserId, 'Cannot send to self');
const lock = await lockBitcoind();
try {
const amountN = n(amount);
assert(!hasTooManyDecimalsForSats(amountN), 'Too many decimals');
assert(amountN.isFinite(), 'Not finite');
assert(amountN.gt(0), 'Less than or equal to zero');
const prevBalance = n(await fetchRpc('getbalance', [getUserAccount(fromUserId)]));
const nextBalance = prevBalance.minus(amountN);
if (nextBalance.lt(0)) {
throw new BalanceWouldBecomeNegativeError('Balance would become negative');
}
const moved = await fetchRpc('move', [
getUserAccount(fromUserId),
getUserAccount(toUserId),
amountN.toFixed(8),
]);
assert.equal(moved, true, 'Could not move funds');
// TODO: Move outside lock
const transferId = shortid.generate();
await redisClient
.multi()
.rpush('transfers', transferId)
.rpush(`user:${fromUserId}:transfers`, transferId)
.rpush(`user:${toUserId}:transfers`, transferId)
.set(`transfers:${transferId}`, {
transferId,
fromUserId,
toUserId,
timestamp: +new Date(),
amount,
})
.execAsync();
return amountN.toFixed(8);
} finally {
await lock.unlock();
}
};
const withdraw = async (fromUserId, address, amount, { fetchRpc, lockBitcoind }) => {
assert(isValidTelegramUserIdFormat(fromUserId));
assert.equal(typeof address, 'string');
const lock = await lockBitcoind();
try {
const amountN = n(amount);
assert(!hasTooManyDecimalsForSats(amountN), 'Too many decimals');
assert(amountN.isFinite(), 'Not finite');
assert(amountN.gt(0), 'Less than or equal to zero');
assert(amountN.gte(MIN_WITHDRAW_AMOUNT), `Amount less than minimum of ${MIN_WITHDRAW_AMOUNT}`);
const prevBalance = n(await fetchRpc('getbalance', [getUserAccount(fromUserId)]));
const nextBalance = prevBalance.minus(amountN);
if (nextBalance.lt(0)) {
throw new BalanceWouldBecomeNegativeError('Balance would become negative');
}
const txid = await fetchRpc('sendfrom', [
getUserAccount(fromUserId),
address,
amountN.toFixed(8),
]);
assert(txid, 'Could not withdraw funds');
return { amount: amountN.toFixed(8), txid };
} finally {
await lock.unlock();
}
};
exports.fetchCoinmarketcap = fetchCoinmarketcap;
exports.bchToUsd = bchToUsd;
exports.formatBchWithUsd = formatBchWithUsd;
exports.getBalanceForAccount = getBalanceForAccount;
exports.getBalanceForUser = getBalanceForUser;
Object.assign(exports, { transfer, withdraw });