-
-
Save belopash/5d61dcce7739f60d55c4faaec0148282 to your computer and use it in GitHub Desktop.
substrate items ordering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const CALL_FIRST = 1 // 1 means TRUE, -1 means FALSE | |
function orderItems(block: Block): Item[] { | |
const items: Item[] = [] | |
for (const call of block.calls) { | |
items.push({ | |
kind: 'call', | |
value: call, | |
}) | |
} | |
for (const event of block.events) { | |
items.push({ | |
kind: 'event', | |
value: event, | |
}) | |
} | |
items.sort((a, b) => { | |
switch (a.kind) { | |
case 'call': | |
switch (b.kind) { | |
case 'call': | |
return compareCalls(a.value, b.value) | |
case 'event': | |
return compareCallEvent(a.value, b.value) | |
} | |
case 'event': | |
switch (b.kind) { | |
case 'call': | |
return compareCallEvent(b.value, a.value) * -1 | |
case 'event': | |
return compareEvents(a.value, b.value) | |
} | |
} | |
}) | |
return items | |
} | |
function compareEvents(a: {index: number}, b: {index: number}) { | |
return a.index - b.index | |
} | |
function compareCalls(a: {extrinsicIndex: number; address: number[]}, b: {extrinsicIndex: number; address: number[]}) { | |
return ( | |
a.extrinsicIndex - b.extrinsicIndex || | |
a.address.length - b.address.length || | |
(a.address.length == 0 ? 0 : last(a.address) - last(b.address)) | |
) | |
} | |
function compareCallEvent( | |
a: {extrinsicIndex: number; address: number[]}, | |
b: {extrinsicIndex?: number; callAddress?: number[]} | |
) { | |
return b.extrinsicIndex == null || b.callAddress == null | |
? 1 | |
: a.extrinsicIndex - b.extrinsicIndex || | |
a.address.length - b.callAddress.length || | |
(a.address.length == 0 ? 0 : last(a.address) - last(b.callAddress)) || | |
CALL_FIRST | |
} | |
function last<T>(arr: T[]): T { | |
assert(arr.length > 0) | |
return arr[arr.length - 1] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment