contract-address.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { keccak256 } from "../crypto/index.js";
  2. import { concat, dataSlice, getBigInt, getBytes, encodeRlp, assertArgument } from "../utils/index.js";
  3. import { getAddress } from "./address.js";
  4. // http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed
  5. /**
  6. * Returns the address that would result from a ``CREATE`` for %%tx%%.
  7. *
  8. * This can be used to compute the address a contract will be
  9. * deployed to by an EOA when sending a deployment transaction (i.e.
  10. * when the ``to`` address is ``null``).
  11. *
  12. * This can also be used to compute the address a contract will be
  13. * deployed to by a contract, by using the contract's address as the
  14. * ``to`` and the contract's nonce.
  15. *
  16. * @example
  17. * from = "0x8ba1f109551bD432803012645Ac136ddd64DBA72";
  18. * nonce = 5;
  19. *
  20. * getCreateAddress({ from, nonce });
  21. * //_result:
  22. */
  23. export function getCreateAddress(tx) {
  24. const from = getAddress(tx.from);
  25. const nonce = getBigInt(tx.nonce, "tx.nonce");
  26. let nonceHex = nonce.toString(16);
  27. if (nonceHex === "0") {
  28. nonceHex = "0x";
  29. }
  30. else if (nonceHex.length % 2) {
  31. nonceHex = "0x0" + nonceHex;
  32. }
  33. else {
  34. nonceHex = "0x" + nonceHex;
  35. }
  36. return getAddress(dataSlice(keccak256(encodeRlp([from, nonceHex])), 12));
  37. }
  38. /**
  39. * Returns the address that would result from a ``CREATE2`` operation
  40. * with the given %%from%%, %%salt%% and %%initCodeHash%%.
  41. *
  42. * To compute the %%initCodeHash%% from a contract's init code, use
  43. * the [[keccak256]] function.
  44. *
  45. * For a quick overview and example of ``CREATE2``, see [[link-ricmoo-wisps]].
  46. *
  47. * @example
  48. * // The address of the contract
  49. * from = "0x8ba1f109551bD432803012645Ac136ddd64DBA72"
  50. *
  51. * // The salt
  52. * salt = id("HelloWorld")
  53. *
  54. * // The hash of the initCode
  55. * initCode = "0x6394198df16000526103ff60206004601c335afa6040516060f3";
  56. * initCodeHash = keccak256(initCode)
  57. *
  58. * getCreate2Address(from, salt, initCodeHash)
  59. * //_result:
  60. */
  61. export function getCreate2Address(_from, _salt, _initCodeHash) {
  62. const from = getAddress(_from);
  63. const salt = getBytes(_salt, "salt");
  64. const initCodeHash = getBytes(_initCodeHash, "initCodeHash");
  65. assertArgument(salt.length === 32, "salt must be 32 bytes", "salt", _salt);
  66. assertArgument(initCodeHash.length === 32, "initCodeHash must be 32 bytes", "initCodeHash", _initCodeHash);
  67. return getAddress(dataSlice(keccak256(concat(["0xff", from, salt, initCodeHash])), 12));
  68. }
  69. //# sourceMappingURL=contract-address.js.map