fragments.js 46 KB

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