on 6941c77 help sign in
bridge/src/lib/lib.js
84 lines 1.9 kB history raw
1import ob from 'urbit-ob';
2import patp2dec from './patp2dec';
3import { fromWei, toWei, toBN } from 'web3-utils';
5const safeFromWei = (num, target) => {
6 try {
7 return fromWei(toBN(num), target);
8 } catch (e) {
9 e.message =
10 `(safeFromWei got ${typeof num} (${num}), made ${typeof toBN(
11 num
12 )}. Please report this issue!) ` + e.message;
13 throw e;
14 }
15};
17const safeToWei = (num, source) => {
18 try {
19 return toWei(toBN(num), source);
20 } catch (e) {
21 e.message =
22 `(safeToWei got ${typeof num} (${num}), made ${typeof toBN(
23 num
24 )}. Please report this issue!) ` + e.message;
25 throw e;
26 }
27};
29const compose = (...fs) =>
30 fs.reduceRight((pF, nF) => (...args) => nF(pF(...args)), v => v);
32const allFalse = (...args) => args.every(a => a === false);
34const isLast = (l, i) => i === l - 1;
36const isUndefined = v => v === undefined;
38const defaultTo = (v, d) => (isUndefined(v) ? d : v);
40const seq = n => Array.from(Array(n), (_, i) => i);
42const fill = (n, v) => Array.from(Array(n), () => v);
44const strSplice = (arr, i, val) => `${arr.slice(0, i)}${val}${arr.slice(i)}`;
46const isValidGalaxy = name => {
47 let point;
48 try {
49 point = patp2dec(name);
50 } catch (err) {
51 return false;
52 }
53 return point >= 0 && point < 256;
54};
56const randomPatq = len => {
57 let bytes = window.crypto.getRandomValues(new Uint8Array(len));
58 let hex = bytes.reduce(
59 (acc, byt) => acc + byt.toString(16).padStart(2, '0'),
60 ''
61 );
62 return ob.hex2patq(hex);
63};
65// TODO: is there a function for this calculation in urbit-ob or similar?
66// 3 characters per byte, plus a tilde and hypen prefix per pair of bytes
67const patpStringLength = byteLength =>
68 byteLength * 3 + Math.ceil(byteLength / 2);
70export {
71 safeFromWei,
72 safeToWei,
73 compose,
74 allFalse,
75 isLast,
76 isUndefined,
77 defaultTo,
78 seq,
79 fill,
80 strSplice,
81 isValidGalaxy,
82 randomPatq,
83 patpStringLength,
84};