Skip to content

Commit

Permalink
move resetbutton to seperate box, add a rate fetching toggle
Browse files Browse the repository at this point in the history
  • Loading branch information
Einliterflasche committed Nov 12, 2024
1 parent 9c3d812 commit b4df7b9
Show file tree
Hide file tree
Showing 11 changed files with 188 additions and 102 deletions.
46 changes: 37 additions & 9 deletions src-gui/src/renderer/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
// - and to submit feedback
// - fetch currency rates from CoinGecko
import { Alert, ExtendedProviderStatus } from "models/apiModel";
import { store } from "./store/storeRenderer";
import { setBtcPrice, setXmrBtcRate, setXmrPrice } from "store/features/ratesSlice";
import { FiatCurrency } from "store/features/settingsSlice";

const API_BASE_URL = "https://api.unstoppableswap.net";

Expand Down Expand Up @@ -45,20 +48,20 @@ export async function submitFeedbackViaHttp(
return responseBody.feedbackId;
}

async function fetchCurrencyUsdPrice(currency: string): Promise<number> {
async function fetchCurrencyPrice(currency: string, fiatCurrency: FiatCurrency): Promise<number> {
try {
const response = await fetch(
`https://api.coingecko.com/api/v3/simple/price?ids=${currency}&vs_currencies=usd`,
`https://api.coingecko.com/api/v3/simple/price?ids=${currency}&vs_currencies=${fiatCurrency.toLowerCase()}`,
);
const data = await response.json();
return data[currency].usd;
return data[currency][fiatCurrency.toLowerCase()];
} catch (error) {
console.error(`Error fetching ${currency} price:`, error);
throw error;
}
}

export async function fetchXmrBtcRate(): Promise<number> {
async function fetchXmrBtcRate(): Promise<number> {
try {
const response = await fetch('https://api.kraken.com/0/public/Ticker?pair=XMRXBT');
const data = await response.json();
Expand All @@ -78,10 +81,35 @@ export async function fetchXmrBtcRate(): Promise<number> {
}


export async function fetchBtcPrice(): Promise<number> {
return fetchCurrencyUsdPrice("bitcoin");
async function fetchBtcPrice(fiatCurrency: FiatCurrency): Promise<number> {
return fetchCurrencyPrice("bitcoin", fiatCurrency);
}

export async function fetchXmrPrice(): Promise<number> {
return fetchCurrencyUsdPrice("monero");
}
async function fetchXmrPrice(fiatCurrency: FiatCurrency): Promise<number> {
return fetchCurrencyPrice("monero", fiatCurrency);
}

/**
* If enabled by the user, fetch the XMR, BTC and XMR/BTC rates
* and store them in the Redux store.
*/
export async function updateRates(): Promise<void> {
const settings = store.getState().settings;
if (!settings.fetchFiatPrices)
return;

console.log(`currency: ${settings.fiatCurrency}`);

try {
const btcPrice = await fetchBtcPrice(settings.fiatCurrency);
store.dispatch(setBtcPrice(btcPrice));

const xmrPrice = await fetchXmrPrice(settings.fiatCurrency);
store.dispatch(setXmrPrice(xmrPrice));

const xmrBtcRate = await fetchXmrBtcRate();
store.dispatch(setXmrBtcRate(xmrBtcRate));
} catch (error) {
console.error("Error fetching rates:", error);
}
}
27 changes: 6 additions & 21 deletions src-gui/src/renderer/components/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,9 @@ import GlobalSnackbarProvider from "./snackbar/GlobalSnackbarProvider";
import { useSettings } from "store/hooks";
import { themes } from "./theme";
import { initEventListeners } from "renderer/rpc";
import { fetchAlertsViaHttp, fetchBtcPrice, fetchProvidersViaHttp } from "renderer/api";
import { setXmrPrice } from "store/features/ratesSlice";
import { fetchAlertsViaHttp, fetchProvidersViaHttp, updateRates } from "renderer/api";
import { store } from "renderer/store/storeRenderer";
import { setBtcPrice } from "store/features/ratesSlice";
import { fetchXmrPrice } from "renderer/api";
import logger from "utils/logger";
import { setXmrBtcRate } from "store/features/ratesSlice";
import { fetchXmrBtcRate } from "renderer/api";
import { setAlerts } from "store/features/alertsSlice";
import { setRegistryProviders } from "store/features/providersSlice";
import { registryConnectionFailed } from "store/features/providersSlice";
Expand Down Expand Up @@ -94,23 +89,13 @@ async function fetchInitialData() {
logger.error(e, "Failed to fetch alerts via UnstoppableSwap HTTP API");
}

// Update XMR/BTC rates immediately and then at regular intervals
try {
const xmrPrice = await fetchXmrPrice();
store.dispatch(setXmrPrice(xmrPrice));
logger.info({ xmrPrice }, "Fetched XMR price");

const btcPrice = await fetchBtcPrice();
store.dispatch(setBtcPrice(btcPrice));
logger.info({ btcPrice }, "Fetched BTC price");
await updateRates();
} catch (e) {
logger.error(e, "Error retrieving fiat prices");
}

try {
const xmrBtcRate = await fetchXmrBtcRate();
store.dispatch(setXmrBtcRate(xmrBtcRate));
logger.info({ xmrBtcRate }, "Fetched XMR/BTC rate");
} catch (e) {
logger.error(e, "Error retrieving XMR/BTC rate");
}
}
const UPDATE_INTERVAL = 30_000;
setInterval(updateRates, UPDATE_INTERVAL);
}
10 changes: 5 additions & 5 deletions src-gui/src/renderer/components/modal/provider/ProviderInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ function ProviderSpreadChip({ provider }: { provider: ExtendedProviderStatus })
const spread = ((providerPrice - xmrBtcPrice) / xmrBtcPrice) * 100;

return (
<Tooltip title="The spread is the difference between the provider's exchange rate and the market rate. A high spread indicates that the provider is charging more than the market rate.">
<Chip label={`Spread: ${spread.toFixed(2)} %`} />
<Tooltip title="The spread is how many percent the provider's exchange rate is above the market rate on centralized exchanges.">
<Chip label={`Spread: ${spread.toFixed(2)}%`} />
</Tooltip>
);

Expand Down Expand Up @@ -74,8 +74,8 @@ export default function ProviderInfo({
<Box className={classes.chipsOuter}>
<Chip label={provider.testnet ? "Testnet" : "Mainnet"} />
{provider.uptime && (
<Tooltip title="A high uptime indicates reliability. Providers with low uptime may be unreliable and cause swaps to take longer to complete or fail entirely.">
<Chip label={`${Math.round(provider.uptime * 100)} % uptime`} />
<Tooltip title="A high uptime (>90%) indicates reliability. Providers with very low uptime may be unreliable and cause swaps to take longer to complete or fail entirely.">
<Chip label={`${Math.round(provider.uptime * 100)}% uptime`} />
</Tooltip>
)}
{provider.age ? (
Expand All @@ -93,7 +93,7 @@ export default function ProviderInfo({
</Tooltip>
)}
{isOutdated && (
<Tooltip title="This provider is running an outdated version of the software. Outdated providers may be unreliable and cause swaps to take longer to complete or fail entirely.">
<Tooltip title="This provider is running an older version of the software. Outdated providers may be unreliable and cause swaps to take longer to complete or fail entirely.">
<Chip label="Outdated" icon={<WarningIcon />} color="primary" />
</Tooltip>
)}
Expand Down
20 changes: 11 additions & 9 deletions src-gui/src/renderer/components/other/Units.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,18 @@ export function AmountWithUnit({
amount,
unit,
fixedPrecision,
dollarRate,
exchangeRate,
}: {
amount: Amount;
unit: string;
fixedPrecision: number;
dollarRate?: Amount;
exchangeRate?: Amount;
}) {
const fetchFiatPrices = useAppSelector((state) => state.settings.fetchFiatPrices);
const fiatCurrency = useAppSelector((state) => state.settings.fiatCurrency);
const title =
dollarRate != null && amount != null
? `≈ $${(dollarRate * amount).toFixed(2)}`
fetchFiatPrices && exchangeRate != null && amount != null && fiatCurrency != null
? `≈ ${(exchangeRate * amount).toFixed(2)} ${fiatCurrency}`
: "";

return (
Expand All @@ -33,31 +35,31 @@ export function AmountWithUnit({
}

AmountWithUnit.defaultProps = {
dollarRate: null,
exchangeRate: null,
};

export function BitcoinAmount({ amount }: { amount: Amount }) {
const btcUsdRate = useAppSelector((state) => state.rates.btcPrice);
const btcRate = useAppSelector((state) => state.rates.btcPrice);

return (
<AmountWithUnit
amount={amount}
unit="BTC"
fixedPrecision={6}
dollarRate={btcUsdRate}
exchangeRate={btcRate}
/>
);
}

export function MoneroAmount({ amount }: { amount: Amount }) {
const xmrUsdRate = useAppSelector((state) => state.rates.xmrPrice);
const xmrRate = useAppSelector((state) => state.rates.xmrPrice);

return (
<AmountWithUnit
amount={amount}
unit="XMR"
fixedPrecision={4}
dollarRate={xmrUsdRate}
exchangeRate={xmrRate}
/>
);
}
Expand Down
4 changes: 3 additions & 1 deletion src-gui/src/renderer/components/other/ValidatedTextField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ interface ValidatedTextFieldProps extends Omit<TextFieldProps, "onChange" | "val
isValid: (value: string) => boolean;
onValidatedChange: (value: string | null) => void;
allowEmpty?: boolean;
noErrorWhenEmpty?: boolean;
helperText?: string;
}

Expand All @@ -17,6 +18,7 @@ export default function ValidatedTextField({
helperText = "Invalid input",
variant = "standard",
allowEmpty = false,
noErrorWhenEmpty = false,
...props
}: ValidatedTextFieldProps) {
const [inputValue, setInputValue] = useState(value || "");
Expand All @@ -39,7 +41,7 @@ export default function ValidatedTextField({
setInputValue(value || "");
}, [value]);

const isError = allowEmpty && inputValue === "" ? false : !isValid(inputValue);
const isError = allowEmpty && inputValue === "" || inputValue === "" && noErrorWhenEmpty ? false : !isValid(inputValue);

return (
<TextField
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default function DonateInfoBox() {
<Typography variant="subtitle2">
<p>
As part of the Monero Community Crowdfunding System (CCS), we received funding for 6 months of full-time development by
generous donors from the Monero community (<Link href="https://ccs.getmonero.org/proposals/mature-atomic-swaps-ecosystem.html" target="_blank">Link</Link>).
generous donors from the Monero community (<Link href="https://ccs.getmonero.org/proposals/mature-atomic-swaps-ecosystem.html" target="_blank">link</Link>).
</p>
<p>
If you want to support our effort event further, you can do so at this address.
Expand Down
Loading

0 comments on commit b4df7b9

Please sign in to comment.