Skip to content
This repository has been archived by the owner on Jul 16, 2024. It is now read-only.

Commit

Permalink
feat: Add TxnHash
Browse files Browse the repository at this point in the history
  • Loading branch information
lightwalker-eth committed Apr 26, 2024
1 parent 8211ace commit e57b1e6
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ export * from "./nameparser";
export * from "./nft";
export * from "./number";
export * from "./price";
export * from "./time";
export * from "./time";
export * from "./transaction";
30 changes: 30 additions & 0 deletions src/transaction.test.ts
Original file line number Diff line number Diff line change
@@ -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());
});
});
21 changes: 21 additions & 0 deletions src/transaction.ts
Original file line number Diff line number Diff line change
@@ -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
};
}

0 comments on commit e57b1e6

Please sign in to comment.