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

Better amount inputs #246

Merged
merged 3 commits into from
Dec 27, 2022
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
99 changes: 99 additions & 0 deletions frontend/src/components/AmountInput.tsx
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))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this be?

setAmount(satsToUSD(parsedAmount, price))

This is for where the input is formatting for USD when the Currency.USD option is selected correct?

Copy link
Collaborator

@benalleng benalleng Dec 20, 2022

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

Copy link
Contributor Author

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?

// 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>
</>
)

}
19 changes: 7 additions & 12 deletions frontend/src/components/MainBalance.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { useQuery } from "@tanstack/react-query";
import { satsToUsd } from "@util/conversions";
import prettyPrintAmount from "@util/prettyPrintAmount";
import { usePriceQuery } from "@util/queries";
import { MutinyBalance } from "node-manager";
import { useContext, useState } from "react";
import { NodeManagerContext } from "./GlobalStateProvider";
Expand All @@ -22,9 +24,8 @@ function prettyPrintUnconfirmedUsd(b: MutinyBalance, price: number): string {
}

function prettyPrintUSD(amount: number, price: number): string {
let btc = amount / 100000000;
let usd = btc * price;
return prettyPrintAmount(Number(usd.toFixed(2)))
let usd = satsToUsd(amount, price);
return prettyPrintAmount(Number(usd))
}

export default function MainBalance() {
Expand All @@ -40,14 +41,8 @@ export default function MainBalance() {
},
enabled: !!nodeManager,
})
const { data: price } = useQuery({
queryKey: ['price'],
queryFn: async () => {
console.log("Checking bitcoin price...")
return await nodeManager?.get_bitcoin_price()
},
enabled: !!nodeManager,
})

const { data: price } = usePriceQuery(nodeManager);

return (<div className="flex flex-col gap-4 cursor-pointer" onClick={() => setShowFiat(!showFiat)}>
{showFiat && price &&
Expand All @@ -57,7 +52,7 @@ export default function MainBalance() {
}
{(!showFiat || !price) &&
<h1 className='text-4xl font-light uppercase'>
{balance && prettyPrintBalance(balance)} <span className='text-2xl'>sats</span>
{balance && prettyPrintBalance(balance)} <span className='text-2xl'>sats</span>
</h1>
}
{(balance && balance.unconfirmed?.valueOf() > 0) && showFiat && price &&
Expand Down
21 changes: 21 additions & 0 deletions frontend/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,24 @@ dd {
.fileInputButton:hover {
cursor: pointer;
}

select {
@apply appearance-none;
@apply block;
@apply border-[2px] focus:outline-none focus:ring-2 focus:ring-offset-2 ring-offset-black;
@apply font-light text-lg;
@apply py-4 pl-4 pr-8;
}

.select-wrapper {
@apply relative;
}

.select-wrapper::after {
/* A down arrow because the platform sucks */
content: url("data:image/svg+xml,%3Csvg aria-hidden='true' class='w-4 h-4 ml-1' fill='white' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' d='M5.293 7.293a1 1 0 0 1 1.414 0L10 10.586l3.293-3.293a1 1 0 1 1 1.414 1.414l-4 4a1 1 0 0 1-1.414 0l-4-4a1 1 0 0 1 0-1.414z' clip-rule='evenodd'/%3E%3C/svg%3E");
right: 0.5rem;
top: 1.2rem;
width: 1.5rem;
@apply absolute;
}
5 changes: 3 additions & 2 deletions frontend/src/routes/Receive.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";
import ActionButton from "@components/ActionButton";
import MutinyToaster from "@components/MutinyToaster";
import AmountInput from "@components/AmountInput";

function Receive() {
let navigate = useNavigate();
Expand All @@ -19,7 +20,7 @@ function Receive() {
const queryClient = useQueryClient()

async function handleContinue() {
const amount = receiveAmount.replace(/,/g, "")
const amount = receiveAmount.replace(/_/g, "")
if (amount.match(/\D/)) {
setAmount('')
toast("That doesn't look right")
Expand All @@ -43,7 +44,7 @@ function Receive() {
<div />
<p className="text-2xl font-light">Want some sats?</p>
<div className="flex flex-col gap-4">
<input onChange={e => setAmount(e.target.value)} value={receiveAmount} className={`w-full ${inputStyle({ accent: "blue" })}`} type="text" inputMode="numeric" placeholder='How much? (optional)' />
<AmountInput amountSats={receiveAmount} setAmount={setAmount} accent="blue" placeholder="How much? (optional)" />
<input onChange={(e) => setDescription(e.target.value)} className={`w-full ${inputStyle({ accent: "blue" })}`} type="text" placeholder='What for? (optional)' />
</div>
<ActionButton onClick={() => handleContinue()}>
Expand Down
13 changes: 7 additions & 6 deletions frontend/src/routes/SendAmount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,24 @@ import { useNavigate } from "react-router";
import Close from "../components/Close";
import PageTitle from "../components/PageTitle";
import ScreenMain from "../components/ScreenMain";
import { inputStyle } from "../styles";
import toast from "react-hot-toast"
import MutinyToaster from "../components/MutinyToaster";
import { useSearchParams } from "react-router-dom";
import ActionButton from "@components/ActionButton";
import AmountInput from "@components/AmountInput";

export default function SendAmount() {
let navigate = useNavigate();

const [searchParams] = useSearchParams();
const destination = searchParams.get("destination")

const [receiveAmount, setAmount] = useState("")
const [sendAmount, setAmount] = useState("")

function handleContinue() {
const amount = receiveAmount.replace(/,/g, "")
if (!amount || amount.match(/\D/)) {
const amount = sendAmount.replace(/_/g, "")
const parsedAmount = parseInt(amount);
if (!parsedAmount) {
setAmount('')
toast("That doesn't look right")
return
Expand All @@ -29,7 +30,7 @@ export default function SendAmount() {
return
}

if (destination && amount.match(/^[\d.]+$/)) {
if (destination && typeof parsedAmount === "number") {
navigate(`/send/confirm?destination=${destination}&amount=${amount}`)
}
}
Expand All @@ -43,7 +44,7 @@ export default function SendAmount() {
<div />
<div className="flex flex-col gap-4">
<p className="text-2xl font-light">How much would you like to send?</p>
<input onChange={e => setAmount(e.target.value)} value={receiveAmount} className={`w-full ${inputStyle({ accent: "green" })}`} type="text" inputMode="numeric" placeholder='sats' />
<AmountInput amountSats={sendAmount} setAmount={setAmount} accent="green" placeholder="You're the boss" />
</div>
<ActionButton onClick={handleContinue}>
Continue
Expand Down
12 changes: 11 additions & 1 deletion frontend/src/styles/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,14 @@ const inputStyle = cva("", {
}
});

export { inputStyle }
const selectStyle = cva("", {
variants: {
accent: {
green: "bg-green focus:ring-green",
blue: "bg-blue focus:ring-blue",
red: "bg-red focus:ring-red",
},
}
});

export { inputStyle, selectStyle }
29 changes: 29 additions & 0 deletions frontend/src/utility/conversions.ts
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 ""
}
}
12 changes: 12 additions & 0 deletions frontend/src/utility/queries.ts
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,
})
8 changes: 6 additions & 2 deletions node-manager/src/nodemanager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Copy link
Collaborator

Choose a reason for hiding this comment

The 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()
}
Expand Down