expectEvent.js 1.5 KB

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