diff --git a/src/index.ts b/src/index.ts index 53fead4..87a8895 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,4 +9,5 @@ export * from "./nameparser"; export * from "./nft"; export * from "./number"; export * from "./price"; -export * from "./time"; \ No newline at end of file +export * from "./time"; +export * from "./transaction"; \ No newline at end of file diff --git a/src/transaction.test.ts b/src/transaction.test.ts new file mode 100644 index 0000000..30bf7e9 --- /dev/null +++ b/src/transaction.test.ts @@ -0,0 +1,30 @@ +import { describe, it, expect } from "vitest"; +import { buildTxnHash } from "./transaction"; + +describe("buildTxnHash() function", () => { + + it("doesn't begin with 0x", () => { + const hash = "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"; + + expect(() => buildTxnHash(hash)).toThrow(); + }); + + it("too few digits", () => { + const hash = "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcde"; + + expect(() => buildTxnHash(hash)).toThrow(); + }); + + it("too many digits", () => { + const hash = "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1"; + + expect(() => buildTxnHash(hash)).toThrow(); + }); + + it("valid hash", () => { + const hash = "0x1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF"; + + const result = buildTxnHash(hash); + expect(result.hash).toStrictEqual(hash.toLowerCase()); + }); +}); \ No newline at end of file diff --git a/src/transaction.ts b/src/transaction.ts new file mode 100644 index 0000000..8400bde --- /dev/null +++ b/src/transaction.ts @@ -0,0 +1,21 @@ +export interface TxnHash { + hash: `0x${string}`; +} + +const regex = /^0x[0-9a-fA-F]{64}$/; + +const isTxnHash = (maybeTxnHash: string): boolean => { + return regex.test(maybeTxnHash); +} + +export const buildTxnHash = (maybeTxnHash: string): TxnHash => { + + if (!isTxnHash(maybeTxnHash)) + throw new Error(`Invalid transaction hash: ${maybeTxnHash}`); + + const normalizedHash = maybeTxnHash.toLowerCase() as `0x${string}`; + + return { + hash: normalizedHash + }; +} \ No newline at end of file