Skip to content

Commit

Permalink
Feat: Add toE8s to TokenAmountV2
Browse files Browse the repository at this point in the history
  • Loading branch information
lmuntaner committed Jan 26, 2024
1 parent f89b3d0 commit 1908f7f
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
72 changes: 72 additions & 0 deletions packages/utils/src/parser/token.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,32 @@ describe("TokenAmountV2 with 18 decimals", () => {
FromStringToTokenError.InvalidFormat,
);
});

it("returns the value in e8s", () => {
expect(
(
TokenAmountV2.fromString({ amount: "2", token }) as TokenAmountV2
).toE8s(),
).toEqual(200_000_000n);

expect(
(
TokenAmountV2.fromString({ amount: "0.21", token }) as TokenAmountV2
).toE8s(),
).toEqual(21_000_000n);

expect(
(
TokenAmountV2.fromString({ amount: "0.00021", token }) as TokenAmountV2
).toE8s(),
).toEqual(21_000n);

expect(
(
TokenAmountV2.fromString({ amount: "2000", token }) as TokenAmountV2
).toE8s(),
).toEqual(200_000_000_000n);
});
});

describe("TokenAmountV2 with 2 decimals", () => {
Expand Down Expand Up @@ -393,6 +419,26 @@ describe("TokenAmountV2 with 2 decimals", () => {
}),
);
});

it("returns the value in e8s", () => {
expect(
(
TokenAmountV2.fromString({ amount: "2", token }) as TokenAmountV2
).toE8s(),
).toEqual(200_000_000n);

expect(
(
TokenAmountV2.fromString({ amount: "0.21", token }) as TokenAmountV2
).toE8s(),
).toEqual(21_000_000n);

expect(
(
TokenAmountV2.fromString({ amount: "2000", token }) as TokenAmountV2
).toE8s(),
).toEqual(200_000_000_000n);
});
});

describe("TokenAmountV2 with 0 decimals", () => {
Expand Down Expand Up @@ -472,4 +518,30 @@ describe("TokenAmountV2 with 8 decimals", () => {
TokenAmountV2.fromUlps({ token: token, amount: 0n }),
);
});

it("returns the value in e8s", () => {
expect(
(
TokenAmountV2.fromString({ amount: "2", token }) as TokenAmountV2
).toE8s(),
).toEqual(200_000_000n);

expect(
(
TokenAmountV2.fromString({ amount: "0.21", token }) as TokenAmountV2
).toE8s(),
).toEqual(21_000_000n);

expect(
(
TokenAmountV2.fromString({ amount: "0.00021", token }) as TokenAmountV2
).toE8s(),
).toEqual(21_000n);

expect(
(
TokenAmountV2.fromString({ amount: "2000", token }) as TokenAmountV2
).toE8s(),
).toEqual(200_000_000_000n);
});
});
14 changes: 14 additions & 0 deletions packages/utils/src/parser/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,4 +322,18 @@ export class TokenAmountV2 {
public toUlps(): bigint {
return this.ulps;
}

/**
*
* @returns The amount of ulps in e8s precision
*/
public toE8s(): bigint {
if (this.token.decimals < 8) {
return this.ulps * 10n ** BigInt(8 - this.token.decimals);
} else if (this.token.decimals === 8) {
return this.ulps;
} else {
return this.ulps / 10n ** BigInt(this.token.decimals - 8);
}
}
}

0 comments on commit 1908f7f

Please sign in to comment.