diff --git a/packages/faucet/src/addresses.spec.ts b/packages/faucet/src/addresses.spec.ts new file mode 100644 index 0000000000..639f52970d --- /dev/null +++ b/packages/faucet/src/addresses.spec.ts @@ -0,0 +1,22 @@ +import { isValidAddress } from "./addresses"; + +describe("isValidAddress", () => { + it("accepts account address", () => { + expect(isValidAddress("cosmos1h806c7khnvmjlywdrkdgk2vrayy2mmvf9rxk2r", "cosmos")).toBe(true); + }); + + it("accepts an ics-27 address", () => { + expect(isValidAddress("osmo1d6em9ea5y3dye6em0awqyss7ssp0a7sgjk792x8cx647cfs7a4msk0fr45", "osmo")).toBe( + true, + ); + }); + + it("rejects an invalid address", () => { + expect(isValidAddress("cosmos1fail", "cosmos")).toBe(false); + }); + + it("requires a prefix argument", () => { + // @ts-expect-error intentionally omitting an argument + expect(isValidAddress("cosmos1h806c7khnvmjlywdrkdgk2vrayy2mmvf9rxk2r")).toBe(false); + }); +}); diff --git a/packages/faucet/src/addresses.ts b/packages/faucet/src/addresses.ts index 6792a5414d..825de6bf9e 100644 --- a/packages/faucet/src/addresses.ts +++ b/packages/faucet/src/addresses.ts @@ -1,12 +1,14 @@ import { fromBech32 } from "@cosmjs/encoding"; +/** + * Check length based on Bech32 from {@link https://github.com/bitcoin/bips/blob/e1e7b77c027b3d40d07d306cc75c2b5859c91db2/bip-0173.mediawiki#bech32 | BIP173} + */ export function isValidAddress(input: string, requiredPrefix: string): boolean { try { const { prefix, data } = fromBech32(input); - if (prefix !== requiredPrefix) { - return false; - } - return data.length === 20; + return ( + prefix === requiredPrefix && input.length >= 8 && input.length <= 90 && data.length >= 4 // 6 chars = 30 bits (3.75 bytes), rounded to whole byte + ); } catch { return false; }