utils.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import baseX from 'base-x';
  2. import PAKO from 'pako';
  3. import {Buffer} from 'safe-buffer';
  4. export const pako = PAKO;
  5. const BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
  6. const BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  7. const bs58 = baseX(BASE58);
  8. const bs64 = baseX(BASE64);
  9. export function sleep(ms) {
  10. return new Promise(resolve => setTimeout(resolve, ms));
  11. }
  12. export function stringToHex(str) {
  13. return Buffer.from(str).toString('hex');
  14. }
  15. export function hexToString(str) {
  16. return Buffer.from(str, 'hex').toString();
  17. }
  18. export function randomArray(len) {
  19. const a = new Uint8Array(len);
  20. crypto.getRandomValues(a);
  21. return a;
  22. }
  23. export function randomHexString(len) {
  24. return Buffer.from(randomArray(len)).toString('hex');
  25. }
  26. export function formatDate(d, format) {
  27. if (!format)
  28. format = 'normal';
  29. switch (format) {
  30. case 'normal':
  31. return `${d.getDate().toString().padStart(2, '0')}.${(d.getMonth() + 1).toString().padStart(2, '0')}.${d.getFullYear()} ` +
  32. `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
  33. }
  34. }
  35. export function fallbackCopyTextToClipboard(text) {
  36. let textArea = document.createElement('textarea');
  37. textArea.value = text;
  38. document.body.appendChild(textArea);
  39. textArea.focus();
  40. textArea.select();
  41. let result = false;
  42. try {
  43. result = document.execCommand('copy');
  44. } catch (e) {
  45. //
  46. }
  47. document.body.removeChild(textArea);
  48. return result;
  49. }
  50. export async function copyTextToClipboard(text) {
  51. if (!navigator.clipboard) {
  52. return fallbackCopyTextToClipboard(text);
  53. }
  54. let result = false;
  55. try {
  56. await navigator.clipboard.writeText(text);
  57. result = true;
  58. } catch (e) {
  59. //
  60. }
  61. return result;
  62. }
  63. export function toBase58(data) {
  64. return bs58.encode(data);
  65. }
  66. export function fromBase58(data) {
  67. return bs58.decode(data);
  68. }
  69. export function toBase64(data) {
  70. return bs64.encode(data);
  71. }
  72. export function fromBase64(data) {
  73. return bs64.decode(data);
  74. }