expectEvent.js 1.6 KB

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