Skip to content

Commit

Permalink
fix: multiple tabs localstorage issue
Browse files Browse the repository at this point in the history
closes #498
refactor how to add/update/get a swap via globalContext
  • Loading branch information
dni committed Apr 2, 2024
1 parent 70f4842 commit 3b310a8
Show file tree
Hide file tree
Showing 12 changed files with 105 additions and 91 deletions.
7 changes: 3 additions & 4 deletions src/components/CreateButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,12 @@ import { validateResponse } from "../utils/validation";
export const CreateButton = () => {
const navigate = useNavigate();
const {
addSwap,
denomination,
pairs,
separator,
setPairs,
online,
swaps,
setSwaps,
separator,
notify,
ref,
t,
Expand Down Expand Up @@ -243,7 +242,7 @@ export const CreateButton = () => {
navigate("/error/");
return;
}
setSwaps(swaps().concat(data));
addSwap(data);
setInvoice("");
setInvoiceValid(false);
setOnchainAddress("");
Expand Down
19 changes: 6 additions & 13 deletions src/components/RefundButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ const RefundButton = ({
const {
setNotificationType,
setNotification,
swaps,
setSwaps,
getSwap,
updateSwap,
setRefundAddress,
refundAddress,
t,
Expand All @@ -36,13 +36,6 @@ const RefundButton = ({
if (swap() && swap().asset === RBTC) {
const { getEtherSwap, getSigner } = useWeb3Signer();

const updateSwaps = (cb: any) => {
const swapsTmp = swaps();
const currentSwap = swapsTmp.find((s: any) => swap().id === s.id);
cb(currentSwap);
setSwaps(swapsTmp);
};

return (
<ContractTransaction
onClick={async () => {
Expand Down Expand Up @@ -86,7 +79,8 @@ const RefundButton = ({
);
}

updateSwaps((current: any) => (current.refundTx = tx.hash));
currentSwap.refundTx = tx.hash;
updateSwap(currentSwap);
await tx.wait(1);
}}
buttonText={t("refund")}
Expand Down Expand Up @@ -143,10 +137,9 @@ const RefundButton = ({
// only if the swaps was not initiated with the refund json
// refundjson has no date
if (res.date !== undefined) {
const swapsTmp = swaps();
const currentSwap = swapsTmp.find((s: any) => res.id === s.id);
const currentSwap = getSwap(res.id);
currentSwap.refundTx = res.refundTx;
setSwaps(swapsTmp);
updateSwap(currentSwap);
} else {
if (setRefundTxId) {
setRefundTxId(res.refundTx);
Expand Down
14 changes: 7 additions & 7 deletions src/components/SwapChecker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,8 @@ export const SwapChecker = () => {
setTimeoutEta,
setTimeoutBlockheight,
} = usePayContext();
const { notify, updateSwapStatus, swaps, setSwaps } = useGlobalContext();
const { notify, updateSwapStatus, getSwap, getSwaps, updateSwap } =
useGlobalContext();

const assetWebsocket = new Map<string, BoltzWebSocket>();

Expand Down Expand Up @@ -152,7 +153,7 @@ export const SwapChecker = () => {
};

const prepareSwap = (swapId: string, data: any) => {
const currentSwap = swaps().find((s: any) => swapId === s.id);
const currentSwap = getSwap(swapId);
if (currentSwap === undefined) {
log.warn(`prepareSwap: swap ${swapId} not found`);
return;
Expand All @@ -167,7 +168,7 @@ export const SwapChecker = () => {
};

const claimSwap = async (swapId: string, data: any) => {
const currentSwap = swaps().find((s) => swapId === s.id);
const currentSwap = getSwap(swapId);
if (currentSwap === undefined) {
log.warn(`claimSwap: swap ${swapId} not found`);
return;
Expand Down Expand Up @@ -198,10 +199,9 @@ export const SwapChecker = () => {
) {
try {
const res = await claim(currentSwap, data.transaction);
const swapsTmp = swaps();
const claimedSwap = swapsTmp.find((s) => res.id === s.id);
const claimedSwap = getSwap(res.id);
claimedSwap.claimTx = res.claimTx;
setSwaps(swapsTmp);
updateSwap(claimedSwap);
notify("success", `swap ${res.id} claimed`);
} catch (e) {
log.warn("swapchecker failed to claim swap", e);
Expand All @@ -227,7 +227,7 @@ export const SwapChecker = () => {
urlsToAsset.set(url, (urlsToAsset.get(url) || []).concat(asset));
}

const swapsToCheck = swaps()
const swapsToCheck = getSwaps()
.filter(
(s) =>
!swapStatusFinal.includes(s.status) ||
Expand Down
13 changes: 5 additions & 8 deletions src/components/SwapList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const SwapList = ({
deleteButton?: boolean;
}) => {
const navigate = useNavigate();
const { t } = useGlobalContext();
const { deleteSwap, t } = useGlobalContext();
const [sortedSwaps, setSortedSwaps] = createSignal([]);
const [lastSwap, setLastSwap] = createSignal();

Expand All @@ -39,12 +39,9 @@ const SwapList = ({
return date.toLocaleDateString();
};

const deleteSwap = (swapId: string) => {
if (
setSwapSignal !== undefined &&
confirm(t("delete_localstorage_single_swap", { id: swapId }))
) {
setSwapSignal(swapsSignal().filter((s: any) => s.id !== swapId));
const deleteSwapAction = (swapId: string) => {
if (confirm(t("delete_localstorage_single_swap", { id: swapId }))) {
deleteSwap(swapId);
}
};

Expand Down Expand Up @@ -74,7 +71,7 @@ const SwapList = ({
<Show when={deleteButton}>
<span
class="btn-small btn-danger"
onClick={() => deleteSwap(swap.id)}>
onClick={() => deleteSwapAction(swap.id)}>
{t("delete")}
</span>
</Show>
Expand Down
53 changes: 45 additions & 8 deletions src/context/Global.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ export type GlobalContextType = {
setI18nConfigured: Setter<string | null>;
denomination: Accessor<string>;
setDenomination: Setter<string>;
swaps: Accessor<any>;
setSwaps: Setter<any>;
hideHero: Accessor<boolean>;
setHideHero: Setter<boolean>;
embedded: Accessor<boolean>;
Expand All @@ -61,6 +59,11 @@ export type GlobalContextType = {
notify: (type: string, message: string) => void;
fetchPairs: (asset?: string) => void;
updateSwapStatus: (id: string, newStatus: string) => boolean;
addSwap: (swap: any) => void;
updateSwap: (swap: any) => void;
getSwap: (id: string) => any;
getSwaps: () => any[];
deleteSwap: (id: string) => void;
};

// Local storage serializer to support the values created by the deprecated "createStorageSignal"
Expand Down Expand Up @@ -150,14 +153,45 @@ const GlobalProvider = (props: { children: any }) => {
});
};

const addSwap = (swap: any) => {
setSwaps(getSwaps().concat(swap));
};

const deleteSwap = (id: string) => {
setSwaps(getSwaps().filter((s: any) => s.id !== id));
};

const updateSwap = (swap: any) => {
const swapsTmp = getSwaps();
const index = swapsTmp.findIndex((s: any) => s.id === swap.id);
swapsTmp[index] = swap;
setSwaps(swapsTmp);
};

const getSwap = (id: string) => {
return getSwaps().find((s: any) => s.id === id);
};

const getSwaps = () => {
const tmpSwaps = swaps();
try {
// check if the local storage is different
const localSwapsJson = localStorage.getItem("swaps");
if (localSwapsJson && localSwapsJson !== JSON.stringify(tmpSwaps)) {
const localSwaps = JSON.parse(localSwapsJson);
setSwaps(localSwaps);
return localSwaps;
}
} catch {}
return tmpSwaps;
};

const updateSwapStatus = (id: string, newStatus: string) => {
if (swapStatusFinal.includes(newStatus)) {
const swapsTmp = swaps();
const swap = swapsTmp.find((swap) => swap.id === id);

const swap = getSwap(id);
if (swap.status !== newStatus) {
swap.status = newStatus;
setSwaps(swapsTmp);
updateSwap(swap);
return true;
}
}
Expand Down Expand Up @@ -224,8 +258,6 @@ const GlobalProvider = (props: { children: any }) => {
setI18nConfigured,
denomination,
setDenomination,
swaps,
setSwaps,
hideHero,
setHideHero,
embedded,
Expand All @@ -237,6 +269,11 @@ const GlobalProvider = (props: { children: any }) => {
notify,
fetchPairs,
updateSwapStatus,
addSwap,
updateSwap,
getSwap,
deleteSwap,
getSwaps,
}}>
{props.children}
</GlobalContext.Provider>
Expand Down
21 changes: 13 additions & 8 deletions src/pages/History.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,14 @@ const History = () => {

let importRef: HTMLInputElement;

const { swaps, setSwaps, setNotification, setNotificationType, t } =
useGlobalContext();
const {
swaps,
setSwaps,
getSwaps,
setNotification,
setNotificationType,
t,
} = useGlobalContext();

const deleteLocalStorage = () => {
if (confirm(t("delete_localstorage"))) {
Expand All @@ -34,7 +40,10 @@ const History = () => {
};

const backupLocalStorage = () => {
downloadJson(`boltz-backup-${Math.floor(Date.now() / 1000)}`, swaps());
downloadJson(
`boltz-backup-${Math.floor(Date.now() / 1000)}`,
getSwaps(),
);
};

const importLocalStorage = (e: Event) => {
Expand Down Expand Up @@ -85,11 +94,7 @@ const History = () => {
</button>
</div>
}>
<SwapList
swapsSignal={swaps}
setSwapSignal={setSwaps}
deleteButton={true}
/>
<SwapList swapsSignal={swaps} deleteButton={true} />
<hr />
<Show when={swaps().length > 0}>
<Show when={!isIos}>
Expand Down
26 changes: 9 additions & 17 deletions src/pages/Pay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const Pay = () => {
const [contractTransactionType, setContractTransactionType] =
createSignal("lockup_tx");

const { swaps, t } = useGlobalContext();
const { getSwap, t } = useGlobalContext();
const {
swap,
setSwap,
Expand All @@ -41,22 +41,14 @@ const Pay = () => {
} = usePayContext();

createEffect(async () => {
let tmpSwaps = swaps();
if (tmpSwaps) {
const currentSwap = tmpSwaps
.filter((s) => s.id === params.id)
.pop();
if (currentSwap) {
log.debug("selecting swap", currentSwap);
setSwap(currentSwap);
const res = await getSwapStatus(
currentSwap.asset,
currentSwap.id,
);
setSwapStatus(res.status);
setSwapStatusTransaction(res.transaction);
setFailureReason(res.failureReason);
}
const currentSwap = getSwap(params.id);
if (currentSwap) {
log.debug("selecting swap", currentSwap);
setSwap(currentSwap);
const res = await getSwapStatus(currentSwap.asset, currentSwap.id);
setSwapStatus(res.status);
setSwapStatusTransaction(res.transaction);
setFailureReason(res.failureReason);
}
});

Expand Down
9 changes: 5 additions & 4 deletions src/pages/Refund.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import ErrorWasm from "./ErrorWasm";

const Refund = () => {
const navigate = useNavigate();
const { updateSwapStatus, wasmSupported, swaps, t } = useGlobalContext();
const { getSwap, getSwaps, updateSwapStatus, wasmSupported, t } =
useGlobalContext();
const { setTimeoutEta, setTimeoutBlockheight } = usePayContext();

const [swapFound, setSwapFound] = createSignal(null);
Expand All @@ -32,7 +33,7 @@ const Refund = () => {

// When the swap id is found in the local storage, there is no need for the validation,
// all relevant data is there already and we just need to show the button to redirect
const localStorageSwap = swaps().find((s: any) => s.id === json.id);
const localStorageSwap = getSwap(json.id);
if (localStorageSwap !== undefined) {
setSwapFound(json.id);
return;
Expand Down Expand Up @@ -97,7 +98,7 @@ const Refund = () => {
};

onMount(() => {
const swapsToRefund = swaps()
const swapsToRefund = getSwaps()
.filter(refundSwapsSanityFilter)
.filter((swap) =>
[
Expand All @@ -107,7 +108,7 @@ const Refund = () => {
);
setRefundableSwaps(swapsToRefund);

swaps()
getSwaps()
.filter(refundSwapsSanityFilter)
.filter(
(swap) =>
Expand Down
13 changes: 5 additions & 8 deletions src/pages/RefundStep.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,13 @@ const RefundStep = () => {
const params = useParams();
const navigate = useNavigate();
const { setSwap } = usePayContext();
const { swaps, t } = useGlobalContext();
const { getSwap, t } = useGlobalContext();

createEffect(() => {
let tmpSwaps = swaps();
if (tmpSwaps) {
let currentSwap = tmpSwaps.filter((s) => s.id === params.id).pop();
if (currentSwap) {
log.debug("selecting swap", currentSwap);
setSwap(currentSwap);
}
const currentSwap = getSwap(params.id);
if (currentSwap) {
log.debug("selecting swap", currentSwap);
setSwap(currentSwap);
}
});

Expand Down
Loading

0 comments on commit 3b310a8

Please sign in to comment.