address.ts 951 B

12345678910111213141516171819202122232425262728
  1. import { getAddress } from "../address/index.js";
  2. import { keccak256, SigningKey } from "../crypto/index.js";
  3. import type { SignatureLike } from "../crypto/index.js";
  4. import type { BytesLike } from "../utils/index.js";
  5. /**
  6. * Returns the address for the %%key%%.
  7. *
  8. * The key may be any standard form of public key or a private key.
  9. */
  10. export function computeAddress(key: string | SigningKey): string {
  11. let pubkey: string;
  12. if (typeof(key) === "string") {
  13. pubkey = SigningKey.computePublicKey(key, false);
  14. } else {
  15. pubkey = key.publicKey;
  16. }
  17. return getAddress(keccak256("0x" + pubkey.substring(4)).substring(26));
  18. }
  19. /**
  20. * Returns the recovered address for the private key that was
  21. * used to sign %%digest%% that resulted in %%signature%%.
  22. */
  23. export function recoverAddress(digest: BytesLike, signature: SignatureLike): string {
  24. return computeAddress(SigningKey.recoverPublicKey(digest, signature));
  25. }