-
Notifications
You must be signed in to change notification settings - Fork 110
/
event-schema.ts
65 lines (60 loc) · 1.74 KB
/
event-schema.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import {
MichelsonV1Expression,
MichelsonV1ExpressionExtended,
ScriptResponse,
} from '@taquito/rpc';
import { deepEqual } from './storage';
export class EventSchema {
constructor(
public readonly tag?: string,
public readonly type?: MichelsonV1ExpressionExtended
) {}
static fromMichelineValue(val: MichelsonV1ExpressionExtended) {
return new EventSchema(
val.annots?.[0],
val.args?.[0] as MichelsonV1ExpressionExtended
);
}
static fromRPCResponse(val: { script: ScriptResponse }): EventSchema[] {
const allEventSchema: EventSchema[] = [];
val.script.code.forEach((code) => {
if (
!('prim' in code) ||
code.prim !== 'code' ||
!('args' in code) ||
!code.args
) {
return;
}
allEventSchema.push(...EventSchema.extractEventsRecursively(code.args));
});
return EventSchema.removeDuplicates(allEventSchema);
}
static removeDuplicates(events: EventSchema[]): EventSchema[] {
const uniqueEvents: EventSchema[] = [];
events.forEach((event) => {
const idx = uniqueEvents.findIndex(
(e) => e.tag === event.tag && deepEqual(e.type, event.type)
);
if (idx === -1) {
uniqueEvents.push(event);
}
});
return uniqueEvents;
}
static extractEventsRecursively(code: MichelsonV1Expression): EventSchema[] {
if (Array.isArray(code)) {
return code.flatMap((c) => EventSchema.extractEventsRecursively(c));
}
if (!('prim' in code)) {
return [];
}
if (code.prim === 'EMIT') {
return [EventSchema.fromMichelineValue(code)];
}
if (!('args' in code) || !code.args) {
return [];
}
return code.args.flatMap((c) => EventSchema.extractEventsRecursively(c));
}
}