fragments.ts 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  1. /**
  2. * A fragment is a single item from an ABI, which may represent any of:
  3. *
  4. * - [Functions](FunctionFragment)
  5. * - [Events](EventFragment)
  6. * - [Constructors](ConstructorFragment)
  7. * - Custom [Errors](ErrorFragment)
  8. * - [Fallback or Receive](FallbackFragment) functions
  9. *
  10. * @_subsection api/abi/abi-coder:Fragments [about-fragments]
  11. */
  12. import {
  13. defineProperties, getBigInt, getNumber,
  14. assert, assertPrivate, assertArgument
  15. } from "../utils/index.js";
  16. import { id } from "../hash/index.js";
  17. /**
  18. * A Type description in a [JSON ABI format](link-solc-jsonabi).
  19. */
  20. export interface JsonFragmentType {
  21. /**
  22. * The parameter name.
  23. */
  24. readonly name?: string;
  25. /**
  26. * If the parameter is indexed.
  27. */
  28. readonly indexed?: boolean;
  29. /**
  30. * The type of the parameter.
  31. */
  32. readonly type?: string;
  33. /**
  34. * The internal Solidity type.
  35. */
  36. readonly internalType?: string;
  37. /**
  38. * The components for a tuple.
  39. */
  40. readonly components?: ReadonlyArray<JsonFragmentType>;
  41. }
  42. /**
  43. * A fragment for a method, event or error in a [JSON ABI format](link-solc-jsonabi).
  44. */
  45. export interface JsonFragment {
  46. /**
  47. * The name of the error, event, function, etc.
  48. */
  49. readonly name?: string;
  50. /**
  51. * The type of the fragment (e.g. ``event``, ``"function"``, etc.)
  52. */
  53. readonly type?: string;
  54. /**
  55. * If the event is anonymous.
  56. */
  57. readonly anonymous?: boolean;
  58. /**
  59. * If the function is payable.
  60. */
  61. readonly payable?: boolean;
  62. /**
  63. * If the function is constant.
  64. */
  65. readonly constant?: boolean;
  66. /**
  67. * The mutability state of the function.
  68. */
  69. readonly stateMutability?: string;
  70. /**
  71. * The input parameters.
  72. */
  73. readonly inputs?: ReadonlyArray<JsonFragmentType>;
  74. /**
  75. * The output parameters.
  76. */
  77. readonly outputs?: ReadonlyArray<JsonFragmentType>;
  78. /**
  79. * The gas limit to use when sending a transaction for this function.
  80. */
  81. readonly gas?: string;
  82. };
  83. /**
  84. * The format to serialize the output as.
  85. *
  86. * **``"sighash"``** - the bare formatting, used to compute the selector
  87. * or topic hash; this format cannot be reversed (as it discards ``indexed``)
  88. * so cannot by used to export an [[Interface]].
  89. *
  90. * **``"minimal"``** - Human-Readable ABI with minimal spacing and without
  91. * names, so it is compact, but will result in Result objects that cannot
  92. * be accessed by name.
  93. *
  94. * **``"full"``** - Full Human-Readable ABI, with readable spacing and names
  95. * intact; this is generally the recommended format.
  96. *
  97. * **``"json"``** - The [JSON ABI format](link-solc-jsonabi).
  98. */
  99. export type FormatType = "sighash" | "minimal" | "full" | "json";
  100. // [ "a", "b" ] => { "a": 1, "b": 1 }
  101. function setify(items: Array<string>): ReadonlySet<string> {
  102. const result: Set<string> = new Set();
  103. items.forEach((k) => result.add(k));
  104. return Object.freeze(result);
  105. }
  106. const _kwVisibDeploy = "external public payable override";
  107. const KwVisibDeploy = setify(_kwVisibDeploy.split(" "));
  108. // Visibility Keywords
  109. const _kwVisib = "constant external internal payable private public pure view override";
  110. const KwVisib = setify(_kwVisib.split(" "));
  111. const _kwTypes = "constructor error event fallback function receive struct";
  112. const KwTypes = setify(_kwTypes.split(" "));
  113. const _kwModifiers = "calldata memory storage payable indexed";
  114. const KwModifiers = setify(_kwModifiers.split(" "));
  115. const _kwOther = "tuple returns";
  116. // All Keywords
  117. const _keywords = [ _kwTypes, _kwModifiers, _kwOther, _kwVisib ].join(" ");
  118. const Keywords = setify(_keywords.split(" "));
  119. // Single character tokens
  120. const SimpleTokens: Record<string, string> = {
  121. "(": "OPEN_PAREN", ")": "CLOSE_PAREN",
  122. "[": "OPEN_BRACKET", "]": "CLOSE_BRACKET",
  123. ",": "COMMA", "@": "AT"
  124. };
  125. // Parser regexes to consume the next token
  126. const regexWhitespacePrefix = new RegExp("^(\\s*)");
  127. const regexNumberPrefix = new RegExp("^([0-9]+)");
  128. const regexIdPrefix = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)");
  129. // Parser regexs to check validity
  130. const regexId = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$");
  131. const regexType = new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");
  132. /**
  133. * @ignore:
  134. */
  135. type Token = Readonly<{
  136. // Type of token (e.g. TYPE, KEYWORD, NUMBER, etc)
  137. type: string;
  138. // Offset into the original source code
  139. offset: number;
  140. // Actual text content of the token
  141. text: string;
  142. // The parenthesis depth
  143. depth: number;
  144. // If a parenthesis, the offset (in tokens) that balances it
  145. match: number;
  146. // For parenthesis and commas, the offset (in tokens) to the
  147. // previous/next parenthesis or comma in the list
  148. linkBack: number;
  149. linkNext: number;
  150. // If a BRACKET, the value inside
  151. value: number;
  152. }>;
  153. class TokenString {
  154. #offset: number;
  155. #tokens: ReadonlyArray<Token>;
  156. get offset(): number { return this.#offset; }
  157. get length(): number { return this.#tokens.length - this.#offset; }
  158. constructor(tokens: ReadonlyArray<Token>) {
  159. this.#offset = 0;
  160. this.#tokens = tokens.slice();
  161. }
  162. clone(): TokenString { return new TokenString(this.#tokens); }
  163. reset(): void { this.#offset = 0; }
  164. #subTokenString(from: number = 0, to: number = 0): TokenString {
  165. return new TokenString(this.#tokens.slice(from, to).map((t) => {
  166. return Object.freeze(Object.assign({ }, t, {
  167. match: (t.match - from),
  168. linkBack: (t.linkBack - from),
  169. linkNext: (t.linkNext - from),
  170. }));
  171. }));
  172. }
  173. // Pops and returns the value of the next token, if it is a keyword in allowed; throws if out of tokens
  174. popKeyword(allowed: ReadonlySet<string>): string {
  175. const top = this.peek();
  176. if (top.type !== "KEYWORD" || !allowed.has(top.text)) { throw new Error(`expected keyword ${ top.text }`); }
  177. return this.pop().text;
  178. }
  179. // Pops and returns the value of the next token if it is `type`; throws if out of tokens
  180. popType(type: string): string {
  181. if (this.peek().type !== type) {
  182. const top = this.peek();
  183. throw new Error(`expected ${ type }; got ${ top.type } ${ JSON.stringify(top.text) }`);
  184. }
  185. return this.pop().text;
  186. }
  187. // Pops and returns a "(" TOKENS ")"
  188. popParen(): TokenString {
  189. const top = this.peek();
  190. if (top.type !== "OPEN_PAREN") { throw new Error("bad start"); }
  191. const result = this.#subTokenString(this.#offset + 1, top.match + 1);
  192. this.#offset = top.match + 1;
  193. return result;
  194. }
  195. // Pops and returns the items within "(" ITEM1 "," ITEM2 "," ... ")"
  196. popParams(): Array<TokenString> {
  197. const top = this.peek();
  198. if (top.type !== "OPEN_PAREN") { throw new Error("bad start"); }
  199. const result: Array<TokenString> = [ ];
  200. while(this.#offset < top.match - 1) {
  201. const link = this.peek().linkNext;
  202. result.push(this.#subTokenString(this.#offset + 1, link));
  203. this.#offset = link;
  204. }
  205. this.#offset = top.match + 1;
  206. return result;
  207. }
  208. // Returns the top Token, throwing if out of tokens
  209. peek(): Token {
  210. if (this.#offset >= this.#tokens.length) {
  211. throw new Error("out-of-bounds");
  212. }
  213. return this.#tokens[this.#offset];
  214. }
  215. // Returns the next value, if it is a keyword in `allowed`
  216. peekKeyword(allowed: ReadonlySet<string>): null | string {
  217. const top = this.peekType("KEYWORD");
  218. return (top != null && allowed.has(top)) ? top: null;
  219. }
  220. // Returns the value of the next token if it is `type`
  221. peekType(type: string): null | string {
  222. if (this.length === 0) { return null; }
  223. const top = this.peek();
  224. return (top.type === type) ? top.text: null;
  225. }
  226. // Returns the next token; throws if out of tokens
  227. pop(): Token {
  228. const result = this.peek();
  229. this.#offset++;
  230. return result;
  231. }
  232. toString(): string {
  233. const tokens: Array<string> = [ ];
  234. for (let i = this.#offset; i < this.#tokens.length; i++) {
  235. const token = this.#tokens[i];
  236. tokens.push(`${ token.type }:${ token.text }`);
  237. }
  238. return `<TokenString ${ tokens.join(" ") }>`
  239. }
  240. }
  241. type Writeable<T> = { -readonly [P in keyof T]: T[P] };
  242. function lex(text: string): TokenString {
  243. const tokens: Array<Token> = [ ];
  244. const throwError = (message: string) => {
  245. const token = (offset < text.length) ? JSON.stringify(text[offset]): "$EOI";
  246. throw new Error(`invalid token ${ token } at ${ offset }: ${ message }`);
  247. };
  248. let brackets: Array<number> = [ ];
  249. let commas: Array<number> = [ ];
  250. let offset = 0;
  251. while (offset < text.length) {
  252. // Strip off any leading whitespace
  253. let cur = text.substring(offset);
  254. let match = cur.match(regexWhitespacePrefix);
  255. if (match) {
  256. offset += match[1].length;
  257. cur = text.substring(offset);
  258. }
  259. const token = { depth: brackets.length, linkBack: -1, linkNext: -1, match: -1, type: "", text: "", offset, value: -1 };
  260. tokens.push(token);
  261. let type = (SimpleTokens[cur[0]] || "");
  262. if (type) {
  263. token.type = type;
  264. token.text = cur[0];
  265. offset++;
  266. if (type === "OPEN_PAREN") {
  267. brackets.push(tokens.length - 1);
  268. commas.push(tokens.length - 1);
  269. } else if (type == "CLOSE_PAREN") {
  270. if (brackets.length === 0) { throwError("no matching open bracket"); }
  271. token.match = brackets.pop() as number;
  272. (<Writeable<Token>>(tokens[token.match])).match = tokens.length - 1;
  273. token.depth--;
  274. token.linkBack = commas.pop() as number;
  275. (<Writeable<Token>>(tokens[token.linkBack])).linkNext = tokens.length - 1;
  276. } else if (type === "COMMA") {
  277. token.linkBack = commas.pop() as number;
  278. (<Writeable<Token>>(tokens[token.linkBack])).linkNext = tokens.length - 1;
  279. commas.push(tokens.length - 1);
  280. } else if (type === "OPEN_BRACKET") {
  281. token.type = "BRACKET";
  282. } else if (type === "CLOSE_BRACKET") {
  283. // Remove the CLOSE_BRACKET
  284. let suffix = (tokens.pop() as Token).text;
  285. if (tokens.length > 0 && tokens[tokens.length - 1].type === "NUMBER") {
  286. const value = (tokens.pop() as Token).text;
  287. suffix = value + suffix;
  288. (<Writeable<Token>>(tokens[tokens.length - 1])).value = getNumber(value);
  289. }
  290. if (tokens.length === 0 || tokens[tokens.length - 1].type !== "BRACKET") {
  291. throw new Error("missing opening bracket");
  292. }
  293. (<Writeable<Token>>(tokens[tokens.length - 1])).text += suffix;
  294. }
  295. continue;
  296. }
  297. match = cur.match(regexIdPrefix);
  298. if (match) {
  299. token.text = match[1];
  300. offset += token.text.length;
  301. if (Keywords.has(token.text)) {
  302. token.type = "KEYWORD";
  303. continue;
  304. }
  305. if (token.text.match(regexType)) {
  306. token.type = "TYPE";
  307. continue;
  308. }
  309. token.type = "ID";
  310. continue;
  311. }
  312. match = cur.match(regexNumberPrefix);
  313. if (match) {
  314. token.text = match[1];
  315. token.type = "NUMBER";
  316. offset += token.text.length;
  317. continue;
  318. }
  319. throw new Error(`unexpected token ${ JSON.stringify(cur[0]) } at position ${ offset }`);
  320. }
  321. return new TokenString(tokens.map((t) => Object.freeze(t)));
  322. }
  323. // Check only one of `allowed` is in `set`
  324. function allowSingle(set: ReadonlySet<string>, allowed: ReadonlySet<string>): void {
  325. let included: Array<string> = [ ];
  326. for (const key in allowed.keys()) {
  327. if (set.has(key)) { included.push(key); }
  328. }
  329. if (included.length > 1) { throw new Error(`conflicting types: ${ included.join(", ") }`); }
  330. }
  331. // Functions to process a Solidity Signature TokenString from left-to-right for...
  332. // ...the name with an optional type, returning the name
  333. function consumeName(type: string, tokens: TokenString): string {
  334. if (tokens.peekKeyword(KwTypes)) {
  335. const keyword = tokens.pop().text;
  336. if (keyword !== type) {
  337. throw new Error(`expected ${ type }, got ${ keyword }`);
  338. }
  339. }
  340. return tokens.popType("ID");
  341. }
  342. // ...all keywords matching allowed, returning the keywords
  343. function consumeKeywords(tokens: TokenString, allowed?: ReadonlySet<string>): ReadonlySet<string> {
  344. const keywords: Set<string> = new Set();
  345. while (true) {
  346. const keyword = tokens.peekType("KEYWORD");
  347. if (keyword == null || (allowed && !allowed.has(keyword))) { break; }
  348. tokens.pop();
  349. if (keywords.has(keyword)) { throw new Error(`duplicate keywords: ${ JSON.stringify(keyword) }`); }
  350. keywords.add(keyword);
  351. }
  352. return Object.freeze(keywords);
  353. }
  354. // ...all visibility keywords, returning the coalesced mutability
  355. function consumeMutability(tokens: TokenString): "payable" | "nonpayable" | "view" | "pure" {
  356. let modifiers = consumeKeywords(tokens, KwVisib);
  357. // Detect conflicting modifiers
  358. allowSingle(modifiers, setify("constant payable nonpayable".split(" ")));
  359. allowSingle(modifiers, setify("pure view payable nonpayable".split(" ")));
  360. // Process mutability states
  361. if (modifiers.has("view")) { return "view"; }
  362. if (modifiers.has("pure")) { return "pure"; }
  363. if (modifiers.has("payable")) { return "payable"; }
  364. if (modifiers.has("nonpayable")) { return "nonpayable"; }
  365. // Process legacy `constant` last
  366. if (modifiers.has("constant")) { return "view"; }
  367. return "nonpayable";
  368. }
  369. // ...a parameter list, returning the ParamType list
  370. function consumeParams(tokens: TokenString, allowIndexed?: boolean): Array<ParamType> {
  371. return tokens.popParams().map((t) => ParamType.from(t, allowIndexed));
  372. }
  373. // ...a gas limit, returning a BigNumber or null if none
  374. function consumeGas(tokens: TokenString): null | bigint {
  375. if (tokens.peekType("AT")) {
  376. tokens.pop();
  377. if (tokens.peekType("NUMBER")) {
  378. return getBigInt(tokens.pop().text);
  379. }
  380. throw new Error("invalid gas");
  381. }
  382. return null;
  383. }
  384. function consumeEoi(tokens: TokenString): void {
  385. if (tokens.length) {
  386. throw new Error(`unexpected tokens at offset ${ tokens.offset }: ${ tokens.toString() }`);
  387. }
  388. }
  389. const regexArrayType = new RegExp(/^(.*)\[([0-9]*)\]$/);
  390. function verifyBasicType(type: string): string {
  391. const match = type.match(regexType);
  392. assertArgument(match, "invalid type", "type", type);
  393. if (type === "uint") { return "uint256"; }
  394. if (type === "int") { return "int256"; }
  395. if (match[2]) {
  396. // bytesXX
  397. const length = parseInt(match[2]);
  398. assertArgument(length !== 0 && length <= 32, "invalid bytes length", "type", type);
  399. } else if (match[3]) {
  400. // intXX or uintXX
  401. const size = parseInt(match[3] as string);
  402. assertArgument(size !== 0 && size <= 256 && (size % 8) === 0, "invalid numeric width", "type", type);
  403. }
  404. return type;
  405. }
  406. // Make the Fragment constructors effectively private
  407. const _guard = { };
  408. /**
  409. * When [walking](ParamType-walk) a [[ParamType]], this is called
  410. * on each component.
  411. */
  412. export type ParamTypeWalkFunc = (type: string, value: any) => any;
  413. /**
  414. * When [walking asynchronously](ParamType-walkAsync) a [[ParamType]],
  415. * this is called on each component.
  416. */
  417. export type ParamTypeWalkAsyncFunc = (type: string, value: any) => any | Promise<any>;
  418. const internal = Symbol.for("_ethers_internal");
  419. const ParamTypeInternal = "_ParamTypeInternal";
  420. const ErrorFragmentInternal = "_ErrorInternal";
  421. const EventFragmentInternal = "_EventInternal";
  422. const ConstructorFragmentInternal = "_ConstructorInternal";
  423. const FallbackFragmentInternal = "_FallbackInternal";
  424. const FunctionFragmentInternal = "_FunctionInternal";
  425. const StructFragmentInternal = "_StructInternal";
  426. /**
  427. * Each input and output of a [[Fragment]] is an Array of **ParamType**.
  428. */
  429. export class ParamType {
  430. /**
  431. * The local name of the parameter (or ``""`` if unbound)
  432. */
  433. readonly name!: string;
  434. /**
  435. * The fully qualified type (e.g. ``"address"``, ``"tuple(address)"``,
  436. * ``"uint256[3][]"``)
  437. */
  438. readonly type!: string;
  439. /**
  440. * The base type (e.g. ``"address"``, ``"tuple"``, ``"array"``)
  441. */
  442. readonly baseType!: string;
  443. /**
  444. * True if the parameters is indexed.
  445. *
  446. * For non-indexable types this is ``null``.
  447. */
  448. readonly indexed!: null | boolean;
  449. /**
  450. * The components for the tuple.
  451. *
  452. * For non-tuple types this is ``null``.
  453. */
  454. readonly components!: null | ReadonlyArray<ParamType>;
  455. /**
  456. * The array length, or ``-1`` for dynamic-lengthed arrays.
  457. *
  458. * For non-array types this is ``null``.
  459. */
  460. readonly arrayLength!: null | number;
  461. /**
  462. * The type of each child in the array.
  463. *
  464. * For non-array types this is ``null``.
  465. */
  466. readonly arrayChildren!: null | ParamType;
  467. /**
  468. * @private
  469. */
  470. constructor(guard: any, name: string, type: string, baseType: string, indexed: null | boolean, components: null | ReadonlyArray<ParamType>, arrayLength: null | number, arrayChildren: null | ParamType) {
  471. assertPrivate(guard, _guard, "ParamType");
  472. Object.defineProperty(this, internal, { value: ParamTypeInternal });
  473. if (components) { components = Object.freeze(components.slice()); }
  474. if (baseType === "array") {
  475. if (arrayLength == null || arrayChildren == null) {
  476. throw new Error("");
  477. }
  478. } else if (arrayLength != null || arrayChildren != null) {
  479. throw new Error("");
  480. }
  481. if (baseType === "tuple") {
  482. if (components == null) { throw new Error(""); }
  483. } else if (components != null) {
  484. throw new Error("");
  485. }
  486. defineProperties<ParamType>(this, {
  487. name, type, baseType, indexed, components, arrayLength, arrayChildren
  488. });
  489. }
  490. /**
  491. * Return a string representation of this type.
  492. *
  493. * For example,
  494. *
  495. * ``sighash" => "(uint256,address)"``
  496. *
  497. * ``"minimal" => "tuple(uint256,address) indexed"``
  498. *
  499. * ``"full" => "tuple(uint256 foo, address bar) indexed baz"``
  500. */
  501. format(format?: FormatType): string {
  502. if (format == null) { format = "sighash"; }
  503. if (format === "json") {
  504. const name = this.name || "";
  505. if (this.isArray()) {
  506. const result = JSON.parse(this.arrayChildren.format("json"));
  507. result.name = name;
  508. result.type += `[${ (this.arrayLength < 0 ? "": String(this.arrayLength)) }]`;
  509. return JSON.stringify(result);
  510. }
  511. const result: any = {
  512. type: ((this.baseType === "tuple") ? "tuple": this.type),
  513. name
  514. };
  515. if (typeof(this.indexed) === "boolean") { result.indexed = this.indexed; }
  516. if (this.isTuple()) {
  517. result.components = this.components.map((c) => JSON.parse(c.format(format)));
  518. }
  519. return JSON.stringify(result);
  520. }
  521. let result = "";
  522. // Array
  523. if (this.isArray()) {
  524. result += this.arrayChildren.format(format);
  525. result += `[${ (this.arrayLength < 0 ? "": String(this.arrayLength)) }]`;
  526. } else {
  527. if (this.isTuple()) {
  528. result += "(" + this.components.map(
  529. (comp) => comp.format(format)
  530. ).join((format === "full") ? ", ": ",") + ")";
  531. } else {
  532. result += this.type;
  533. }
  534. }
  535. if (format !== "sighash") {
  536. if (this.indexed === true) { result += " indexed"; }
  537. if (format === "full" && this.name) {
  538. result += " " + this.name;
  539. }
  540. }
  541. return result;
  542. }
  543. /**
  544. * Returns true if %%this%% is an Array type.
  545. *
  546. * This provides a type gaurd ensuring that [[arrayChildren]]
  547. * and [[arrayLength]] are non-null.
  548. */
  549. isArray(): this is (ParamType & { arrayChildren: ParamType, arrayLength: number }) {
  550. return (this.baseType === "array")
  551. }
  552. /**
  553. * Returns true if %%this%% is a Tuple type.
  554. *
  555. * This provides a type gaurd ensuring that [[components]]
  556. * is non-null.
  557. */
  558. isTuple(): this is (ParamType & { components: ReadonlyArray<ParamType> }) {
  559. return (this.baseType === "tuple");
  560. }
  561. /**
  562. * Returns true if %%this%% is an Indexable type.
  563. *
  564. * This provides a type gaurd ensuring that [[indexed]]
  565. * is non-null.
  566. */
  567. isIndexable(): this is (ParamType & { indexed: boolean }) {
  568. return (this.indexed != null);
  569. }
  570. /**
  571. * Walks the **ParamType** with %%value%%, calling %%process%%
  572. * on each type, destructing the %%value%% recursively.
  573. */
  574. walk(value: any, process: ParamTypeWalkFunc): any {
  575. if (this.isArray()) {
  576. if (!Array.isArray(value)) { throw new Error("invalid array value"); }
  577. if (this.arrayLength !== -1 && value.length !== this.arrayLength) {
  578. throw new Error("array is wrong length");
  579. }
  580. const _this = this;
  581. return value.map((v) => (_this.arrayChildren.walk(v, process)));
  582. }
  583. if (this.isTuple()) {
  584. if (!Array.isArray(value)) { throw new Error("invalid tuple value"); }
  585. if (value.length !== this.components.length) {
  586. throw new Error("array is wrong length");
  587. }
  588. const _this = this;
  589. return value.map((v, i) => (_this.components[i].walk(v, process)));
  590. }
  591. return process(this.type, value);
  592. }
  593. #walkAsync(promises: Array<Promise<void>>, value: any, process: ParamTypeWalkAsyncFunc, setValue: (value: any) => void): void {
  594. if (this.isArray()) {
  595. if (!Array.isArray(value)) { throw new Error("invalid array value"); }
  596. if (this.arrayLength !== -1 && value.length !== this.arrayLength) {
  597. throw new Error("array is wrong length");
  598. }
  599. const childType = this.arrayChildren;
  600. const result = value.slice();
  601. result.forEach((value, index) => {
  602. childType.#walkAsync(promises, value, process, (value: any) => {
  603. result[index] = value;
  604. });
  605. });
  606. setValue(result);
  607. return;
  608. }
  609. if (this.isTuple()) {
  610. const components = this.components;
  611. // Convert the object into an array
  612. let result: Array<any>;
  613. if (Array.isArray(value)) {
  614. result = value.slice();
  615. } else {
  616. if (value == null || typeof(value) !== "object") {
  617. throw new Error("invalid tuple value");
  618. }
  619. result = components.map((param) => {
  620. if (!param.name) { throw new Error("cannot use object value with unnamed components"); }
  621. if (!(param.name in value)) {
  622. throw new Error(`missing value for component ${ param.name }`);
  623. }
  624. return value[param.name];
  625. });
  626. }
  627. if (result.length !== this.components.length) {
  628. throw new Error("array is wrong length");
  629. }
  630. result.forEach((value, index) => {
  631. components[index].#walkAsync(promises, value, process, (value: any) => {
  632. result[index] = value;
  633. });
  634. });
  635. setValue(result);
  636. return;
  637. }
  638. const result = process(this.type, value);
  639. if (result.then) {
  640. promises.push((async function() { setValue(await result); })());
  641. } else {
  642. setValue(result);
  643. }
  644. }
  645. /**
  646. * Walks the **ParamType** with %%value%%, asynchronously calling
  647. * %%process%% on each type, destructing the %%value%% recursively.
  648. *
  649. * This can be used to resolve ENS names by walking and resolving each
  650. * ``"address"`` type.
  651. */
  652. async walkAsync(value: any, process: ParamTypeWalkAsyncFunc): Promise<any> {
  653. const promises: Array<Promise<void>> = [ ];
  654. const result: [ any ] = [ value ];
  655. this.#walkAsync(promises, value, process, (value: any) => {
  656. result[0] = value;
  657. });
  658. if (promises.length) { await Promise.all(promises); }
  659. return result[0];
  660. }
  661. /**
  662. * Creates a new **ParamType** for %%obj%%.
  663. *
  664. * If %%allowIndexed%% then the ``indexed`` keyword is permitted,
  665. * otherwise the ``indexed`` keyword will throw an error.
  666. */
  667. static from(obj: any, allowIndexed?: boolean): ParamType {
  668. if (ParamType.isParamType(obj)) { return obj; }
  669. if (typeof(obj) === "string") {
  670. try {
  671. return ParamType.from(lex(obj), allowIndexed);
  672. } catch (error) {
  673. assertArgument(false, "invalid param type", "obj", obj);
  674. }
  675. } else if (obj instanceof TokenString) {
  676. let type = "", baseType = "";
  677. let comps: null | Array<ParamType> = null;
  678. if (consumeKeywords(obj, setify([ "tuple" ])).has("tuple") || obj.peekType("OPEN_PAREN")) {
  679. // Tuple
  680. baseType = "tuple";
  681. comps = obj.popParams().map((t) => ParamType.from(t));
  682. type = `tuple(${ comps.map((c) => c.format()).join(",") })`;
  683. } else {
  684. // Normal
  685. type = verifyBasicType(obj.popType("TYPE"));
  686. baseType = type;
  687. }
  688. // Check for Array
  689. let arrayChildren: null | ParamType = null;
  690. let arrayLength: null | number = null;
  691. while (obj.length && obj.peekType("BRACKET")) {
  692. const bracket = obj.pop(); //arrays[i];
  693. arrayChildren = new ParamType(_guard, "", type, baseType, null, comps, arrayLength, arrayChildren);
  694. arrayLength = bracket.value;
  695. type += bracket.text;
  696. baseType = "array";
  697. comps = null;
  698. }
  699. let indexed: null | boolean = null;
  700. const keywords = consumeKeywords(obj, KwModifiers);
  701. if (keywords.has("indexed")) {
  702. if (!allowIndexed) { throw new Error(""); }
  703. indexed = true;
  704. }
  705. const name = (obj.peekType("ID") ? obj.pop().text: "");
  706. if (obj.length) { throw new Error("leftover tokens"); }
  707. return new ParamType(_guard, name, type, baseType, indexed, comps, arrayLength, arrayChildren);
  708. }
  709. const name = obj.name;
  710. assertArgument(!name || (typeof(name) === "string" && name.match(regexId)),
  711. "invalid name", "obj.name", name);
  712. let indexed = obj.indexed;
  713. if (indexed != null) {
  714. assertArgument(allowIndexed, "parameter cannot be indexed", "obj.indexed", obj.indexed);
  715. indexed = !!indexed;
  716. }
  717. let type = obj.type;
  718. let arrayMatch = type.match(regexArrayType);
  719. if (arrayMatch) {
  720. const arrayLength = parseInt(arrayMatch[2] || "-1");
  721. const arrayChildren = ParamType.from({
  722. type: arrayMatch[1],
  723. components: obj.components
  724. });
  725. return new ParamType(_guard, name || "", type, "array", indexed, null, arrayLength, arrayChildren);
  726. }
  727. if (type === "tuple" || type.startsWith("tuple("/* fix: ) */) || type.startsWith("(" /* fix: ) */)) {
  728. const comps = (obj.components != null) ? obj.components.map((c: any) => ParamType.from(c)): null;
  729. const tuple = new ParamType(_guard, name || "", type, "tuple", indexed, comps, null, null);
  730. // @TODO: use lexer to validate and normalize type
  731. return tuple;
  732. }
  733. type = verifyBasicType(obj.type);
  734. return new ParamType(_guard, name || "", type, type, indexed, null, null, null);
  735. }
  736. /**
  737. * Returns true if %%value%% is a **ParamType**.
  738. */
  739. static isParamType(value: any): value is ParamType {
  740. return (value && value[internal] === ParamTypeInternal);
  741. }
  742. }
  743. /**
  744. * The type of a [[Fragment]].
  745. */
  746. export type FragmentType = "constructor" | "error" | "event" | "fallback" | "function" | "struct";
  747. /**
  748. * An abstract class to represent An individual fragment from a parse ABI.
  749. */
  750. export abstract class Fragment {
  751. /**
  752. * The type of the fragment.
  753. */
  754. readonly type!: FragmentType;
  755. /**
  756. * The inputs for the fragment.
  757. */
  758. readonly inputs!: ReadonlyArray<ParamType>;
  759. /**
  760. * @private
  761. */
  762. constructor(guard: any, type: FragmentType, inputs: ReadonlyArray<ParamType>) {
  763. assertPrivate(guard, _guard, "Fragment");
  764. inputs = Object.freeze(inputs.slice());
  765. defineProperties<Fragment>(this, { type, inputs });
  766. }
  767. /**
  768. * Returns a string representation of this fragment as %%format%%.
  769. */
  770. abstract format(format?: FormatType): string;
  771. /**
  772. * Creates a new **Fragment** for %%obj%%, wich can be any supported
  773. * ABI frgament type.
  774. */
  775. static from(obj: any): Fragment {
  776. if (typeof(obj) === "string") {
  777. // Try parsing JSON...
  778. try {
  779. Fragment.from(JSON.parse(obj));
  780. } catch (e) { }
  781. // ...otherwise, use the human-readable lexer
  782. return Fragment.from(lex(obj));
  783. }
  784. if (obj instanceof TokenString) {
  785. // Human-readable ABI (already lexed)
  786. const type = obj.peekKeyword(KwTypes);
  787. switch (type) {
  788. case "constructor": return ConstructorFragment.from(obj);
  789. case "error": return ErrorFragment.from(obj);
  790. case "event": return EventFragment.from(obj);
  791. case "fallback": case "receive":
  792. return FallbackFragment.from(obj);
  793. case "function": return FunctionFragment.from(obj);
  794. case "struct": return StructFragment.from(obj);
  795. }
  796. } else if (typeof(obj) === "object") {
  797. // JSON ABI
  798. switch (obj.type) {
  799. case "constructor": return ConstructorFragment.from(obj);
  800. case "error": return ErrorFragment.from(obj);
  801. case "event": return EventFragment.from(obj);
  802. case "fallback": case "receive":
  803. return FallbackFragment.from(obj);
  804. case "function": return FunctionFragment.from(obj);
  805. case "struct": return StructFragment.from(obj);
  806. }
  807. assert(false, `unsupported type: ${ obj.type }`, "UNSUPPORTED_OPERATION", {
  808. operation: "Fragment.from"
  809. });
  810. }
  811. assertArgument(false, "unsupported frgament object", "obj", obj);
  812. }
  813. /**
  814. * Returns true if %%value%% is a [[ConstructorFragment]].
  815. */
  816. static isConstructor(value: any): value is ConstructorFragment {
  817. return ConstructorFragment.isFragment(value);
  818. }
  819. /**
  820. * Returns true if %%value%% is an [[ErrorFragment]].
  821. */
  822. static isError(value: any): value is ErrorFragment {
  823. return ErrorFragment.isFragment(value);
  824. }
  825. /**
  826. * Returns true if %%value%% is an [[EventFragment]].
  827. */
  828. static isEvent(value: any): value is EventFragment {
  829. return EventFragment.isFragment(value);
  830. }
  831. /**
  832. * Returns true if %%value%% is a [[FunctionFragment]].
  833. */
  834. static isFunction(value: any): value is FunctionFragment {
  835. return FunctionFragment.isFragment(value);
  836. }
  837. /**
  838. * Returns true if %%value%% is a [[StructFragment]].
  839. */
  840. static isStruct(value: any): value is StructFragment {
  841. return StructFragment.isFragment(value);
  842. }
  843. }
  844. /**
  845. * An abstract class to represent An individual fragment
  846. * which has a name from a parse ABI.
  847. */
  848. export abstract class NamedFragment extends Fragment {
  849. /**
  850. * The name of the fragment.
  851. */
  852. readonly name!: string;
  853. /**
  854. * @private
  855. */
  856. constructor(guard: any, type: FragmentType, name: string, inputs: ReadonlyArray<ParamType>) {
  857. super(guard, type, inputs);
  858. assertArgument(typeof(name) === "string" && name.match(regexId),
  859. "invalid identifier", "name", name);
  860. inputs = Object.freeze(inputs.slice());
  861. defineProperties<NamedFragment>(this, { name });
  862. }
  863. }
  864. function joinParams(format: FormatType, params: ReadonlyArray<ParamType>): string {
  865. return "(" + params.map((p) => p.format(format)).join((format === "full") ? ", ": ",") + ")";
  866. }
  867. /**
  868. * A Fragment which represents a //Custom Error//.
  869. */
  870. export class ErrorFragment extends NamedFragment {
  871. /**
  872. * @private
  873. */
  874. constructor(guard: any, name: string, inputs: ReadonlyArray<ParamType>) {
  875. super(guard, "error", name, inputs);
  876. Object.defineProperty(this, internal, { value: ErrorFragmentInternal });
  877. }
  878. /**
  879. * The Custom Error selector.
  880. */
  881. get selector(): string {
  882. return id(this.format("sighash")).substring(0, 10);
  883. }
  884. /**
  885. * Returns a string representation of this fragment as %%format%%.
  886. */
  887. format(format?: FormatType): string {
  888. if (format == null) { format = "sighash"; }
  889. if (format === "json") {
  890. return JSON.stringify({
  891. type: "error",
  892. name: this.name,
  893. inputs: this.inputs.map((input) => JSON.parse(input.format(format))),
  894. });
  895. }
  896. const result: Array<string> = [ ];
  897. if (format !== "sighash") { result.push("error"); }
  898. result.push(this.name + joinParams(format, this.inputs));
  899. return result.join(" ");
  900. }
  901. /**
  902. * Returns a new **ErrorFragment** for %%obj%%.
  903. */
  904. static from(obj: any): ErrorFragment {
  905. if (ErrorFragment.isFragment(obj)) { return obj; }
  906. if (typeof(obj) === "string") {
  907. return ErrorFragment.from(lex(obj));
  908. } else if (obj instanceof TokenString) {
  909. const name = consumeName("error", obj);
  910. const inputs = consumeParams(obj);
  911. consumeEoi(obj);
  912. return new ErrorFragment(_guard, name, inputs);
  913. }
  914. return new ErrorFragment(_guard, obj.name,
  915. obj.inputs ? obj.inputs.map(ParamType.from): [ ]);
  916. }
  917. /**
  918. * Returns ``true`` and provides a type guard if %%value%% is an
  919. * **ErrorFragment**.
  920. */
  921. static isFragment(value: any): value is ErrorFragment {
  922. return (value && value[internal] === ErrorFragmentInternal);
  923. }
  924. }
  925. /**
  926. * A Fragment which represents an Event.
  927. */
  928. export class EventFragment extends NamedFragment {
  929. /**
  930. * Whether this event is anonymous.
  931. */
  932. readonly anonymous!: boolean;
  933. /**
  934. * @private
  935. */
  936. constructor(guard: any, name: string, inputs: ReadonlyArray<ParamType>, anonymous: boolean) {
  937. super(guard, "event", name, inputs);
  938. Object.defineProperty(this, internal, { value: EventFragmentInternal });
  939. defineProperties<EventFragment>(this, { anonymous });
  940. }
  941. /**
  942. * The Event topic hash.
  943. */
  944. get topicHash(): string {
  945. return id(this.format("sighash"));
  946. }
  947. /**
  948. * Returns a string representation of this event as %%format%%.
  949. */
  950. format(format?: FormatType): string {
  951. if (format == null) { format = "sighash"; }
  952. if (format === "json") {
  953. return JSON.stringify({
  954. type: "event",
  955. anonymous: this.anonymous,
  956. name: this.name,
  957. inputs: this.inputs.map((i) => JSON.parse(i.format(format)))
  958. });
  959. }
  960. const result: Array<string> = [ ];
  961. if (format !== "sighash") { result.push("event"); }
  962. result.push(this.name + joinParams(format, this.inputs));
  963. if (format !== "sighash" && this.anonymous) { result.push("anonymous"); }
  964. return result.join(" ");
  965. }
  966. /**
  967. * Return the topic hash for an event with %%name%% and %%params%%.
  968. */
  969. static getTopicHash(name: string, params?: Array<any>): string {
  970. params = (params || []).map((p) => ParamType.from(p));
  971. const fragment = new EventFragment(_guard, name, params, false);
  972. return fragment.topicHash;
  973. }
  974. /**
  975. * Returns a new **EventFragment** for %%obj%%.
  976. */
  977. static from(obj: any): EventFragment {
  978. if (EventFragment.isFragment(obj)) { return obj; }
  979. if (typeof(obj) === "string") {
  980. try {
  981. return EventFragment.from(lex(obj));
  982. } catch (error) {
  983. assertArgument(false, "invalid event fragment", "obj", obj);
  984. }
  985. } else if (obj instanceof TokenString) {
  986. const name = consumeName("event", obj);
  987. const inputs = consumeParams(obj, true);
  988. const anonymous = !!consumeKeywords(obj, setify([ "anonymous" ])).has("anonymous");
  989. consumeEoi(obj);
  990. return new EventFragment(_guard, name, inputs, anonymous);
  991. }
  992. return new EventFragment(_guard, obj.name,
  993. obj.inputs ? obj.inputs.map((p: any) => ParamType.from(p, true)): [ ], !!obj.anonymous);
  994. }
  995. /**
  996. * Returns ``true`` and provides a type guard if %%value%% is an
  997. * **EventFragment**.
  998. */
  999. static isFragment(value: any): value is EventFragment {
  1000. return (value && value[internal] === EventFragmentInternal);
  1001. }
  1002. }
  1003. /**
  1004. * A Fragment which represents a constructor.
  1005. */
  1006. export class ConstructorFragment extends Fragment {
  1007. /**
  1008. * Whether the constructor can receive an endowment.
  1009. */
  1010. readonly payable!: boolean;
  1011. /**
  1012. * The recommended gas limit for deployment or ``null``.
  1013. */
  1014. readonly gas!: null | bigint;
  1015. /**
  1016. * @private
  1017. */
  1018. constructor(guard: any, type: FragmentType, inputs: ReadonlyArray<ParamType>, payable: boolean, gas: null | bigint) {
  1019. super(guard, type, inputs);
  1020. Object.defineProperty(this, internal, { value: ConstructorFragmentInternal });
  1021. defineProperties<ConstructorFragment>(this, { payable, gas });
  1022. }
  1023. /**
  1024. * Returns a string representation of this constructor as %%format%%.
  1025. */
  1026. format(format?: FormatType): string {
  1027. assert(format != null && format !== "sighash", "cannot format a constructor for sighash",
  1028. "UNSUPPORTED_OPERATION", { operation: "format(sighash)" });
  1029. if (format === "json") {
  1030. return JSON.stringify({
  1031. type: "constructor",
  1032. stateMutability: (this.payable ? "payable": "undefined"),
  1033. payable: this.payable,
  1034. gas: ((this.gas != null) ? this.gas: undefined),
  1035. inputs: this.inputs.map((i) => JSON.parse(i.format(format)))
  1036. });
  1037. }
  1038. const result = [ `constructor${ joinParams(format, this.inputs) }` ];
  1039. if (this.payable) { result.push("payable"); }
  1040. if (this.gas != null) { result.push(`@${ this.gas.toString() }`); }
  1041. return result.join(" ");
  1042. }
  1043. /**
  1044. * Returns a new **ConstructorFragment** for %%obj%%.
  1045. */
  1046. static from(obj: any): ConstructorFragment {
  1047. if (ConstructorFragment.isFragment(obj)) { return obj; }
  1048. if (typeof(obj) === "string") {
  1049. try {
  1050. return ConstructorFragment.from(lex(obj));
  1051. } catch (error) {
  1052. assertArgument(false, "invalid constuctor fragment", "obj", obj);
  1053. }
  1054. } else if (obj instanceof TokenString) {
  1055. consumeKeywords(obj, setify([ "constructor" ]));
  1056. const inputs = consumeParams(obj);
  1057. const payable = !!consumeKeywords(obj, KwVisibDeploy).has("payable");
  1058. const gas = consumeGas(obj);
  1059. consumeEoi(obj);
  1060. return new ConstructorFragment(_guard, "constructor", inputs, payable, gas);
  1061. }
  1062. return new ConstructorFragment(_guard, "constructor",
  1063. obj.inputs ? obj.inputs.map(ParamType.from): [ ],
  1064. !!obj.payable, (obj.gas != null) ? obj.gas: null);
  1065. }
  1066. /**
  1067. * Returns ``true`` and provides a type guard if %%value%% is a
  1068. * **ConstructorFragment**.
  1069. */
  1070. static isFragment(value: any): value is ConstructorFragment {
  1071. return (value && value[internal] === ConstructorFragmentInternal);
  1072. }
  1073. }
  1074. /**
  1075. * A Fragment which represents a method.
  1076. */
  1077. export class FallbackFragment extends Fragment {
  1078. /**
  1079. * If the function can be sent value during invocation.
  1080. */
  1081. readonly payable!: boolean;
  1082. constructor(guard: any, inputs: ReadonlyArray<ParamType>, payable: boolean) {
  1083. super(guard, "fallback", inputs);
  1084. Object.defineProperty(this, internal, { value: FallbackFragmentInternal });
  1085. defineProperties<FallbackFragment>(this, { payable });
  1086. }
  1087. /**
  1088. * Returns a string representation of this fallback as %%format%%.
  1089. */
  1090. format(format?: FormatType): string {
  1091. const type = ((this.inputs.length === 0) ? "receive": "fallback");
  1092. if (format === "json") {
  1093. const stateMutability = (this.payable ? "payable": "nonpayable");
  1094. return JSON.stringify({ type, stateMutability });
  1095. }
  1096. return `${ type }()${ this.payable ? " payable": "" }`;
  1097. }
  1098. /**
  1099. * Returns a new **FallbackFragment** for %%obj%%.
  1100. */
  1101. static from(obj: any): FallbackFragment {
  1102. if (FallbackFragment.isFragment(obj)) { return obj; }
  1103. if (typeof(obj) === "string") {
  1104. try {
  1105. return FallbackFragment.from(lex(obj));
  1106. } catch (error) {
  1107. assertArgument(false, "invalid fallback fragment", "obj", obj);
  1108. }
  1109. } else if (obj instanceof TokenString) {
  1110. const errorObj = obj.toString();
  1111. const topIsValid = obj.peekKeyword(setify([ "fallback", "receive" ]));
  1112. assertArgument(topIsValid, "type must be fallback or receive", "obj", errorObj);
  1113. const type = obj.popKeyword(setify([ "fallback", "receive" ]));
  1114. // receive()
  1115. if (type === "receive") {
  1116. const inputs = consumeParams(obj);
  1117. assertArgument(inputs.length === 0, `receive cannot have arguments`, "obj.inputs", inputs);
  1118. consumeKeywords(obj, setify([ "payable" ]));
  1119. consumeEoi(obj);
  1120. return new FallbackFragment(_guard, [ ], true);
  1121. }
  1122. // fallback() [payable]
  1123. // fallback(bytes) [payable] returns (bytes)
  1124. let inputs = consumeParams(obj);
  1125. if (inputs.length) {
  1126. assertArgument(inputs.length === 1 && inputs[0].type === "bytes",
  1127. "invalid fallback inputs", "obj.inputs",
  1128. inputs.map((i) => i.format("minimal")).join(", "));
  1129. } else {
  1130. inputs = [ ParamType.from("bytes") ];
  1131. }
  1132. const mutability = consumeMutability(obj);
  1133. assertArgument(mutability === "nonpayable" || mutability === "payable", "fallback cannot be constants", "obj.stateMutability", mutability);
  1134. if (consumeKeywords(obj, setify([ "returns" ])).has("returns")) {
  1135. const outputs = consumeParams(obj);
  1136. assertArgument(outputs.length === 1 && outputs[0].type === "bytes",
  1137. "invalid fallback outputs", "obj.outputs",
  1138. outputs.map((i) => i.format("minimal")).join(", "));
  1139. }
  1140. consumeEoi(obj);
  1141. return new FallbackFragment(_guard, inputs, mutability === "payable");
  1142. }
  1143. if (obj.type === "receive") {
  1144. return new FallbackFragment(_guard, [ ], true);
  1145. }
  1146. if (obj.type === "fallback") {
  1147. const inputs = [ ParamType.from("bytes") ];
  1148. const payable = (obj.stateMutability === "payable");
  1149. return new FallbackFragment(_guard, inputs, payable);
  1150. }
  1151. assertArgument(false, "invalid fallback description", "obj", obj);
  1152. }
  1153. /**
  1154. * Returns ``true`` and provides a type guard if %%value%% is a
  1155. * **FallbackFragment**.
  1156. */
  1157. static isFragment(value: any): value is FallbackFragment {
  1158. return (value && value[internal] === FallbackFragmentInternal);
  1159. }
  1160. }
  1161. /**
  1162. * A Fragment which represents a method.
  1163. */
  1164. export class FunctionFragment extends NamedFragment {
  1165. /**
  1166. * If the function is constant (e.g. ``pure`` or ``view`` functions).
  1167. */
  1168. readonly constant!: boolean;
  1169. /**
  1170. * The returned types for the result of calling this function.
  1171. */
  1172. readonly outputs!: ReadonlyArray<ParamType>;
  1173. /**
  1174. * The state mutability (e.g. ``payable``, ``nonpayable``, ``view``
  1175. * or ``pure``)
  1176. */
  1177. readonly stateMutability!: "payable" | "nonpayable" | "view" | "pure";
  1178. /**
  1179. * If the function can be sent value during invocation.
  1180. */
  1181. readonly payable!: boolean;
  1182. /**
  1183. * The recommended gas limit to send when calling this function.
  1184. */
  1185. readonly gas!: null | bigint;
  1186. /**
  1187. * @private
  1188. */
  1189. constructor(guard: any, name: string, stateMutability: "payable" | "nonpayable" | "view" | "pure", inputs: ReadonlyArray<ParamType>, outputs: ReadonlyArray<ParamType>, gas: null | bigint) {
  1190. super(guard, "function", name, inputs);
  1191. Object.defineProperty(this, internal, { value: FunctionFragmentInternal });
  1192. outputs = Object.freeze(outputs.slice());
  1193. const constant = (stateMutability === "view" || stateMutability === "pure");
  1194. const payable = (stateMutability === "payable");
  1195. defineProperties<FunctionFragment>(this, { constant, gas, outputs, payable, stateMutability });
  1196. }
  1197. /**
  1198. * The Function selector.
  1199. */
  1200. get selector(): string {
  1201. return id(this.format("sighash")).substring(0, 10);
  1202. }
  1203. /**
  1204. * Returns a string representation of this function as %%format%%.
  1205. */
  1206. format(format?: FormatType): string {
  1207. if (format == null) { format = "sighash"; }
  1208. if (format === "json") {
  1209. return JSON.stringify({
  1210. type: "function",
  1211. name: this.name,
  1212. constant: this.constant,
  1213. stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability: undefined),
  1214. payable: this.payable,
  1215. gas: ((this.gas != null) ? this.gas: undefined),
  1216. inputs: this.inputs.map((i) => JSON.parse(i.format(format))),
  1217. outputs: this.outputs.map((o) => JSON.parse(o.format(format))),
  1218. });
  1219. }
  1220. const result: Array<string> = [];
  1221. if (format !== "sighash") { result.push("function"); }
  1222. result.push(this.name + joinParams(format, this.inputs));
  1223. if (format !== "sighash") {
  1224. if (this.stateMutability !== "nonpayable") {
  1225. result.push(this.stateMutability);
  1226. }
  1227. if (this.outputs && this.outputs.length) {
  1228. result.push("returns");
  1229. result.push(joinParams(format, this.outputs));
  1230. }
  1231. if (this.gas != null) { result.push(`@${ this.gas.toString() }`); }
  1232. }
  1233. return result.join(" ");
  1234. }
  1235. /**
  1236. * Return the selector for a function with %%name%% and %%params%%.
  1237. */
  1238. static getSelector(name: string, params?: Array<any>): string {
  1239. params = (params || []).map((p) => ParamType.from(p));
  1240. const fragment = new FunctionFragment(_guard, name, "view", params, [ ], null);
  1241. return fragment.selector;
  1242. }
  1243. /**
  1244. * Returns a new **FunctionFragment** for %%obj%%.
  1245. */
  1246. static from(obj: any): FunctionFragment {
  1247. if (FunctionFragment.isFragment(obj)) { return obj; }
  1248. if (typeof(obj) === "string") {
  1249. try {
  1250. return FunctionFragment.from(lex(obj));
  1251. } catch (error) {
  1252. assertArgument(false, "invalid function fragment", "obj", obj);
  1253. }
  1254. } else if (obj instanceof TokenString) {
  1255. const name = consumeName("function", obj);
  1256. const inputs = consumeParams(obj);
  1257. const mutability = consumeMutability(obj);
  1258. let outputs: Array<ParamType> = [ ];
  1259. if (consumeKeywords(obj, setify([ "returns" ])).has("returns")) {
  1260. outputs = consumeParams(obj);
  1261. }
  1262. const gas = consumeGas(obj);
  1263. consumeEoi(obj);
  1264. return new FunctionFragment(_guard, name, mutability, inputs, outputs, gas);
  1265. }
  1266. let stateMutability = obj.stateMutability;
  1267. // Use legacy Solidity ABI logic if stateMutability is missing
  1268. if (stateMutability == null) {
  1269. stateMutability = "payable";
  1270. if (typeof(obj.constant) === "boolean") {
  1271. stateMutability = "view";
  1272. if (!obj.constant) {
  1273. stateMutability = "payable"
  1274. if (typeof(obj.payable) === "boolean" && !obj.payable) {
  1275. stateMutability = "nonpayable";
  1276. }
  1277. }
  1278. } else if (typeof(obj.payable) === "boolean" && !obj.payable) {
  1279. stateMutability = "nonpayable";
  1280. }
  1281. }
  1282. // @TODO: verifyState for stateMutability (e.g. throw if
  1283. // payable: false but stateMutability is "nonpayable")
  1284. return new FunctionFragment(_guard, obj.name, stateMutability,
  1285. obj.inputs ? obj.inputs.map(ParamType.from): [ ],
  1286. obj.outputs ? obj.outputs.map(ParamType.from): [ ],
  1287. (obj.gas != null) ? obj.gas: null);
  1288. }
  1289. /**
  1290. * Returns ``true`` and provides a type guard if %%value%% is a
  1291. * **FunctionFragment**.
  1292. */
  1293. static isFragment(value: any): value is FunctionFragment {
  1294. return (value && value[internal] === FunctionFragmentInternal);
  1295. }
  1296. }
  1297. /**
  1298. * A Fragment which represents a structure.
  1299. */
  1300. export class StructFragment extends NamedFragment {
  1301. /**
  1302. * @private
  1303. */
  1304. constructor(guard: any, name: string, inputs: ReadonlyArray<ParamType>) {
  1305. super(guard, "struct", name, inputs);
  1306. Object.defineProperty(this, internal, { value: StructFragmentInternal });
  1307. }
  1308. /**
  1309. * Returns a string representation of this struct as %%format%%.
  1310. */
  1311. format(): string {
  1312. throw new Error("@TODO");
  1313. }
  1314. /**
  1315. * Returns a new **StructFragment** for %%obj%%.
  1316. */
  1317. static from(obj: any): StructFragment {
  1318. if (typeof(obj) === "string") {
  1319. try {
  1320. return StructFragment.from(lex(obj));
  1321. } catch (error) {
  1322. assertArgument(false, "invalid struct fragment", "obj", obj);
  1323. }
  1324. } else if (obj instanceof TokenString) {
  1325. const name = consumeName("struct", obj);
  1326. const inputs = consumeParams(obj);
  1327. consumeEoi(obj);
  1328. return new StructFragment(_guard, name, inputs);
  1329. }
  1330. return new StructFragment(_guard, obj.name, obj.inputs ? obj.inputs.map(ParamType.from): [ ]);
  1331. }
  1332. // @TODO: fix this return type
  1333. /**
  1334. * Returns ``true`` and provides a type guard if %%value%% is a
  1335. * **StructFragment**.
  1336. */
  1337. static isFragment(value: any): value is FunctionFragment {
  1338. return (value && value[internal] === StructFragmentInternal);
  1339. }
  1340. }