diff --git a/packages/utils/src/transactions/index.ts b/packages/utils/src/transactions/index.ts index c9f6f047d..ce4acb574 100644 --- a/packages/utils/src/transactions/index.ts +++ b/packages/utils/src/transactions/index.ts @@ -1 +1,2 @@ export * from './types' +export * from './utils' diff --git a/packages/utils/src/transactions/utils.ts b/packages/utils/src/transactions/utils.ts new file mode 100644 index 000000000..f5e9ff0f0 --- /dev/null +++ b/packages/utils/src/transactions/utils.ts @@ -0,0 +1,7 @@ +import { OmniTransaction } from './types' + +const isNonNullable = (value: T | null | undefined): value is T => value != null + +export const flattenTransactions = ( + transations: (OmniTransaction | OmniTransaction[] | null | undefined)[] +): OmniTransaction[] => transations.filter(isNonNullable).flat() diff --git a/packages/utils/test/transactions/utils.test.ts b/packages/utils/test/transactions/utils.test.ts new file mode 100644 index 000000000..b03534f73 --- /dev/null +++ b/packages/utils/test/transactions/utils.test.ts @@ -0,0 +1,53 @@ +import fc from 'fast-check' +import { pointArbitrary } from '@layerzerolabs/test-utils' +import { OmniTransaction, flattenTransactions } from '@/transactions' + +describe('transactions/utils', () => { + const nullableArbitrary = fc.constantFrom(null, undefined) + const transactionArbitrary: fc.Arbitrary = fc.record({ + point: pointArbitrary, + data: fc.hexaString(), + }) + + describe('flattenTransactions', () => { + it('should return an empty array when called with an empty array', () => { + expect(flattenTransactions([])).toEqual([]) + }) + + it('should return an empty array when called with an array of nulls and undefineds', () => { + fc.assert( + fc.property(fc.array(nullableArbitrary), (transactions) => { + expect(flattenTransactions(transactions)).toEqual([]) + }) + ) + }) + + it('should remove any nulls or undefineds', () => { + fc.assert( + fc.property(fc.array(fc.oneof(transactionArbitrary, nullableArbitrary)), (transactions) => { + const flattened = flattenTransactions(transactions) + + for (const transaction of flattened) { + expect(transaction).not.toBeNull() + expect(transaction).not.toBeUndefined() + } + }) + ) + }) + + it('should flatten any arrays', () => { + fc.assert( + fc.property( + fc.array(fc.oneof(transactionArbitrary, nullableArbitrary, fc.array(transactionArbitrary))), + (transactions) => { + const flattened = flattenTransactions(transactions) + + for (const transaction of flattened) { + expect(transaction).not.toBeInstanceOf(Array) + } + } + ) + ) + }) + }) +})