expectEvent.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const { should, BigNumber } = require('./setup');
  2. const SolidityEvent = require('web3/lib/web3/event.js');
  3. const { ethGetTransactionReceipt } = require('./web3');
  4. function inLogs (logs, eventName, eventArgs = {}) {
  5. const event = logs.find(function (e) {
  6. if (e.event === eventName) {
  7. for (const [k, v] of Object.entries(eventArgs)) {
  8. contains(e.args, k, v);
  9. }
  10. return true;
  11. }
  12. });
  13. should.exist(event);
  14. return event;
  15. }
  16. async function inConstruction (contract, eventName, eventArgs = {}) {
  17. return inTransaction(contract.transactionHash, contract.constructor, eventName, eventArgs);
  18. }
  19. async function inTransaction (txHash, emitter, eventName, eventArgs = {}) {
  20. const receipt = await ethGetTransactionReceipt(txHash);
  21. const logs = decodeLogs(receipt.logs, emitter.events);
  22. return inLogs(logs, eventName, eventArgs);
  23. }
  24. function contains (args, key, value) {
  25. if (isBigNumber(args[key])) {
  26. args[key].should.be.bignumber.equal(value);
  27. } else {
  28. args[key].should.be.equal(value);
  29. }
  30. }
  31. function isBigNumber (object) {
  32. return object.isBigNumber ||
  33. object instanceof BigNumber ||
  34. (object.constructor && object.constructor.name === 'BigNumber');
  35. }
  36. function decodeLogs (logs, events) {
  37. return Array.prototype.concat(...logs.map(log =>
  38. log.topics.filter(topic => topic in events).map(topic => {
  39. const event = new SolidityEvent(null, events[topic], 0);
  40. return event.decode(log);
  41. })
  42. ));
  43. }
  44. module.exports = {
  45. inLogs,
  46. inConstruction,
  47. inTransaction,
  48. };