abi-coder.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. /**
  2. * When sending values to or receiving values from a [[Contract]], the
  3. * data is generally encoded using the [ABI standard](link-solc-abi).
  4. *
  5. * The AbiCoder provides a utility to encode values to ABI data and
  6. * decode values from ABI data.
  7. *
  8. * Most of the time, developers should favour the [[Contract]] class,
  9. * which further abstracts a lot of the finer details of ABI data.
  10. *
  11. * @_section api/abi/abi-coder:ABI Encoding
  12. */
  13. // See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI
  14. import { assertArgumentCount, assertArgument } from "../utils/index.js";
  15. import { Reader, Writer } from "./coders/abstract-coder.js";
  16. import { AddressCoder } from "./coders/address.js";
  17. import { ArrayCoder } from "./coders/array.js";
  18. import { BooleanCoder } from "./coders/boolean.js";
  19. import { BytesCoder } from "./coders/bytes.js";
  20. import { FixedBytesCoder } from "./coders/fixed-bytes.js";
  21. import { NullCoder } from "./coders/null.js";
  22. import { NumberCoder } from "./coders/number.js";
  23. import { StringCoder } from "./coders/string.js";
  24. import { TupleCoder } from "./coders/tuple.js";
  25. import { ParamType } from "./fragments.js";
  26. import { getAddress } from "../address/index.js";
  27. import { getBytes, hexlify, makeError } from "../utils/index.js";
  28. // https://docs.soliditylang.org/en/v0.8.17/control-structures.html
  29. const PanicReasons = new Map();
  30. PanicReasons.set(0x00, "GENERIC_PANIC");
  31. PanicReasons.set(0x01, "ASSERT_FALSE");
  32. PanicReasons.set(0x11, "OVERFLOW");
  33. PanicReasons.set(0x12, "DIVIDE_BY_ZERO");
  34. PanicReasons.set(0x21, "ENUM_RANGE_ERROR");
  35. PanicReasons.set(0x22, "BAD_STORAGE_DATA");
  36. PanicReasons.set(0x31, "STACK_UNDERFLOW");
  37. PanicReasons.set(0x32, "ARRAY_RANGE_ERROR");
  38. PanicReasons.set(0x41, "OUT_OF_MEMORY");
  39. PanicReasons.set(0x51, "UNINITIALIZED_FUNCTION_CALL");
  40. const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/);
  41. const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/);
  42. let defaultCoder = null;
  43. let defaultMaxInflation = 1024;
  44. function getBuiltinCallException(action, tx, data, abiCoder) {
  45. let message = "missing revert data";
  46. let reason = null;
  47. const invocation = null;
  48. let revert = null;
  49. if (data) {
  50. message = "execution reverted";
  51. const bytes = getBytes(data);
  52. data = hexlify(data);
  53. if (bytes.length === 0) {
  54. message += " (no data present; likely require(false) occurred";
  55. reason = "require(false)";
  56. }
  57. else if (bytes.length % 32 !== 4) {
  58. message += " (could not decode reason; invalid data length)";
  59. }
  60. else if (hexlify(bytes.slice(0, 4)) === "0x08c379a0") {
  61. // Error(string)
  62. try {
  63. reason = abiCoder.decode(["string"], bytes.slice(4))[0];
  64. revert = {
  65. signature: "Error(string)",
  66. name: "Error",
  67. args: [reason]
  68. };
  69. message += `: ${JSON.stringify(reason)}`;
  70. }
  71. catch (error) {
  72. message += " (could not decode reason; invalid string data)";
  73. }
  74. }
  75. else if (hexlify(bytes.slice(0, 4)) === "0x4e487b71") {
  76. // Panic(uint256)
  77. try {
  78. const code = Number(abiCoder.decode(["uint256"], bytes.slice(4))[0]);
  79. revert = {
  80. signature: "Panic(uint256)",
  81. name: "Panic",
  82. args: [code]
  83. };
  84. reason = `Panic due to ${PanicReasons.get(code) || "UNKNOWN"}(${code})`;
  85. message += `: ${reason}`;
  86. }
  87. catch (error) {
  88. message += " (could not decode panic code)";
  89. }
  90. }
  91. else {
  92. message += " (unknown custom error)";
  93. }
  94. }
  95. const transaction = {
  96. to: (tx.to ? getAddress(tx.to) : null),
  97. data: (tx.data || "0x")
  98. };
  99. if (tx.from) {
  100. transaction.from = getAddress(tx.from);
  101. }
  102. return makeError(message, "CALL_EXCEPTION", {
  103. action, data, reason, transaction, invocation, revert
  104. });
  105. }
  106. /**
  107. * The **AbiCoder** is a low-level class responsible for encoding JavaScript
  108. * values into binary data and decoding binary data into JavaScript values.
  109. */
  110. export class AbiCoder {
  111. #getCoder(param) {
  112. if (param.isArray()) {
  113. return new ArrayCoder(this.#getCoder(param.arrayChildren), param.arrayLength, param.name);
  114. }
  115. if (param.isTuple()) {
  116. return new TupleCoder(param.components.map((c) => this.#getCoder(c)), param.name);
  117. }
  118. switch (param.baseType) {
  119. case "address":
  120. return new AddressCoder(param.name);
  121. case "bool":
  122. return new BooleanCoder(param.name);
  123. case "string":
  124. return new StringCoder(param.name);
  125. case "bytes":
  126. return new BytesCoder(param.name);
  127. case "":
  128. return new NullCoder(param.name);
  129. }
  130. // u?int[0-9]*
  131. let match = param.type.match(paramTypeNumber);
  132. if (match) {
  133. let size = parseInt(match[2] || "256");
  134. assertArgument(size !== 0 && size <= 256 && (size % 8) === 0, "invalid " + match[1] + " bit length", "param", param);
  135. return new NumberCoder(size / 8, (match[1] === "int"), param.name);
  136. }
  137. // bytes[0-9]+
  138. match = param.type.match(paramTypeBytes);
  139. if (match) {
  140. let size = parseInt(match[1]);
  141. assertArgument(size !== 0 && size <= 32, "invalid bytes length", "param", param);
  142. return new FixedBytesCoder(size, param.name);
  143. }
  144. assertArgument(false, "invalid type", "type", param.type);
  145. }
  146. /**
  147. * Get the default values for the given %%types%%.
  148. *
  149. * For example, a ``uint`` is by default ``0`` and ``bool``
  150. * is by default ``false``.
  151. */
  152. getDefaultValue(types) {
  153. const coders = types.map((type) => this.#getCoder(ParamType.from(type)));
  154. const coder = new TupleCoder(coders, "_");
  155. return coder.defaultValue();
  156. }
  157. /**
  158. * Encode the %%values%% as the %%types%% into ABI data.
  159. *
  160. * @returns DataHexstring
  161. */
  162. encode(types, values) {
  163. assertArgumentCount(values.length, types.length, "types/values length mismatch");
  164. const coders = types.map((type) => this.#getCoder(ParamType.from(type)));
  165. const coder = (new TupleCoder(coders, "_"));
  166. const writer = new Writer();
  167. coder.encode(writer, values);
  168. return writer.data;
  169. }
  170. /**
  171. * Decode the ABI %%data%% as the %%types%% into values.
  172. *
  173. * If %%loose%% decoding is enabled, then strict padding is
  174. * not enforced. Some older versions of Solidity incorrectly
  175. * padded event data emitted from ``external`` functions.
  176. */
  177. decode(types, data, loose) {
  178. const coders = types.map((type) => this.#getCoder(ParamType.from(type)));
  179. const coder = new TupleCoder(coders, "_");
  180. return coder.decode(new Reader(data, loose, defaultMaxInflation));
  181. }
  182. static _setDefaultMaxInflation(value) {
  183. assertArgument(typeof (value) === "number" && Number.isInteger(value), "invalid defaultMaxInflation factor", "value", value);
  184. defaultMaxInflation = value;
  185. }
  186. /**
  187. * Returns the shared singleton instance of a default [[AbiCoder]].
  188. *
  189. * On the first call, the instance is created internally.
  190. */
  191. static defaultAbiCoder() {
  192. if (defaultCoder == null) {
  193. defaultCoder = new AbiCoder();
  194. }
  195. return defaultCoder;
  196. }
  197. /**
  198. * Returns an ethers-compatible [[CallExceptionError]] Error for the given
  199. * result %%data%% for the [[CallExceptionAction]] %%action%% against
  200. * the Transaction %%tx%%.
  201. */
  202. static getBuiltinCallException(action, tx, data) {
  203. return getBuiltinCallException(action, tx, data, AbiCoder.defaultAbiCoder());
  204. }
  205. }
  206. //# sourceMappingURL=abi-coder.js.map