forked from dawsbot/satoshi-bitcoin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (66 loc) · 1.8 KB
/
index.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
/**
* @module satoshi-ecash
*/
var Big = require('big.js')
// @private
var conversion = 100
// es6 polyfill
if (!Number.isInteger) {
Number.isInteger = function (num) {
return typeof num === 'number' && num % 1 === 0
}
}
// @private
function toNumber(notNum) {
return Number(notNum)
}
module.exports = {
/**
* Convert Satoshi to eCash
* @param {number|string} satoshi Amount of Satoshi to convert. Must be a whole number
* @throws {TypeError} Thrown if input is not a number or string
* @throws {TypeError} Thrown if input is not a whole number or string format whole number
* @returns {number}
*/
toECash: function (satoshi) {
//validate arg
var satoshiType = typeof satoshi
if (satoshiType === 'string') {
satoshi = toNumber(satoshi)
satoshiType = 'number'
}
if (satoshiType !== 'number') {
throw new TypeError(
'toECash must be called on a number or string, got ' + satoshiType
)
}
if (!Number.isInteger(satoshi)) {
throw new TypeError(
'toECash must be called on a whole number or string format whole number'
)
}
var bigSatoshi = new Big(satoshi)
return Number(bigSatoshi.div(conversion))
},
/**
* Convert eCash to Satoshi
* @param {number|string} eCash Amount of eCash to convert
* @throws {TypeError} Thrown if input is not a number or string
* @returns {number}
*/
toSatoshi: function (eCash) {
//validate arg
var eCashType = typeof eCash
if (eCashType === 'string') {
eCash = toNumber(eCash)
eCashType = 'number'
}
if (eCashType !== 'number') {
throw new TypeError(
'toSatoshi must be called on a number or string, got ' + eCashType
)
}
var bigECash = new Big(eCash)
return Number(bigECash.times(conversion))
},
}