Skip to content

Commit

Permalink
fix(faucet): isValidAddress should accept all bech32 addresses
Browse files Browse the repository at this point in the history
  • Loading branch information
0xpatrickdev committed Jun 7, 2024
1 parent f71cdc3 commit c512de3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
20 changes: 20 additions & 0 deletions packages/faucet/src/addresses.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
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);
});
});
13 changes: 9 additions & 4 deletions packages/faucet/src/addresses.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
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;
}
Expand Down

0 comments on commit c512de3

Please sign in to comment.