-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
93 lines (76 loc) · 2.07 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
function isHexString(value, length) {
if (typeof(value) !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) {
return false;
}
if (length && value.length !== 2 + 2 * length) { return false; }
return true;
}
function padToEven(value) {
var a = value;
if (typeof a !== 'string') {
throw new Error(`While padding to even, value must be string, is currently ${typeof a}, while padToEven.`);
}
if (a.length % 2) {
a = `0${a}`;
}
return a;
}
function stripHexPrefix(str) {
if (typeof str !== 'string') {
return str;
}
return isHexPrefixed(str) ? str.slice(2) : str;
}
function isHexPrefixed(str) {
if (typeof str !== 'string') {
throw new Error("Value must be type 'string', is currently type " + (typeof str) + ", while checking isHexPrefixed.");
}
return str.slice(0, 2) === '0x';
}
function intToBuffer(i) {
const hex = intToHex(i);
return new Buffer(padToEven(hex.slice(2)), 'hex');
}
function intToHex(i) {
var hex = i.toString(16);
return `0x${hex}`;
}
function addPrefix0x(hexString){
return hexString.startsWith('0x') ? hexString : `0x${hexString}`
}
function toBuffer(v){
if (!Buffer.isBuffer(v)) {
if (Array.isArray(v)) {
v = Buffer.from(v)
} else if (typeof v === 'string') {
if (isHexString(v)) {
v = Buffer.from(padToEven(stripHexPrefix(v)), 'hex')
} else {
throw new Error(
`Cannot convert string to buffer. toBuffer only supports 0x-prefixed hex strings and this string was given: ${v}`,
)
}
} else if (typeof v === 'number') {
v = intToBuffer(v)
} else if (v === null || v === undefined) {
v = Buffer.allocUnsafe(0)
} else if (BN.isBN(v)) {
v = v.toArrayLike(Buffer)
} else if (v.toArray) {
v = Buffer.from(v.toArray())
} else {
throw new Error('invalid type')
}
}
return v
}
module.exports = {
toBuffer,
isHexString,
padToEven,
stripHexPrefix,
isHexPrefixed,
intToBuffer,
intToHex,
addPrefix0x
}