Add parseBankToken/parseBankTokens

This commit is contained in:
Simon Warta 2020-08-11 09:03:22 +02:00
parent 1e347d1de5
commit da4648374a
2 changed files with 95 additions and 0 deletions

View File

@ -0,0 +1,70 @@
import { parseBankToken, parseBankTokens } from "./tokens";
describe("tokens", () => {
describe("parseBankToken", () => {
it("works", () => {
expect(parseBankToken("COSM=10^6ucosm")).toEqual({
tickerSymbol: "COSM",
fractionalDigits: 6,
denom: "ucosm",
});
});
});
describe("parseBankTokens", () => {
it("works for one", () => {
expect(parseBankTokens("COSM=10^6ucosm")).toEqual([
{
tickerSymbol: "COSM",
fractionalDigits: 6,
denom: "ucosm",
},
]);
});
it("works for two", () => {
expect(parseBankTokens("COSM=10^6ucosm,STAKE=10^3mstake")).toEqual([
{
tickerSymbol: "COSM",
fractionalDigits: 6,
denom: "ucosm",
},
{
tickerSymbol: "STAKE",
fractionalDigits: 3,
denom: "mstake",
},
]);
});
it("ignores whitespace", () => {
expect(parseBankTokens("COSM=10^6ucosm, STAKE=10^3mstake\n")).toEqual([
{
tickerSymbol: "COSM",
fractionalDigits: 6,
denom: "ucosm",
},
{
tickerSymbol: "STAKE",
fractionalDigits: 3,
denom: "mstake",
},
]);
});
it("ignores empty elements", () => {
expect(parseBankTokens("COSM=10^6ucosm,STAKE=10^3mstake,")).toEqual([
{
tickerSymbol: "COSM",
fractionalDigits: 6,
denom: "ucosm",
},
{
tickerSymbol: "STAKE",
fractionalDigits: 3,
denom: "mstake",
},
]);
});
});
});

View File

@ -1,3 +1,5 @@
import { Uint53 } from "@cosmjs/math";
export interface BankTokenMeta {
readonly denom: string;
/**
@ -15,3 +17,26 @@ export interface BankTokenMeta {
*/
readonly fractionalDigits: number;
}
const parseBankTokenPattern = /^([a-zA-Z]{2,20})=10\^([0-9]+)([a-zA-Z]{2,20})$/;
export function parseBankToken(input: string): BankTokenMeta {
const match = input.match(parseBankTokenPattern);
if (!match) {
throw new Error("Token could not be parsed. Format: DISPLAY=10^DIGITSbase, e.g. ATOM=10^6uatom");
}
return {
tickerSymbol: match[1],
fractionalDigits: Uint53.fromString(match[2]).toNumber(),
denom: match[3],
};
}
export function parseBankTokens(input: string): BankTokenMeta[] {
return input
.trim()
.split(",")
.map((part) => part.trim())
.filter((part) => part !== "")
.map((part) => parseBankToken(part));
}