it('should work', async () => {
            await fc.assert(
                fc.asyncProperty(keypairArbitrary, keypairArbitrary, async (sender, recipient) => {
                    const transfer = SystemProgram.transfer({
                        fromPubkey: sender.publicKey,
                        toPubkey: recipient.publicKey,
                        lamports: 49,
                    })

                    const transaction = new Transaction().add(transfer)

                    // Transaction in Solana require a recent block hash to be set in order for them to be serialized
                    transaction.recentBlockhash = 'EETubP5AKHgjPAhzPAFcb8BAY1hMH639CWCFTqi3hq1k'

                    // Transactions in Solana require a fee payer to be set in order for them to be serialized
                    transaction.feePayer = sender.publicKey

                    // First we serialize the transaction
                    const serializedTransaction = serializeTransactionMessage(transaction)
                    // Then we deserialize it
                    const deserializedTransaction = deserializeTransactionMessage(serializedTransaction)
                    // And check that the fields match the original transaction
                    //
                    // The reason why we don't compare the transactions directly is that the signers will not match
                    // after deserialization (the signers get stripped out of the original transaction)
                    expect(deserializedTransaction.instructions).toEqual(transaction.instructions)
                    expect(deserializedTransaction.recentBlockhash).toEqual(transaction.recentBlockhash)
                    expect(deserializedTransaction.feePayer).toEqual(transaction.feePayer)

                    // Now we serialize the deserialized transaction again and check that it fully matches the serialized transaction
                    const reserializedTransaction = serializeTransactionMessage(deserializedTransaction)
                    expect(reserializedTransaction).toEqual(serializedTransaction)
                })
            )
        })

Summary: Serialization and deserialization of Solana transactions should preserve instructions, recent blockhash, and fee payer, and reserialization should match the original serialized transaction.


unknown

it('should add a feePayer and the latest block hash to the transaction', async () => {
            await fc.assert(
                fc.asyncProperty(
                    endpointArbitrary,
                    solanaAddressArbitrary,
                    keypairArbitrary,
                    keypairArbitrary,
                    solanaBlockhashArbitrary,
                    async (eid, address, sender, recipient, blockhash) => {
                        class TestOmniSDK extends OmniSDK {
                            test() {
                                const transfer = SystemProgram.transfer({
                                    fromPubkey: sender.publicKey,
                                    toPubkey: recipient.publicKey,
                                    lamports: 49,
                                })
                                const transaction = new Transaction().add(transfer)

                                return this.createTransaction(transaction)
                            }
                        }

                        const connection = new Connection('http://soyllama.com')
                        jest.spyOn(connection, 'getLatestBlockhash').mockResolvedValue({
                            blockhash,
                            lastValidBlockHeight: NaN,
                        })

                        const sdk = new TestOmniSDK(connection, { eid, address }, sender.publicKey)
                        const omniTransaction = await sdk.test()

                        expect(omniTransaction).toEqual({
                            data: expect.any(String),
                            point: { eid, address },
                        })
                    }
                )
            )
        })

Summary: Adds a feePayer and the latest block hash to a transaction and verifies the transaction data and point properties.


it('should reject if urlFactory throws', async () => {
            await fc.assert(
                fc.asyncProperty(errorArbitrary, endpointArbitrary, async (error, eid) => {
                    const urlFactory = jest.fn().mockImplementation(() => {
                        throw error
                    })
                    const providerFactory = createConnectionFactory(urlFactory)

                    await expect(providerFactory(eid)).rejects.toBe(error)
                })
            )
        })

Summary: The test ensures that when `urlFactory` throws an error, the `providerFactory` correctly rejects with that same error.


it('should reject if urlFactory rejects', async () => {
            await fc.assert(
                fc.asyncProperty(errorArbitrary, endpointArbitrary, async (error, eid) => {
                    const urlFactory = jest.fn().mockRejectedValue(error)
                    const providerFactory = createConnectionFactory(urlFactory)

                    await expect(providerFactory(eid)).rejects.toBe(error)
                })
            )
        })

Summary: The function should reject when the `urlFactory` promise is rejected with an error.


it('should resolve with Connection if urlFactory returns a URL', async () => {
            await fc.assert(
                fc.asyncProperty(urlArbitrary, endpointArbitrary, async (url, eid) => {
                    const urlFactory = jest.fn().mockReturnValue(url)
                    const connectionFactory = createConnectionFactory(urlFactory)
                    const connection = await connectionFactory(eid)

                    expect(connection).toBeInstanceOf(Connection)
                    expect(connection.rpcEndpoint).toBe(url)
                })
            )
        })

Summary: If the `urlFactory` returns a URL, the connection resolved should be an instance of `Connection` with the `rpcEndpoint` matching the URL.


it('should resolve with JsonRpcProvider if urlFactory resolves with a URL', async () => {
            await fc.assert(
                fc.asyncProperty(urlArbitrary, endpointArbitrary, async (url, eid) => {
                    const urlFactory = jest.fn().mockResolvedValue(url)
                    const connectionFactory = createConnectionFactory(urlFactory)
                    const connection = await connectionFactory(eid)

                    expect(connection).toBeInstanceOf(Connection)
                    expect(connection.rpcEndpoint).toBe(url)
                })
            )
        })

Summary: A URL resolved by `urlFactory` should result in `createConnectionFactory` producing a `Connection` instance with the corresponding RPC endpoint.


it('should throw an error for other endpoints', () => {
            fc.assert(
                fc.property(endpointArbitrary, (eid) => {
                    fc.pre(eid !== EndpointId.SOLANA_V2_MAINNET)
                    fc.pre(eid !== EndpointId.SOLANA_V2_TESTNET)
                    fc.pre(eid !== EndpointId.SOLANA_MAINNET)
                    fc.pre(eid !== EndpointId.SOLANA_TESTNET)

                    expect(() => defaultRpcUrlFactory(eid)).toThrow(
                        `Could not find a default Solana RPC URL for eid ${eid} (${formatEid(eid)})`
                    )
                })
            )
        })

Summary: The connection factory should throw an error when given an endpoint ID that is not one of the predefined valid Solana endpoints.


it('should not parse anything else', () => {
            fc.assert(
                fc.property(fc.anything(), (value) => {
                    expect(() => BNBigIntSchema.parse(value)).toThrow(/Input not instance of BN/)
                })
            )
        })

Summary: `BNBigIntSchema.parse` throws an error when attempting to parse values that are not instances of `BN`.


it('should not parse anything else', () => {
            fc.assert(
                fc.property(fc.anything(), (value) => {
                    expect(() => PublicKeySchema.parse(value)).toThrow(/Input not instance of PublicKey/)
                })
            )
        })

Summary: `PublicKeySchema.parse` throws an error when given an input that is not an instance of `PublicKey`.


it('should return undefined if the account has not been initialized', async () => {
            getAccountInfoMock.mockResolvedValue(null)

            await fc.assert(
                fc.asyncProperty(solanaEndpointArbitrary, keypairArbitrary, async (eid, keypair) => {
                    fc.pre(eid !== EndpointId.SOLANA_V2_SANDBOX)

                    const address = keypair.publicKey.toBase58()

                    const connection = await connectionFactory(oftConfig.eid)
                    const getAccountInfo = createGetAccountInfo(connection)

                    expect(await getAccountInfo(address)).toBeUndefined()
                })
            )
        })

Summary: The property ensures that `getAccountInfo` returns `undefined` for uninitialized accounts when tested against various valid endpoints and keypairs.


it('should reject if the eid of the transaction does not match the eid of the signer', async () => {
                await fc.assert(
                    fc.asyncProperty(endpointArbitrary, transactionArbitrary, async (eid, transaction) => {
                        fc.pre(eid !== transaction.point.eid)

                        const signer = {} as Signer
                        const omniSigner = new OmniSignerEVM(eid, signer)

                        await expect(() => omniSigner.sign(transaction)).rejects.toThrow(/Could not use signer/)
                    })
                )
            })

Summary: An `OmniSignerEVM` should reject a transaction if the transaction's eid does not match the eid of the signer, throwing an error indicating that the signer could not be used.


it('should sign the transaction using the signer if the eids match', async () => {
                await fc.assert(
                    fc.asyncProperty(
                        transactionArbitrary,
                        signedTransactionArbitrary,
                        async (transaction, signedTransaction) => {
                            const signTransaction = jest.fn().mockResolvedValue(signedTransaction)
                            const signer = { signTransaction } as unknown as Signer
                            const omniSigner = new OmniSignerEVM(transaction.point.eid, signer)

                            expect(await omniSigner.sign(transaction)).toBe(signedTransaction)
                            expect(signTransaction).toHaveBeenCalledWith({
                                to: transaction.point.address,
                                data: transaction.data,
                                value: transaction.value,
                            })
                        }
                    )
                )
            })

Summary: The `OmniSignerEVM` signs a transaction using a signer when the `eids` match.


it('should reject if the eid of the transaction does not match the eid of the signer', async () => {
                await fc.assert(
                    fc.asyncProperty(endpointArbitrary, transactionArbitrary, async (eid, transaction) => {
                        fc.pre(eid !== transaction.point.eid)

                        const signer = {} as Signer
                        const omniSigner = new OmniSignerEVM(eid, signer)

                        await expect(() => omniSigner.signAndSend(transaction)).rejects.toThrow(/Could not use signer/)
                    })
                )
            })

Summary: The test checks if `OmniSignerEVM.signAndSend` rejects with an error when the `eid` of the transaction does not match the `eid` of the signer.


it('should send the transaction using the signer if the eids match', async () => {
                await fc.assert(
                    fc.asyncProperty(transactionArbitrary, transactionHashArbitrary, async (transaction, hash) => {
                        const sendTransaction = jest.fn().mockResolvedValue({ hash })
                        const signer = { sendTransaction } as unknown as Signer
                        const omniSigner = new OmniSignerEVM(transaction.point.eid, signer)

                        expect(await omniSigner.signAndSend(transaction)).toEqual({ transactionHash: hash })
                        expect(sendTransaction).toHaveBeenCalledWith({
                            to: transaction.point.address,
                            data: transaction.data,
                            value: transaction.value,
                        })
                    })
                )
            })

Summary: `OmniSignerEVM` sends a transaction using the signer if the transaction's `eid` matches, verifying that the transaction hash is returned and the signer is called with the correct parameters.


it('should not be supported', async () => {
                await fc.assert(
                    fc.asyncProperty(
                        evmAddressArbitrary,
                        endpointArbitrary,
                        transactionArbitrary,
                        async (safeAddress, eid, transaction) => {
                            const signer = {} as Signer

                            const apiKit = {
                                getNextNonce: jest.fn(),
                            } as unknown as SafeApiKit

                            const safe = {
                                createTransaction: jest.fn().mockResolvedValue({ data: 'transaction' }),
                                getAddress: jest.fn().mockResolvedValue(safeAddress),
                                signTransaction: jest.fn().mockResolvedValue({ data: { data: '0xsigned' } }),
                            } as unknown as Safe

                            const omniSigner = new GnosisOmniSignerEVM(eid, signer, '', {}, undefined, apiKit, safe)

                            await expect(omniSigner.sign(transaction)).rejects.toThrow(
                                /Signing transactions with safe is currently not supported, use signAndSend instead/
                            )
                        }
                    )
                )
            })

