-
Notifications
You must be signed in to change notification settings - Fork 35
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
Better amount inputs #246
Merged
Merged
Better amount inputs #246
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
import { satsToUsd, usdToSats } from "@util/conversions"; | ||
import prettyPrintAmount from "@util/prettyPrintAmount"; | ||
import { usePriceQuery } from "@util/queries"; | ||
import { Dispatch, SetStateAction, useContext, useState } from "react"; | ||
import { inputStyle, selectStyle } from "../styles"; | ||
import { NodeManagerContext } from "./GlobalStateProvider"; | ||
|
||
type Props = { | ||
amountSats: string, | ||
setAmount: Dispatch<SetStateAction<string>>, | ||
accent: "green" | "blue" | "red", | ||
placeholder: string, | ||
} | ||
|
||
export enum Currency { | ||
USD = "USD", | ||
SATS = "SATS" | ||
} | ||
|
||
export default function AmountInput({ amountSats, setAmount, accent, placeholder }: Props) { | ||
const [currency, setCurrency] = useState(Currency.SATS) | ||
|
||
// amountSats will be our source of truth, this is just for showing to the user | ||
const [localDisplayAmount, setLocalDisplayAmount] = useState(amountSats) | ||
|
||
const { nodeManager } = useContext(NodeManagerContext); | ||
|
||
const { data: price } = usePriceQuery(nodeManager); | ||
|
||
function setAmountFormatted(value: string) { | ||
if (value.length === 0 || value === "0") { | ||
setAmount('') | ||
setLocalDisplayAmount('') | ||
return | ||
} | ||
//Use a regex to replace all commas and underscores with empty string | ||
const amount = value.replace(/[_,]/g, ""); | ||
let parsedAmount = parseInt(amount) | ||
if (typeof parsedAmount === "number" && parsedAmount !== 0 && price) { | ||
// If the currency is set to usd, we need to convert the input amount to sats and store that in setAmount | ||
if (currency === Currency.USD) { | ||
setAmount(usdToSats(parsedAmount, price)) | ||
// Then we set the usd amount to localDisplayAmount | ||
setLocalDisplayAmount(prettyPrintAmount(parsedAmount)) | ||
} else { | ||
// Otherwise we can just set the amount to the parsed amount | ||
setAmount(prettyPrintAmount(parsedAmount)) | ||
// And the localDisplayAmount to the same thing | ||
setLocalDisplayAmount(prettyPrintAmount(parsedAmount)) | ||
} | ||
} else { | ||
setAmount('') | ||
setLocalDisplayAmount('') | ||
} | ||
} | ||
|
||
function handleCurrencyChange(value: Currency) { | ||
setCurrency(value) | ||
const amount = amountSats.replace(/[_,]/g, ""); | ||
let parsedAmount = parseInt(amount) | ||
if (typeof parsedAmount === "number" && price) { | ||
if (value === Currency.USD) { | ||
// Then we set the usd amount to localDisplayAmount | ||
let dollars = satsToUsd(parsedAmount, price) | ||
let parsedDollars = Number(dollars); | ||
if (parsedDollars === 0) { | ||
// 0 looks lame | ||
setLocalDisplayAmount(""); | ||
} else { | ||
setLocalDisplayAmount(prettyPrintAmount(parsedDollars)) | ||
} | ||
} else if (value === Currency.SATS) { | ||
if (!parsedAmount) { | ||
// 0 looks lame | ||
setLocalDisplayAmount("") | ||
} else { | ||
setLocalDisplayAmount(prettyPrintAmount(parsedAmount)) | ||
} | ||
} | ||
} | ||
} | ||
|
||
return ( | ||
<> | ||
{/* HANDY DEBUGGER FOR UNDERSTANDING */} | ||
{/* <pre>{JSON.stringify({ currency, amountSats, localDisplayAmount }, null, 2)}</pre> */} | ||
<div className="flex gap-2"> | ||
<input onChange={e => setAmountFormatted(e.target.value)} value={localDisplayAmount} className={inputStyle({ accent, width: "wide" })} type="text" inputMode={currency === Currency.SATS ? "numeric" : "decimal"} placeholder={placeholder} /> | ||
<div className="select-wrapper bg-red"> | ||
<select id="currency" value={currency} onChange={e => handleCurrencyChange(e.target.value as Currency)} className={selectStyle({ accent })}> | ||
<option value={Currency.SATS}>SATS</option> | ||
<option value={Currency.USD}>USD</option> | ||
</select> | ||
</div> | ||
</div> | ||
</> | ||
) | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import { NodeManager } from "node-manager"; | ||
|
||
export function satsToUsd(amount: number, price: number): string { | ||
if (typeof amount !== "number" || isNaN(amount)) { | ||
return "" | ||
} | ||
try { | ||
let btc = NodeManager.convert_sats_to_btc(BigInt(Math.floor(amount))); | ||
let usd = btc * price; | ||
return usd.toFixed(2); | ||
} catch (e) { | ||
console.error(e); | ||
return "" | ||
} | ||
} | ||
|
||
export function usdToSats(amount: number, price: number): string { | ||
if (typeof amount !== "number" || isNaN(amount)) { | ||
return "" | ||
} | ||
try { | ||
let btc = amount / price; | ||
let sats = NodeManager.convert_btc_to_sats(btc); | ||
return sats.toString(); | ||
} catch (e) { | ||
console.error(e); | ||
return "" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import { useQuery } from "@tanstack/react-query" | ||
import { NodeManager } from "node-manager" | ||
|
||
export const usePriceQuery = (nodeManager: NodeManager | undefined) => | ||
useQuery({ | ||
queryKey: ['price'], | ||
queryFn: async () => { | ||
console.log("Checking bitcoin price...") | ||
return await nodeManager?.get_bitcoin_price() | ||
}, | ||
enabled: !!nodeManager, | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -921,15 +921,19 @@ impl NodeManager { | |
|
||
#[wasm_bindgen] | ||
pub fn convert_btc_to_sats(btc: f64) -> Result<u64, MutinyJsError> { | ||
if let Ok(amount) = bitcoin::Amount::from_btc(btc) { | ||
// rust bitcoin doesn't like extra precision in the float | ||
// so we round to the nearest satoshi | ||
// explained here: https://stackoverflow.com/questions/28655362/how-does-one-round-a-floating-point-number-to-a-specified-number-of-digits | ||
let truncated = 10i32.pow(8) as f64; | ||
let btc = (btc * truncated).round() / truncated; | ||
if let Ok(amount) = bitcoin::Amount::from_btc(btc as f64) { | ||
Comment on lines
+924
to
+929
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Oof this does not sound fun. |
||
Ok(amount.to_sat()) | ||
} else { | ||
Err(MutinyJsError::BadAmountError) | ||
} | ||
} | ||
|
||
#[wasm_bindgen] | ||
// Hopefully we only use this when preparing bip21 strings | ||
pub fn convert_sats_to_btc(sats: u64) -> f64 { | ||
bitcoin::Amount::from_sat(sats).to_btc() | ||
} | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
should this be?
This is for where the input is formatting for USD when the Currency.USD option is selected correct?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If this is correct I think this is what is causing the input to not be able to have a pre-switched value of less than $1 or just cents in general
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yeah it's correct, the "source of truth" is sats so we always need to set that.
yeah I gave up before I could manage to support less than $1. maybe a good follow-on pr?