forked from abrkn/tipmebch
-
Notifications
You must be signed in to change notification settings - Fork 1
/
apis.js
238 lines (188 loc) · 5.63 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
const shortid = require('shortid');
const {
isValidTelegramUserIdFormat,
getUserAccount,
viaAddressToInternal,
} = require('./utils');
const { BalanceWouldBecomeNegativeError } = require('./errors');
const assert = require('assert');
const superagent = require('superagent');
const pMemoize = require('p-memoize');
const {
n,
formatVia,
formatUsd,
hasTooManyDecimalsForSats,
} = require('./utils');
const MIN_WITHDRAW_AMOUNT = 0.0001;
const fetchCoinmarketcap = async coin => {
const { body } = await superagent(
'https://api.coinmarketcap.com/v1/ticker/viacoin/'
);
const [item] = body.filter(_ => _.id === coin);
assert(item, `${coin} not found`);
return item;
};
const memFetchCoinmarketcap = pMemoize(fetchCoinmarketcap, { maxAge: 10e3 });
exports.fetchViaAddressBalance = async address => {
const { body } = await superagent(
`https://explorer.viacoin.org/api/addr/${address}/?noTxList=1`
);
const { balance } = body;
return balance;
};
const viaToUsd = async amount => {
const usdRate = (await memFetchCoinmarketcap('viacoin')).price_usd;
const asUsd = n(amount)
.times(usdRate)
.toNumber();
return asUsd;
};
const usdToVia = async amount => {
const usdRate = (await memFetchCoinmarketcap('viacoin')).price_usd;
return +parseFloat(n(amount).div(usdRate)).toFixed(8);
};
const formatViaWithUsd = async amount => {
const amountAsUsd = await viaToUsd(amount);
return `${formatVia(amount)} (${formatUsd(amountAsUsd)})`;
};
exports.formatConfirmedAndUnconfirmedBalances = async (
confirmed,
withUnconfirmed
) => {
const pending = n(withUnconfirmed)
.minus(confirmed)
.toNumber();
const confirmedText = await formatViaWithUsd(confirmed);
const parts = [confirmedText];
if (pending > 0) {
const formatted = await formatViaWithUsd(pending);
parts.push(`. Pending deposits: ${formatted}`);
}
return parts.join('');
};
exports.parseViaOrUsdAmount = async value => {
assert.equal(typeof value, 'string');
const match = value.match(/^(\$?)([0-9\.]+)$/);
if (!match) {
return null;
}
const [, symbol, amount] = match;
let viaAmount;
if (symbol === '$') {
viaAmount = await usdToVia(amount);
} else {
viaAmount = +amount;
}
if (n(viaAmount).decimalPlaces() > 8) {
throw new Error(`Too many decimals in ${viaAmount}`);
}
return viaAmount;
};
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, lockViacoind, redisClient }
) => {
assert.equal(typeof toUserId, 'string');
assert.equal(typeof fromUserId, 'string');
assert.notEqual(fromUserId, toUserId, 'Cannot send to self');
const lock = await lockViacoind();
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, lockViacoind }
) => {
assert(isValidTelegramUserIdFormat(fromUserId));
assert.equal(typeof address, 'string');
const lock = await lockViacoind();
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),
viaAddressToInternal(address),
amountN.toFixed(8),
]);
assert(txid, 'Could not withdraw funds');
return { amount: amountN.toFixed(8), txid };
} finally {
await lock.unlock();
}
};
exports.fetchCoinmarketcap = fetchCoinmarketcap;
exports.viaToUsd = viaToUsd;
exports.formatViaWithUsd = formatViaWithUsd;
exports.getBalanceForAccount = getBalanceForAccount;
exports.getBalanceForUser = getBalanceForUser;
Object.assign(exports, { transfer, withdraw });