Summary: The test ensures that attempting to sign a transaction using `GnosisOmniSignerEVM` throws an error indicating that signing with a safe is not supported, and suggests using `signAndSend` instead.


it('should reject if the eid of the transaction does not match the eid of the signer', async () => {
                await fc.assert(
                    fc.asyncProperty(
                        evmAddressArbitrary,
                        endpointArbitrary,
                        transactionArbitrary,
                        async (safeAddress, eid, transaction) => {
                            fc.pre(eid !== transaction.point.eid)

                            const signer = {} as Signer
                            const safe = {
                                createTransaction: jest.fn().mockResolvedValue({ data: 'transaction' }),
                                getAddress: jest.fn().mockResolvedValue(safeAddress),
                                signTransactionHash: jest.fn().mockResolvedValue({ data: 'signature' }),
                            } as unknown as Safe
                            const omniSigner = new GnosisOmniSignerEVM(eid, signer, '', {}, undefined, undefined, safe)

                            await expect(() => omniSigner.signAndSend(transaction)).rejects.toThrow(
                                /Could not use signer/
                            )
                        }
                    )
                )
            })

Summary: Rejection occurs if the transaction's `eid` does not match the signer's `eid` in `GnosisOmniSignerEVM`.


it('should send the transaction using the signer if the eids match', async () => {
                await fc.assert(
                    fc.asyncProperty(
                        evmAddressArbitrary,
                        transactionArbitrary,
                        transactionHashArbitrary,
                        async (safeAddress, transaction, transactionHash) => {
                            const signer = { getAddress: jest.fn(), sendTransaction: jest.fn() } as unknown as Signer
                            const apiKit = {
                                proposeTransaction: jest.fn(),
                                getNextNonce: jest.fn(),
                            } as unknown as SafeApiKit
                            const safe = {
                                createTransaction: jest.fn().mockResolvedValue({ data: 'transaction' }),
                                getTransactionHash: jest.fn().mockResolvedValue(transactionHash),
                                getAddress: jest.fn().mockResolvedValue(safeAddress),
                                signTransactionHash: jest.fn().mockResolvedValue({ data: 'signature' }),
                            } as unknown as Safe

                            const omniSigner = new GnosisOmniSignerEVM(
                                transaction.point.eid,
                                signer,
                                '',
                                {
                                    safeAddress,
                                },
                                undefined,
                                apiKit,
                                safe
                            )

                            const result = await omniSigner.signAndSend(transaction)
                            expect(result.transactionHash).toEqual(transactionHash)

                            expect(await result.wait()).toEqual({ transactionHash })

                            expect(apiKit.getNextNonce).toHaveBeenCalledWith(safeAddress)
                            expect(apiKit.proposeTransaction).toHaveBeenCalledWith({
                                safeAddress,
                                safeTransactionData: 'transaction',
                                safeTxHash: transactionHash,
                                senderAddress: undefined,
                                senderSignature: 'signature',
                            })
                        }
                    )
                )
            })

Summary: Ensures that `GnosisOmniSignerEVM.signAndSend` sends a transaction using the signer when the eids match by verifying transaction hash and expected API calls.


it('should create a date from the zoned date on a JS Date.', () => {
      fc.assert(
        fc.property(
          fc.date({
            max: temporalUtil.newDate(MAX_UTC_IN_MS - ONE_DAY_IN_MS),
            min: temporalUtil.newDate(MIN_UTC_IN_MS + ONE_DAY_IN_MS)
          }),
          standardDate => {
            const date = Date.fromStandardDateLocal(standardDate)
            const receivedDate = date.toStandardDate()

            expect(receivedDate.getUTCFullYear()).toEqual(standardDate.getFullYear())
            expect(receivedDate.getUTCMonth()).toEqual(standardDate.getMonth())
            expect(receivedDate.getUTCDate()).toEqual(standardDate.getDate())
            expect(receivedDate.getUTCHours()).toEqual(0)
            expect(receivedDate.getUTCMinutes()).toEqual(0)
          })
      )
    })

Summary: Creating a date from a zoned date on a JavaScript Date should correctly match the UTC year, month, and date, with hours and minutes set to zero.


it('should reject with no transactions', async () => {
                await fc.assert(
                    fc.asyncProperty(evmAddressArbitrary, endpointArbitrary, async (safeAddress, eid) => {
                        const signer = {} as Signer
                        const safe = {} as unknown as Safe
                        const omniSigner = new GnosisOmniSignerEVM(eid, signer, '', {}, undefined, undefined, safe)

                        await expect(() => omniSigner.signAndSendBatch([])).rejects.toThrow(
                            /signAndSendBatch received 0 transactions/
                        )
                    })
                )
            })

Summary: `GnosisOmniSignerEVM.signAndSendBatch` throws an error when called with an empty transaction array.


it('should be the reverse operation of toStandardDateUTC but losing time information', () => {
      fc.assert(
        fc.property(
          fc.date({
            max: temporalUtil.newDate(MAX_UTC_IN_MS - ONE_DAY_IN_MS),
            min: temporalUtil.newDate(MIN_UTC_IN_MS + ONE_DAY_IN_MS)
          }),
          standardDate => {
            const date = Date.fromStandardDateUTC(standardDate)
            const receivedDate = date.toStandardDate()

            expect(receivedDate.getUTCFullYear()).toEqual(standardDate.getUTCFullYear())
            expect(receivedDate.getUTCMonth()).toEqual(standardDate.getUTCMonth())
            expect(receivedDate.getUTCDate()).toEqual(standardDate.getUTCDate())
            expect(receivedDate.getUTCHours()).toEqual(0)
            expect(receivedDate.getUTCMinutes()).toEqual(0)
          })
      )
    })

Summary: Converting a `standardDate` to a `Date` and back should preserve the year, month, and date, but reset the time to midnight UTC.


it('should reject if at least one of the transaction eids do not match the signer eid', async () => {
                await fc.assert(
                    fc.asyncProperty(
                        evmAddressArbitrary,
                        endpointArbitrary,
                        fc.array(transactionArbitrary, { minLength: 1 }),
                        async (safeAddress, eid, transactions) => {
                            fc.pre(transactions.some((transaction) => eid !== transaction.point.eid))

                            const signer = {} as Signer
                            const safe = {
                                createTransaction: jest.fn().mockResolvedValue({ data: 'transaction' }),
                                getAddress: jest.fn().mockResolvedValue(safeAddress),
                                signTransactionHash: jest.fn().mockResolvedValue({ data: 'signature' }),
                            } as unknown as Safe
                            const omniSigner = new GnosisOmniSignerEVM(eid, signer, '', {}, undefined, undefined, safe)

                            await expect(() => omniSigner.signAndSendBatch(transactions)).rejects.toThrow(
                                /Could not use signer/
                            )
                        }
                    )
                )
            })

Summary: Rejects if at least one transaction eid does not match the signer eid, by throwing an error when attempting to sign and send a batch of transactions.


it('should be the reverse operation of fromStandardDate', () => {
      fc.assert(
        fc.property(fc.date(), (date) => {
          const localDatetime = LocalDateTime.fromStandardDate(date)
          const receivedDate = localDatetime.toStandardDate()

          expect(receivedDate).toEqual(date)
        })
      )
    })

Summary: Converting a date to `LocalDateTime` and back should yield the original date.


it('should be the reverse operation of fromStandardDate', () => {
      fc.assert(
        fc.property(
          fc.date({
            max: temporalUtil.newDate(MAX_UTC_IN_MS - ONE_DAY_IN_MS),
            min: temporalUtil.newDate(MIN_UTC_IN_MS + ONE_DAY_IN_MS)
          }), (date) => {
            const datetime = DateTime.fromStandardDate(date)
            const receivedDate = datetime.toStandardDate()

            expect(receivedDate).toEqual(date)
          })
      )
    })

Summary: Converting a date to `DateTime` using `fromStandardDate` and back with `toStandardDate` should return the original date.


it('should send the transaction using the signer if the eids match', async () => {
                await fc.assert(
                    fc.asyncProperty(
                        evmAddressArbitrary,
                        endpointArbitrary,
                        fc.array(transactionArbitrary, { minLength: 1 }),
                        transactionHashArbitrary,
                        async (safeAddress, eid, transactions, transactionHash) => {
                            const nonce = 17
                            const signer = { getAddress: jest.fn(), sendTransaction: jest.fn() } as unknown as Signer
                            const apiKit = {
                                proposeTransaction: jest.fn(),
                                getNextNonce: jest.fn().mockResolvedValue(nonce),
                            } as unknown as SafeApiKit
                            const safe = {
                                createTransaction: jest.fn().mockResolvedValue({ data: 'transaction' }),
                                getTransactionHash: jest.fn().mockResolvedValue(transactionHash),
                                getAddress: jest.fn().mockResolvedValue(safeAddress),
                                signTransactionHash: jest.fn().mockResolvedValue({ data: 'signature' }),
                            } as unknown as Safe

                            const omniSigner = new GnosisOmniSignerEVM(
                                eid,
                                signer,
                                '',
                                {
                                    safeAddress,
                                },
                                undefined,
                                apiKit,
                                safe
                            )

                            const transactionsWithMatchingEids = transactions.map((t) => ({
                                ...t,
                                point: { ...t.point, eid },
                            }))

                            const result = await omniSigner.signAndSendBatch(transactionsWithMatchingEids)
                            expect(result.transactionHash).toEqual(transactionHash)

                            expect(await result.wait()).toEqual({ transactionHash })

                            expect(safe.createTransaction).toHaveBeenCalledWith({
                                safeTransactionData: transactions.map((t) => ({
                                    to: t.point.address,
                                    data: t.data,
                                    value: String(t.value ?? 0),
                                    operation: OperationType.Call,
                                })),
                                options: { nonce },
                            })

                            expect(apiKit.getNextNonce).toHaveBeenCalledWith(safeAddress)
                            expect(apiKit.proposeTransaction).toHaveBeenCalledWith({
                                safeAddress,
                                safeTransactionData: 'transaction',
                                safeTxHash: transactionHash,
                                senderAddress: undefined,
                                senderSignature: 'signature',
                            })
                        }
                    )
                )
            })

Summary: When `eid`s match, the transaction should be sent using the signer, verifying that the transaction hash and the process of signing, proposing, and waiting for the transaction are correctly executed.


