-
Notifications
You must be signed in to change notification settings - Fork 503
/
utils.js
110 lines (97 loc) · 2.62 KB
/
utils.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
/* @flow */
'use strict';
const _ = require('lodash');
const BigNumber = require('bignumber.js');
const core = require('../../core');
const errors = require('./errors');
const es6promisify = require('es6-promisify');
const keypairs = require('ripple-keypairs');
type Amount = {currency: string, issuer: string, value: string}
function dropsToXrp(drops: string): string {
return (new BigNumber(drops)).dividedBy(1000000.0).toString();
}
function xrpToDrops(xrp: string): string {
return (new BigNumber(xrp)).times(1000000.0).floor().toString();
}
function toRippledAmount(amount: Amount): string|Amount {
if (amount.currency === 'XRP') {
return xrpToDrops(amount.value);
}
return {
currency: amount.currency,
issuer: amount.counterparty ? amount.counterparty : amount.issuer,
value: amount.value
};
}
function generateWallet(options?: Object): Object {
const {accountID, seed} = keypairs.generateWallet(options);
return {secret: seed, address: accountID};
}
type AsyncFunction = (...x: any) => void
function wrapCatch(asyncFunction: AsyncFunction): AsyncFunction {
return function() {
try {
asyncFunction.apply(this, arguments);
} catch (error) {
const callback = arguments[arguments.length - 1];
callback(error);
}
};
}
type Callback = (err: any, data: any) => void
type Wrapper = (data: any) => any
function composeAsync(wrapper: Wrapper, callback: Callback): Callback {
return function(error, data) {
if (error) {
callback(error);
return;
}
let result;
try {
result = wrapper(data);
} catch (exception) {
callback(exception);
return;
}
callback(null, result);
};
}
function convertExceptions<T>(f: () => T): () => T {
return function() {
try {
return f.apply(this, arguments);
} catch (error) {
throw new errors.ApiError(error.message);
}
};
}
const FINDSNAKE = /([a-zA-Z]_[a-zA-Z])/g;
function convertKeysFromSnakeCaseToCamelCase(obj: any): any {
if (typeof obj === 'object') {
let newKey;
return _.reduce(obj, (result, value, key) => {
newKey = key;
if (FINDSNAKE.test(key)) {
newKey = key.replace(FINDSNAKE, r => r[0] + r[2].toUpperCase());
}
result[newKey] = convertKeysFromSnakeCaseToCamelCase(value);
return result;
}, {});
}
return obj;
}
function promisify<T>(asyncFunction: AsyncFunction): Function {
return es6promisify(wrapCatch(asyncFunction));
}
module.exports = {
core,
dropsToXrp,
xrpToDrops,
toRippledAmount,
generateWallet,
composeAsync,
wrapCatch,
convertExceptions,
convertKeysFromSnakeCaseToCamelCase,
promisify
};