fragments.js 44 KB

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