it('should parse BigNumberish', () => {
            fc.assert(
                fc.property(bigNumberishArbitrary, (bigNumberish) => {
                    expect(BigNumberishSchema.parse(bigNumberish)).toBe(bigNumberish)
                })
            )
        })

Summary: `BigNumberishSchema` correctly parses and returns the original `bigNumberish` input.


it('should handle Integer with maxSafeInteger', () => {
      return fc.assert(
        fc.property(
          fc.maxSafeInteger().map(value => [int(value), value]),
          ([value, expectedValue]) => {
            const rawProfilePlan = {
              [field]: value
            }

            const profilePlan = new ProfiledPlan(rawProfilePlan)

            return profilePlan[field] === expectedValue
          }
        )
      )
    })

Summary: `ProfiledPlan` should correctly handle `Integer` objects wrapped with `maxSafeInteger`, ensuring the field value matches the expected unwrapped integer.


it('should handle Integer with arbitrary integer', () => {
      return fc.assert(
        fc.property(
          fc.integer().map(value => [int(value), value]),
          ([value, expectedValue]) => {
            const rawProfilePlan = {
              [field]: value
            }

            const profilePlan = new ProfiledPlan(rawProfilePlan)

            return profilePlan[field] === expectedValue
          }
        )
      )
    })

Summary: The property verifies that `ProfiledPlan` correctly retains the value of an integer field converted to and from Neo4j's `int` type.


it('should parse BigNumberish into a bigint', () => {
            fc.assert(
                fc.property(bigNumberishArbitrary, (bigNumberish) => {
                    const parsed = BigNumberishBigIntSchema.parse(bigNumberish)

                    expect(typeof parsed).toBe('bigint')
                    expect(BigNumber.from(parsed)).toEqual(BigNumber.from(bigNumberish))
                })
            )
        })

Summary: Parsing `BigNumberish` values should yield a `bigint` type, and the value should be equivalent when converted back using `BigNumber`.


it('should parse BigNumberish into a number if within bounds', () => {
            fc.assert(
                fc.property(bigNumberishArbitrary, (bigNumberish) => {
                    fc.pre(BigNumber.from(bigNumberish).abs().lte(BigInt(Number.MAX_SAFE_INTEGER)))

                    const parsed = BigNumberishNumberSchema.parse(bigNumberish)

                    expect(typeof parsed).toBe('number')
                    expect(BigNumber.from(parsed)).toEqual(BigNumber.from(bigNumberish))
                })
            )
        })

Summary: BigNumberish values within the bounds of JavaScript's safe integer range are parsed into numbers without altering their value.


it('should handle BigInt with maxSafeInteger', () => {
      return fc.assert(
        fc.property(
          fc.maxSafeInteger().map(value => [BigInt(value), value]),
          ([value, expectedValue]) => {
            const rawProfilePlan = {
              [field]: value
            }

            const profilePlan = new ProfiledPlan(rawProfilePlan)

            return profilePlan[field] === expectedValue
          }
        )
      )
    })

Summary: A `ProfiledPlan` should handle `BigInt` values correctly, ensuring they equal their corresponding `maxSafeInteger` values.


it('should handle Integer with arbitrary integer', () => {
      return fc.assert(
        fc.property(
          fc.integer().map(value => [BigInt(value), value]),
          ([value, expectedValue]) => {
            const rawProfilePlan = {
              [field]: value
            }

            const profilePlan = new ProfiledPlan(rawProfilePlan)

            return profilePlan[field] === expectedValue
          }
        )
      )
    })

Summary: `ProfiledPlan` correctly handles properties where the field is set to both a `BigInt` and its original integer value, ensuring they are equivalent.


it('should throw an error if there is an overflow', () => {
            fc.assert(
                fc.property(bigNumberishArbitrary, (bigNumberish) => {
                    fc.pre(BigNumber.from(bigNumberish).abs().gt(BigInt(Number.MAX_SAFE_INTEGER)))

                    expect(() => BigNumberishNumberSchema.parse(bigNumberish)).toThrow('overflow')
                })
            )
        })

Summary: An error should be thrown if `BigNumberishNumberSchema` attempts to parse a number larger than `Number.MAX_SAFE_INTEGER`.


it('should reject if urlFactory throws', async () => {
            await fc.assert(
                fc.asyncProperty(errorArbitrary, endpointArbitrary, async (error, eid) => {
                    const urlFactory = jest.fn().mockImplementation(() => {
                        throw error
                    })
                    const providerFactory = createProviderFactory(urlFactory)

                    await expect(providerFactory(eid)).rejects.toBe(error)
                })
            )
        })

Summary: If `urlFactory` throws an error, `providerFactory` should reject with that same error.


it('should handle Integer with maxSafeInteger', () => {
      return fc.assert(
        fc.property(
          fc.maxSafeInteger().map(value => [int(value), value]),
          ([value, expectedValue]) => {
            const stats = {
              [rawField]: value
            }

            const queryStatistics = new QueryStatistics(stats)

            return queryStatistics.updates()[field] === expectedValue
          }
        )
      )
    })

Summary: `QueryStatistics` correctly returns `updates()` when handling integers with `maxSafeInteger`.


it('should reject if urlFactory rejects', async () => {
            await fc.assert(
                fc.asyncProperty(errorArbitrary, endpointArbitrary, async (error, eid) => {
                    const urlFactory = jest.fn().mockRejectedValue(error)
                    const providerFactory = createProviderFactory(urlFactory)

                    await expect(providerFactory(eid)).rejects.toBe(error)
                })
            )
        })

Summary: The test confirms that if `urlFactory` rejects with an error, `providerFactory` is expected to reject with the same error.


it('should handle Integer with arbitrary integer', () => {
      return fc.assert(
        fc.property(
          fc.integer().map(value => [BigInt(value), value]),
          ([value, expectedValue]) => {
            const stats = {
              [rawField]: value
            }

            const queryStatistics = new QueryStatistics(stats)

            return queryStatistics.updates()[field] === expectedValue
          }
        )
      )
    })

Summary: Handling of arbitrary integers with `QueryStatistics` ensures updates return the original integer value.


it('should resolve with JsonRpcProvider if urlFactory returns a URL', async () => {
            await fc.assert(
                fc.asyncProperty(urlArbitrary, endpointArbitrary, async (url, eid) => {
                    const urlFactory = jest.fn().mockReturnValue(url)
                    const providerFactory = createProviderFactory(urlFactory)
                    const provider = await providerFactory(eid)

                    expect(provider).toBeInstanceOf(JsonRpcProvider)
                    expect(provider.connection.url).toBe(url)
                })
            )
        })

Summary: The test checks that if `urlFactory` returns a URL, the `providerFactory` resolves to an instance of `JsonRpcProvider` with a connection URL matching the provided URL.


it('should create an OmniPoint with the address of the contract', () => {
            fc.assert(
                fc.property(evmAddressArbitrary, endpointArbitrary, (address, eid) => {
                    const contract = new Contract(address, [])
                    const omniContract: OmniContract = { eid, contract }

                    expect(omniContractToPoint(omniContract)).toEqual({ eid, address })
                })
            )
        })

Summary: `omniContractToPoint` converts an `OmniContract` object to an `OmniPoint` with the same contract address and endpoint identifier (`eid`).


it('should serialize correctly with a message', () => {
            fc.assert(
                fc.property(reasonArbitrary, messageArbitrary, (reason, message) => {
                    fc.pre(message !== '')

                    expect(String(new PanicError(reason, message))).toBe(`PanicError: ${message}. Error code ${reason}`)
                })
            )
        })

Summary: `PanicError` serialization includes the message and error code when the message is not empty.


it('should pack and unpack DateTimeWithOffset', () => {
      fc.assert(
        fc.property(
          fc.date({
            min: temporalUtil.newDate(utils.MIN_UTC_IN_MS + utils.ONE_DAY_IN_MS),
            max: temporalUtil.newDate(utils.MAX_UTC_IN_MS - utils.ONE_DAY_IN_MS)
          }),
          fc.integer({ min: 0, max: 999_999 }),
          utils.arbitraryTimeZoneId(),
          (date, nanoseconds, timeZoneId) => {
            const object = new DateTime(
              date.getUTCFullYear(),
              date.getUTCMonth() + 1,
              date.getUTCDate(),
              date.getUTCHours(),
              date.getUTCMinutes(),
              date.getUTCSeconds(),
              date.getUTCMilliseconds() * 1_000_000 + nanoseconds,
              undefined,
              timeZoneId
            )
            const buffer = alloc(256)
            const loggerFunction = jest.fn()
            const protocol = new BoltProtocolV5x7(
              new utils.MessageRecordingConnection(),
              buffer,
              {
                disableLosslessIntegers: true
              },
              undefined,
              new Logger('debug', loggerFunction)
            )

            const packable = protocol.packable(object)

            expect(packable).not.toThrow()
            expect(loggerFunction)
              .toBeCalledWith('warn',
                'DateTime objects without "timeZoneOffsetSeconds" property ' +
                'are prune to bugs related to ambiguous times. For instance, ' +
                '2022-10-30T2:30:00[Europe/Berlin] could be GMT+1 or GMT+2.')

            buffer.reset()

            const unpacked = protocol.unpack(buffer)

            expect(unpacked.timeZoneOffsetSeconds).toBeDefined()

            const unpackedDateTimeWithoutOffset = new DateTime(
              unpacked.year,
              unpacked.month,
              unpacked.day,
              unpacked.hour,
              unpacked.minute,
              unpacked.second,
              unpacked.nanosecond,
              undefined,
              unpacked.timeZoneId
            )

            expect(unpackedDateTimeWithoutOffset).toEqual(object)
          })
      )
    })

Summary: Packing and unpacking `DateTimeWithOffset` should preserve the original object properties, while managing potential issues related to missing `timeZoneOffsetSeconds` and logging a warning for ambiguous times.


it('should serialize correctly when message is not passed', () => {
            fc.assert(
                fc.property(reasonArbitrary, (reason) => {
                    expect(String(new RevertError(reason))).toBe(
                        `RevertError: Contract reverted. Error reason '${reason}'`
                    )
                })
            )
        })

Summary: `RevertError` serializes correctly into a string when a message is provided, showing the error reason.


it('should serialize correctly when message is empty', () => {
            fc.assert(
                fc.property(reasonArbitrary, (reason) => {
                    expect(String(new RevertError(reason, ''))).toBe(`RevertError. Error reason '${reason}'`)
                })
            )
        })

Summary: `RevertError` with an empty message serializes to `"RevertError. Error reason '${reason}'"`.


