diff --git a/.changeset/strange-vans-sit.md b/.changeset/strange-vans-sit.md new file mode 100644 index 00000000..483011fe --- /dev/null +++ b/.changeset/strange-vans-sit.md @@ -0,0 +1,5 @@ +--- +"permissionless": patch +--- + +Added encodeNonce util function diff --git a/packages/permissionless/utils/encodeNonce.test.ts b/packages/permissionless/utils/encodeNonce.test.ts new file mode 100644 index 00000000..f3214f2e --- /dev/null +++ b/packages/permissionless/utils/encodeNonce.test.ts @@ -0,0 +1,38 @@ +import { encodeNonce } from "permissionless/utils" +import { toHex } from "viem" +import { describe, expect, test } from "vitest" + +describe("encodeNonce", () => { + test("should encode key and sequence correctly", async () => { + const key = 123456789012345678901234n + const sequence = 9876543210n + const expectedKey = BigInt(toHex(key, { size: 24 })) + const expectedSequence = BigInt(toHex(sequence, { size: 8 })) + + const result = encodeNonce({ key, sequence }) + + expect(result).toBe((expectedKey << BigInt(64)) + expectedSequence) + }) + + test("should handle zero values correctly", () => { + const key = BigInt(0) + const sequence = BigInt(0) + const expectedKey = BigInt(toHex(key, { size: 24 })) + const expectedSequence = BigInt(toHex(sequence, { size: 8 })) + + const result = encodeNonce({ key, sequence }) + + expect(result).toBe((expectedKey << BigInt(64)) + expectedSequence) + }) + + test("should handle large values correctly", () => { + const key = BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFF") + const sequence = BigInt("0xFFFFFFFF") + const expectedKey = BigInt(toHex(key, { size: 24 })) + const expectedSequence = BigInt(toHex(sequence, { size: 8 })) + + const result = encodeNonce({ key, sequence }) + + expect(result).toBe((expectedKey << BigInt(64)) + expectedSequence) + }) +}) diff --git a/packages/permissionless/utils/encodeNonce.ts b/packages/permissionless/utils/encodeNonce.ts new file mode 100644 index 00000000..89387fa5 --- /dev/null +++ b/packages/permissionless/utils/encodeNonce.ts @@ -0,0 +1,8 @@ +import { toHex } from "viem" + +export function encodeNonce(args: { key: bigint; sequence: bigint }): bigint { + const key = BigInt(toHex(args.key, { size: 24 })) + const sequence = BigInt(toHex(args.sequence, { size: 8 })) + + return (key << BigInt(64)) + sequence +} diff --git a/packages/permissionless/utils/index.ts b/packages/permissionless/utils/index.ts index 99d5896c..ef3fee6a 100644 --- a/packages/permissionless/utils/index.ts +++ b/packages/permissionless/utils/index.ts @@ -23,6 +23,7 @@ export function parseAccount(account: Address | Account): Account { return { address: account, type: "json-rpc" } return account } +import { encodeNonce } from "./encodeNonce" import { ENTRYPOINT_ADDRESS_V06, ENTRYPOINT_ADDRESS_V07, @@ -47,6 +48,7 @@ export { getAddressFromInitCodeOrPaymasterAndData, getPackedUserOperation, getEntryPointVersion, + encodeNonce, ENTRYPOINT_ADDRESS_V06, ENTRYPOINT_ADDRESS_V07 }