on 75770da help sign in
bridge/src/lib/lib.js
91 lines 2.1 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(
31 (pF, nF) => (...args) => nF(pF(...args)),
32 v => v
33 );
35const allFalse = (...args) => args.every(a => a === false);
37const isLast = (l, i) => i === l - 1;
39const isUndefined = v => v === undefined;
41const defaultTo = (v, d) => (isUndefined(v) ? d : v);
43const seq = n => Array.from(Array(n), (_, i) => i);
45const fill = (n, v) => Array.from(Array(n), () => v);
47const strSplice = (arr, i, val) => `${arr.slice(0, i)}${val}${arr.slice(i)}`;
49const isValidGalaxy = name => {
50 let point;
51 try {
52 point = patp2dec(name);
53 } catch (err) {
54 return false;
55 }
56 return point >= 0 && point < 256;
57};
59const randomPatq = len => {
60 let bytes = window.crypto.getRandomValues(new Uint8Array(len));
61 let hex = bytes.reduce(
62 (acc, byt) => acc + byt.toString(16).padStart(2, '0'),
63 ''
64 );
65 return ob.hex2patq(hex);
66};
68// TODO: is there a function for this calculation in urbit-ob or similar?
69// 3 characters per byte, plus a tilde and hypen prefix per pair of bytes
70const patpStringLength = byteLength =>
71 byteLength * 3 + Math.ceil(byteLength / 2);
73const deSiggedString = siggedString =>
74 siggedString.startsWith('~') ? siggedString.slice(1) : siggedString;
76export {
77 safeFromWei,
78 safeToWei,
79 compose,
80 allFalse,
81 isLast,
82 isUndefined,
83 defaultTo,
84 seq,
85 fill,
86 strSplice,
87 isValidGalaxy,
88 randomPatq,
89 patpStringLength,
90 deSiggedString,
91};