it('should pack and unpack DateTimeWithZoneIdAndNoOffset', () => {
      fc.assert(
        fc.property(fc.date(), date => {
          const object = DateTime.fromStandardDate(date)
          const buffer = alloc(256)
          const loggerFunction = jest.fn()
          const protocol = new BoltProtocolV5x7(
            new utils.MessageRecordingConnection(),
            buffer,
            {
              disableLosslessIntegers: true
            },
            undefined,
            new Logger('debug', loggerFunction)
          )

          const packable = protocol.packable(object)

          expect(packable).not.toThrow()

          buffer.reset()

          const unpacked = protocol.unpack(buffer)

          expect(unpacked.timeZoneOffsetSeconds).toBeDefined()

          expect(unpacked).toEqual(object)
        })
      )
    })

Summary: Packing and unpacking `DateTimeWithZoneIdAndNoOffset` with `BoltProtocolV5x7` should maintain equality with the original object, including a defined `timeZoneOffsetSeconds`.


it('should serialize correctly with a message', () => {
            fc.assert(
                fc.property(reasonArbitrary, messageArbitrary, (reason, message) => {
                    fc.pre(message !== '')

                    expect(String(new RevertError(reason, message))).toBe(
                        `RevertError: ${message}. Error reason '${reason}'`
                    )
                })
            )
        })

Summary: A `RevertError` object should serialize to a string format with the message displayed, provided the message is not empty.


it('should serialize correctly when message is not passed', () => {
            fc.assert(
                fc.property(reasonArbitrary, argsArbitrary, (reason, args) => {
                    const formattedArgs = args.map((arg) => printJson(arg, false))

                    expect(String(new CustomError(reason, args))).toBe(
                        `CustomError: Contract reverted with custom error. Error ${reason}(${formattedArgs})`
                    )
                })
            )
        })

Summary: `CustomError` serialization without a message should match the format `CustomError: Contract reverted with custom error. Error <reason>(<formattedArgs>)`.


it('should serialize correctly when message is empty', () => {
            fc.assert(
                fc.property(reasonArbitrary, argsArbitrary, (reason, args) => {
                    const formattedArgs = args.map((arg) => printJson(arg, false))

                    expect(String(new CustomError(reason, args, ''))).toBe(
                        `CustomError. Error ${reason}(${formattedArgs})`
                    )
                })
            )
        })

Summary: `CustomError` with an empty message should serialize to a string representation containing the error reason and formatted arguments.


it('should serialize correctly with a message', () => {
            fc.assert(
                fc.property(reasonArbitrary, argsArbitrary, messageArbitrary, (reason, args, message) => {
                    fc.pre(message !== '')

                    const formattedArgs = args.map((arg) => printJson(arg, false))

                    expect(String(new CustomError(reason, args, message))).toBe(
                        `CustomError: ${message}. Error ${reason}(${formattedArgs})`
                    )
                })
            )
        })

Summary: `CustomError` must serialize to a string format that includes a non-empty message, reason, and argument list formatted as JSON.


it('should pack and unpack DateTimeWithOffset', () => {
      fc.assert(
        fc.property(
          fc.date({
            min: temporalUtil.newDate(utils.MIN_UTC_IN_MS + utils.ONE_DAY_IN_MS),
            max: temporalUtil.newDate(utils.MAX_UTC_IN_MS - utils.ONE_DAY_IN_MS)
          }),
          fc.integer({ min: 0, max: 999_999 }),
          utils.arbitraryTimeZoneId(),
          (date, nanoseconds, timeZoneId) => {
            const object = new DateTime(
              date.getUTCFullYear(),
              date.getUTCMonth() + 1,
              date.getUTCDate(),
              date.getUTCHours(),
              date.getUTCMinutes(),
              date.getUTCSeconds(),
              date.getUTCMilliseconds() * 1_000_000 + nanoseconds,
              undefined,
              timeZoneId
            )
            const buffer = alloc(256)
            const loggerFunction = jest.fn()
            const protocol = new BoltProtocolV5x6(
              new utils.MessageRecordingConnection(),
              buffer,
              {
                disableLosslessIntegers: true
              },
              undefined,
              new Logger('debug', loggerFunction)
            )

            const packable = protocol.packable(object)

            expect(packable).not.toThrow()
            expect(loggerFunction)
              .toBeCalledWith('warn',
                'DateTime objects without "timeZoneOffsetSeconds" property ' +
                'are prune to bugs related to ambiguous times. For instance, ' +
                '2022-10-30T2:30:00[Europe/Berlin] could be GMT+1 or GMT+2.')

            buffer.reset()

            const unpacked = protocol.unpack(buffer)

            expect(unpacked.timeZoneOffsetSeconds).toBeDefined()

            const unpackedDateTimeWithoutOffset = new DateTime(
              unpacked.year,
              unpacked.month,
              unpacked.day,
              unpacked.hour,
              unpacked.minute,
              unpacked.second,
              unpacked.nanosecond,
              undefined,
              unpacked.timeZoneId
            )

            expect(unpackedDateTimeWithoutOffset).toEqual(object)
          })
      )
    })

Summary: Packing and unpacking `DateTimeWithOffset` should indicate a warning for potential bugs when `timeZoneOffsetSeconds` is missing, and correctly reconstruct the original `DateTime` object, filling in the necessary timezone offset information.


it('should return a valid EVM address', () => {
            fc.assert(
                fc.property(evmAddressArbitrary, (address) => {
                    expect(isAddress(addChecksum(address))).toBe(true)
                })
            )
        })

Summary: `addChecksum` applied to an EVM address results in `isAddress` returning true.


it('should resolve if the first task resolves', async () => {
            await fc.assert(
                fc.asyncProperty(valueArbitrary, valuesArbitrary, async (value, errors) => {
                    const task = jest.fn().mockResolvedValue(value)
                    const tasks = errors.map((error) => jest.fn().mockRejectedValue(error))

                    expect(await first([task, ...tasks])).toBe(value)

                    // Make sure none of the other factories got called
                    for (const factory of tasks) {
                        expect(factory).not.toHaveBeenCalled()
                    }
                })
            )
        })

Summary: `first` resolves with the value of the first task that resolves, and ensures subsequent tasks are not called.


it('should reject with the last rejected task error', async () => {
            await fc.assert(
                fc.asyncProperty(valuesArbitrary, valueArbitrary, async (errors, error) => {
                    const tasks = errors.map((error) => jest.fn().mockRejectedValue(error))
                    const task = jest.fn().mockRejectedValue(error)

                    await expect(first([...tasks, task])).rejects.toBe(error)

                    // Make sure all the tasks got called
                    for (const factory of tasks) {
                        expect(factory).toHaveBeenCalledTimes(1)
                    }

                    expect(task).toHaveBeenCalledTimes(1)
                })
            )
        })

Summary: The function `first` should reject with the last task's rejection error, and all tasks should be called exactly once.


it('should resolve if the first factory resolves', async () => {
            await fc.assert(
                fc.asyncProperty(valueArbitrary, valuesArbitrary, async (value, values) => {
                    const successful = jest.fn().mockResolvedValue(value)
                    const successfulOther = values.map((value) => jest.fn().mockResolvedValue(value))
                    const factory = firstFactory(successful, ...successfulOther)

                    expect(await factory()).toBe(value)

                    // Make sure none of the other factories got called
                    for (const factory of successfulOther) {
                        expect(factory).not.toHaveBeenCalled()
                    }
                })
            )
        })

Summary: First factory function resolves successfully and no subsequent factories are invoked.


it('should resolve with the first successful factory', async () => {
            await fc.assert(
                fc.asyncProperty(valuesArbitrary, valueArbitrary, async (errors, value) => {
                    const failing = errors.map((error) => jest.fn().mockRejectedValue(error))
                    const successful = jest.fn().mockResolvedValue(value)
                    const factory = firstFactory(...failing, successful)

                    expect(await factory()).toBe(value)

                    // Make sure all the tasks got called
                    for (const factory of failing) {
                        expect(factory).toHaveBeenCalledTimes(1)
                    }
                })
            )
        })

Summary: `firstFactory` resolves with the value from the first successful promise factory after a series of failing ones, ensuring all factories are called once.


it('should pass the input to factories', async () => {
            await fc.assert(
                fc.asyncProperty(valuesArbitrary, valueArbitrary, valuesArbitrary, async (errors, value, args) => {
                    const failing = errors.map((error) => jest.fn().mockRejectedValue(error))
                    const successful = jest.fn().mockResolvedValue(value)
                    const factory = firstFactory(...failing, successful)

                    expect(await factory(...args)).toBe(value)

                    // Make sure all the tasks got called with the correct arguments
                    for (const factory of failing) {
                        expect(factory).toHaveBeenCalledTimes(1)
                        expect(factory).toHaveBeenCalledWith(...args)
                    }

                    expect(successful).toHaveBeenCalledTimes(1)
                    expect(successful).toHaveBeenCalledWith(...args)
                })
            )
        })

Summary: The input is correctly passed to factories, ensuring that failing promises are executed once with the correct arguments before a successful promise returns a value.


it('should resolve with the resolution value of an asynchronous task', async () => {
            await fc.assert(
                fc.asyncProperty(valueArbitrary, async (value) => {
                    const task = jest.fn().mockResolvedValue(value)
                    const handleError = jest.fn()

                    await expect(mapError(task, handleError)).resolves.toBe(value)
                    expect(handleError).not.toHaveBeenCalled()
                })
            )
        })

Summary: `mapError` resolves an asynchronous task to its resolution value without calling `handleError`.


it('should pack and unpack DateTimeWithZoneIdAndNoOffset', () => {
      fc.assert(
        fc.property(fc.date(), date => {
          const object = DateTime.fromStandardDate(date)
          const buffer = alloc(256)
          const loggerFunction = jest.fn()
          const protocol = new BoltProtocolV6x0(
            new utils.MessageRecordingConnection(),
            buffer,
            {
              disableLosslessIntegers: true
            },
            undefined,
            new Logger('debug', loggerFunction)
          )

          const packable = protocol.packable(object)

          expect(packable).not.toThrow()

          buffer.reset()

          const unpacked = protocol.unpack(buffer)

          expect(unpacked.timeZoneOffsetSeconds).toBeDefined()

          expect(unpacked).toEqual(object)
        })
      )
    })

Summary: Packing and unpacking a `DateTimeWithZoneIdAndNoOffset` should correctly handle conversion and reconstruction, ensuring the unpacked object matches the original.


it('should reject and call the toError callback if a synchronous task throws', async () => {
            await fc.assert(
                fc.asyncProperty(valueArbitrary, valueArbitrary, async (error, mappedError) => {
                    const task = jest.fn().mockImplementation(() => {
                        throw error
                    })
                    const handleError = jest.fn().mockReturnValue(mappedError)

                    await expect(mapError(task, handleError)).rejects.toBe(mappedError)
                    expect(handleError).toHaveBeenCalledOnce()
                    expect(handleError).toHaveBeenCalledExactlyOnceWith(error)
                })
            )
        })

Summary: A synchronous task that throws should cause rejection, and the `toError` callback should be invoked once with the thrown error and return the mapped error.


