Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions packages/mesh-common/src/data/value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ import {
const compareByteOrder = (a: string, b: string): number =>
a < b ? -1 : a > b ? 1 : 0;

// A JS number cannot hold every lovelace amount. 2^53 + 1 is still under max ADA.
const jsInteger = (amount: bigint): number | bigint => {
const asNumber = Number(amount);
return BigInt(asNumber) === amount ? asNumber : amount;
};

/**
* Aiken alias
* Value is the JSON representation of Cardano data Value
Expand Down Expand Up @@ -377,7 +383,7 @@ export class MeshValue {
toJSON = (): Value => {
const valueMapToParse: [CurrencySymbol, AssocMap<TokenName, Integer>][] =
[];
const valueMap: { [key: string]: { [key: string]: number } } = {};
const valueMap: { [key: string]: { [key: string]: bigint } } = {};

this.toAssets().forEach((asset) => {
const sanitizedName = asset.unit.replace("lovelace", "");
Expand All @@ -388,10 +394,11 @@ export class MeshValue {
valueMap[policy] = {};
}

if (!valueMap[policy]![token]) {
valueMap[policy]![token] = Number(asset.quantity);
const quantity = BigInt(asset.quantity);
if (valueMap[policy]![token] === undefined) {
valueMap[policy]![token] = quantity;
} else {
valueMap[policy]![token] += Number(asset.quantity);
valueMap[policy]![token] += quantity;
}
});

Expand All @@ -406,7 +413,7 @@ export class MeshValue {
);
const tokens: [TokenName, Integer][] = sortedTokenNames.map((name) => [
tokenName(name),
integer(valueMap[policy]![name]!),
integer(jsInteger(valueMap[policy]![name]!)),
]);

const policyMap = assocMap(tokens);
Expand Down
9 changes: 9 additions & 0 deletions packages/mesh-common/test/data/value/convertor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,15 @@ describe("MeshValue class", () => {
expect(JSON.stringify(jsonValue)).toEqual(JSON.stringify(expectedValue));
});

test("keeps a lovelace quantity that does not fit in a JS number", () => {
const quantity = "9007199254740993";
const meshValue = new MeshValue();
meshValue.toAssets = () => [{ unit: "lovelace", quantity }];

const jsonValue = meshValue.toJSON();
expect(jsonValue.map[0].v.map[0].v.int).toBe(BigInt(quantity));
});

test("should correctly convert MeshValue to JSON with no asset", () => {
const assets: Asset[] = [];

Expand Down