contract.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.Contract = exports.BaseContract = exports.resolveArgs = exports.copyOverrides = void 0;
  4. const index_js_1 = require("../abi/index.js");
  5. const index_js_2 = require("../address/index.js");
  6. // import from provider.ts instead of index.ts to prevent circular dep
  7. // from EtherscanProvider
  8. const provider_js_1 = require("../providers/provider.js");
  9. const index_js_3 = require("../utils/index.js");
  10. const wrappers_js_1 = require("./wrappers.js");
  11. const BN_0 = BigInt(0);
  12. function canCall(value) {
  13. return (value && typeof (value.call) === "function");
  14. }
  15. function canEstimate(value) {
  16. return (value && typeof (value.estimateGas) === "function");
  17. }
  18. function canResolve(value) {
  19. return (value && typeof (value.resolveName) === "function");
  20. }
  21. function canSend(value) {
  22. return (value && typeof (value.sendTransaction) === "function");
  23. }
  24. function getResolver(value) {
  25. if (value != null) {
  26. if (canResolve(value)) {
  27. return value;
  28. }
  29. if (value.provider) {
  30. return value.provider;
  31. }
  32. }
  33. return undefined;
  34. }
  35. class PreparedTopicFilter {
  36. #filter;
  37. fragment;
  38. constructor(contract, fragment, args) {
  39. (0, index_js_3.defineProperties)(this, { fragment });
  40. if (fragment.inputs.length < args.length) {
  41. throw new Error("too many arguments");
  42. }
  43. // Recursively descend into args and resolve any addresses
  44. const runner = getRunner(contract.runner, "resolveName");
  45. const resolver = canResolve(runner) ? runner : null;
  46. this.#filter = (async function () {
  47. const resolvedArgs = await Promise.all(fragment.inputs.map((param, index) => {
  48. const arg = args[index];
  49. if (arg == null) {
  50. return null;
  51. }
  52. return param.walkAsync(args[index], (type, value) => {
  53. if (type === "address") {
  54. if (Array.isArray(value)) {
  55. return Promise.all(value.map((v) => (0, index_js_2.resolveAddress)(v, resolver)));
  56. }
  57. return (0, index_js_2.resolveAddress)(value, resolver);
  58. }
  59. return value;
  60. });
  61. }));
  62. return contract.interface.encodeFilterTopics(fragment, resolvedArgs);
  63. })();
  64. }
  65. getTopicFilter() {
  66. return this.#filter;
  67. }
  68. }
  69. // A = Arguments passed in as a tuple
  70. // R = The result type of the call (i.e. if only one return type,
  71. // the qualified type, otherwise Result)
  72. // D = The type the default call will return (i.e. R for view/pure,
  73. // TransactionResponse otherwise)
  74. //export interface ContractMethod<A extends Array<any> = Array<any>, R = any, D extends R | ContractTransactionResponse = ContractTransactionResponse> {
  75. function getRunner(value, feature) {
  76. if (value == null) {
  77. return null;
  78. }
  79. if (typeof (value[feature]) === "function") {
  80. return value;
  81. }
  82. if (value.provider && typeof (value.provider[feature]) === "function") {
  83. return value.provider;
  84. }
  85. return null;
  86. }
  87. function getProvider(value) {
  88. if (value == null) {
  89. return null;
  90. }
  91. return value.provider || null;
  92. }
  93. /**
  94. * @_ignore:
  95. */
  96. async function copyOverrides(arg, allowed) {
  97. // Make sure the overrides passed in are a valid overrides object
  98. const _overrides = index_js_1.Typed.dereference(arg, "overrides");
  99. (0, index_js_3.assertArgument)(typeof (_overrides) === "object", "invalid overrides parameter", "overrides", arg);
  100. // Create a shallow copy (we'll deep-ify anything needed during normalizing)
  101. const overrides = (0, provider_js_1.copyRequest)(_overrides);
  102. (0, index_js_3.assertArgument)(overrides.to == null || (allowed || []).indexOf("to") >= 0, "cannot override to", "overrides.to", overrides.to);
  103. (0, index_js_3.assertArgument)(overrides.data == null || (allowed || []).indexOf("data") >= 0, "cannot override data", "overrides.data", overrides.data);
  104. // Resolve any from
  105. if (overrides.from) {
  106. overrides.from = overrides.from;
  107. }
  108. return overrides;
  109. }
  110. exports.copyOverrides = copyOverrides;
  111. /**
  112. * @_ignore:
  113. */
  114. async function resolveArgs(_runner, inputs, args) {
  115. // Recursively descend into args and resolve any addresses
  116. const runner = getRunner(_runner, "resolveName");
  117. const resolver = canResolve(runner) ? runner : null;
  118. return await Promise.all(inputs.map((param, index) => {
  119. return param.walkAsync(args[index], (type, value) => {
  120. value = index_js_1.Typed.dereference(value, type);
  121. if (type === "address") {
  122. return (0, index_js_2.resolveAddress)(value, resolver);
  123. }
  124. return value;
  125. });
  126. }));
  127. }
  128. exports.resolveArgs = resolveArgs;
  129. function buildWrappedFallback(contract) {
  130. const populateTransaction = async function (overrides) {
  131. // If an overrides was passed in, copy it and normalize the values
  132. const tx = (await copyOverrides(overrides, ["data"]));
  133. tx.to = await contract.getAddress();
  134. if (tx.from) {
  135. tx.from = await (0, index_js_2.resolveAddress)(tx.from, getResolver(contract.runner));
  136. }
  137. const iface = contract.interface;
  138. const noValue = ((0, index_js_3.getBigInt)((tx.value || BN_0), "overrides.value") === BN_0);
  139. const noData = ((tx.data || "0x") === "0x");
  140. if (iface.fallback && !iface.fallback.payable && iface.receive && !noData && !noValue) {
  141. (0, index_js_3.assertArgument)(false, "cannot send data to receive or send value to non-payable fallback", "overrides", overrides);
  142. }
  143. (0, index_js_3.assertArgument)(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data);
  144. // Only allow payable contracts to set non-zero value
  145. const payable = iface.receive || (iface.fallback && iface.fallback.payable);
  146. (0, index_js_3.assertArgument)(payable || noValue, "cannot send value to non-payable fallback", "overrides.value", tx.value);
  147. // Only allow fallback contracts to set non-empty data
  148. (0, index_js_3.assertArgument)(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data);
  149. return tx;
  150. };
  151. const staticCall = async function (overrides) {
  152. const runner = getRunner(contract.runner, "call");
  153. (0, index_js_3.assert)(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" });
  154. const tx = await populateTransaction(overrides);
  155. try {
  156. return await runner.call(tx);
  157. }
  158. catch (error) {
  159. if ((0, index_js_3.isCallException)(error) && error.data) {
  160. throw contract.interface.makeError(error.data, tx);
  161. }
  162. throw error;
  163. }
  164. };
  165. const send = async function (overrides) {
  166. const runner = contract.runner;
  167. (0, index_js_3.assert)(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" });
  168. const tx = await runner.sendTransaction(await populateTransaction(overrides));
  169. const provider = getProvider(contract.runner);
  170. // @TODO: the provider can be null; make a custom dummy provider that will throw a
  171. // meaningful error
  172. return new wrappers_js_1.ContractTransactionResponse(contract.interface, provider, tx);
  173. };
  174. const estimateGas = async function (overrides) {
  175. const runner = getRunner(contract.runner, "estimateGas");
  176. (0, index_js_3.assert)(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" });
  177. return await runner.estimateGas(await populateTransaction(overrides));
  178. };
  179. const method = async (overrides) => {
  180. return await send(overrides);
  181. };
  182. (0, index_js_3.defineProperties)(method, {
  183. _contract: contract,
  184. estimateGas,
  185. populateTransaction,
  186. send, staticCall
  187. });
  188. return method;
  189. }
  190. function buildWrappedMethod(contract, key) {
  191. const getFragment = function (...args) {
  192. const fragment = contract.interface.getFunction(key, args);
  193. (0, index_js_3.assert)(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", {
  194. operation: "fragment",
  195. info: { key, args }
  196. });
  197. return fragment;
  198. };
  199. const populateTransaction = async function (...args) {
  200. const fragment = getFragment(...args);
  201. // If an overrides was passed in, copy it and normalize the values
  202. let overrides = {};
  203. if (fragment.inputs.length + 1 === args.length) {
  204. overrides = await copyOverrides(args.pop());
  205. if (overrides.from) {
  206. overrides.from = await (0, index_js_2.resolveAddress)(overrides.from, getResolver(contract.runner));
  207. }
  208. }
  209. if (fragment.inputs.length !== args.length) {
  210. throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");
  211. }
  212. const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args);
  213. return Object.assign({}, overrides, await (0, index_js_3.resolveProperties)({
  214. to: contract.getAddress(),
  215. data: contract.interface.encodeFunctionData(fragment, resolvedArgs)
  216. }));
  217. };
  218. const staticCall = async function (...args) {
  219. const result = await staticCallResult(...args);
  220. if (result.length === 1) {
  221. return result[0];
  222. }
  223. return result;
  224. };
  225. const send = async function (...args) {
  226. const runner = contract.runner;
  227. (0, index_js_3.assert)(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" });
  228. const tx = await runner.sendTransaction(await populateTransaction(...args));
  229. const provider = getProvider(contract.runner);
  230. // @TODO: the provider can be null; make a custom dummy provider that will throw a
  231. // meaningful error
  232. return new wrappers_js_1.ContractTransactionResponse(contract.interface, provider, tx);
  233. };
  234. const estimateGas = async function (...args) {
  235. const runner = getRunner(contract.runner, "estimateGas");
  236. (0, index_js_3.assert)(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" });
  237. return await runner.estimateGas(await populateTransaction(...args));
  238. };
  239. const staticCallResult = async function (...args) {
  240. const runner = getRunner(contract.runner, "call");
  241. (0, index_js_3.assert)(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" });
  242. const tx = await populateTransaction(...args);
  243. let result = "0x";
  244. try {
  245. result = await runner.call(tx);
  246. }
  247. catch (error) {
  248. if ((0, index_js_3.isCallException)(error) && error.data) {
  249. throw contract.interface.makeError(error.data, tx);
  250. }
  251. throw error;
  252. }
  253. const fragment = getFragment(...args);
  254. return contract.interface.decodeFunctionResult(fragment, result);
  255. };
  256. const method = async (...args) => {
  257. const fragment = getFragment(...args);
  258. if (fragment.constant) {
  259. return await staticCall(...args);
  260. }
  261. return await send(...args);
  262. };
  263. (0, index_js_3.defineProperties)(method, {
  264. name: contract.interface.getFunctionName(key),
  265. _contract: contract, _key: key,
  266. getFragment,
  267. estimateGas,
  268. populateTransaction,
  269. send, staticCall, staticCallResult,
  270. });
  271. // Only works on non-ambiguous keys (refined fragment is always non-ambiguous)
  272. Object.defineProperty(method, "fragment", {
  273. configurable: false,
  274. enumerable: true,
  275. get: () => {
  276. const fragment = contract.interface.getFunction(key);
  277. (0, index_js_3.assert)(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", {
  278. operation: "fragment",
  279. info: { key }
  280. });
  281. return fragment;
  282. }
  283. });
  284. return method;
  285. }
  286. function buildWrappedEvent(contract, key) {
  287. const getFragment = function (...args) {
  288. const fragment = contract.interface.getEvent(key, args);
  289. (0, index_js_3.assert)(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", {
  290. operation: "fragment",
  291. info: { key, args }
  292. });
  293. return fragment;
  294. };
  295. const method = function (...args) {
  296. return new PreparedTopicFilter(contract, getFragment(...args), args);
  297. };
  298. (0, index_js_3.defineProperties)(method, {
  299. name: contract.interface.getEventName(key),
  300. _contract: contract, _key: key,
  301. getFragment
  302. });
  303. // Only works on non-ambiguous keys (refined fragment is always non-ambiguous)
  304. Object.defineProperty(method, "fragment", {
  305. configurable: false,
  306. enumerable: true,
  307. get: () => {
  308. const fragment = contract.interface.getEvent(key);
  309. (0, index_js_3.assert)(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", {
  310. operation: "fragment",
  311. info: { key }
  312. });
  313. return fragment;
  314. }
  315. });
  316. return method;
  317. }
  318. // The combination of TypeScrype, Private Fields and Proxies makes
  319. // the world go boom; so we hide variables with some trickery keeping
  320. // a symbol attached to each BaseContract which its sub-class (even
  321. // via a Proxy) can reach and use to look up its internal values.
  322. const internal = Symbol.for("_ethersInternal_contract");
  323. const internalValues = new WeakMap();
  324. function setInternal(contract, values) {
  325. internalValues.set(contract[internal], values);
  326. }
  327. function getInternal(contract) {
  328. return internalValues.get(contract[internal]);
  329. }
  330. function isDeferred(value) {
  331. return (value && typeof (value) === "object" && ("getTopicFilter" in value) &&
  332. (typeof (value.getTopicFilter) === "function") && value.fragment);
  333. }
  334. async function getSubInfo(contract, event) {
  335. let topics;
  336. let fragment = null;
  337. // Convert named events to topicHash and get the fragment for
  338. // events which need deconstructing.
  339. if (Array.isArray(event)) {
  340. const topicHashify = function (name) {
  341. if ((0, index_js_3.isHexString)(name, 32)) {
  342. return name;
  343. }
  344. const fragment = contract.interface.getEvent(name);
  345. (0, index_js_3.assertArgument)(fragment, "unknown fragment", "name", name);
  346. return fragment.topicHash;
  347. };
  348. // Array of Topics and Names; e.g. `[ "0x1234...89ab", "Transfer(address)" ]`
  349. topics = event.map((e) => {
  350. if (e == null) {
  351. return null;
  352. }
  353. if (Array.isArray(e)) {
  354. return e.map(topicHashify);
  355. }
  356. return topicHashify(e);
  357. });
  358. }
  359. else if (event === "*") {
  360. topics = [null];
  361. }
  362. else if (typeof (event) === "string") {
  363. if ((0, index_js_3.isHexString)(event, 32)) {
  364. // Topic Hash
  365. topics = [event];
  366. }
  367. else {
  368. // Name or Signature; e.g. `"Transfer", `"Transfer(address)"`
  369. fragment = contract.interface.getEvent(event);
  370. (0, index_js_3.assertArgument)(fragment, "unknown fragment", "event", event);
  371. topics = [fragment.topicHash];
  372. }
  373. }
  374. else if (isDeferred(event)) {
  375. // Deferred Topic Filter; e.g. `contract.filter.Transfer(from)`
  376. topics = await event.getTopicFilter();
  377. }
  378. else if ("fragment" in event) {
  379. // ContractEvent; e.g. `contract.filter.Transfer`
  380. fragment = event.fragment;
  381. topics = [fragment.topicHash];
  382. }
  383. else {
  384. (0, index_js_3.assertArgument)(false, "unknown event name", "event", event);
  385. }
  386. // Normalize topics and sort TopicSets
  387. topics = topics.map((t) => {
  388. if (t == null) {
  389. return null;
  390. }
  391. if (Array.isArray(t)) {
  392. const items = Array.from(new Set(t.map((t) => t.toLowerCase())).values());
  393. if (items.length === 1) {
  394. return items[0];
  395. }
  396. items.sort();
  397. return items;
  398. }
  399. return t.toLowerCase();
  400. });
  401. const tag = topics.map((t) => {
  402. if (t == null) {
  403. return "null";
  404. }
  405. if (Array.isArray(t)) {
  406. return t.join("|");
  407. }
  408. return t;
  409. }).join("&");
  410. return { fragment, tag, topics };
  411. }
  412. async function hasSub(contract, event) {
  413. const { subs } = getInternal(contract);
  414. return subs.get((await getSubInfo(contract, event)).tag) || null;
  415. }
  416. async function getSub(contract, operation, event) {
  417. // Make sure our runner can actually subscribe to events
  418. const provider = getProvider(contract.runner);
  419. (0, index_js_3.assert)(provider, "contract runner does not support subscribing", "UNSUPPORTED_OPERATION", { operation });
  420. const { fragment, tag, topics } = await getSubInfo(contract, event);
  421. const { addr, subs } = getInternal(contract);
  422. let sub = subs.get(tag);
  423. if (!sub) {
  424. const address = (addr ? addr : contract);
  425. const filter = { address, topics };
  426. const listener = (log) => {
  427. let foundFragment = fragment;
  428. if (foundFragment == null) {
  429. try {
  430. foundFragment = contract.interface.getEvent(log.topics[0]);
  431. }
  432. catch (error) { }
  433. }
  434. // If fragment is null, we do not deconstruct the args to emit
  435. if (foundFragment) {
  436. const _foundFragment = foundFragment;
  437. const args = fragment ? contract.interface.decodeEventLog(fragment, log.data, log.topics) : [];
  438. emit(contract, event, args, (listener) => {
  439. return new wrappers_js_1.ContractEventPayload(contract, listener, event, _foundFragment, log);
  440. });
  441. }
  442. else {
  443. emit(contract, event, [], (listener) => {
  444. return new wrappers_js_1.ContractUnknownEventPayload(contract, listener, event, log);
  445. });
  446. }
  447. };
  448. let starting = [];
  449. const start = () => {
  450. if (starting.length) {
  451. return;
  452. }
  453. starting.push(provider.on(filter, listener));
  454. };
  455. const stop = async () => {
  456. if (starting.length == 0) {
  457. return;
  458. }
  459. let started = starting;
  460. starting = [];
  461. await Promise.all(started);
  462. provider.off(filter, listener);
  463. };
  464. sub = { tag, listeners: [], start, stop };
  465. subs.set(tag, sub);
  466. }
  467. return sub;
  468. }
  469. // We use this to ensure one emit resolves before firing the next to
  470. // ensure correct ordering (note this cannot throw and just adds the
  471. // notice to the event queu using setTimeout).
  472. let lastEmit = Promise.resolve();
  473. async function _emit(contract, event, args, payloadFunc) {
  474. await lastEmit;
  475. const sub = await hasSub(contract, event);
  476. if (!sub) {
  477. return false;
  478. }
  479. const count = sub.listeners.length;
  480. sub.listeners = sub.listeners.filter(({ listener, once }) => {
  481. const passArgs = Array.from(args);
  482. if (payloadFunc) {
  483. passArgs.push(payloadFunc(once ? null : listener));
  484. }
  485. try {
  486. listener.call(contract, ...passArgs);
  487. }
  488. catch (error) { }
  489. return !once;
  490. });
  491. if (sub.listeners.length === 0) {
  492. sub.stop();
  493. getInternal(contract).subs.delete(sub.tag);
  494. }
  495. return (count > 0);
  496. }
  497. async function emit(contract, event, args, payloadFunc) {
  498. try {
  499. await lastEmit;
  500. }
  501. catch (error) { }
  502. const resultPromise = _emit(contract, event, args, payloadFunc);
  503. lastEmit = resultPromise;
  504. return await resultPromise;
  505. }
  506. const passProperties = ["then"];
  507. class BaseContract {
  508. /**
  509. * The target to connect to.
  510. *
  511. * This can be an address, ENS name or any [[Addressable]], such as
  512. * another contract. To get the resovled address, use the ``getAddress``
  513. * method.
  514. */
  515. target;
  516. /**
  517. * The contract Interface.
  518. */
  519. interface;
  520. /**
  521. * The connected runner. This is generally a [[Provider]] or a
  522. * [[Signer]], which dictates what operations are supported.
  523. *
  524. * For example, a **Contract** connected to a [[Provider]] may
  525. * only execute read-only operations.
  526. */
  527. runner;
  528. /**
  529. * All the Events available on this contract.
  530. */
  531. filters;
  532. /**
  533. * @_ignore:
  534. */
  535. [internal];
  536. /**
  537. * The fallback or receive function if any.
  538. */
  539. fallback;
  540. /**
  541. * Creates a new contract connected to %%target%% with the %%abi%% and
  542. * optionally connected to a %%runner%% to perform operations on behalf
  543. * of.
  544. */
  545. constructor(target, abi, runner, _deployTx) {
  546. (0, index_js_3.assertArgument)(typeof (target) === "string" || (0, index_js_2.isAddressable)(target), "invalid value for Contract target", "target", target);
  547. if (runner == null) {
  548. runner = null;
  549. }
  550. const iface = index_js_1.Interface.from(abi);
  551. (0, index_js_3.defineProperties)(this, { target, runner, interface: iface });
  552. Object.defineProperty(this, internal, { value: {} });
  553. let addrPromise;
  554. let addr = null;
  555. let deployTx = null;
  556. if (_deployTx) {
  557. const provider = getProvider(runner);
  558. // @TODO: the provider can be null; make a custom dummy provider that will throw a
  559. // meaningful error
  560. deployTx = new wrappers_js_1.ContractTransactionResponse(this.interface, provider, _deployTx);
  561. }
  562. let subs = new Map();
  563. // Resolve the target as the address
  564. if (typeof (target) === "string") {
  565. if ((0, index_js_3.isHexString)(target)) {
  566. addr = target;
  567. addrPromise = Promise.resolve(target);
  568. }
  569. else {
  570. const resolver = getRunner(runner, "resolveName");
  571. if (!canResolve(resolver)) {
  572. throw (0, index_js_3.makeError)("contract runner does not support name resolution", "UNSUPPORTED_OPERATION", {
  573. operation: "resolveName"
  574. });
  575. }
  576. addrPromise = resolver.resolveName(target).then((addr) => {
  577. if (addr == null) {
  578. throw (0, index_js_3.makeError)("an ENS name used for a contract target must be correctly configured", "UNCONFIGURED_NAME", {
  579. value: target
  580. });
  581. }
  582. getInternal(this).addr = addr;
  583. return addr;
  584. });
  585. }
  586. }
  587. else {
  588. addrPromise = target.getAddress().then((addr) => {
  589. if (addr == null) {
  590. throw new Error("TODO");
  591. }
  592. getInternal(this).addr = addr;
  593. return addr;
  594. });
  595. }
  596. // Set our private values
  597. setInternal(this, { addrPromise, addr, deployTx, subs });
  598. // Add the event filters
  599. const filters = new Proxy({}, {
  600. get: (target, prop, receiver) => {
  601. // Pass important checks (like `then` for Promise) through
  602. if (typeof (prop) === "symbol" || passProperties.indexOf(prop) >= 0) {
  603. return Reflect.get(target, prop, receiver);
  604. }
  605. try {
  606. return this.getEvent(prop);
  607. }
  608. catch (error) {
  609. if (!(0, index_js_3.isError)(error, "INVALID_ARGUMENT") || error.argument !== "key") {
  610. throw error;
  611. }
  612. }
  613. return undefined;
  614. },
  615. has: (target, prop) => {
  616. // Pass important checks (like `then` for Promise) through
  617. if (passProperties.indexOf(prop) >= 0) {
  618. return Reflect.has(target, prop);
  619. }
  620. return Reflect.has(target, prop) || this.interface.hasEvent(String(prop));
  621. }
  622. });
  623. (0, index_js_3.defineProperties)(this, { filters });
  624. (0, index_js_3.defineProperties)(this, {
  625. fallback: ((iface.receive || iface.fallback) ? (buildWrappedFallback(this)) : null)
  626. });
  627. // Return a Proxy that will respond to functions
  628. return new Proxy(this, {
  629. get: (target, prop, receiver) => {
  630. if (typeof (prop) === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) {
  631. return Reflect.get(target, prop, receiver);
  632. }
  633. // Undefined properties should return undefined
  634. try {
  635. return target.getFunction(prop);
  636. }
  637. catch (error) {
  638. if (!(0, index_js_3.isError)(error, "INVALID_ARGUMENT") || error.argument !== "key") {
  639. throw error;
  640. }
  641. }
  642. return undefined;
  643. },
  644. has: (target, prop) => {
  645. if (typeof (prop) === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) {
  646. return Reflect.has(target, prop);
  647. }
  648. return target.interface.hasFunction(prop);
  649. }
  650. });
  651. }
  652. /**
  653. * Return a new Contract instance with the same target and ABI, but
  654. * a different %%runner%%.
  655. */
  656. connect(runner) {
  657. return new BaseContract(this.target, this.interface, runner);
  658. }
  659. /**
  660. * Return a new Contract instance with the same ABI and runner, but
  661. * a different %%target%%.
  662. */
  663. attach(target) {
  664. return new BaseContract(target, this.interface, this.runner);
  665. }
  666. /**
  667. * Return the resolved address of this Contract.
  668. */
  669. async getAddress() { return await getInternal(this).addrPromise; }
  670. /**
  671. * Return the deployed bytecode or null if no bytecode is found.
  672. */
  673. async getDeployedCode() {
  674. const provider = getProvider(this.runner);
  675. (0, index_js_3.assert)(provider, "runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "getDeployedCode" });
  676. const code = await provider.getCode(await this.getAddress());
  677. if (code === "0x") {
  678. return null;
  679. }
  680. return code;
  681. }
  682. /**
  683. * Resolve to this Contract once the bytecode has been deployed, or
  684. * resolve immediately if already deployed.
  685. */
  686. async waitForDeployment() {
  687. // We have the deployement transaction; just use that (throws if deployement fails)
  688. const deployTx = this.deploymentTransaction();
  689. if (deployTx) {
  690. await deployTx.wait();
  691. return this;
  692. }
  693. // Check for code
  694. const code = await this.getDeployedCode();
  695. if (code != null) {
  696. return this;
  697. }
  698. // Make sure we can subscribe to a provider event
  699. const provider = getProvider(this.runner);
  700. (0, index_js_3.assert)(provider != null, "contract runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "waitForDeployment" });
  701. return new Promise((resolve, reject) => {
  702. const checkCode = async () => {
  703. try {
  704. const code = await this.getDeployedCode();
  705. if (code != null) {
  706. return resolve(this);
  707. }
  708. provider.once("block", checkCode);
  709. }
  710. catch (error) {
  711. reject(error);
  712. }
  713. };
  714. checkCode();
  715. });
  716. }
  717. /**
  718. * Return the transaction used to deploy this contract.
  719. *
  720. * This is only available if this instance was returned from a
  721. * [[ContractFactory]].
  722. */
  723. deploymentTransaction() {
  724. return getInternal(this).deployTx;
  725. }
  726. /**
  727. * Return the function for a given name. This is useful when a contract
  728. * method name conflicts with a JavaScript name such as ``prototype`` or
  729. * when using a Contract programatically.
  730. */
  731. getFunction(key) {
  732. if (typeof (key) !== "string") {
  733. key = key.format();
  734. }
  735. const func = buildWrappedMethod(this, key);
  736. return func;
  737. }
  738. /**
  739. * Return the event for a given name. This is useful when a contract
  740. * event name conflicts with a JavaScript name such as ``prototype`` or
  741. * when using a Contract programatically.
  742. */
  743. getEvent(key) {
  744. if (typeof (key) !== "string") {
  745. key = key.format();
  746. }
  747. return buildWrappedEvent(this, key);
  748. }
  749. /**
  750. * @_ignore:
  751. */
  752. async queryTransaction(hash) {
  753. throw new Error("@TODO");
  754. }
  755. /*
  756. // @TODO: this is a non-backwards compatible change, but will be added
  757. // in v7 and in a potential SmartContract class in an upcoming
  758. // v6 release
  759. async getTransactionReceipt(hash: string): Promise<null | ContractTransactionReceipt> {
  760. const provider = getProvider(this.runner);
  761. assert(provider, "contract runner does not have a provider",
  762. "UNSUPPORTED_OPERATION", { operation: "queryTransaction" });
  763. const receipt = await provider.getTransactionReceipt(hash);
  764. if (receipt == null) { return null; }
  765. return new ContractTransactionReceipt(this.interface, provider, receipt);
  766. }
  767. */
  768. /**
  769. * Provide historic access to event data for %%event%% in the range
  770. * %%fromBlock%% (default: ``0``) to %%toBlock%% (default: ``"latest"``)
  771. * inclusive.
  772. */
  773. async queryFilter(event, fromBlock, toBlock) {
  774. if (fromBlock == null) {
  775. fromBlock = 0;
  776. }
  777. if (toBlock == null) {
  778. toBlock = "latest";
  779. }
  780. const { addr, addrPromise } = getInternal(this);
  781. const address = (addr ? addr : (await addrPromise));
  782. const { fragment, topics } = await getSubInfo(this, event);
  783. const filter = { address, topics, fromBlock, toBlock };
  784. const provider = getProvider(this.runner);
  785. (0, index_js_3.assert)(provider, "contract runner does not have a provider", "UNSUPPORTED_OPERATION", { operation: "queryFilter" });
  786. return (await provider.getLogs(filter)).map((log) => {
  787. let foundFragment = fragment;
  788. if (foundFragment == null) {
  789. try {
  790. foundFragment = this.interface.getEvent(log.topics[0]);
  791. }
  792. catch (error) { }
  793. }
  794. if (foundFragment) {
  795. try {
  796. return new wrappers_js_1.EventLog(log, this.interface, foundFragment);
  797. }
  798. catch (error) {
  799. return new wrappers_js_1.UndecodedEventLog(log, error);
  800. }
  801. }
  802. return new provider_js_1.Log(log, provider);
  803. });
  804. }
  805. /**
  806. * Add an event %%listener%% for the %%event%%.
  807. */
  808. async on(event, listener) {
  809. const sub = await getSub(this, "on", event);
  810. sub.listeners.push({ listener, once: false });
  811. sub.start();
  812. return this;
  813. }
  814. /**
  815. * Add an event %%listener%% for the %%event%%, but remove the listener
  816. * after it is fired once.
  817. */
  818. async once(event, listener) {
  819. const sub = await getSub(this, "once", event);
  820. sub.listeners.push({ listener, once: true });
  821. sub.start();
  822. return this;
  823. }
  824. /**
  825. * Emit an %%event%% calling all listeners with %%args%%.
  826. *
  827. * Resolves to ``true`` if any listeners were called.
  828. */
  829. async emit(event, ...args) {
  830. return await emit(this, event, args, null);
  831. }
  832. /**
  833. * Resolves to the number of listeners of %%event%% or the total number
  834. * of listeners if unspecified.
  835. */
  836. async listenerCount(event) {
  837. if (event) {
  838. const sub = await hasSub(this, event);
  839. if (!sub) {
  840. return 0;
  841. }
  842. return sub.listeners.length;
  843. }
  844. const { subs } = getInternal(this);
  845. let total = 0;
  846. for (const { listeners } of subs.values()) {
  847. total += listeners.length;
  848. }
  849. return total;
  850. }
  851. /**
  852. * Resolves to the listeners subscribed to %%event%% or all listeners
  853. * if unspecified.
  854. */
  855. async listeners(event) {
  856. if (event) {
  857. const sub = await hasSub(this, event);
  858. if (!sub) {
  859. return [];
  860. }
  861. return sub.listeners.map(({ listener }) => listener);
  862. }
  863. const { subs } = getInternal(this);
  864. let result = [];
  865. for (const { listeners } of subs.values()) {
  866. result = result.concat(listeners.map(({ listener }) => listener));
  867. }
  868. return result;
  869. }
  870. /**
  871. * Remove the %%listener%% from the listeners for %%event%% or remove
  872. * all listeners if unspecified.
  873. */
  874. async off(event, listener) {
  875. const sub = await hasSub(this, event);
  876. if (!sub) {
  877. return this;
  878. }
  879. if (listener) {
  880. const index = sub.listeners.map(({ listener }) => listener).indexOf(listener);
  881. if (index >= 0) {
  882. sub.listeners.splice(index, 1);
  883. }
  884. }
  885. if (listener == null || sub.listeners.length === 0) {
  886. sub.stop();
  887. getInternal(this).subs.delete(sub.tag);
  888. }
  889. return this;
  890. }
  891. /**
  892. * Remove all the listeners for %%event%% or remove all listeners if
  893. * unspecified.
  894. */
  895. async removeAllListeners(event) {
  896. if (event) {
  897. const sub = await hasSub(this, event);
  898. if (!sub) {
  899. return this;
  900. }
  901. sub.stop();
  902. getInternal(this).subs.delete(sub.tag);
  903. }
  904. else {
  905. const { subs } = getInternal(this);
  906. for (const { tag, stop } of subs.values()) {
  907. stop();
  908. subs.delete(tag);
  909. }
  910. }
  911. return this;
  912. }
  913. /**
  914. * Alias for [on].
  915. */
  916. async addListener(event, listener) {
  917. return await this.on(event, listener);
  918. }
  919. /**
  920. * Alias for [off].
  921. */
  922. async removeListener(event, listener) {
  923. return await this.off(event, listener);
  924. }
  925. /**
  926. * Create a new Class for the %%abi%%.
  927. */
  928. static buildClass(abi) {
  929. class CustomContract extends BaseContract {
  930. constructor(address, runner = null) {
  931. super(address, abi, runner);
  932. }
  933. }
  934. return CustomContract;
  935. }
  936. ;
  937. /**
  938. * Create a new BaseContract with a specified Interface.
  939. */
  940. static from(target, abi, runner) {
  941. if (runner == null) {
  942. runner = null;
  943. }
  944. const contract = new this(target, abi, runner);
  945. return contract;
  946. }
  947. }
  948. exports.BaseContract = BaseContract;
  949. function _ContractBase() {
  950. return BaseContract;
  951. }
  952. /**
  953. * A [[BaseContract]] with no type guards on its methods or events.
  954. */
  955. class Contract extends _ContractBase() {
  956. }
  957. exports.Contract = Contract;
  958. //# sourceMappingURL=contract.js.map