it('should reject and call the toError callback if an asynchronous task rejects', async () => {
            await fc.assert(
                fc.asyncProperty(valueArbitrary, valueArbitrary, async (error, mappedError) => {
                    const task = jest.fn().mockRejectedValue(error)
                    const handleError = jest.fn().mockReturnValue(mappedError)

                    await expect(mapError(task, handleError)).rejects.toBe(mappedError)
                    expect(handleError).toHaveBeenCalledOnce()
                    expect(handleError).toHaveBeenCalledExactlyOnceWith(error)
                })
            )
        })

Summary: When an asynchronous task rejects, `mapError` should reject with a mapped error from the `handleError` callback, ensuring the callback is invoked exactly once with the original error.


it('should resolve with the resolution value of an asynchronous task', async () => {
            await fc.assert(
                fc.asyncProperty(valueArbitrary, async (value) => {
                    const task = jest.fn().mockResolvedValue(value)
                    const handleError = jest.fn()

                    await expect(tapError(task, handleError)).resolves.toBe(value)
                    expect(handleError).not.toHaveBeenCalled()
                })
            )
        })

Summary: `tapError` should resolve with the value of a successfully resolved asynchronous task and ensure `handleError` is not called.


it('should reject and call the onError callback if a synchronous task throws', async () => {
            await fc.assert(
                fc.asyncProperty(valueArbitrary, async (error) => {
                    const task = jest.fn().mockImplementation(() => {
                        throw error
                    })
                    const handleError = jest.fn()

                    await expect(tapError(task, handleError)).rejects.toBe(error)
                    expect(handleError).toHaveBeenCalledOnce()
                    expect(handleError).toHaveBeenCalledExactlyOnceWith(error)
                })
            )
        })

Summary: `tapError` should reject with the thrown error and invoke the `onError` callback exactly once when a task throws an error.


it('should reject and call the onError callback if an asynchronous task rejects', async () => {
            await fc.assert(
                fc.asyncProperty(valueArbitrary, async (error) => {
                    const task = jest.fn().mockRejectedValue(error)
                    const handleError = jest.fn()

                    await expect(tapError(task, handleError)).rejects.toBe(error)
                    expect(handleError).toHaveBeenCalledOnce()
                    expect(handleError).toHaveBeenCalledExactlyOnceWith(error)
                })
            )
        })

Summary: `tapError` function should reject with the same error an asynchronous task rejects with and call the `onError` callback once with that error.


it('should pack and unpack DateTimeWithZoneIdAndNoOffset', () => {
      fc.assert(
        fc.property(fc.date(), date => {
          const object = DateTime.fromStandardDate(date)
          const buffer = alloc(256)
          const loggerFunction = jest.fn()
          const protocol = new BoltProtocolV5x8(
            new utils.MessageRecordingConnection(),
            buffer,
            {
              disableLosslessIntegers: true
            },
            undefined,
            new Logger('debug', loggerFunction)
          )

          const packable = protocol.packable(object)

          expect(packable).not.toThrow()

          buffer.reset()

          const unpacked = protocol.unpack(buffer)

          expect(unpacked.timeZoneOffsetSeconds).toBeDefined()

          expect(unpacked).toEqual(object)
        })
      )
    })

Summary: Packing and unpacking of `DateTimeWithZoneIdAndNoOffset` should preserve the original object, including the defined `timeZoneOffsetSeconds`.


it('should reject with the original error if the onError callback rejects', async () => {
            await fc.assert(
                fc.asyncProperty(valueArbitrary, valueArbitrary, async (error, anotherError) => {
                    const task = jest.fn().mockRejectedValue(error)
                    const handleError = jest.fn().mockRejectedValue(anotherError)

                    await expect(tapError(task, handleError)).rejects.toBe(error)
                    expect(handleError).toHaveBeenCalledOnce()
                    expect(handleError).toHaveBeenCalledExactlyOnceWith(error)
                })
            )
        })

Summary: `tapError` should reject with the original error if the `onError` callback itself rejects, while ensuring the callback is called once with the original error.


it('should not override user values if provided', () => {
            fc.assert(
                fc.property(
                    fc.integer(),
                    fc.string(),
                    mnemonicArbitrary,
                    fc.boolean(),
                    (port, directory, mnemonic, overwriteAccounts) => {
                        expect(
                            resolveSimulationConfig(
                                { port, directory, overwriteAccounts, anvil: { mnemonic } },
                                hre.config
                            )
                        ).toEqual({
                            port,
                            directory: resolve(hre.config.paths.root, directory),
                            overwriteAccounts,
                            anvil: {
                                host: '0.0.0.0',
                                port: 8545,
                                mnemonic,
                            },
                        })
                    }
                )
            )
        })

Summary: `resolveSimulationConfig` function preserves user-specified values for port, directory, mnemonic, and `overwriteAccounts` without overriding them.


it('should pack and unpack DateTimeWithOffset', () => {
      fc.assert(
        fc.property(
          fc.date({
            min: temporalUtil.newDate(utils.MIN_UTC_IN_MS + utils.ONE_DAY_IN_MS),
            max: temporalUtil.newDate(utils.MAX_UTC_IN_MS - utils.ONE_DAY_IN_MS)
          }),
          fc.integer({ min: 0, max: 999_999 }),
          utils.arbitraryTimeZoneId(),
          (date, nanoseconds, timeZoneId) => {
            const object = new DateTime(
              date.getUTCFullYear(),
              date.getUTCMonth() + 1,
              date.getUTCDate(),
              date.getUTCHours(),
              date.getUTCMinutes(),
              date.getUTCSeconds(),
              date.getUTCMilliseconds() * 1_000_000 + nanoseconds,
              undefined,
              timeZoneId
            )
            const buffer = alloc(256)
            const loggerFunction = jest.fn()
            const protocol = new BoltProtocolV5x1(
              new utils.MessageRecordingConnection(),
              buffer,
              {
                disableLosslessIntegers: true
              },
              undefined,
              new Logger('debug', loggerFunction)
            )

            const packable = protocol.packable(object)

            expect(packable).not.toThrow()
            expect(loggerFunction)
              .toBeCalledWith('warn',
                'DateTime objects without "timeZoneOffsetSeconds" property ' +
                'are prune to bugs related to ambiguous times. For instance, ' +
                '2022-10-30T2:30:00[Europe/Berlin] could be GMT+1 or GMT+2.')

            buffer.reset()

            const unpacked = protocol.unpack(buffer)

            expect(unpacked.timeZoneOffsetSeconds).toBeDefined()

            const unpackedDateTimeWithoutOffset = new DateTime(
              unpacked.year,
              unpacked.month,
              unpacked.day,
              unpacked.hour,
              unpacked.minute,
              unpacked.second,
              unpacked.nanosecond,
              undefined,
              unpacked.timeZoneId
            )

            expect(unpackedDateTimeWithoutOffset).toEqual(object)
          })
      )
    })

Summary: Packing and unpacking of `DateTimeWithOffset` should maintain equivalence with original, ensuring `timeZoneOffsetSeconds` is defined and logging a warning if missing.


it('should work with anvil options', async () => {
            await fc.assert(
                fc.asyncProperty(anvilOptionsArbitrary, async (anvilOptions) => {
                    const spec = serializeDockerComposeSpec({
                        version: '3.9',
                        services: {
                            anvil: createEvmNodeServiceSpec(anvilOptions),
                        },
                    })

                    await writeFile(SPEC_FILE_PATH, spec)

                    const result = validateSpec()

                    expect(result.stderr.toString('utf8')).toBe('')
                    expect(result.status).toBe(0)
                }),
                { numRuns: 20 }
            )
        })

Summary: Composition of the Docker Compose specification with Anvil options should produce a valid specification without errors.


it('should pack and unpack DateTimeWithOffset', () => {
        fc.assert(
          fc.property(
            fc.date({
              min: temporalUtil.newDate(utils.MIN_UTC_IN_MS + utils.ONE_DAY_IN_MS),
              max: temporalUtil.newDate(utils.MAX_UTC_IN_MS - utils.ONE_DAY_IN_MS)
            }),
            fc.integer({ min: 0, max: 999_999 }),
            utils.arbitraryTimeZoneId(),
            (date, nanoseconds, timeZoneId) => {
              const object = new DateTime(
                date.getUTCFullYear(),
                date.getUTCMonth() + 1,
                date.getUTCDate(),
                date.getUTCHours(),
                date.getUTCMinutes(),
                date.getUTCSeconds(),
                date.getUTCMilliseconds() * 1_000_000 + nanoseconds,
                undefined,
                timeZoneId
              )

              buffer.reset()

              const packable = protocol.packable(object)

              expect(packable).not.toThrow()
              expect(loggerFunction)
                .toBeCalledWith('warn',
                  'DateTime objects without "timeZoneOffsetSeconds" property ' +
                  'are prune to bugs related to ambiguous times. For instance, ' +
                  '2022-10-30T2:30:00[Europe/Berlin] could be GMT+1 or GMT+2.')

              buffer.reset()

              const unpacked = protocol.unpack(buffer)

              expect(unpacked.timeZoneOffsetSeconds).toBeDefined()

              const unpackedDateTimeWithoutOffset = new DateTime(
                unpacked.year,
                unpacked.month,
                unpacked.day,
                unpacked.hour,
                unpacked.minute,
                unpacked.second,
                unpacked.nanosecond,
                undefined,
                unpacked.timeZoneId
              )

              expect(unpackedDateTimeWithoutOffset).toEqual(object)
            })
        )
      })

Summary: Packing and unpacking `DateTimeWithOffset` should correctly handle conversion, logging warnings for ambiguous times, while ensuring the `timeZoneOffsetSeconds` is defined and the unpacked `DateTime` matches the original.


it('should work with anvil services', async () => {
            await fc.assert(
                fc.asyncProperty(portArbitrary, servicesArbitrary, async (port, services) => {
                    const spec = serializeDockerComposeSpec({
                        version: '3.9',
                        services: {
                            ...services,
                            rpc: createEvmNodeProxyServiceSpec(port, services),
                        },
                    })

                    await writeFile(SPEC_FILE_PATH, spec)

                    const result = validateSpec()

                    expect(result.stderr.toString('utf8')).toBe('')
                    expect(result.status).toBe(0)
                }),
                { numRuns: 20 }
            )
        })

Summary: Validating that serialized Docker Compose specs with EVM node proxy services, based on arbitrary ports and services, result in a successful validation without errors.


