Skip to content

Commit

Permalink
feat: make create context
Browse files Browse the repository at this point in the history
revert
  • Loading branch information
dni committed Jan 4, 2024
1 parent b31bc7d commit 45dac22
Show file tree
Hide file tree
Showing 43 changed files with 1,225 additions and 972 deletions.
149 changes: 78 additions & 71 deletions src/Create.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,47 +5,16 @@ import { Show, createEffect, createMemo, on, onMount } from "solid-js";
import AddressInput from "./components/AddressInput";
import Asset from "./components/Asset";
import AssetSelect from "./components/AssetSelect";
import ClickableAmount from "./components/ClickableAmount";
import ConnectMetamask from "./components/ConnectMetamask";
import { CreateButton, setButtonLabel } from "./components/CreateButton";
import Fees from "./components/Fees";
import InvoiceInput from "./components/InvoiceInput";
import QrScan from "./components/QrScan";
import Reverse from "./components/Reverse";
import { RBTC, sideReceive, sideSend } from "./consts";
import { isMobile } from "./helper";
import { useCreateContext } from "./context/Create";
import t from "./i18n";
import {
addressValid,
amountChanged,
asset,
assetReceive,
assetSelect,
assetSelected,
assetSend,
boltzFee,
denomination,
invoiceValid,
maximum,
minerFee,
minimum,
receiveAmount,
receiveAmountFormatted,
reverse,
sendAmount,
sendAmountFormatted,
sendAmountValid,
setAmountChanged,
setInvoice,
setReceiveAmount,
setReceiveAmountFormatted,
setSendAmount,
setSendAmountFormatted,
setSendAmountValid,
setValid,
wasmSupported,
webln,
} from "./signals";
import { boltzFee, denomination, minerFee, webln } from "./signals";
import { calculateReceiveAmount, calculateSendAmount } from "./utils/calculate";
import {
calculateDigits,
Expand All @@ -56,16 +25,44 @@ import {
import { enableWebln } from "./utils/webln";

const Create = () => {
let receiveAmountRef: HTMLInputElement, sendAmountRef: HTMLInputElement;
let receiveAmountRef: HTMLInputElement;
let sendAmountRef: HTMLInputElement;

const {
asset,
assetReceive,
assetSend,
addressValid,
reverse,
setInvoice,
invoiceValid,
receiveAmount,
receiveAmountFormatted,
sendAmount,
sendAmountFormatted,
sendAmountValid,
setReceiveAmount,
setReceiveAmountFormatted,
setSendAmount,
setSendAmountFormatted,
setSendAmountValid,
setValid,
assetSelect,
assetSelected,
amountChanged,
setAmountChanged,
minimum,
maximum,
} = useCreateContext();

const changeReceiveAmount = (evt: InputEvent) => {
const target = evt.currentTarget as HTMLInputElement;
const amount = target.value.trim();
const satAmount = convertAmount(Number(amount), denomination());
const sendAmount = calculateSendAmount(satAmount);
const sendAmount = calculateSendAmount(satAmount, reverse());
setAmountChanged(sideReceive);
setReceiveAmount(BigNumber(satAmount));
setSendAmount(BigNumber(sendAmount));
setReceiveAmount(BigInt(satAmount));
setSendAmount(BigInt(sendAmount));
validateAmount();
target.setCustomValidity("");
target.classList.remove("invalid");
Expand All @@ -75,7 +72,7 @@ const Create = () => {
const target = evt.currentTarget as HTMLInputElement;
const amount = target.value.trim();
const satAmount = convertAmount(Number(amount), denomination());
const receiveAmount = calculateReceiveAmount(satAmount);
const receiveAmount = calculateReceiveAmount(satAmount, reverse());
setAmountChanged(sideSend);
setSendAmount(BigNumber(satAmount));
setReceiveAmount(BigNumber(receiveAmount));
Expand All @@ -87,6 +84,7 @@ const Create = () => {
const createWeblnInvoice = async () => {
enableWebln(async () => {
const amount = Number(receiveAmount());
// @ts-ignore
const invoice = await window.webln.makeInvoice({ amount: amount });
validateAmount();
log.debug("created webln invoice", invoice);
Expand All @@ -100,25 +98,24 @@ const Create = () => {
const hasDot = input.value.includes(".");
const regex = denomination() == "sat" || hasDot ? /[0-9]/ : /[0-9]|\./;
if (!regex.test(keycode)) {
evt.stopPropagation();
evt.preventDefault();
}
};

const validatePaste = (evt: ClipboardEvent) => {
const clipboardData = evt.clipboardData || globalThis.clipboardData;
const pastedData = clipboardData.getData("Text").trim();
if (!getValidationRegex().test(pastedData)) {
if (!getValidationRegex(maximum(), denomination()).test(pastedData)) {
evt.stopPropagation();
evt.preventDefault();
}
};

const validateAmount = () => {
const setCustomValidity = (val: string, isZero: boolean) => {
const setCustomValidity = (msg: string, isZero: boolean = true) => {
[sendAmountRef, receiveAmountRef].forEach((ref) => {
ref.setCustomValidity(val);
if (!isZero && val !== "") {
ref.setCustomValidity(msg);
if (!isZero && msg !== "") {
ref.classList.add("invalid");
} else {
ref.classList.remove("invalid");
Expand All @@ -133,7 +130,10 @@ const Create = () => {

if (lessThanMin || amount > maximum()) {
const params = {
amount: formatAmount(lessThanMin ? minimum() : maximum()),
amount: formatAmount(
lessThanMin ? minimum() : maximum(),
denomination(),
),
denomination: denomination(),
};
const label = lessThanMin ? "minimum_amount" : "maximum_amount";
Expand All @@ -147,8 +147,8 @@ const Create = () => {
};

const setAmount = (amount: number) => {
setSendAmount(BigNumber(amount));
setReceiveAmount(BigNumber(calculateReceiveAmount(amount)));
setSendAmount(BigInt(amount));
setReceiveAmount(BigInt(calculateReceiveAmount(amount, reverse())));
validateAmount();
sendAmountRef.focus();
};
Expand All @@ -161,22 +161,23 @@ const Create = () => {
on([boltzFee, minerFee, reverse, asset], () => {
if (amountChanged() === sideReceive) {
setSendAmount(
BigNumber(calculateSendAmount(receiveAmount().toNumber())),
BigInt(
calculateSendAmount(Number(receiveAmount()), reverse()),
),
);
} else {
setReceiveAmount(
BigNumber(calculateReceiveAmount(sendAmount().toNumber())),
BigInt(
calculateReceiveAmount(Number(sendAmount()), reverse()),
),
);
}
validateAmount();
}),
);

createEffect(() => {
if (assetSelect()) {
return;
}

if (assetSelect()) return;
const ref =
assetSelected() === sideSend ? sendAmountRef : receiveAmountRef;
ref.focus();
Expand All @@ -185,11 +186,15 @@ const Create = () => {
createMemo(() => {
const rAmount = Number(receiveAmount());
if (rAmount > 0) {
setReceiveAmountFormatted(formatAmount(rAmount).toString());
setReceiveAmountFormatted(
formatAmount(rAmount, denomination()).toString(),
);
}
const sAmount = Number(sendAmount());
if (sAmount > 0) {
setSendAmountFormatted(formatAmount(sAmount).toString());
setSendAmountFormatted(
formatAmount(sAmount, denomination()).toString(),
);
}
});

Expand Down Expand Up @@ -227,17 +232,18 @@ const Create = () => {
<h2>{t("create_swap")}</h2>
<p>
{t("create_swap_subline")} <br />
{t("send")}{" "}
<ClickableAmount
label={"min"}
onClick={setAmount}
amount={minimum}
/>{" "}
<ClickableAmount
label={"max"}
onClick={setAmount}
amount={maximum}
/>
{t("send")} {t("min")}{" "}
<span
class="btn-small btn-light"
onClick={() => setAmount(minimum())}>
{formatAmount(minimum(), denomination())}
</span>{" "}
{t("max")}{" "}
<span
class="btn-small btn-light"
onClick={() => setAmount(maximum())}>
{formatAmount(maximum(), denomination())}
</span>
</p>
<div class="icons">
<div>
Expand All @@ -247,8 +253,8 @@ const Create = () => {
autofocus
required
type="text"
placeholder={formatAmount(minimum())}
maxlength={calculateDigits()}
placeholder={formatAmount(minimum(), denomination())}
maxlength={calculateDigits(maximum(), denomination())}
inputmode={
denomination() == "btc" ? "decimal" : "numeric"
}
Expand All @@ -260,7 +266,7 @@ const Create = () => {
: sendAmountFormatted()
}
onpaste={(e) => validatePaste(e)}
onkeypress={(e) => validateInput(e)}
onKeyPress={(e) => validateInput(e)}
onInput={(e) => changeSendAmount(e)}
/>
</div>
Expand All @@ -272,9 +278,10 @@ const Create = () => {
required
type="text"
placeholder={formatAmount(
calculateReceiveAmount(minimum()),
calculateReceiveAmount(minimum(), reverse()),
denomination(),
)}
maxlength={calculateDigits()}
maxlength={calculateDigits(maximum(), denomination())}
inputmode={
denomination() == "btc" ? "decimal" : "numeric"
}
Expand All @@ -286,7 +293,7 @@ const Create = () => {
: receiveAmountFormatted()
}
onpaste={(e) => validatePaste(e)}
onkeypress={(e) => validateInput(e)}
onKeyPress={(e) => validateInput(e)}
onInput={(e) => changeReceiveAmount(e)}
/>
</div>
Expand Down
13 changes: 7 additions & 6 deletions src/Hero.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import bitcoin from "./assets/bitcoin-icon.svg";
import lightning from "./assets/lightning-icon.svg";
import liquid from "./assets/liquid-icon.svg";
import { ambossUrl } from "./config";
import { fetcher } from "./helper";
import { BTC } from "./consts";
import { fetcher, getApiUrl } from "./helper";
import t from "./i18n";
import "./style/hero.scss";

Expand All @@ -16,10 +17,10 @@ export const [hideHero, setHideHero] = createSignal(false);
export const Hero = () => {
const navigate = useNavigate();
const [nodeStats, setNodeStats] = createSignal(null);
const [numChannel, setNumChannel] = createSignal("0");
const [numPeers, setNumPeers] = createSignal("0");
const [capacity, setCapacity] = createSignal("0");
const [oldestChannel, setOldestChannel] = createSignal("0");
const [numChannel, setNumChannel] = createSignal<string>("0");
const [numPeers, setNumPeers] = createSignal<string>("0");
const [capacity, setCapacity] = createSignal<string>("0");
const [oldestChannel, setOldestChannel] = createSignal<string>("0");

createMemo(() => {
const stats = nodeStats();
Expand All @@ -36,7 +37,7 @@ export const Hero = () => {
window.open(ambossUrl, "_blank");
};

fetcher("/nodestats", (data: any) => {
fetcher(getApiUrl("/nodestats", BTC), (data: any) => {
log.debug("nodestats", data);
setNodeStats(data.nodes.BTC);
});
Expand Down
1 change: 0 additions & 1 deletion src/History.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ const History = () => {
setSwapSignal={setSwaps}
deleteButton={true}
/>
<hr />
<Show when={swaps().length > 0}>
<Show when={!isIos}>
<button
Expand Down
3 changes: 1 addition & 2 deletions src/Nav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ import "./style/nav.scss";

const Nav = ({ network }) => {
let timeout: ReturnType<typeof setTimeout> | undefined;

const [hamburger, setHamburger] = createSignal(false);
const [hamburger, setHamburger] = createSignal<boolean>(false);
return (
<nav>
<Warnings />
Expand Down
9 changes: 4 additions & 5 deletions src/Pay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,14 @@ import { Show, createEffect, createSignal, onCleanup } from "solid-js";
import BlockExplorer from "./components/BlockExplorer";
import LoadingSpinner from "./components/LoadingSpinner";
import { RBTC } from "./consts";
import { fetcher } from "./helper";
import { fetcher, getApiUrl } from "./helper";
import t from "./i18n";
import {
setFailureReason,
setSwap,
setSwapStatus,
setSwapStatusTransaction,
swap,
swapStatus,
swapStatusTransaction,
swaps,
} from "./signals";
import InvoiceExpired from "./status/InvoiceExpired";
Expand All @@ -32,6 +30,7 @@ import { swapStatusFailed } from "./utils/swapStatus";

const Pay = () => {
const params = useParams();
const [swapStatusTransaction, setSwapStatusTransaction] = createSignal("");
const [contractTransaction, setContractTransaction] =
createSignal(undefined);
const [contractTransactionType, setContractTransactionType] =
Expand All @@ -47,8 +46,8 @@ const Pay = () => {
log.debug("selecting swap", currentSwap);
setSwap(currentSwap);
fetcher(
"/swapstatus",
(data: any) => {
getApiUrl("/swapstatus", currentSwap.asset),
(data) => {
setSwapStatus(data.status);
setSwapStatusTransaction(data.transaction);
setFailureReason(data.failureReason);
Expand Down
Loading

0 comments on commit 45dac22

Please sign in to comment.