address.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { hexStr2byteArray, byteArray2hexStr } from './code.js';
  2. import { decodeBase58Address, getBase58CheckAddress, isAddressValid, pkToAddress } from './crypto.js';
  3. import { isHex, isString } from './validations.js';
  4. import { keccak256 } from './ethersUtils.js';
  5. import { ADDRESS_PREFIX } from './constants.js';
  6. export function fromHex(address) {
  7. if (!isHex(address))
  8. return address;
  9. return getBase58CheckAddress(hexStr2byteArray(address.replace(/^0x/, ADDRESS_PREFIX)));
  10. }
  11. export function toHex(address) {
  12. if (isHex(address))
  13. return address.toLowerCase().replace(/^0x/, ADDRESS_PREFIX);
  14. return byteArray2hexStr(decodeBase58Address(address)).toLowerCase();
  15. }
  16. function getChecksumAddress(address) {
  17. address = address.toLowerCase();
  18. const chars = address.substring(2).split('');
  19. const expanded = new Uint8Array(40);
  20. for (let i = 0; i < 40; i++) {
  21. expanded[i] = chars[i].charCodeAt(0);
  22. }
  23. const hashed = hexStr2byteArray(keccak256(expanded).slice(2));
  24. for (let i = 0; i < 40; i += 2) {
  25. if ((hashed[i >> 1] >> 4) >= 8) {
  26. chars[i] = chars[i].toUpperCase();
  27. }
  28. if ((hashed[i >> 1] & 0x0f) >= 8) {
  29. chars[i + 1] = chars[i + 1].toUpperCase();
  30. }
  31. }
  32. return ADDRESS_PREFIX + chars.join('');
  33. }
  34. export function toChecksumAddress(address) {
  35. if (!isAddress(address))
  36. throw new Error(`'${address}' is not a valid address string`);
  37. return getChecksumAddress(toHex(address));
  38. }
  39. export function isChecksumAddress(address) {
  40. if (!isHex(address) || address.length !== 42)
  41. return false;
  42. try {
  43. return toChecksumAddress(address) === address;
  44. }
  45. catch {
  46. return false;
  47. }
  48. }
  49. export function fromPrivateKey(privateKey, strict = false) {
  50. try {
  51. return pkToAddress(privateKey, strict);
  52. }
  53. catch {
  54. return false;
  55. }
  56. }
  57. export function isAddress(address) {
  58. if (!address || !isString(address))
  59. return false;
  60. // Convert HEX to Base58
  61. if (address.length === 42) {
  62. try {
  63. // it throws an error if the address starts with 0x
  64. return isAddress(getBase58CheckAddress(hexStr2byteArray(address)));
  65. }
  66. catch (err) {
  67. return false;
  68. }
  69. }
  70. try {
  71. return isAddressValid(address);
  72. }
  73. catch (err) {
  74. return false;
  75. }
  76. }
  77. //# sourceMappingURL=address.js.map