it('should have addition, update and deletion working correctly', () => {
                fc.assert(
                    fc.property(keyArbitrary, valueArbitrary, valueArbitrary, (key, value1, value2) => {
                        const map = new TestMap()

                        // Sanity check first
                        expect(map.has(key)).toBeFalsy()

                        // Set a value first
                        map.set(key, value1)

                        // Check whether the insertion worked
                        expect(map.has(key)).toBeTruthy()
                        expect(map.size).toBe(1)
                        expect(map.get(key)).toBe(value1)
                        expect(Array.from(map.keys())).toEqual([key])
                        expect(Array.from(map.values())).toEqual([value1])
                        expect(Array.from(map.entries())).toEqual([[key, value1]])

                        // Now overwrite the value
                        map.set(key, value2)

                        // Check whether the insertion worked
                        expect(map.has(key)).toBeTruthy()
                        expect(map.size).toBe(1)
                        expect(map.get(key)).toBe(value2)
                        expect(Array.from(map.keys())).toEqual([key])
                        expect(Array.from(map.values())).toEqual([value2])
                        expect(Array.from(map.entries())).toEqual([[key, value2]])

                        // Now delete the value
                        map.delete(key)

                        // And check that the deletion worked
                        expect(map.has(key)).toBeFalsy()
                        expect(map.size).toBe(0)
                        expect(map.get(key)).toBeUndefined()
                        expect(Array.from(map.keys())).toEqual([])
                        expect(Array.from(map.values())).toEqual([])
                        expect(Array.from(map.entries())).toEqual([])
                    })
                )
            })

Summary: The `TestMap` should correctly handle addition, update, and deletion of key-value pairs while maintaining accurate size and iterable properties.


it('should pack and unpack DateTimeWithZoneIdAndNoOffset', () => {
      fc.assert(
        fc.property(fc.date(), date => {
          const object = DateTime.fromStandardDate(date)
          const buffer = alloc(256)
          const loggerFunction = jest.fn()
          const protocol = new BoltProtocolV5x0(
            new utils.MessageRecordingConnection(),
            buffer,
            {
              disableLosslessIntegers: true
            },
            undefined,
            new Logger('debug', loggerFunction)
          )

          const packable = protocol.packable(object)

          expect(packable).not.toThrow()

          buffer.reset()

          const unpacked = protocol.unpack(buffer)

          expect(unpacked.timeZoneOffsetSeconds).toBeDefined()

          expect(unpacked).toEqual(object)
        })
      )
    })

Summary: DateTime objects are correctly packed and unpacked, preserving time zone offset and equality.


it('should serialize an internal message', () => {
            fc.assert(
                fc.property(fc.bigInt({ min: 0n, max: 1000n }), fc.boolean(), cellArbitrary, (value, bounce, body) => {
                    const messageRelaxed = internal({
                        value,
                        to: wallet.address,
                        bounce,
                        body,
                    })

                    const serialized = serializeMessageRelaxed(messageRelaxed)
                    const deserialized = deserializeMessageRelaxed(serialized)

                    // FIXME Jest comparison operators don't work well with message objects
                    // so a workaround expectation is used
                    //
                    // See https://github.com/ton-core/ton-core/blob/e0ed819973daf0484dfbacd0c30a0dcfe4714f8d/src/types/MessageRelaxed.spec.ts
                    expect(Cell.fromBase64(serialized).equals(messageRelaxedToCell(messageRelaxed))).toBeTruthy()

                    const reserialized = serializeMessageRelaxed(deserialized)
                    expect(reserialized).toEqual(serialized)
                })
            )
        })

Summary: Serializing and deserializing an internal message should result in equivalent serialized outputs.


it('should serialize an external message', () => {
            fc.assert(
                fc.property(cellArbitrary, (body) => {
                    const message = external({
                        to: wallet.address,
                        body,
                    })

                    const serialized = serializeMessage(message)
                    const deserialized = deserialize(serialized)

                    // FIXME Jest comparison operators don't work well with message objects
                    // so a workaround expectation is used
                    //
                    // See https://github.com/ton-core/ton-core/blob/e0ed819973daf0484dfbacd0c30a0dcfe4714f8d/src/types/MessageRelaxed.spec.ts
                    expect(Cell.fromBase64(serialized).equals(messageToCell(message))).toBeTruthy()

                    const reserialized = serializeMessage(deserialized as Message)
                    expect(reserialized).toEqual(serialized)
                })
            )
        })

Summary: Serializing and deserializing an external message should yield consistent results, ensuring equality between the original and re-serialized messages.


it('should pack and unpack DateTimeWithZoneIdAndNoOffset', () => {
        fc.assert(
          fc.property(fc.date(), date => {
            const object = DateTime.fromStandardDate(date)

            buffer.reset()

            const packable = protocol.packable(object)

            expect(packable).not.toThrow()

            buffer.reset()

            const unpacked = protocol.unpack(buffer)

            expect(unpacked.timeZoneOffsetSeconds).toBeDefined()

            expect(unpacked).toEqual(object)
          })
        )
      })


it('should serialize an internal message', () => {
            fc.assert(
                fc.property(fc.bigInt({ min: 0n, max: 1000n }), fc.boolean(), cellArbitrary, (value, bounce, body) => {
                    const messageRelaxed = internal({
                        value,
                        to: wallet.address,
                        bounce,
                        body,
                    })

                    const serialized = serializeMessageRelaxed(messageRelaxed)
                    const deserialized = deserialize(serialized)

                    // FIXME Jest comparison operators don't work well with message objects
                    // so a workaround expectation is used
                    //
                    // See https://github.com/ton-core/ton-core/blob/e0ed819973daf0484dfbacd0c30a0dcfe4714f8d/src/types/MessageRelaxed.spec.ts
                    expect(Cell.fromBase64(serialized).equals(messageRelaxedToCell(messageRelaxed))).toBeTruthy()

                    const reserialized = serializeMessage(deserialized as Message)
                    expect(reserialized).toEqual(serialized)
                })
            )
        })

Summary: Serialization and deserialization of an internal message should maintain consistency, producing equivalent serialized outputs.


it('should return undefined if called with undefined definition', async () => {
            await fc.assert(
                fc.asyncProperty(endpointArbitrary, async (eid) => {
                    await expect(createSignerAddressOrIndexFactory()(eid)).resolves.toBeUndefined()
                })
            )
        })

Summary: Calling `createSignerAddressOrIndexFactory()` with an undefined definition should return undefined.


it('should return address if called with address definition', async () => {
            await fc.assert(
                fc.asyncProperty(evmAddressArbitrary, endpointArbitrary, async (address, eid) => {
                    await expect(createSignerAddressOrIndexFactory({ type: 'address', address })(eid)).resolves.toBe(
                        address
                    )
                })
            )
        })

Summary: Calling `createSignerAddressOrIndexFactory` with an address definition should return the provided address.


it('should return index if called with index definition', async () => {
            await fc.assert(
                fc.asyncProperty(fc.integer(), endpointArbitrary, async (index, eid) => {
                    await expect(createSignerAddressOrIndexFactory({ type: 'index', index })(eid)).resolves.toBe(index)
                })
            )
        })

Summary: The `createSignerAddressOrIndexFactory` function should resolve with the given index when called with an index definition.


it('should reject if called with a missing named definition', async () => {
            const mockGetNamedAccounts = jest.fn().mockResolvedValue({ wombat: '0xwombat' })
            const mockHre = {
                getNamedAccounts: mockGetNamedAccounts,
            }
            const hreFactory = jest.fn().mockResolvedValue(mockHre)

            await fc.assert(
                fc.asyncProperty(endpointArbitrary, async (eid) => {
                    await expect(
                        createSignerAddressOrIndexFactory({ type: 'named', name: 'no-wombat' }, hreFactory)(eid)
                    ).rejects.toThrow(`Missing named account 'no-wombat' for eid ${formatEid(eid)}`)
                })
            )
        })

Summary: Calling `createSignerAddressOrIndexFactory` with a non-existent named definition should result in a rejection with a specific error message indicating the missing account.


it('should resolve with an address if called with a defined named definition', async () => {
            const mockGetNamedAccounts = jest.fn().mockResolvedValue({ wombat: '0xwombat' })
            const mockHre = {
                getNamedAccounts: mockGetNamedAccounts,
            }
            const hreFactory = jest.fn().mockResolvedValue(mockHre)

            await fc.assert(
                fc.asyncProperty(endpointArbitrary, async (eid) => {
                    await expect(
                        createSignerAddressOrIndexFactory({ type: 'named', name: 'wombat' }, hreFactory)(eid)
                    ).resolves.toBe('0xwombat')
                })
            )
        })

Summary: The function `createSignerAddressOrIndexFactory` should resolve to the specific address `'0xwombat'` when provided with a named definition of type `'named'` and name `'wombat'`.


UnitTest.test('DialogChanges.init - no initial data', () => {
  const dialogChange = DialogChanges.init({ title: '', text: '' } as LinkDialogData, { } as LinkDialogCatalog);

  fc.assert(fc.property(fc.webUrl(), fc.asciiString(), fc.asciiString(), (url, title, text) => {
    const data = Fun.constant({ url: {
      value: url,
      meta: { title, text }
    }} as LinkDialogData);
    const dataNoMeta = Fun.constant({ url: {
      value: url,
      meta: { }
    }} as LinkDialogData);

    Assert.eq('on url change should include url title and text',
      Option.some<Partial<LinkDialogData>>({ title, text }),
      dialogChange.onChange(data, { name: 'url' }),
      tOption()
    );

    Assert.eq('on url change should fallback to url for text',
      Option.some<Partial<LinkDialogData>>({ title: '', text: url }),
      dialogChange.onChange(dataNoMeta, { name: 'url' }),
      tOption()
    );
  }));
})

Summary: `DialogChanges.onChange` should update with title and text from metadata when present, and fall back to using the URL as text when metadata is missing.


UnitTest.test('DialogChanges.init - with original data', () => {
  const dialogChange = DialogChanges.init({ title: 'orig title', text: 'orig text' } as LinkDialogData, { } as LinkDialogCatalog);
  const dialogChangeNoTitle = DialogChanges.init({ title: '', text: 'orig text' } as LinkDialogData, { } as LinkDialogCatalog);
  const dialogChangeNoText = DialogChanges.init({ title: 'orig title', text: '' } as LinkDialogData, { } as LinkDialogCatalog);

  fc.assert(fc.property(fc.webUrl(), fc.asciiString(), fc.asciiString(), (url, title, text) => {
    const data = Fun.constant({ url: {
      value: url,
      meta: { title, text }
    }} as LinkDialogData);

    Assert.eq('on url change should not try to change title and text',
      Option.none(),
      dialogChange.onChange(data, { name: 'url' }),
      tOption()
    );

    Assert.eq('No Title - on url change should only try to change title',
      Option.some<Partial<LinkDialogData>>({ title }),
      dialogChangeNoTitle.onChange(data, { name: 'url' }),
      tOption()
    );

    Assert.eq('No Text - on url change should only try to change text',
      Option.some<Partial<LinkDialogData>>({ text }),
      dialogChangeNoText.onChange(data, { name: 'url' }),
      tOption()
    );
  }));
})

Summary: `DialogChanges.init` verifies that on a URL change, it neither alters the title nor text if both are initially provided, updates only the title if absent, and updates only the text if it is missing.


