Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(xrp): return 0 as default balance #8242

Merged
merged 4 commits into from
Oct 30, 2024
Merged
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
5 changes: 5 additions & 0 deletions .changeset/new-plums-shout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ledgerhq/coin-xrp": patch
---

Fix Cardano getAccountInfo
24 changes: 17 additions & 7 deletions libs/coin-modules/coin-xrp/src/api/index.integ.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { sign } from "ripple-keypairs";

describe("Xrp Api", () => {
let module: Api;
const address = "rKtXXTVno77jhu6tto1MAXjepyuaKaLcqB";
const address = "rh1HPuRVsYYvThxG2Bs1MfjmrVC73S16Fb";
const emptyAddress = "rKtXXTVno77jhu6tto1MAXjepyuaKaLcqB"; // Account with no transaction (at the time of this writing)
const xrpPubKey = process.env["PUB_KEY"]!;
const xrpSecretKey = process.env["SECRET_KEY"]!;

Expand All @@ -16,7 +17,6 @@ describe("Xrp Api", () => {
describe("estimateFees", () => {
it("returns a default value", async () => {
// Given
const address = "rDCyjRD2TcSSGUQpEcEhJGmDWfjPJpuGxu";
const amount = BigInt(100);

// When
Expand Down Expand Up @@ -56,12 +56,20 @@ describe("Xrp Api", () => {
});

describe("getBalance", () => {
it("returns a list regarding address parameter", async () => {
it("returns an amount above 0 when address has transactions", async () => {
// When
const result = await module.getBalance(address);

// Then
expect(result).toBeGreaterThan(0);
expect(result).toBeGreaterThan(BigInt(0));
});

it("returns 0 when address has no transaction", async () => {
// When
const result = await module.getBalance(emptyAddress);

// Then
expect(result).toBe(BigInt(0));
});
});

Expand All @@ -76,14 +84,16 @@ describe("Xrp Api", () => {
});

// Then
expect(result.slice(0, 34)).toEqual("120000228000000024001BCDA6201B001F");
expect(result.slice(0, 34)).toEqual("1200002280000000240002588F201B001D");
expect(result.slice(38)).toEqual(
"61400000000000000A6840000000000000018114CF30F590D7A9067B2604D80D46090FBF342EBE988314CA26FB6B0EF6859436C2037BA0A9913208A59B98",
"61400000000000000A68400000000000000181142A6ADC782DAFDDB464E434B684F01416B8A33B208314CA26FB6B0EF6859436C2037BA0A9913208A59B98",
);
});
});

describe("combine", () => {
// To enable this test, you need to fill an `.env` file at the root of this package. Example can be found in `.env.integ.test.example`.
// The value hardcoded here depends on the value filled in the `.env` file.
describe.skip("combine", () => {
it("returns a signed raw transaction", async () => {
// Given
const rawTx =
Expand Down
10 changes: 5 additions & 5 deletions libs/coin-modules/coin-xrp/src/bridge/synchronization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Operation } from "@ledgerhq/types-live";
import { encodeAccountId } from "@ledgerhq/coin-framework/account/index";
import { GetAccountShape, mergeOps } from "@ledgerhq/coin-framework/bridge/jsHelpers";
import { getAccountInfo, getServerInfos, getTransactions } from "../network";
import { NEW_ACCOUNT_ERROR_MESSAGE, parseAPIValue } from "../logic";
import { parseAPIValue } from "../logic";
import { filterOperations } from "./logic";

export const getAccountShape: GetAccountShape = async info => {
Expand All @@ -17,7 +17,7 @@ export const getAccountShape: GetAccountShape = async info => {
});
const accountInfo = await getAccountInfo(address);

if (!accountInfo || accountInfo.error === NEW_ACCOUNT_ERROR_MESSAGE) {
if (accountInfo.isNewAccount) {
return {
id: accountId,
xpub: address,
Expand All @@ -42,10 +42,10 @@ export const getAccountShape: GetAccountShape = async info => {
const minLedgerVersion = Number(ledgers[0]);
const maxLedgerVersion = Number(ledgers[1]);

const trustlines = accountInfo.account_data.OwnerCount;
const trustlines = accountInfo.ownerCount;

const balance = new BigNumber(accountInfo.account_data.Balance);
const spendableBalance = new BigNumber(accountInfo.account_data.Balance)
const balance = new BigNumber(accountInfo.balance);
const spendableBalance = new BigNumber(accountInfo.balance)
.minus(reserveMinXRP)
.minus(reservePerTrustline.times(trustlines));

Expand Down
6 changes: 2 additions & 4 deletions libs/coin-modules/coin-xrp/src/logic/getBalance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { getBalance } from "./getBalance";

const mockGetAccountInfo = jest.fn();
jest.mock("../network", () => ({
getAccountInfo: (arg: unknown) => mockGetAccountInfo(arg),
getAccountInfo: (address: string) => mockGetAccountInfo(address),
}));

describe("getBalance", () => {
Expand All @@ -16,9 +16,7 @@ describe("getBalance", () => {
const balance = faker.number.bigInt(100_000_000);
const address = "ACCOUNT_ADDRESS";
mockGetAccountInfo.mockResolvedValue({
account_data: {
Balance: balance.toString(),
},
balance,
});

// When
Expand Down
2 changes: 1 addition & 1 deletion libs/coin-modules/coin-xrp/src/logic/getBalance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ import { getAccountInfo } from "../network";

export async function getBalance(address: string): Promise<bigint> {
const accountInfo = await getAccountInfo(address);
return BigInt(accountInfo.account_data.Balance);
return BigInt(accountInfo.balance);
}
3 changes: 0 additions & 3 deletions libs/coin-modules/coin-xrp/src/logic/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,3 @@ export {
} from "./utils";

export { parseAPIValue } from "./common";

//FIXME
export { NEW_ACCOUNT_ERROR_MESSAGE } from "../network";
60 changes: 60 additions & 0 deletions libs/coin-modules/coin-xrp/src/logic/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { cachedRecipientIsNew } from "./utils";

jest.mock("ripple-address-codec", () => ({
isValidClassicAddress: () => true,
}));
const mockGetAccountInfo = jest.fn();
jest.mock("../network", () => ({
getAccountInfo: (address: string) => mockGetAccountInfo(address),
}));

describe("cachedRecipientIsNew", () => {
afterEach(() => {
mockGetAccountInfo.mockClear();
});

it("returns true when network returns a new empty account", async () => {
// Given
mockGetAccountInfo.mockResolvedValueOnce({
isNewAccount: true,
balance: "0",
ownerCount: 0,
sequence: 0,
});

// When
const result = await cachedRecipientIsNew("address1");

// Then
expect(mockGetAccountInfo).toHaveBeenCalledTimes(1);
expect(result).toBeTruthy();
});

it("returns false when network a valid AccountInfo", async () => {
// Given
mockGetAccountInfo.mockResolvedValueOnce({
isNewAccount: false,
balance: "999441667919804",
ownerCount: 0,
sequence: 999441667919804,
});

// When
const result = await cachedRecipientIsNew("address2");

// Then
expect(mockGetAccountInfo).toHaveBeenCalledTimes(1);
expect(result).toBeFalsy();
});

it("throws an error when network throws an error", async () => {
// Given
mockGetAccountInfo.mockImplementationOnce(() => {
throw new Error("Malformed address");
});

// When & Then
await expect(cachedRecipientIsNew("address3")).rejects.toThrow("Malformed address");
expect(mockGetAccountInfo).toHaveBeenCalledTimes(1);
});
});
9 changes: 3 additions & 6 deletions libs/coin-modules/coin-xrp/src/logic/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import BigNumber from "bignumber.js";
import { isValidClassicAddress } from "ripple-address-codec";
import { getAccountInfo, NEW_ACCOUNT_ERROR_MESSAGE } from "../network";
import { getAccountInfo } from "../network";

export const UINT32_MAX = new BigNumber(2).pow(32).minus(1);

Expand All @@ -15,7 +15,7 @@ export const validateTag = (tag: BigNumber) => {

export const getNextValidSequence = async (address: string) => {
const accInfo = await getAccountInfo(address, true);
return accInfo.account_data.Sequence;
return accInfo.sequence;
};

function isRecipientValid(recipient: string): boolean {
Expand All @@ -26,10 +26,7 @@ const recipientIsNew = async (recipient: string): Promise<boolean> => {
if (!isRecipientValid(recipient)) return false;

const info = await getAccountInfo(recipient);
if (info.error === NEW_ACCOUNT_ERROR_MESSAGE) {
return true;
}
return false;
return info.isNewAccount;
};

const cacheRecipientsNew: Record<string, boolean> = {};
Expand Down
114 changes: 114 additions & 0 deletions libs/coin-modules/coin-xrp/src/network/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import network from "@ledgerhq/live-network";
import { getAccountInfo } from ".";
import coinConfig, { type XrpCoinConfig } from "../config";

jest.mock("@ledgerhq/live-network");

describe("getAccountInfo", () => {
beforeAll(() => {
coinConfig.setCoinConfig(
() =>
({
node: "",
}) as XrpCoinConfig,
);
});

it("returns an empty AccountInfo when returns an error 'actNotFound'", async () => {
// Given
const emptyAddress = "rNCgVpHinUDjXP2vHDFDMjm7ssBwpveHya";
(network as jest.Mock).mockResolvedValue({
data: {
result: {
account: emptyAddress,
error: "actNotFound",
error_code: 19,
error_message: "Account not found.",
ledger_hash: "F2E6EFD279C3663B62D9DC9977106EC25BA8F89DA551C2D7AB3AE5D75B146258",
ledger_index: 91772714,
request: {
account: emptyAddress,
command: "account_info",
ledger_index: "validated",
},
status: "error",
validated: true,
},
},
});

// When
const result = await getAccountInfo(emptyAddress);

// Then
expect(result).toEqual({
isNewAccount: true,
balance: "0",
ownerCount: 0,
sequence: 0,
});
});

it("returns a valid AccountInfo when return a correct AccountInfo", async () => {
// Given
const address = "rh1HPuRVsYYvThxG2Bs1MfjmrVC73S16Fb";
(network as jest.Mock).mockResolvedValue({
data: {
result: {
account_data: {
Account: address,
Balance: "999441667919804",
Flags: 0,
LedgerEntryType: "AccountRoot",
OwnerCount: 0,
PreviousTxnID: "947F03794C982FE4C7C9FECC4C33C543BB25B82938895EBA8F9B6021CC27A571",
PreviousTxnLgrSeq: 725208,
Sequence: 153743,
index: "BC0DAE09C0BFBC4A49AA94B849266588BFD6E1F554B184B5788AC55D6E07EB95",
},
ledger_hash: "93E952B2770233B0ABFBFBBFBC3E2E2159DCABD07FEB5F4C49174027935D9FBB",
ledger_index: 1908009,
status: "success",
validated: true,
},
},
});

// When
const result = await getAccountInfo(address);

// Then
expect(result).toEqual({
isNewAccount: false,
balance: "999441667919804",
ownerCount: 0,
sequence: 153743,
});
});

it("throws an error when backend returns any other error", async () => {
// Given
const invalidAddress = "rNCgVpHinUDjXP2vHDFDMjm7ssBwpveHyaa";
(network as jest.Mock).mockResolvedValue({
result: {
error: "actMalformed",
error_code: 35,
error_message: "Account malformed.",
ledger_hash: "87DE2DD287BCAD6E81720BC6E6361EF01A66EE70A37B6BDF1EFF2E719D9410AE",
ledger_index: 91772741,
request: {
account: invalidAddress,
command: "account_info",
ledger_index: "validated",
},
status: "error",
validated: true,
},
});

// When & Then
await expect(getAccountInfo(invalidAddress)).rejects.toThrow(
"Cannot read properties of undefined (reading 'result')",
);
});
});
23 changes: 20 additions & 3 deletions libs/coin-modules/coin-xrp/src/network/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import network from "@ledgerhq/live-network";
import coinConfig from "../config";
import type { AccountInfo } from "../types/model";
import {
isErrorResponse,
isResponseStatus,
type AccountInfoResponse,
type AccountTxResponse,
type ErrorResponse,
type LedgerResponse,
type ServerInfoResponse,
type SubmitReponse,
Expand All @@ -20,10 +23,10 @@ export const submit = async (signature: string): Promise<SubmitReponse> => {
export const getAccountInfo = async (
recipient: string,
current?: boolean,
): Promise<AccountInfoResponse> => {
): Promise<AccountInfo> => {
const {
data: { result },
} = await network<{ result: AccountInfoResponse }>({
} = await network<{ result: AccountInfoResponse | ErrorResponse }>({
method: "POST",
url: getNodeUrl(),
data: {
Expand All @@ -41,7 +44,21 @@ export const getAccountInfo = async (
throw new Error(`couldn't fetch account info ${recipient}`);
}

return result;
if (isErrorResponse(result)) {
return {
isNewAccount: true,
balance: "0",
ownerCount: 0,
sequence: 0,
};
} else {
return {
isNewAccount: false,
balance: result.account_data.Balance,
ownerCount: result.account_data.OwnerCount,
sequence: result.account_data.Sequence,
};
}
};

export const getServerInfos = async (): Promise<ServerInfoResponse> => {
Expand Down
Loading
Loading