interface.ts 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  1. /**
  2. * The Interface class is a low-level class that accepts an
  3. * ABI and provides all the necessary functionality to encode
  4. * and decode paramaters to and results from methods, events
  5. * and errors.
  6. *
  7. * It also provides several convenience methods to automatically
  8. * search and find matching transactions and events to parse them.
  9. *
  10. * @_subsection api/abi:Interfaces [interfaces]
  11. */
  12. import { keccak256 } from "../crypto/index.js"
  13. import { id } from "../hash/index.js"
  14. import {
  15. concat, dataSlice, getBigInt, getBytes, getBytesCopy,
  16. hexlify, zeroPadBytes, zeroPadValue, isHexString, defineProperties,
  17. assertArgument, toBeHex, assert
  18. } from "../utils/index.js";
  19. import { AbiCoder } from "./abi-coder.js";
  20. import { checkResultErrors, Result } from "./coders/abstract-coder.js";
  21. import {
  22. ConstructorFragment, ErrorFragment, EventFragment, FallbackFragment,
  23. Fragment, FunctionFragment, ParamType
  24. } from "./fragments.js";
  25. import { Typed } from "./typed.js";
  26. import type { BigNumberish, BytesLike, CallExceptionError, CallExceptionTransaction } from "../utils/index.js";
  27. import type { JsonFragment } from "./fragments.js";
  28. export { checkResultErrors, Result };
  29. /**
  30. * When using the [[Interface-parseLog]] to automatically match a Log to its event
  31. * for parsing, a **LogDescription** is returned.
  32. */
  33. export class LogDescription {
  34. /**
  35. * The matching fragment for the ``topic0``.
  36. */
  37. readonly fragment!: EventFragment;
  38. /**
  39. * The name of the Event.
  40. */
  41. readonly name!: string;
  42. /**
  43. * The full Event signature.
  44. */
  45. readonly signature!: string;
  46. /**
  47. * The topic hash for the Event.
  48. */
  49. readonly topic!: string;
  50. /**
  51. * The arguments passed into the Event with ``emit``.
  52. */
  53. readonly args!: Result
  54. /**
  55. * @_ignore:
  56. */
  57. constructor(fragment: EventFragment, topic: string, args: Result) {
  58. const name = fragment.name, signature = fragment.format();
  59. defineProperties<LogDescription>(this, {
  60. fragment, name, signature, topic, args
  61. });
  62. }
  63. }
  64. /**
  65. * When using the [[Interface-parseTransaction]] to automatically match
  66. * a transaction data to its function for parsing,
  67. * a **TransactionDescription** is returned.
  68. */
  69. export class TransactionDescription {
  70. /**
  71. * The matching fragment from the transaction ``data``.
  72. */
  73. readonly fragment!: FunctionFragment;
  74. /**
  75. * The name of the Function from the transaction ``data``.
  76. */
  77. readonly name!: string;
  78. /**
  79. * The arguments passed to the Function from the transaction ``data``.
  80. */
  81. readonly args!: Result;
  82. /**
  83. * The full Function signature from the transaction ``data``.
  84. */
  85. readonly signature!: string;
  86. /**
  87. * The selector for the Function from the transaction ``data``.
  88. */
  89. readonly selector!: string;
  90. /**
  91. * The ``value`` (in wei) from the transaction.
  92. */
  93. readonly value!: bigint;
  94. /**
  95. * @_ignore:
  96. */
  97. constructor(fragment: FunctionFragment, selector: string, args: Result, value: bigint) {
  98. const name = fragment.name, signature = fragment.format();
  99. defineProperties<TransactionDescription>(this, {
  100. fragment, name, args, signature, selector, value
  101. });
  102. }
  103. }
  104. /**
  105. * When using the [[Interface-parseError]] to automatically match an
  106. * error for a call result for parsing, an **ErrorDescription** is returned.
  107. */
  108. export class ErrorDescription {
  109. /**
  110. * The matching fragment.
  111. */
  112. readonly fragment!: ErrorFragment;
  113. /**
  114. * The name of the Error.
  115. */
  116. readonly name!: string;
  117. /**
  118. * The arguments passed to the Error with ``revert``.
  119. */
  120. readonly args!: Result;
  121. /**
  122. * The full Error signature.
  123. */
  124. readonly signature!: string;
  125. /**
  126. * The selector for the Error.
  127. */
  128. readonly selector!: string;
  129. /**
  130. * @_ignore:
  131. */
  132. constructor(fragment: ErrorFragment, selector: string, args: Result) {
  133. const name = fragment.name, signature = fragment.format();
  134. defineProperties<ErrorDescription>(this, {
  135. fragment, name, args, signature, selector
  136. });
  137. }
  138. }
  139. /**
  140. * An **Indexed** is used as a value when a value that does not
  141. * fit within a topic (i.e. not a fixed-length, 32-byte type). It
  142. * is the ``keccak256`` of the value, and used for types such as
  143. * arrays, tuples, bytes and strings.
  144. */
  145. export class Indexed {
  146. /**
  147. * The ``keccak256`` of the value logged.
  148. */
  149. readonly hash!: null | string;
  150. /**
  151. * @_ignore:
  152. */
  153. readonly _isIndexed!: boolean;
  154. /**
  155. * Returns ``true`` if %%value%% is an **Indexed**.
  156. *
  157. * This provides a Type Guard for property access.
  158. */
  159. static isIndexed(value: any): value is Indexed {
  160. return !!(value && value._isIndexed);
  161. }
  162. /**
  163. * @_ignore:
  164. */
  165. constructor(hash: null | string) {
  166. defineProperties<Indexed>(this, { hash, _isIndexed: true })
  167. }
  168. }
  169. type ErrorInfo = {
  170. signature: string,
  171. inputs: Array<string>,
  172. name: string,
  173. reason: (...args: Array<any>) => string;
  174. };
  175. // https://docs.soliditylang.org/en/v0.8.13/control-structures.html?highlight=panic#panic-via-assert-and-error-via-require
  176. const PanicReasons: Record<string, string> = {
  177. "0": "generic panic",
  178. "1": "assert(false)",
  179. "17": "arithmetic overflow",
  180. "18": "division or modulo by zero",
  181. "33": "enum overflow",
  182. "34": "invalid encoded storage byte array accessed",
  183. "49": "out-of-bounds array access; popping on an empty array",
  184. "50": "out-of-bounds access of an array or bytesN",
  185. "65": "out of memory",
  186. "81": "uninitialized function",
  187. }
  188. const BuiltinErrors: Record<string, ErrorInfo> = {
  189. "0x08c379a0": {
  190. signature: "Error(string)",
  191. name: "Error",
  192. inputs: [ "string" ],
  193. reason: (message: string) => {
  194. return `reverted with reason string ${ JSON.stringify(message) }`;
  195. }
  196. },
  197. "0x4e487b71": {
  198. signature: "Panic(uint256)",
  199. name: "Panic",
  200. inputs: [ "uint256" ],
  201. reason: (code: bigint) => {
  202. let reason = "unknown panic code";
  203. if (code >= 0 && code <= 0xff && PanicReasons[code.toString()]) {
  204. reason = PanicReasons[code.toString()];
  205. }
  206. return `reverted with panic code 0x${ code.toString(16) } (${ reason })`;
  207. }
  208. }
  209. }
  210. /*
  211. function wrapAccessError(property: string, error: Error): Error {
  212. const wrap = new Error(`deferred error during ABI decoding triggered accessing ${ property }`);
  213. (<any>wrap).error = error;
  214. return wrap;
  215. }
  216. */
  217. /*
  218. function checkNames(fragment: Fragment, type: "input" | "output", params: Array<ParamType>): void {
  219. params.reduce((accum, param) => {
  220. if (param.name) {
  221. if (accum[param.name]) {
  222. logger.throwArgumentError(`duplicate ${ type } parameter ${ JSON.stringify(param.name) } in ${ fragment.format("full") }`, "fragment", fragment);
  223. }
  224. accum[param.name] = true;
  225. }
  226. return accum;
  227. }, <{ [ name: string ]: boolean }>{ });
  228. }
  229. */
  230. /**
  231. * An **InterfaceAbi** may be any supported ABI format.
  232. *
  233. * A string is expected to be a JSON string, which will be parsed
  234. * using ``JSON.parse``. This means that the value **must** be a valid
  235. * JSON string, with no stray commas, etc.
  236. *
  237. * An array may contain any combination of:
  238. * - Human-Readable fragments
  239. * - Parsed JSON fragment
  240. * - [[Fragment]] instances
  241. *
  242. * A **Human-Readable Fragment** is a string which resembles a Solidity
  243. * signature and is introduced in [this blog entry](link-ricmoo-humanreadableabi).
  244. * For example, ``function balanceOf(address) view returns (uint)``.
  245. *
  246. * A **Parsed JSON Fragment** is a JavaScript Object desribed in the
  247. * [Solidity documentation](link-solc-jsonabi).
  248. */
  249. export type InterfaceAbi = string | ReadonlyArray<Fragment | JsonFragment | string>;
  250. /**
  251. * An Interface abstracts many of the low-level details for
  252. * encoding and decoding the data on the blockchain.
  253. *
  254. * An ABI provides information on how to encode data to send to
  255. * a Contract, how to decode the results and events and how to
  256. * interpret revert errors.
  257. *
  258. * The ABI can be specified by [any supported format](InterfaceAbi).
  259. */
  260. export class Interface {
  261. /**
  262. * All the Contract ABI members (i.e. methods, events, errors, etc).
  263. */
  264. readonly fragments!: ReadonlyArray<Fragment>;
  265. /**
  266. * The Contract constructor.
  267. */
  268. readonly deploy!: ConstructorFragment;
  269. /**
  270. * The Fallback method, if any.
  271. */
  272. readonly fallback!: null | FallbackFragment;
  273. /**
  274. * If receiving ether is supported.
  275. */
  276. readonly receive!: boolean;
  277. #errors: Map<string, ErrorFragment>;
  278. #events: Map<string, EventFragment>;
  279. #functions: Map<string, FunctionFragment>;
  280. // #structs: Map<string, StructFragment>;
  281. #abiCoder: AbiCoder;
  282. /**
  283. * Create a new Interface for the %%fragments%%.
  284. */
  285. constructor(fragments: InterfaceAbi) {
  286. let abi: ReadonlyArray<Fragment | JsonFragment | string> = [ ];
  287. if (typeof(fragments) === "string") {
  288. abi = JSON.parse(fragments);
  289. } else {
  290. abi = fragments;
  291. }
  292. this.#functions = new Map();
  293. this.#errors = new Map();
  294. this.#events = new Map();
  295. // this.#structs = new Map();
  296. const frags: Array<Fragment> = [ ];
  297. for (const a of abi) {
  298. try {
  299. frags.push(Fragment.from(a));
  300. } catch (error: any) {
  301. console.log(`[Warning] Invalid Fragment ${ JSON.stringify(a) }:`, error.message);
  302. }
  303. }
  304. defineProperties<Interface>(this, {
  305. fragments: Object.freeze(frags)
  306. });
  307. let fallback: null | FallbackFragment = null;
  308. let receive = false;
  309. this.#abiCoder = this.getAbiCoder();
  310. // Add all fragments by their signature
  311. this.fragments.forEach((fragment, index) => {
  312. let bucket: Map<string, Fragment>;
  313. switch (fragment.type) {
  314. case "constructor":
  315. if (this.deploy) {
  316. console.log("duplicate definition - constructor");
  317. return;
  318. }
  319. //checkNames(fragment, "input", fragment.inputs);
  320. defineProperties<Interface>(this, { deploy: <ConstructorFragment>fragment });
  321. return;
  322. case "fallback":
  323. if (fragment.inputs.length === 0) {
  324. receive = true;
  325. } else {
  326. assertArgument(!fallback || (<FallbackFragment>fragment).payable !== fallback.payable,
  327. "conflicting fallback fragments", `fragments[${ index }]`, fragment);
  328. fallback = <FallbackFragment>fragment;
  329. receive = fallback.payable;
  330. }
  331. return;
  332. case "function":
  333. //checkNames(fragment, "input", fragment.inputs);
  334. //checkNames(fragment, "output", (<FunctionFragment>fragment).outputs);
  335. bucket = this.#functions;
  336. break;
  337. case "event":
  338. //checkNames(fragment, "input", fragment.inputs);
  339. bucket = this.#events;
  340. break;
  341. case "error":
  342. bucket = this.#errors;
  343. break;
  344. default:
  345. return;
  346. }
  347. // Two identical entries; ignore it
  348. const signature = fragment.format();
  349. if (bucket.has(signature)) { return; }
  350. bucket.set(signature, fragment);
  351. });
  352. // If we do not have a constructor add a default
  353. if (!this.deploy) {
  354. defineProperties<Interface>(this, {
  355. deploy: ConstructorFragment.from("constructor()")
  356. });
  357. }
  358. defineProperties<Interface>(this, { fallback, receive });
  359. }
  360. /**
  361. * Returns the entire Human-Readable ABI, as an array of
  362. * signatures, optionally as %%minimal%% strings, which
  363. * removes parameter names and unneceesary spaces.
  364. */
  365. format(minimal?: boolean): Array<string> {
  366. const format = (minimal ? "minimal": "full");
  367. const abi = this.fragments.map((f) => f.format(format));
  368. return abi;
  369. }
  370. /**
  371. * Return the JSON-encoded ABI. This is the format Solidiy
  372. * returns.
  373. */
  374. formatJson(): string {
  375. const abi = this.fragments.map((f) => f.format("json"));
  376. // We need to re-bundle the JSON fragments a bit
  377. return JSON.stringify(abi.map((j) => JSON.parse(j)));
  378. }
  379. /**
  380. * The ABI coder that will be used to encode and decode binary
  381. * data.
  382. */
  383. getAbiCoder(): AbiCoder {
  384. return AbiCoder.defaultAbiCoder();
  385. }
  386. // Find a function definition by any means necessary (unless it is ambiguous)
  387. #getFunction(key: string, values: null | Array<any | Typed>, forceUnique: boolean): null | FunctionFragment {
  388. // Selector
  389. if (isHexString(key)) {
  390. const selector = key.toLowerCase();
  391. for (const fragment of this.#functions.values()) {
  392. if (selector === fragment.selector) { return fragment; }
  393. }
  394. return null;
  395. }
  396. // It is a bare name, look up the function (will return null if ambiguous)
  397. if (key.indexOf("(") === -1) {
  398. const matching: Array<FunctionFragment> = [ ];
  399. for (const [ name, fragment ] of this.#functions) {
  400. if (name.split("("/* fix:) */)[0] === key) { matching.push(fragment); }
  401. }
  402. if (values) {
  403. const lastValue = (values.length > 0) ? values[values.length - 1]: null;
  404. let valueLength = values.length;
  405. let allowOptions = true;
  406. if (Typed.isTyped(lastValue) && lastValue.type === "overrides") {
  407. allowOptions = false;
  408. valueLength--;
  409. }
  410. // Remove all matches that don't have a compatible length. The args
  411. // may contain an overrides, so the match may have n or n - 1 parameters
  412. for (let i = matching.length - 1; i >= 0; i--) {
  413. const inputs = matching[i].inputs.length;
  414. if (inputs !== valueLength && (!allowOptions || inputs !== valueLength - 1)) {
  415. matching.splice(i, 1);
  416. }
  417. }
  418. // Remove all matches that don't match the Typed signature
  419. for (let i = matching.length - 1; i >= 0; i--) {
  420. const inputs = matching[i].inputs;
  421. for (let j = 0; j < values.length; j++) {
  422. // Not a typed value
  423. if (!Typed.isTyped(values[j])) { continue; }
  424. // We are past the inputs
  425. if (j >= inputs.length) {
  426. if (values[j].type === "overrides") { continue; }
  427. matching.splice(i, 1);
  428. break;
  429. }
  430. // Make sure the value type matches the input type
  431. if (values[j].type !== inputs[j].baseType) {
  432. matching.splice(i, 1);
  433. break;
  434. }
  435. }
  436. }
  437. }
  438. // We found a single matching signature with an overrides, but the
  439. // last value is something that cannot possibly be an options
  440. if (matching.length === 1 && values && values.length !== matching[0].inputs.length) {
  441. const lastArg = values[values.length - 1];
  442. if (lastArg == null || Array.isArray(lastArg) || typeof(lastArg) !== "object") {
  443. matching.splice(0, 1);
  444. }
  445. }
  446. if (matching.length === 0) { return null; }
  447. if (matching.length > 1 && forceUnique) {
  448. const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", ");
  449. assertArgument(false, `ambiguous function description (i.e. matches ${ matchStr })`, "key", key);
  450. }
  451. return matching[0];
  452. }
  453. // Normalize the signature and lookup the function
  454. const result = this.#functions.get(FunctionFragment.from(key).format());
  455. if (result) { return result; }
  456. return null;
  457. }
  458. /**
  459. * Get the function name for %%key%%, which may be a function selector,
  460. * function name or function signature that belongs to the ABI.
  461. */
  462. getFunctionName(key: string): string {
  463. const fragment = this.#getFunction(key, null, false);
  464. assertArgument(fragment, "no matching function", "key", key);
  465. return fragment.name;
  466. }
  467. /**
  468. * Returns true if %%key%% (a function selector, function name or
  469. * function signature) is present in the ABI.
  470. *
  471. * In the case of a function name, the name may be ambiguous, so
  472. * accessing the [[FunctionFragment]] may require refinement.
  473. */
  474. hasFunction(key: string): boolean {
  475. return !!this.#getFunction(key, null, false);
  476. }
  477. /**
  478. * Get the [[FunctionFragment]] for %%key%%, which may be a function
  479. * selector, function name or function signature that belongs to the ABI.
  480. *
  481. * If %%values%% is provided, it will use the Typed API to handle
  482. * ambiguous cases where multiple functions match by name.
  483. *
  484. * If the %%key%% and %%values%% do not refine to a single function in
  485. * the ABI, this will throw.
  486. */
  487. getFunction(key: string, values?: Array<any | Typed>): null | FunctionFragment {
  488. return this.#getFunction(key, values || null, true);
  489. }
  490. /**
  491. * Iterate over all functions, calling %%callback%%, sorted by their name.
  492. */
  493. forEachFunction(callback: (func: FunctionFragment, index: number) => void): void {
  494. const names = Array.from(this.#functions.keys());
  495. names.sort((a, b) => a.localeCompare(b));
  496. for (let i = 0; i < names.length; i++) {
  497. const name = names[i];
  498. callback(<FunctionFragment>(this.#functions.get(name)), i);
  499. }
  500. }
  501. // Find an event definition by any means necessary (unless it is ambiguous)
  502. #getEvent(key: string, values: null | Array<null | any | Typed>, forceUnique: boolean): null | EventFragment {
  503. // EventTopic
  504. if (isHexString(key)) {
  505. const eventTopic = key.toLowerCase();
  506. for (const fragment of this.#events.values()) {
  507. if (eventTopic === fragment.topicHash) { return fragment; }
  508. }
  509. return null;
  510. }
  511. // It is a bare name, look up the function (will return null if ambiguous)
  512. if (key.indexOf("(") === -1) {
  513. const matching: Array<EventFragment> = [ ];
  514. for (const [ name, fragment ] of this.#events) {
  515. if (name.split("("/* fix:) */)[0] === key) { matching.push(fragment); }
  516. }
  517. if (values) {
  518. // Remove all matches that don't have a compatible length.
  519. for (let i = matching.length - 1; i >= 0; i--) {
  520. if (matching[i].inputs.length < values.length) {
  521. matching.splice(i, 1);
  522. }
  523. }
  524. // Remove all matches that don't match the Typed signature
  525. for (let i = matching.length - 1; i >= 0; i--) {
  526. const inputs = matching[i].inputs;
  527. for (let j = 0; j < values.length; j++) {
  528. // Not a typed value
  529. if (!Typed.isTyped(values[j])) { continue; }
  530. // Make sure the value type matches the input type
  531. if (values[j].type !== inputs[j].baseType) {
  532. matching.splice(i, 1);
  533. break;
  534. }
  535. }
  536. }
  537. }
  538. if (matching.length === 0) { return null; }
  539. if (matching.length > 1 && forceUnique) {
  540. const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", ");
  541. assertArgument(false, `ambiguous event description (i.e. matches ${ matchStr })`, "key", key);
  542. }
  543. return matching[0];
  544. }
  545. // Normalize the signature and lookup the function
  546. const result = this.#events.get(EventFragment.from(key).format());
  547. if (result) { return result; }
  548. return null;
  549. }
  550. /**
  551. * Get the event name for %%key%%, which may be a topic hash,
  552. * event name or event signature that belongs to the ABI.
  553. */
  554. getEventName(key: string): string {
  555. const fragment = this.#getEvent(key, null, false);
  556. assertArgument(fragment, "no matching event", "key", key);
  557. return fragment.name;
  558. }
  559. /**
  560. * Returns true if %%key%% (an event topic hash, event name or
  561. * event signature) is present in the ABI.
  562. *
  563. * In the case of an event name, the name may be ambiguous, so
  564. * accessing the [[EventFragment]] may require refinement.
  565. */
  566. hasEvent(key: string): boolean {
  567. return !!this.#getEvent(key, null, false);
  568. }
  569. /**
  570. * Get the [[EventFragment]] for %%key%%, which may be a topic hash,
  571. * event name or event signature that belongs to the ABI.
  572. *
  573. * If %%values%% is provided, it will use the Typed API to handle
  574. * ambiguous cases where multiple events match by name.
  575. *
  576. * If the %%key%% and %%values%% do not refine to a single event in
  577. * the ABI, this will throw.
  578. */
  579. getEvent(key: string, values?: Array<any | Typed>): null | EventFragment {
  580. return this.#getEvent(key, values || null, true)
  581. }
  582. /**
  583. * Iterate over all events, calling %%callback%%, sorted by their name.
  584. */
  585. forEachEvent(callback: (func: EventFragment, index: number) => void): void {
  586. const names = Array.from(this.#events.keys());
  587. names.sort((a, b) => a.localeCompare(b));
  588. for (let i = 0; i < names.length; i++) {
  589. const name = names[i];
  590. callback(<EventFragment>(this.#events.get(name)), i);
  591. }
  592. }
  593. /**
  594. * Get the [[ErrorFragment]] for %%key%%, which may be an error
  595. * selector, error name or error signature that belongs to the ABI.
  596. *
  597. * If %%values%% is provided, it will use the Typed API to handle
  598. * ambiguous cases where multiple errors match by name.
  599. *
  600. * If the %%key%% and %%values%% do not refine to a single error in
  601. * the ABI, this will throw.
  602. */
  603. getError(key: string, values?: Array<any | Typed>): null | ErrorFragment {
  604. if (isHexString(key)) {
  605. const selector = key.toLowerCase();
  606. if (BuiltinErrors[selector]) {
  607. return ErrorFragment.from(BuiltinErrors[selector].signature);
  608. }
  609. for (const fragment of this.#errors.values()) {
  610. if (selector === fragment.selector) { return fragment; }
  611. }
  612. return null;
  613. }
  614. // It is a bare name, look up the function (will return null if ambiguous)
  615. if (key.indexOf("(") === -1) {
  616. const matching: Array<ErrorFragment> = [ ];
  617. for (const [ name, fragment ] of this.#errors) {
  618. if (name.split("("/* fix:) */)[0] === key) { matching.push(fragment); }
  619. }
  620. if (matching.length === 0) {
  621. if (key === "Error") { return ErrorFragment.from("error Error(string)"); }
  622. if (key === "Panic") { return ErrorFragment.from("error Panic(uint256)"); }
  623. return null;
  624. } else if (matching.length > 1) {
  625. const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", ");
  626. assertArgument(false, `ambiguous error description (i.e. ${ matchStr })`, "name", key);
  627. }
  628. return matching[0];
  629. }
  630. // Normalize the signature and lookup the function
  631. key = ErrorFragment.from(key).format()
  632. if (key === "Error(string)") { return ErrorFragment.from("error Error(string)"); }
  633. if (key === "Panic(uint256)") { return ErrorFragment.from("error Panic(uint256)"); }
  634. const result = this.#errors.get(key);
  635. if (result) { return result; }
  636. return null;
  637. }
  638. /**
  639. * Iterate over all errors, calling %%callback%%, sorted by their name.
  640. */
  641. forEachError(callback: (func: ErrorFragment, index: number) => void): void {
  642. const names = Array.from(this.#errors.keys());
  643. names.sort((a, b) => a.localeCompare(b));
  644. for (let i = 0; i < names.length; i++) {
  645. const name = names[i];
  646. callback(<ErrorFragment>(this.#errors.get(name)), i);
  647. }
  648. }
  649. // Get the 4-byte selector used by Solidity to identify a function
  650. /*
  651. getSelector(fragment: ErrorFragment | FunctionFragment): string {
  652. if (typeof(fragment) === "string") {
  653. const matches: Array<Fragment> = [ ];
  654. try { matches.push(this.getFunction(fragment)); } catch (error) { }
  655. try { matches.push(this.getError(<string>fragment)); } catch (_) { }
  656. if (matches.length === 0) {
  657. logger.throwArgumentError("unknown fragment", "key", fragment);
  658. } else if (matches.length > 1) {
  659. logger.throwArgumentError("ambiguous fragment matches function and error", "key", fragment);
  660. }
  661. fragment = matches[0];
  662. }
  663. return dataSlice(id(fragment.format()), 0, 4);
  664. }
  665. */
  666. // Get the 32-byte topic hash used by Solidity to identify an event
  667. /*
  668. getEventTopic(fragment: EventFragment): string {
  669. //if (typeof(fragment) === "string") { fragment = this.getEvent(eventFragment); }
  670. return id(fragment.format());
  671. }
  672. */
  673. _decodeParams(params: ReadonlyArray<ParamType>, data: BytesLike): Result {
  674. return this.#abiCoder.decode(params, data)
  675. }
  676. _encodeParams(params: ReadonlyArray<ParamType>, values: ReadonlyArray<any>): string {
  677. return this.#abiCoder.encode(params, values)
  678. }
  679. /**
  680. * Encodes a ``tx.data`` object for deploying the Contract with
  681. * the %%values%% as the constructor arguments.
  682. */
  683. encodeDeploy(values?: ReadonlyArray<any>): string {
  684. return this._encodeParams(this.deploy.inputs, values || [ ]);
  685. }
  686. /**
  687. * Decodes the result %%data%% (e.g. from an ``eth_call``) for the
  688. * specified error (see [[getError]] for valid values for
  689. * %%key%%).
  690. *
  691. * Most developers should prefer the [[parseCallResult]] method instead,
  692. * which will automatically detect a ``CALL_EXCEPTION`` and throw the
  693. * corresponding error.
  694. */
  695. decodeErrorResult(fragment: ErrorFragment | string, data: BytesLike): Result {
  696. if (typeof(fragment) === "string") {
  697. const f = this.getError(fragment);
  698. assertArgument(f, "unknown error", "fragment", fragment);
  699. fragment = f;
  700. }
  701. assertArgument(dataSlice(data, 0, 4) === fragment.selector,
  702. `data signature does not match error ${ fragment.name }.`, "data", data);
  703. return this._decodeParams(fragment.inputs, dataSlice(data, 4));
  704. }
  705. /**
  706. * Encodes the transaction revert data for a call result that
  707. * reverted from the the Contract with the sepcified %%error%%
  708. * (see [[getError]] for valid values for %%fragment%%) with the %%values%%.
  709. *
  710. * This is generally not used by most developers, unless trying to mock
  711. * a result from a Contract.
  712. */
  713. encodeErrorResult(fragment: ErrorFragment | string, values?: ReadonlyArray<any>): string {
  714. if (typeof(fragment) === "string") {
  715. const f = this.getError(fragment);
  716. assertArgument(f, "unknown error", "fragment", fragment);
  717. fragment = f;
  718. }
  719. return concat([
  720. fragment.selector,
  721. this._encodeParams(fragment.inputs, values || [ ])
  722. ]);
  723. }
  724. /**
  725. * Decodes the %%data%% from a transaction ``tx.data`` for
  726. * the function specified (see [[getFunction]] for valid values
  727. * for %%fragment%%).
  728. *
  729. * Most developers should prefer the [[parseTransaction]] method
  730. * instead, which will automatically detect the fragment.
  731. */
  732. decodeFunctionData(fragment: FunctionFragment | string, data: BytesLike): Result {
  733. if (typeof(fragment) === "string") {
  734. const f = this.getFunction(fragment);
  735. assertArgument(f, "unknown function", "fragment", fragment);
  736. fragment = f;
  737. }
  738. assertArgument(dataSlice(data, 0, 4) === fragment.selector,
  739. `data signature does not match function ${ fragment.name }.`, "data", data);
  740. return this._decodeParams(fragment.inputs, dataSlice(data, 4));
  741. }
  742. /**
  743. * Encodes the ``tx.data`` for a transaction that calls the function
  744. * specified (see [[getFunction]] for valid values for %%fragment%%) with
  745. * the %%values%%.
  746. */
  747. encodeFunctionData(fragment: FunctionFragment | string, values?: ReadonlyArray<any>): string {
  748. if (typeof(fragment) === "string") {
  749. const f = this.getFunction(fragment);
  750. assertArgument(f, "unknown function", "fragment", fragment);
  751. fragment = f;
  752. }
  753. return concat([
  754. fragment.selector,
  755. this._encodeParams(fragment.inputs, values || [ ])
  756. ]);
  757. }
  758. /**
  759. * Decodes the result %%data%% (e.g. from an ``eth_call``) for the
  760. * specified function (see [[getFunction]] for valid values for
  761. * %%key%%).
  762. *
  763. * Most developers should prefer the [[parseCallResult]] method instead,
  764. * which will automatically detect a ``CALL_EXCEPTION`` and throw the
  765. * corresponding error.
  766. */
  767. decodeFunctionResult(fragment: FunctionFragment | string, data: BytesLike): Result {
  768. if (typeof(fragment) === "string") {
  769. const f = this.getFunction(fragment);
  770. assertArgument(f, "unknown function", "fragment", fragment);
  771. fragment = f;
  772. }
  773. let message = "invalid length for result data";
  774. const bytes = getBytesCopy(data);
  775. if ((bytes.length % 32) === 0) {
  776. try {
  777. return this.#abiCoder.decode(fragment.outputs, bytes);
  778. } catch (error) {
  779. message = "could not decode result data";
  780. }
  781. }
  782. // Call returned data with no error, but the data is junk
  783. assert(false, message, "BAD_DATA", {
  784. value: hexlify(bytes),
  785. info: { method: fragment.name, signature: fragment.format() }
  786. });
  787. }
  788. makeError(_data: BytesLike, tx: CallExceptionTransaction): CallExceptionError {
  789. const data = getBytes(_data, "data");
  790. const error = AbiCoder.getBuiltinCallException("call", tx, data);
  791. // Not a built-in error; try finding a custom error
  792. const customPrefix = "execution reverted (unknown custom error)";
  793. if (error.message.startsWith(customPrefix)) {
  794. const selector = hexlify(data.slice(0, 4));
  795. const ef = this.getError(selector);
  796. if (ef) {
  797. try {
  798. const args = this.#abiCoder.decode(ef.inputs, data.slice(4));
  799. error.revert = {
  800. name: ef.name, signature: ef.format(), args
  801. };
  802. error.reason = error.revert.signature;
  803. error.message = `execution reverted: ${ error.reason }`
  804. } catch (e) {
  805. error.message = `execution reverted (coult not decode custom error)`
  806. }
  807. }
  808. }
  809. // Add the invocation, if available
  810. const parsed = this.parseTransaction(tx);
  811. if (parsed) {
  812. error.invocation = {
  813. method: parsed.name,
  814. signature: parsed.signature,
  815. args: parsed.args
  816. };
  817. }
  818. return error;
  819. }
  820. /**
  821. * Encodes the result data (e.g. from an ``eth_call``) for the
  822. * specified function (see [[getFunction]] for valid values
  823. * for %%fragment%%) with %%values%%.
  824. *
  825. * This is generally not used by most developers, unless trying to mock
  826. * a result from a Contract.
  827. */
  828. encodeFunctionResult(fragment: FunctionFragment | string, values?: ReadonlyArray<any>): string {
  829. if (typeof(fragment) === "string") {
  830. const f = this.getFunction(fragment);
  831. assertArgument(f, "unknown function", "fragment", fragment);
  832. fragment = f;
  833. }
  834. return hexlify(this.#abiCoder.encode(fragment.outputs, values || [ ]));
  835. }
  836. /*
  837. spelunk(inputs: Array<ParamType>, values: ReadonlyArray<any>, processfunc: (type: string, value: any) => Promise<any>): Promise<Array<any>> {
  838. const promises: Array<Promise<>> = [ ];
  839. const process = function(type: ParamType, value: any): any {
  840. if (type.baseType === "array") {
  841. return descend(type.child
  842. }
  843. if (type. === "address") {
  844. }
  845. };
  846. const descend = function (inputs: Array<ParamType>, values: ReadonlyArray<any>) {
  847. if (inputs.length !== values.length) { throw new Error("length mismatch"); }
  848. };
  849. const result: Array<any> = [ ];
  850. values.forEach((value, index) => {
  851. if (value == null) {
  852. topics.push(null);
  853. } else if (param.baseType === "array" || param.baseType === "tuple") {
  854. logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value);
  855. } else if (Array.isArray(value)) {
  856. topics.push(value.map((value) => encodeTopic(param, value)));
  857. } else {
  858. topics.push(encodeTopic(param, value));
  859. }
  860. });
  861. }
  862. */
  863. // Create the filter for the event with search criteria (e.g. for eth_filterLog)
  864. encodeFilterTopics(fragment: EventFragment | string, values: ReadonlyArray<any>): Array<null | string | Array<string>> {
  865. if (typeof(fragment) === "string") {
  866. const f = this.getEvent(fragment);
  867. assertArgument(f, "unknown event", "eventFragment", fragment);
  868. fragment = f;
  869. }
  870. assert(values.length <= fragment.inputs.length, `too many arguments for ${ fragment.format() }`,
  871. "UNEXPECTED_ARGUMENT", { count: values.length, expectedCount: fragment.inputs.length })
  872. const topics: Array<null | string | Array<string>> = [];
  873. if (!fragment.anonymous) { topics.push(fragment.topicHash); }
  874. // @TODO: Use the coders for this; to properly support tuples, etc.
  875. const encodeTopic = (param: ParamType, value: any): string => {
  876. if (param.type === "string") {
  877. return id(value);
  878. } else if (param.type === "bytes") {
  879. return keccak256(hexlify(value));
  880. }
  881. if (param.type === "bool" && typeof(value) === "boolean") {
  882. value = (value ? "0x01": "0x00");
  883. } else if (param.type.match(/^u?int/)) {
  884. value = toBeHex(value); // @TODO: Should this toTwos??
  885. } else if (param.type.match(/^bytes/)) {
  886. value = zeroPadBytes(value, 32);
  887. } else if (param.type === "address") {
  888. // Check addresses are valid
  889. this.#abiCoder.encode( [ "address" ], [ value ]);
  890. }
  891. return zeroPadValue(hexlify(value), 32);
  892. };
  893. values.forEach((value, index) => {
  894. const param = (<EventFragment>fragment).inputs[index];
  895. if (!param.indexed) {
  896. assertArgument(value == null,
  897. "cannot filter non-indexed parameters; must be null", ("contract." + param.name), value);
  898. return;
  899. }
  900. if (value == null) {
  901. topics.push(null);
  902. } else if (param.baseType === "array" || param.baseType === "tuple") {
  903. assertArgument(false, "filtering with tuples or arrays not supported", ("contract." + param.name), value);
  904. } else if (Array.isArray(value)) {
  905. topics.push(value.map((value) => encodeTopic(param, value)));
  906. } else {
  907. topics.push(encodeTopic(param, value));
  908. }
  909. });
  910. // Trim off trailing nulls
  911. while (topics.length && topics[topics.length - 1] === null) {
  912. topics.pop();
  913. }
  914. return topics;
  915. }
  916. encodeEventLog(fragment: EventFragment | string, values: ReadonlyArray<any>): { data: string, topics: Array<string> } {
  917. if (typeof(fragment) === "string") {
  918. const f = this.getEvent(fragment);
  919. assertArgument(f, "unknown event", "eventFragment", fragment);
  920. fragment = f;
  921. }
  922. const topics: Array<string> = [ ];
  923. const dataTypes: Array<ParamType> = [ ];
  924. const dataValues: Array<string> = [ ];
  925. if (!fragment.anonymous) {
  926. topics.push(fragment.topicHash);
  927. }
  928. assertArgument(values.length === fragment.inputs.length,
  929. "event arguments/values mismatch", "values", values);
  930. fragment.inputs.forEach((param, index) => {
  931. const value = values[index];
  932. if (param.indexed) {
  933. if (param.type === "string") {
  934. topics.push(id(value))
  935. } else if (param.type === "bytes") {
  936. topics.push(keccak256(value))
  937. } else if (param.baseType === "tuple" || param.baseType === "array") {
  938. // @TODO
  939. throw new Error("not implemented");
  940. } else {
  941. topics.push(this.#abiCoder.encode([ param.type] , [ value ]));
  942. }
  943. } else {
  944. dataTypes.push(param);
  945. dataValues.push(value);
  946. }
  947. });
  948. return {
  949. data: this.#abiCoder.encode(dataTypes , dataValues),
  950. topics: topics
  951. };
  952. }
  953. // Decode a filter for the event and the search criteria
  954. decodeEventLog(fragment: EventFragment | string, data: BytesLike, topics?: ReadonlyArray<string>): Result {
  955. if (typeof(fragment) === "string") {
  956. const f = this.getEvent(fragment);
  957. assertArgument(f, "unknown event", "eventFragment", fragment);
  958. fragment = f;
  959. }
  960. if (topics != null && !fragment.anonymous) {
  961. const eventTopic = fragment.topicHash;
  962. assertArgument(isHexString(topics[0], 32) && topics[0].toLowerCase() === eventTopic,
  963. "fragment/topic mismatch", "topics[0]", topics[0]);
  964. topics = topics.slice(1);
  965. }
  966. const indexed: Array<ParamType> = [];
  967. const nonIndexed: Array<ParamType> = [];
  968. const dynamic: Array<boolean> = [];
  969. fragment.inputs.forEach((param, index) => {
  970. if (param.indexed) {
  971. if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") {
  972. indexed.push(ParamType.from({ type: "bytes32", name: param.name }));
  973. dynamic.push(true);
  974. } else {
  975. indexed.push(param);
  976. dynamic.push(false);
  977. }
  978. } else {
  979. nonIndexed.push(param);
  980. dynamic.push(false);
  981. }
  982. });
  983. const resultIndexed = (topics != null) ? this.#abiCoder.decode(indexed, concat(topics)): null;
  984. const resultNonIndexed = this.#abiCoder.decode(nonIndexed, data, true);
  985. //const result: (Array<any> & { [ key: string ]: any }) = [ ];
  986. const values: Array<any> = [ ];
  987. const keys: Array<null | string> = [ ];
  988. let nonIndexedIndex = 0, indexedIndex = 0;
  989. fragment.inputs.forEach((param, index) => {
  990. let value: null | Indexed | Error = null;
  991. if (param.indexed) {
  992. if (resultIndexed == null) {
  993. value = new Indexed(null);
  994. } else if (dynamic[index]) {
  995. value = new Indexed(resultIndexed[indexedIndex++]);
  996. } else {
  997. try {
  998. value = resultIndexed[indexedIndex++];
  999. } catch (error: any) {
  1000. value = error;
  1001. }
  1002. }
  1003. } else {
  1004. try {
  1005. value = resultNonIndexed[nonIndexedIndex++];
  1006. } catch (error: any) {
  1007. value = error;
  1008. }
  1009. }
  1010. values.push(value);
  1011. keys.push(param.name || null);
  1012. });
  1013. return Result.fromItems(values, keys);
  1014. }
  1015. /**
  1016. * Parses a transaction, finding the matching function and extracts
  1017. * the parameter values along with other useful function details.
  1018. *
  1019. * If the matching function cannot be found, return null.
  1020. */
  1021. parseTransaction(tx: { data: string, value?: BigNumberish }): null | TransactionDescription {
  1022. const data = getBytes(tx.data, "tx.data");
  1023. const value = getBigInt((tx.value != null) ? tx.value: 0, "tx.value");
  1024. const fragment = this.getFunction(hexlify(data.slice(0, 4)));
  1025. if (!fragment) { return null; }
  1026. const args = this.#abiCoder.decode(fragment.inputs, data.slice(4));
  1027. return new TransactionDescription(fragment, fragment.selector, args, value);
  1028. }
  1029. parseCallResult(data: BytesLike): Result {
  1030. throw new Error("@TODO");
  1031. }
  1032. /**
  1033. * Parses a receipt log, finding the matching event and extracts
  1034. * the parameter values along with other useful event details.
  1035. *
  1036. * If the matching event cannot be found, returns null.
  1037. */
  1038. parseLog(log: { topics: ReadonlyArray<string>, data: string}): null | LogDescription {
  1039. const fragment = this.getEvent(log.topics[0]);
  1040. if (!fragment || fragment.anonymous) { return null; }
  1041. // @TODO: If anonymous, and the only method, and the input count matches, should we parse?
  1042. // Probably not, because just because it is the only event in the ABI does
  1043. // not mean we have the full ABI; maybe just a fragment?
  1044. return new LogDescription(fragment, fragment.topicHash, this.decodeEventLog(fragment, log.data, log.topics));
  1045. }
  1046. /**
  1047. * Parses a revert data, finding the matching error and extracts
  1048. * the parameter values along with other useful error details.
  1049. *
  1050. * If the matching error cannot be found, returns null.
  1051. */
  1052. parseError(data: BytesLike): null | ErrorDescription {
  1053. const hexData = hexlify(data);
  1054. const fragment = this.getError(dataSlice(hexData, 0, 4));
  1055. if (!fragment) { return null; }
  1056. const args = this.#abiCoder.decode(fragment.inputs, dataSlice(hexData, 4));
  1057. return new ErrorDescription(fragment, fragment.selector, args);
  1058. }
  1059. /**
  1060. * Creates a new [[Interface]] from the ABI %%value%%.
  1061. *
  1062. * The %%value%% may be provided as an existing [[Interface]] object,
  1063. * a JSON-encoded ABI or any Human-Readable ABI format.
  1064. */
  1065. static from(value: InterfaceAbi | Interface): Interface {
  1066. // Already an Interface, which is immutable
  1067. if (value instanceof Interface) { return value; }
  1068. // JSON
  1069. if (typeof(value) === "string") { return new Interface(JSON.parse(value)); }
  1070. // An Interface; possibly from another v6 instance
  1071. if (typeof((<any>value).formatJson) === "function") {
  1072. return new Interface((<any>value).formatJson());
  1073. }
  1074. // A legacy Interface; from an older version
  1075. if (typeof((<any>value).format) === "function") {
  1076. return new Interface((<any>value).format("json"));
  1077. }
  1078. // Array of fragments
  1079. return new Interface(value);
  1080. }
  1081. }