UnitTest.test('KAssert.eqError: success (reflexivity)', () => {
  fc.assert(fc.property(fc.integer(), (i) => {
    KAssert.eqError('eq', i, Result.error(i));
    KAssert.eqError('eq', i, Result.error(i), tBoom());
    KAssert.eqError('eq', i, Result.error(i), tBoom(), tNumber);
  }));
})

Summary: `KAssert.eqError` ensures that comparing an integer with `Result.error` of the same integer succeeds, demonstrating reflexivity.


t.test('toValue', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), n => {
      t.equal(t_value(n), Number(n));
    }),
    {
      examples: [[0n], [1n], [0xffffffffn], [0xffffffffffffffffn]]
    }
  );

  t.end();
})

Summary: `t_value` correctly converts a bigint to its equivalent number representation.


t.test('toU32', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), n => {
      t.equal(t_u32(n), BigInt.asUintN(32, n));
    }),
    {
      examples: [
        [0n],
        [1n],
        [0xffffn],
        [0xffffffffn],
        [0xffffffffffffffffn],
        [-0xffffn],
        [-0xffffffffn],
        [-0xffffffffffffffffn]
      ]
    }
  );

  t.end();
})

Summary: The function `t_u32` should return the same result as `BigInt.asUintN(32, n)` for various big integers.


t.test('toI32', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), n => {
      t.equal(t_i32(n), BigInt.asIntN(32, n));
    }),
    {
      examples: [
        [0n],
        [1n],
        [0xffffn],
        [0xffffffffn],
        [0xffffffffffffffffn],
        [0xffffffffffff1234n],
        [-0xffffn],
        [-0xffffffffn],
        [-0xffffffffffffffffn],
        [-0xffffffffffff1234n]
      ]
    }
  );

  t.end();
})

Summary: The `t_i32` function should produce the same 32-bit integer result as `BigInt.asIntN(32, n)` for any given bigint `n`.


UnitTest.test('KAssert.eqError: failure', () => {
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('should throw if numbers differ #1', () => {
      KAssert.eqError('eq', a, Result.error(b));
    });
    Assert.throws('should throw if numbers differ #2', () => {
      KAssert.eqError('eq', a, Result.error(b), tBoom());
    });
    Assert.throws('should throw if numbers differ #2', () => {
      KAssert.eqError('eq', a, Result.error(b), tBoom(), tNumber);
    });
  }));

  fc.assert(fc.property(fc.integer(), fc.string(), (i, s) => {
    Assert.throws('should throw if value #1', () => {
      KAssert.eqError('eq', i, Result.value(s));
    });
    Assert.throws('should throw if value #2', () => {
      KAssert.eqError('eq', i, Result.value(s), tBoom());
    });
    Assert.throws('should throw if value #3', () => {
      KAssert.eqError('eq', i, Result.value(s), tBoom(), tBoom());
    });
  }));
})

Summary: KAssert.eqError should throw an error when comparing mismatched integers and when integers are compared with Result objects containing different numbers or strings.


t.test('toU64', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), n => {
      t.equal(t_u64(n), BigInt.asUintN(64, n));
    })
  );

  t.end();
})

Summary: `t_u64` should convert a big integer to its unsigned 64-bit representation, matching `BigInt.asUintN(64, n)`.


t.test('toI64', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), n => {
      t.equal(t_i64(n), BigInt.asIntN(64, n));
    })
  );

  t.end();
})

Summary: The function `t_i64` should return the same result as `BigInt.asIntN(64, n)` when applied to a big integer.


t.test('asUintN', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), fc.integer({ min: 0, max: N }), (n, m) => {
      // t.equal(t_asUintN(m, n), n & ((1n << BigInt(m)) - 1n));
      // t.equal(t_asUintN(m, n), mod(n, 1n << BigInt(m)));
      t.equal(t_asUintN(m, n), BigInt.asUintN(m, n));
    }),
    {
      examples: [
        [0n, 0],
        [1n, 0],
        [-1n, 0],
        [1n, 1],
        [-1n, 1]
      ]
    }
  );

  t.end();
})

Summary: `asUintN` should produce the same result as `BigInt.asUintN` when applied to a big integer and a width in bits.


UnitTest.test('KAssert.eqValue: failure', () => {
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('should throw if numbers differ #1', () => {
      KAssert.eqValue('eq', a, Result.value(b));
    });
    Assert.throws('should throw if numbers differ #2', () => {
      KAssert.eqValue('eq', a, Result.value(b), tNumber);
    });
    Assert.throws('should throw if numbers differ #2', () => {
      KAssert.eqValue('eq', a, Result.value(b), tNumber, tBoom());
    });
  }));

  fc.assert(fc.property(fc.integer(), fc.string(), (i, s) => {
    Assert.throws('should throw if error #1', () => {
      KAssert.eqValue('eq', i, Result.error(s));
    });
    Assert.throws('should throw if error #2', () => {
      KAssert.eqValue('eq', i, Result.error(s), tBoom());
    });
    Assert.throws('should throw if error #3', () => {
      KAssert.eqValue('eq', i, Result.error(s), tBoom(), tBoom());
    });
  }));
})

Summary: `KAssert.eqValue` should throw an error when the actual result, either a different number or an error message, does not match the expected value.


UnitTest.test('KAssert.eqResult: success', () => {
  fc.assert(fc.property(fc.integer(), (i) => {
    KAssert.eqResult('eq', Result.value(i), Result.value(i));
    KAssert.eqResult('eq', Result.value(i), Result.value(i), tNumber);
    KAssert.eqResult('eq', Result.value(i), Result.value(i), tNumber, tBoom());
    KAssert.eqResult('eq', Result.error(i), Result.error(i));
    KAssert.eqResult('eq', Result.error(i), Result.error(i), tBoom());
    KAssert.eqResult('eq', Result.error(i), Result.error(i), tBoom(), tNumber);
  }));
})

Summary: `KAssert.eqResult` verifies the equality between `Result.value` and `Result.error` instances for the same integer, with optional type and testable checks.


t.test('log2', t => {
  fc.assert(
    fc.property(fc.bigInt({ min: 1n, max: M }), n => {
      t.equal(t_log2(n), BigIntMath.log(2, n));
    })
  );

  // Identity
  fc.assert(
    fc.property(fc.bigInt(1n, 1000n), n => {
      t.equal(t_log2(2n ** n), n);
    })
  );

  t.end();
})


t.test('log10', t => {
  fc.assert(
    fc.property(fc.bigInt({ min: 1n, max: M }), n => {
      t.equal(t_log10(n), BigIntMath.log(10, n));
    })
  );

  // Identity
  fc.assert(
    fc.property(fc.bigInt(1n, 1000n), n => {
      t.equal(t_log10(10n ** n), n);
    })
  );

  t.end();
})


Summary: `log2` of a big integer `n` should match `BigIntMath.log(2, n)`, and for `2^n`, the result should be `n`.


UnitTest.test('KAssert.eqResult: fail', () => {
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('value(a) != (value(!a)) #1', () => {
      KAssert.eqResult('eq', Result.value(a), Result.value(b));
    });
    Assert.throws('value(a) != (value(!a)) #2', () => {
      KAssert.eqResult('eq', Result.value(a), Result.value(b), tNumber);
    });
    Assert.throws('value(a) != (value(!a)) #2', () => {
      KAssert.eqResult('eq', Result.value(a), Result.value(b), tNumber, tBoom());
    });
  }));

  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('error(a) != (error(!a)) #1', () => {
      KAssert.eqResult('eq', Result.error(a), Result.error(b));
    });
    Assert.throws('error(a) != (error(!a)) #2', () => {
      KAssert.eqResult('eq', Result.error(a), Result.error(b), tBoom());
    });
    Assert.throws('result(a) != (result(!a)) #2', () => {
      KAssert.eqResult('eq', Result.error(a), Result.error(b), tBoom(), tNumber);
    });
  }));

  fc.assert(fc.property(fc.integer(), fc.string(), (i, s) => {
    Assert.throws('value != error #1', () => {
      KAssert.eqResult('eq', Result.value(i), Result.error(s));
    });
    Assert.throws('value != error #2', () => {
      KAssert.eqResult('eq', Result.value(i), Result.error(s), tBoom());
    });
    Assert.throws('value != error #3', () => {
      KAssert.eqResult('eq', Result.value(i), Result.error(s), tBoom());
    });

    Assert.throws('error != value #1', () => {
      KAssert.eqResult('eq', Result.error(i), Result.value(s));
    });
    Assert.throws('error != value #2', () => {
      KAssert.eqResult('eq', Result.error(i), Result.value(s), tBoom());
    });
    Assert.throws('error != value #3', () => {
      KAssert.eqResult('eq', Result.error(i), Result.value(s), tBoom(), tBoom());
    });
  }));
})

Summary: `KAssert.eqResult` throws an error when comparing differing `Result` types or values, verifying mismatches correctly trigger exceptions.


Summary: Verifies that `KAssert.eqResult` throws an exception when comparing different `Result.value` and `Result.error` instances across various configurations and types.


Summary: The modulo operation on randomly generated big integers should yield the same result for both `t_mod` and `BigIntMath.mod`, with specific examples to validate this behavior.


t.test('toString(10)', t => {
    t.equal(t_string('0'), '0');
    t.equal(t_string('-0xbeef'), '-48879');
    t.equal(t_string('0xdeadbeef'), '3735928559');

    fc.assert(
      fc.property(fc.bigIntN(N), n => {
        t.equal(t_string(n), n.toString());
      })
    );

    t.end();
  })

Summary: Converts integers to strings in base 10, ensuring output matches expected representations.


UnitTest.test('KAssert.eqSome: failure', () => {
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('some(i) != some(!i) #1', () => {
      KAssert.eqSome('eq', a, Option.some(b));
    });
  }));
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('some(i) != some(!i) #2', () => {
      KAssert.eqSome('eq', a, Option.some(b), tNumber);
    });
  }));
})

Summary: `KAssert.eqSome` should throw an error when comparing two different numbers wrapped in `Option.some`.


UnitTest.test('KAssert.eqOption: success (reflexivity)', () => {
  fc.assert(fc.property(fc.integer(), (i) => {
    KAssert.eqOption('eq', Option.some(i), Option.some(i));
    KAssert.eqOption('eq', Option.some(i), Option.some(i), tNumber);
  }));
  KAssert.eqOption('eq', Option.none(), Option.none());
})

Summary: `KAssert.eqOption` should confirm that two identical `Option` instances (either `some` with the same integer or `none`) are considered equal.


t.test('toString(16)', t => {
    t.equal(t_string('0', 16), '0');
    t.equal(t_string('-0xbeef', 16), '-beef');
    t.equal(t_string('0xdeadbeef', 16), 'deadbeef');

    fc.assert(
      fc.property(fc.bigIntN(N), n => {
        t.equal(t_string(n, 16), n.toString(16));
      })
    );

    t.end();
  })

