Skip to content

Commit

Permalink
[support] Replace hardcoded countervalues URL with value from env var (
Browse files Browse the repository at this point in the history
…#5650)

* Replace hardcoded countervalues URL with env var

* Add changeset

* Use function instead of static call to getEnv

* Hedera: switch to cvsApi to retrieve USD countervalue

* Update test snapshot

* lint
  • Loading branch information
Hakim authored Jan 5, 2024
1 parent dd5d930 commit e4c8b3a
Show file tree
Hide file tree
Showing 11 changed files with 73 additions and 51 deletions.
6 changes: 6 additions & 0 deletions .changeset/sharp-buttons-rescue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"ledger-live-desktop": patch
"@ledgerhq/live-common": patch
---

Replace hardcoded countervalues URL with env var
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { expect } from "@playwright/test";
import { getEnv } from "@ledgerhq/live-env";
import test from "../../fixtures/common";
import { Layout } from "../../models/Layout";
import { expect } from "@playwright/test";

test.use({ userdata: "1AccountBTC1AccountETH" });

Expand All @@ -18,7 +19,7 @@ test("Countervalues: at least one call is made and successful to the API", async
const firstSuccessfulQuery = new Promise(resolve => {
page.on("response", response => {
if (
response.url().startsWith("https://countervalues.live.ledger.com") &&
response.url().startsWith(getEnv("LEDGER_COUNTERVALUES_API")) &&
response.status() === 200
) {
resolve(response);
Expand Down
3 changes: 2 additions & 1 deletion apps/ledger-live-desktop/tests/specs/market/market.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect } from "@playwright/test";
import { getEnv } from "@ledgerhq/live-env";
import test from "../../fixtures/common";
import { MarketPage } from "../../models/MarketPage";
import { Layout } from "../../models/Layout";
Expand Down Expand Up @@ -41,7 +42,7 @@ test("Market", async ({ page }) => {
await expect.soft(page).toHaveScreenshot("market-page-no-scrollbar.png");
});

await page.route("https://countervalues.live.ledger.com/v2/supported-to", async route => {
await page.route(`${getEnv("LEDGER_COUNTERVALUES_API")}/v2/supported-to`, async route => {
route.fulfill({
headers: { teststatus: "mocked" },
body: JSON.stringify([
Expand Down
2 changes: 1 addition & 1 deletion libs/coin-framework/src/currencies/support.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ async function initializeUserSupportedFiats() {

export async function fetchSupportedFiatsTokens(): Promise<string[]> {
try {
const response = await fetch("https://countervalues.live.ledger.com/v2/supported-to", {
const response = await fetch(`${getEnv("LEDGER_COUNTERVALUES_API")}/v2/supported-to`, {
method: "GET",
headers: {
accept: "application/json",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
exports[`hedera currency bridge scanAccounts hedera seed 1 1`] = `
[
{
"balance": "99460655",
"balance": "89312168",
"currencyId": "hedera",
"derivationMode": "hederaBip44",
"freshAddress": "0.0.1040977",
Expand All @@ -18,10 +18,10 @@ exports[`hedera currency bridge scanAccounts hedera seed 1 1`] = `
"index": 0,
"name": "Hedera 1",
"nfts": undefined,
"operationsCount": 3,
"operationsCount": 4,
"pendingOperations": [],
"seedIdentifier": "9e92a312233d5fd6b5a723875aeea2cea81a8e48ffc00341cff6dffcfd3ab7f2",
"spendableBalance": "99460655",
"spendableBalance": "89312168",
"starred": false,
"swapHistory": [],
"syncHash": undefined,
Expand All @@ -34,6 +34,30 @@ exports[`hedera currency bridge scanAccounts hedera seed 1 1`] = `
exports[`hedera currency bridge scanAccounts hedera seed 1 2`] = `
[
[
{
"accountId": "js:2:hedera:0.0.1040977:hederaBip44",
"blockHash": null,
"blockHeight": 5,
"contract": undefined,
"extra": {
"consensusTimestamp": "1701941251.224927003",
},
"fee": "148487",
"hash": "66faf4cc5ccbda67922281967b426510e84155eb6f8f72171f7389e49cbb93bcd2e312c4223a95eadc51b8f620c37830",
"id": "js:2:hedera:0.0.1040977:hederaBip44-66faf4cc5ccbda67922281967b426510e84155eb6f8f72171f7389e49cbb93bcd2e312c4223a95eadc51b8f620c37830-OUT",
"operator": undefined,
"recipients": [
"0.0.2024333",
],
"senders": [
"0.0.800",
"0.0.1040977",
],
"standard": undefined,
"tokenId": undefined,
"type": "OUT",
"value": "10148487",
},
{
"accountId": "js:2:hedera:0.0.1040977:hederaBip44",
"blockHash": null,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import BigNumber from "bignumber.js";
import { getEstimatedFees } from "./utils";
import type { Account, AccountLike } from "@ledgerhq/types-live";
import { getMainAccount } from "../../account/index";
import type { Transaction } from "./types";
import { getEstimatedFees } from "./utils";

export default async function estimateMaxSpendable({
account,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
parentAccount,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
transaction,
Expand All @@ -16,7 +16,8 @@ export default async function estimateMaxSpendable({
}): Promise<BigNumber> {
const balance = account.balance;

const estimatedFees = await getEstimatedFees();
const mainAccount = getMainAccount(account, parentAccount);
const estimatedFees = await getEstimatedFees(mainAccount);

let maxSpendable = balance.minus(estimatedFees);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export default async function getTransactionStatus(
errors.amount = new NotEnoughBalance("");
}

const estimatedFees = await getEstimatedFees();
const estimatedFees = await getEstimatedFees(account);

return {
amount,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ async function buildOptimisticOperation({
hash: "",
type: "OUT",
value: transaction.amount,
fee: await getEstimatedFees(),
fee: await getEstimatedFees(account),
blockHash: null,
blockHeight: null,
senders: [account.freshAddress.toString()],
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import network from "@ledgerhq/live-network/network";
import type { Account } from "@ledgerhq/types-live";
import BigNumber from "bignumber.js";
import estimateMaxSpendable from "../js-estimateMaxSpendable";
import { getEstimatedFees } from "../utils";

// Balance is 1 Hbar
const account: Account = {
Expand Down Expand Up @@ -55,17 +55,8 @@ const account: Account = {
describe("js-estimateMaxSpendable", () => {
let estimatedFees = new BigNumber("150200").multipliedBy(2); // 0.001502 ℏ (as of 2023-03-14)

it("should return hedera price if available", async () => {
// If get hedera price works, use real estimate, otherwise fallback to hard coded
try {
const { data } = await network({
method: "GET",
url: "https://countervalues.live.ledger.com/latest/direct?pairs=hbar:usd",
});
estimatedFees = new BigNumber(10000).dividedBy(data[0]).integerValue(BigNumber.ROUND_CEIL);
} catch {
console.error("Could not fetch Hedera price");
}
beforeAll(async () => {
estimatedFees = await getEstimatedFees(account);
});

test("estimateMaxSpendable", async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import network from "@ledgerhq/live-network/network";
import type { Account } from "@ledgerhq/types-live";
import BigNumber from "bignumber.js";
import type { Transaction } from "../types";
import { calculateAmount } from "../utils";
import { calculateAmount, getEstimatedFees } from "../utils";

// Balance is 1 Hbar
const account: Account = {
Expand Down Expand Up @@ -63,17 +62,8 @@ const transaction: Transaction = {
describe("utils", () => {
let estimatedFees = new BigNumber("150200").multipliedBy(2); // 0.001502 ℏ (as of 2023-03-14)

it("should return hedera price if available", async () => {
// If get hedera price works, use real estimate, otherwise fallback to hard coded
try {
const { data } = await network({
method: "GET",
url: "https://countervalues.live.ledger.com/latest/direct?pairs=hbar:usd",
});
estimatedFees = new BigNumber(10000).dividedBy(data[0]).integerValue(BigNumber.ROUND_CEIL);
} catch {
console.error("Could not fetch Hedera price");
}
beforeAll(async () => {
estimatedFees = await getEstimatedFees(account);
});

test("calculateAmount transaction.useAllAmount = true", async () => {
Expand Down
36 changes: 22 additions & 14 deletions libs/ledger-live-common/src/families/hedera/utils.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,32 @@
import network from "@ledgerhq/live-network/network";
import type { Account } from "@ledgerhq/types-live";
import BigNumber from "bignumber.js";
import estimateMaxSpendable from "./js-estimateMaxSpendable";
import type { Transaction } from "./types";
import { getFiatCurrencyByTicker } from "../../currencies/index";
import cvsApi from "../../countervalues/api";

export const estimatedFeeSafetyRate = 2;

export async function getEstimatedFees(): Promise<BigNumber> {
export async function getEstimatedFees(account: Account): Promise<BigNumber> {
try {
const { data } = await network({
method: "GET",
url: "https://countervalues.live.ledger.com/latest/direct?pairs=hbar:usd",
});

return new BigNumber(10000).dividedBy(data[0]).integerValue(BigNumber.ROUND_CEIL);
} catch {
// as fees are based on a currency conversion, we stay
// on the safe side here and double the estimate for "max spendable"
return new BigNumber("150200").multipliedBy(estimatedFeeSafetyRate); // 0.001502 ℏ (as of 2023-03-14)
}
const data = await cvsApi.fetchLatest([
{
from: account.currency,
to: getFiatCurrencyByTicker("USD"),
},
]);

if (data[0]) {
return new BigNumber(10000)
.dividedBy(new BigNumber(data[0]))
.integerValue(BigNumber.ROUND_CEIL);
}
// eslint-disable-next-line no-empty
} catch {}

// as fees are based on a currency conversion, we stay
// on the safe side here and double the estimate for "max spendable"
return new BigNumber("150200").multipliedBy(estimatedFeeSafetyRate); // 0.001502 ℏ (as of 2023-03-14)
}

export async function calculateAmount({
Expand All @@ -37,7 +45,7 @@ export async function calculateAmount({

return {
amount,
totalSpent: amount.plus(await getEstimatedFees()),
totalSpent: amount.plus(await getEstimatedFees(account)),
};
}

Expand Down

0 comments on commit e4c8b3a

Please sign in to comment.