events.js

  1. import { StrKey } from './strkey';
  2. import { scValToNative } from './scval';
  3. /**
  4. * Converts raw diagnostic or contract events into something with a flatter,
  5. * human-readable, and understandable structure.
  6. *
  7. * @param {xdr.DiagnosticEvent[] | xdr.ContractEvent[]} events either contract
  8. * events or diagnostic events to parse into a friendly format
  9. *
  10. * @returns {SorobanEvent[]} a list of human-readable event structures, where
  11. * each element has the following properties:
  12. * - type: a string of one of 'system', 'contract', 'diagnostic
  13. * - contractId?: optionally, a `C...` encoded strkey
  14. * - topics: a list of {@link scValToNative} invocations on the topics
  15. * - data: similarly, a {@link scValToNative} invocation on the raw event data
  16. */
  17. export function humanizeEvents(events) {
  18. return events.map((e) => {
  19. // A pseudo-instanceof check for xdr.DiagnosticEvent more reliable
  20. // in mixed SDK environments:
  21. if (e.inSuccessfulContractCall) {
  22. return extractEvent(e.event());
  23. }
  24. return extractEvent(e);
  25. });
  26. }
  27. function extractEvent(event) {
  28. return {
  29. ...(typeof event.contractId === 'function' &&
  30. event.contractId() != null && {
  31. contractId: StrKey.encodeContract(event.contractId())
  32. }),
  33. type: event.type().name,
  34. topics: event
  35. .body()
  36. .value()
  37. .topics()
  38. .map((t) => scValToNative(t)),
  39. data: scValToNative(event.body().value().data())
  40. };
  41. }