Summary: The function `t_string` should correctly convert big integers to their hexadecimal string representation, matching the output of `n.toString(16)`.


UnitTest.test('KAssert.eqOption: failure', () => {
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('some(i) != some(!i) #1', () => {
      KAssert.eqOption('eq', Option.some(a), Option.some(b));
    });
  }));
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('some(i) != some(!i) #2', () => {
      KAssert.eqOption('eq', Option.some(a), Option.some(b), tNumber);
    });
  }));
  fc.assert(fc.property(fc.integer(), (i) => {
    Assert.throws('none != some(i) #1', () => {
      KAssert.eqOption('eq', Option.none(), Option.some(i));
    });
    Assert.throws('none != some(i) #2', () => {
      KAssert.eqOption('eq', Option.none(), Option.some(i), tBoom());
    });
  }));
  fc.assert(fc.property(fc.integer(), (i) => {
    Assert.throws('some(i) != none #1', () => {
      KAssert.eqOption('eq', Option.some(i), Option.none());
    });
    Assert.throws('some(i) != none #2', () => {
      KAssert.eqOption('eq', Option.some(i), Option.none(), tBoom());
    });
  }));
})

Summary: `KAssert.eqOption` throws errors when comparing different `Option` values, verifying the detection of inequality between `some` and `none` or mismatched `some` values.


UnitTest.test('capitalize: head is uppercase', () => {
  fc.assert(fc.property(fc.ascii(), fc.asciiString(30), (h, t) => {
    const actualH = Strings.capitalize(h + t).charAt(0);
    Assert.eq('head is uppercase', h.toUpperCase(), actualH, tString);
  }));
})

Summary: `Strings.capitalize` converts the first character of a string to uppercase.


UnitTest.test('ResultInstances.eq: value(x) = value(x)', () => {
  fc.assert(fc.property(fc.integer(), (i) => {
    Assert.eq(
      'results should be equal',
      Result.value<number, string>(i),
      Result.value<number, string>(i),
      tResult(tNumber, tString)
    );
  }));
})

Summary: `ResultInstances.eq` ensures that two identical `Result.value` instances created with the same integer value are considered equal.


UnitTest.test('ResultInstances.eq: error(x) = error(x)', () => {
  fc.assert(fc.property(fc.integer(), (i) => {
    Assert.eq(
      'results should be equal',
      Result.error<string, number>(i),
      Result.error<string, number>(i),
      tResult(tString, tNumber)
    );
  }));
})

Summary: `ResultInstances.eq` confirms that two `Result.error` instances with the same error value are considered equal.


t.test('div_pow2', t => {
  fc.assert(
    fc.property(
      fc.bigIntN(N),
      fc.bigInt({ min: 0n, max: 2n ** 16n }),
      (n, m) => {
        t.equal(t_div_pow2(n, m), n / 2n ** m);
      }
    ),
    {
      examples: [
        [-1n, 1n],
        [1n, 1n],
        [0xdeadbeefn, 1n],
        [0xdeadbeefn, 8n],
        [0xdeadbeefn, 32n],
        [0xdeadbeefn, 64n],
        [-0xdeadbeefn, 64n]
      ]
    }
  );

  t.end();
})

Summary: The function `t_div_pow2` should correctly divide a given big integer `n` by `2` raised to the power of `m`, matching the expected result of integer division.


t.test('and', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), fc.bigIntN(N), (n, m) => {
      t.equal(t_and(n, m), n & m);
    })
  );

  t.end();
})

Summary: The bitwise `and` operation on two `bigIntN` values should match the result of using the `&` operator.


UnitTest.test('ResultInstances.eq: value(a) != error(e)', () => {
  fc.assert(fc.property(fc.integer(), fc.string(), (a, e) => {
    Assert.eq(
      'results should not be equal #1',
      false,
      tResult(tNumber, tString).eq(
        Result.value<number, string>(a),
        Result.error<number, string>(e)
      ));

    Assert.eq(
      'results should not be equal #2',
      false,
      tResult(tNumber, tString).eq(
        Result.error<number, string>(e),
        Result.value<number, string>(a)
      ));
  }));
})

Summary: The test ensures that `ResultInstances.eq` correctly identifies `Result.value` and `Result.error` as not equal when one is a value and the other is an error, regardless of the order.


UnitTest.test('ResultInstances.eq: (a = b) = (value(a) = value(b))', () => {
  fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => {
    Assert.eq(
      'eq',
      a === b,
      tResult(tNumber, tString).eq(
        Result.value<number, string>(a),
        Result.value<number, string>(b)
      ));
  }));
})

Summary: `ResultInstances.eq` checks if the equality of two `Result` values matches the equality of their contained integer values.


t.test('or', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), fc.bigIntN(N), (n, m) => {
      t.equal(t_or(n, m), n | m);
    })
  );

  t.end();
})

Summary: Verifies that the `t_or` function produces the same result as the bitwise OR operation between two big integers.


t.test('not', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), n => {
      t.equal(t_not(n), ~n);
    })
  );

  t.end();
})

Summary: The `t_not` function should produce the bitwise negation of a given integer.


UnitTest.test('ResultInstances.eq: (a = b) = (error(a) = error(b))', () => {
  fc.assert(fc.property(fc.string(), fc.string(), (a, b) => {
    Assert.eq(
      'eq',
      a === b,
      tResult(tNumber, tString).eq(
        Result.error<number, string>(a),
        Result.error<number, string>(b)
      ));
  }));
})

Summary: `ResultInstances.eq` equates two `Result.error` instances based on the equality of their error values.


UnitTest.test('Options.cat of only nones should be an empty array', () => {
  fc.assert(fc.property(
    fc.array(ArbDataTypes.arbOptionNone()),
    (options) => {
      const output = Options.cat(options);
      Assert.eq('eq', 0, output.length);
    }
  ));
})

Summary: `Options.cat` applied to an array of `None` options results in an empty array.


t.test('identities', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), n => {
      // identity ~(~x) = x
      t.equal(to(mpz.not(mpz.not(from(n)))), n);

      t.equal(t_and(n, n), n);
      t.equal(t_or(n, n), n);
      t.equal(t_xor(n, n), 0n);
    })
  );

  fc.assert(
    fc.property(fc.bigIntN(N), fc.bigInt({ min: 1n, max: 4096n }), (n, m) => {
      // a << b >> b = a
      t.equal(to(mpz.shr(mpz.shl(from(n), from(m)), from(m))), n);
    })
  );

  fc.assert(
    fc.property(fc.bigIntN(N), fc.bigIntN(N), (x, y) => {
      const X = from(x);
      const Y = from(y);

      t.equal(to(mpz.not(mpz.and(X, Y))), ~x | ~y); // ~(x & y) = ~x | ~y
      t.equal(to(mpz.not(mpz.or(X, Y))), ~x & ~y); // ~(x | y) = ~x & ~y
      // TODO: identity x^y == x|y &~ x&y
    })
  );

  t.end();
})


UnitTest.test('Options.cat of Arr.map(xs, Option.some) should be xs', () => {
  fc.assert(fc.property(
    fc.array(fc.json()),
    (arr) => {
      const options = Arr.map(arr, Option.some);
      const output = Options.cat(options);
      Assert.eq('eq', arr, output);
    }
  ));
})

Summary: `Options.cat` applied to an array of `Option.some` should return the original array.


UnitTest.test('Options.cat of somes and nones should have length <= original', () => {
  fc.assert(fc.property(
    fc.array(ArbDataTypes.arbOption(fc.integer())),
    (arr) => {
      const output = Options.cat(arr);
      Assert.eq('eq', output.length <= arr.length, true);
    }
  ));
})

Summary: `Options.cat` should produce an array with a length less than or equal to the original when applied to arrays of optional integers.


UnitTest.test('Options.cat of nones.concat(somes).concat(nones) should be somes', () => {
  fc.assert(fc.property(
    fc.array(fc.json()),
    fc.array(fc.json()),
    fc.array(fc.json()),
    (before, on, after) => {
      const beforeNones = Arr.map(before, Option.none);
      const afterNones = Arr.map(after, Option.none);
      const onSomes = Arr.map(on, Option.some);
      const output = Options.cat(beforeNones.concat(onSomes).concat(afterNones));
      Assert.eq('eq', on, output);
    }
  ));
})

Summary: The `Options.cat` function should return only the `somes` from concatenated arrays of `nones` and `somes`.


UnitTest.test('Option.someIf: false -> none', () => {
  fc.assert(fc.property(fc.integer(), (n) => {
    Assert.eq('eq', Option.none(), Options.someIf<number>(false, n), tOption());
  }));
})

Summary: `Options.someIf` returns `Option.none()` when the condition is false, regardless of the integer provided.


t.test('gcd', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), fc.bigIntN(N), (n, m) => {
      t.equal(t_gcd(n, m), BigIntMath.gcd(n, m));
    })
  );

  t.end();
})

Summary: The test verifies that the `t_gcd` function produces the same result as `BigIntMath.gcd` for pairs of generated big integers.


t.test('lcm', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), fc.bigIntN(N), (n, m) => {
      t.equal(t_lcm(n, m), BigIntMath.lcm(n, m));
    })
  );

  t.end();
})

Summary: The least common multiple of two big integers should match the result of `BigIntMath.lcm`.


t.test('inc', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), n => {
      t.equal(t_inc(n), n + 1n);
    }),
    {
      examples: [[0n], [-1n], [1n]]
    }
  );

  t.end();
})

Summary: `t_inc` increments a given big integer by 1.


t.test('dec', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), n => {
      t.equal(t_dec(n), n - 1n);
    }),
    {
      examples: [[0n], [-1n], [1n]]
    }
  );

  t.end();
})

Summary: `dec` function correctly decrements a given big integer by one.


UnitTest.test('Option.someIf: true -> some', () => {
  fc.assert(fc.property(fc.integer(), (n) => {
    Assert.eq('eq', Option.some(n), Options.someIf<number>(true, n), tOption());
  }));
})

Summary: `Options.someIf` returns `Option.some(n)` when the condition is true.


UnitTest.test('Options.sequence: Single some value', () => {
  fc.assert(fc.property(fc.integer(), (n) => {
    Assert.eq('eq', Option.some([ n ]), Options.sequence([ Option.some(n) ]), tOption());
  }));
})

Summary: `Options.sequence` converts an array containing a single `Option.some` value into an `Option.some` array with the same value.


UnitTest.test('Options.sequence: Two some values', () => {
  fc.assert(fc.property(fc.integer(), fc.integer(), (n, m) => {
    Assert.eq('eq', Option.some([ n, m ]), Options.sequence<number>([ Option.some(n), Option.some(m) ]), tOption());
  }));
})

Summary: `Options.sequence` should return `Option.some` with an array of the input values when given an array of `Option.some` values.