Home Reference Source

packages/oo7-substrate/src/pretty.js

  1. const { ss58Encode } = require('./ss58')
  2. const { bytesToHex } = require('./utils')
  3. const { VecU8, AccountId, Hash, SlashPreference, VoteThreshold, Moment, Balance, BlockNumber, AccountIndex, Tuple, reviver } = require('./types')
  4. const { denominationInfo } = require('./denominationInfo')
  5.  
  6. const numberWithCommas = n => {
  7. let x = n.toString();
  8. if (x.indexOf('.') > -1) {
  9. let [a, b] = x.split('.');
  10. return numberWithCommas(a) + '.' + b;
  11. } else {
  12. return x.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  13. }
  14. }
  15.  
  16. //TODO: AccountIndex
  17.  
  18. function pretty(expr) {
  19. if (expr === null) {
  20. return 'null';
  21. }
  22. if (expr instanceof VoteThreshold) {
  23. return 'VoteThreshold.' + expr;
  24. }
  25. if (expr instanceof SlashPreference) {
  26. return 'SlashPreference{unstake_threshold=' + expr + '}';
  27. }
  28. if (expr instanceof Balance) {
  29. let di = denominationInfo
  30.  
  31. let denomincationSearch = [di.primary, Object.keys(di.denominations)]
  32. let unit = null
  33. let dp = 0
  34. for (ii in denomincationSearch) {
  35. let i = denomincationSearch[ii]
  36. let denom = di.denominations[i]
  37. let divisor = Math.pow(10, denom)
  38. let lower = divisor / 30
  39. let upper = divisor * 30000
  40. if (expr > lower && expr < upper) {
  41. unit = i
  42. expr /= divisor
  43. for (; expr < 3000 / Math.pow(10, dp); dp++) {}
  44. break;
  45. }
  46. }
  47.  
  48. if (unit === null) {
  49. // default
  50. if (expr < Math.pow(10, di.denominations[di.primary]) / 30 && expr !== 0) {
  51. unit = di.unit
  52. } else {
  53. unit = di.primary
  54. expr /= Math.pow(10, di.denominations[unit])
  55. expr = Math.round(expr)
  56. }
  57. }
  58.  
  59. return numberWithCommas(Math.round(expr * Math.pow(10, dp)) / Math.pow(10, dp)) + ' ' + unit
  60. }
  61. if (expr instanceof BlockNumber) {
  62. return numberWithCommas(expr);
  63. }
  64. if (expr instanceof Hash) {
  65. return '0x' + bytesToHex(expr);
  66. }
  67. if (expr instanceof Moment) {
  68. return expr.toLocaleString() + " (" + expr.number + " seconds)";
  69. }
  70. if (expr instanceof AccountId) {
  71. return ss58Encode(expr);
  72. }
  73. if (expr instanceof Tuple) {
  74. return '(' + expr.map(pretty).join(', ') + ')';
  75. }
  76. if (expr instanceof VecU8 || expr instanceof Uint8Array) {
  77. if (expr.length <= 256) {
  78. return '[' + bytesToHex(expr) + ']';
  79. } else {
  80. return `[${bytesToHex(expr.slice(0, 256))}...] (${expr.length} bytes)`;
  81. }
  82. }
  83. if (expr instanceof Array) {
  84. return '[' + expr.map(pretty).join(', ') + ']';
  85. }
  86. if (typeof expr === 'object') {
  87. return '{' + Object.keys(expr).map(k => k + ': ' + pretty(expr[k])).join(', ') + '}';
  88. }
  89. return '' + expr;
  90. }
  91.  
  92. module.exports = { pretty };