From 74e6b9c470486fe57493b6d82a9b8311e514ea15 Mon Sep 17 00:00:00 2001 From: Stoyan Dimitrov Date: Mon, 12 Feb 2024 17:10:35 -0500 Subject: [PATCH] Hex check (#8) * update jest lib * adding increment and toHexNonce methods and tests, adding more readme * adding 0x check --- package.json | 2 +- src/index.ts | 13 +++++++++++++ test/index.spec.ts | 6 ++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 65500f6..86d6ac8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@beamnetwork/nonce-2d", - "version": "0.0.5", + "version": "0.0.6", "description": "", "main": "./dist/index.js", "module": "./dist/index.mjs", diff --git a/src/index.ts b/src/index.ts index 3394fde..f8d3ea3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -32,6 +32,7 @@ export class Nonce2D { private _address: string private constructor(hexNonce2D: string) { + hexNonce2D = include0x(hexNonce2D) const { key, chain, address } = this.getKeyHex(BigInt(hexNonce2D)) this._key = key this._chain = chain @@ -192,6 +193,18 @@ function stripOx(hex: string): string { return hex } +/** + * helper function to include the 0x prefix in a hex string + * @param hex the hex string to include the 0x prefix + * @returns + */ +function include0x(hex: string): string { + if (!hex.startsWith('0x')) { + return '0x' + hex + } + return hex +} + /** * Helper function to padd a string with leading 0s * @param hexInput string to pad diff --git a/test/index.spec.ts b/test/index.spec.ts index f1da571..b16888d 100644 --- a/test/index.spec.ts +++ b/test/index.spec.ts @@ -90,6 +90,12 @@ describe('Nonce2D tests', () => { expect(n.toHexNonce()).toBe(testsHexNonce) }) + it('should support lack of 0x infrom of string', () => { + const missing = testsHexNonce.substring(2) + const n = Nonce2D.fromHexNonce(missing) + expect(n.toHexNonce()).toBe(testsHexNonce) + }) + it('should be able to increment and reconstitute a new hex nonce', () => { // construct new nonce by incrementing the sequence number const nextNonce =