From 255e511d6cc17a8e2629597e67a68bb94aa99bcd Mon Sep 17 00:00:00 2001 From: michael1011 Date: Thu, 15 Aug 2024 18:03:11 +0200 Subject: [PATCH] refactor: remove API endpoint based on pair We do not need that feature anymore and it adds a lot complexity for every single API call that is being made --- src/components/CreateButton.tsx | 2 +- src/components/RefundButton.tsx | 3 -- src/components/SwapChecker.tsx | 62 ++++++--------------- src/context/Global.tsx | 7 ++- src/context/Web3.tsx | 2 +- src/pages/Hero.tsx | 3 +- src/pages/Pay.tsx | 5 +- src/pages/Refund.tsx | 18 ++++--- src/status/SwapExpired.tsx | 6 +-- src/utils/boltzClient.ts | 95 +++++++++++---------------------- src/utils/claim.ts | 10 +--- src/utils/helper.ts | 10 ++-- src/utils/refund.ts | 5 +- 13 files changed, 73 insertions(+), 155 deletions(-) diff --git a/src/components/CreateButton.tsx b/src/components/CreateButton.tsx index 271bd97f..e80889db 100644 --- a/src/components/CreateButton.tsx +++ b/src/components/CreateButton.tsx @@ -259,7 +259,7 @@ export const CreateButton = () => { } if (msg === "invalid pair hash") { - setPairs(await getPairs(assetReceive())); + setPairs(await getPairs()); notify("error", t("feecheck")); } else { notify("error", msg); diff --git a/src/components/RefundButton.tsx b/src/components/RefundButton.tsx index 95c4ae95..221dcbf4 100644 --- a/src/components/RefundButton.tsx +++ b/src/components/RefundButton.tsx @@ -65,7 +65,6 @@ export const RefundEvm = ({ ); } else { const { signature } = await getEipRefundSignature( - asset, // The preimage hash can be used as an identifier preimageHash, // The endpoints for submarine and chain swap call the same endpoint @@ -195,7 +194,6 @@ const RefundButton = ({ setRefundRunning(true); const transactionToRefund = await getLockupTransaction( - swap().assetSend, swap().id, swap().type, ); @@ -255,7 +253,6 @@ const RefundButton = ({ if (!swap()) return; const transactionToRefund = await getLockupTransaction( - swap().assetSend, swap().id, swap().type, ); diff --git a/src/components/SwapChecker.tsx b/src/components/SwapChecker.tsx index 84b4e0b2..18017d94 100644 --- a/src/components/SwapChecker.tsx +++ b/src/components/SwapChecker.tsx @@ -2,7 +2,7 @@ import { OutputType } from "boltz-core"; import log from "loglevel"; import { createEffect, onCleanup, onMount } from "solid-js"; -import { BTC, LBTC, RBTC } from "../consts/Assets"; +import { RBTC } from "../consts/Assets"; import { SwapType } from "../consts/Enums"; import { swapStatusFinal, @@ -133,7 +133,7 @@ export const SwapChecker = () => { const { notify, updateSwapStatus, getSwap, getSwaps, setSwapStorage, t } = useGlobalContext(); - const assetWebsocket = new Map(); + let ws: BoltzWebSocket | undefined = undefined; const prepareSwap = async (swapId: string, data: any) => { const currentSwap = await getSwap(swapId); @@ -170,19 +170,13 @@ export const SwapChecker = () => { } if (data.status === swapStatusSuccess.InvoiceSettled) { - data.transaction = await getReverseTransaction( - getRelevantAssetForSwap(currentSwap), - currentSwap.id, - ); + data.transaction = await getReverseTransaction(currentSwap.id); } else if ( currentSwap.type === SwapType.Chain && data.status === swapStatusSuccess.TransactionClaimed ) { data.transaction = ( - await getChainSwapTransactions( - getRelevantAssetForSwap(currentSwap), - currentSwap.id, - ) + await getChainSwapTransactions(currentSwap.id) ).serverLock.transaction; } @@ -246,14 +240,6 @@ export const SwapChecker = () => { }; onMount(async () => { - const urlsToAsset = new Map(); - for (const [asset, url] of [BTC, LBTC, RBTC].map((asset) => [ - asset, - getApiUrl(asset), - ])) { - urlsToAsset.set(url, (urlsToAsset.get(url) || []).concat(asset)); - } - const swapsToCheck = (await getSwaps()).filter( (s) => !swapStatusFinal.includes(s.status) || @@ -263,32 +249,18 @@ export const SwapChecker = () => { s.claimTx === undefined), ); - for (const [url, assets] of urlsToAsset.entries()) { - log.debug(`opening ws for assets [${assets.join(", ")}]: ${url}`); - const ws = new BoltzWebSocket( - url, - new Set( - swapsToCheck - .filter((s) => - assets.includes(getRelevantAssetForSwap(s)), - ) - .map((s) => s.id), - ), - prepareSwap, - claimSwap, - ); - ws.connect(); - for (const asset of assets) { - assetWebsocket.set(asset, ws); - } - } + log.debug(`Opening WebSocket: ${getApiUrl()}`); + ws = new BoltzWebSocket( + getApiUrl(), + new Set(swapsToCheck.map((s) => s.id)), + prepareSwap, + claimSwap, + ); + ws.connect(); }); onCleanup(() => { - const sockets = assetWebsocket.values(); - assetWebsocket.clear(); - - for (const ws of sockets) { + if (ws !== undefined) { ws.close(); } }); @@ -298,12 +270,10 @@ export const SwapChecker = () => { if (activeSwap === undefined || activeSwap === null) { return; } - // on page reload assetWebsocket is not yet initialized - const ws = assetWebsocket.get(getRelevantAssetForSwap(activeSwap)); - if (ws === undefined) { - return; + // on page reload assetWebsocket might not be initialized yet + if (ws !== undefined) { + ws.subscribeUpdates([activeSwap.id]); } - ws.subscribeUpdates([activeSwap.id]); }); return ""; diff --git a/src/context/Global.tsx b/src/context/Global.tsx index e519c952..9655b4f0 100644 --- a/src/context/Global.tsx +++ b/src/context/Global.tsx @@ -13,7 +13,6 @@ import { } from "solid-js"; import { config } from "../config"; -import { BTC } from "../consts/Assets"; import { Denomination } from "../consts/Enums"; import { swapStatusFinal } from "../consts/SwapStatus"; import { detectLanguage } from "../i18n/detect"; @@ -76,7 +75,7 @@ export type GlobalContextType = { audio?: boolean, ) => void; playNotificationSound: () => void; - fetchPairs: (asset?: string) => void; + fetchPairs: () => void; getLogs: () => Promise>; clearLogs: () => Promise; @@ -192,8 +191,8 @@ const GlobalProvider = (props: { children: any }) => { audio.play(); }; - const fetchPairs = (asset: string = BTC) => { - getPairs(asset) + const fetchPairs = () => { + getPairs() .then((data) => { log.debug("getpairs", data); setOnline(true); diff --git a/src/context/Web3.tsx b/src/context/Web3.tsx index 7505153a..dbc55b31 100644 --- a/src/context/Web3.tsx +++ b/src/context/Web3.tsx @@ -111,7 +111,7 @@ const Web3SignerProvider = (props: { return undefined; } - return (await getContracts(RBTC))["rsk"]; + return (await getContracts())["rsk"]; }); const getEtherSwap = () => { diff --git a/src/pages/Hero.tsx b/src/pages/Hero.tsx index 65b22fd8..c7f8fd3a 100644 --- a/src/pages/Hero.tsx +++ b/src/pages/Hero.tsx @@ -7,7 +7,6 @@ import bitcoin from "../assets/bitcoin-icon.svg"; import lightning from "../assets/lightning-icon.svg"; import liquid from "../assets/liquid-icon.svg"; import rbtc from "../assets/rootstock-icon.svg"; -import { BTC } from "../consts/Assets"; import { Denomination } from "../consts/Enums"; import { useGlobalContext } from "../context/Global"; import Create from "../pages/Create"; @@ -33,7 +32,7 @@ export const Hero = () => { onMount(async () => { try { - const statsRes = await getNodeStats(BTC); + const statsRes = await getNodeStats(); log.debug("node stats", statsRes); const stats = statsRes.BTC.total; diff --git a/src/pages/Pay.tsx b/src/pages/Pay.tsx index 7e4734b9..48b1ebf0 100644 --- a/src/pages/Pay.tsx +++ b/src/pages/Pay.tsx @@ -28,7 +28,6 @@ import TransactionConfirmed from "../status/TransactionConfirmed"; import TransactionLockupFailed from "../status/TransactionLockupFailed"; import TransactionMempool from "../status/TransactionMempool"; import { getSwapStatus } from "../utils/boltzClient"; -import { getRelevantAssetForSwap } from "../utils/swapCreator"; const Pay = () => { const params = useParams(); @@ -48,8 +47,8 @@ const Pay = () => { if (currentSwap) { log.debug("selecting swap", currentSwap); setSwap(currentSwap); - const asset = getRelevantAssetForSwap(currentSwap); - const res = await getSwapStatus(asset, currentSwap.id); + + const res = await getSwapStatus(currentSwap.id); setSwapStatus(res.status); setSwapStatusTransaction(res.transaction); setFailureReason(res.failureReason); diff --git a/src/pages/Refund.tsx b/src/pages/Refund.tsx index a94ad4f6..d7aafffa 100644 --- a/src/pages/Refund.tsx +++ b/src/pages/Refund.tsx @@ -1,7 +1,7 @@ import { useNavigate } from "@solidjs/router"; import log from "loglevel"; import QrScanner from "qr-scanner"; -import { Show, createEffect, createSignal, onMount } from "solid-js"; +import { Show, createEffect, createSignal, onCleanup, onMount } from "solid-js"; import BlockExplorer from "../components/BlockExplorer"; import ConnectWallet from "../components/ConnectWallet"; @@ -105,6 +105,12 @@ const Refund = () => { let refundScanAbort: AbortController | undefined = undefined; + onCleanup(() => { + if (refundScanAbort) { + refundScanAbort.abort(); + } + }); + createEffect(async () => { setLogRefundableSwaps([]); @@ -167,7 +173,7 @@ const Refund = () => { ) .map(async (swap) => { try { - const res = await getSwapStatus(swap.assetSend, swap.id); + const res = await getSwapStatus(swap.id); if ( !(await updateSwapStatus(swap.id, res.status)) && Object.values(swapStatusFailed).includes(res.status) @@ -177,12 +183,8 @@ const Refund = () => { return; } - // Make sure coins were locked for the swap with status "swap.expired" - await getLockupTransaction( - swap.assetSend, - swap.id, - swap.type, - ); + // Make sure coins were locked for the swap with the status "swap.expired" + await getLockupTransaction(swap.id, swap.type); addToRefundableSwaps(swap); } } catch (e) { diff --git a/src/status/SwapExpired.tsx b/src/status/SwapExpired.tsx index c1448e3d..66c9148c 100644 --- a/src/status/SwapExpired.tsx +++ b/src/status/SwapExpired.tsx @@ -17,11 +17,7 @@ const SwapExpired = () => { createEffect(async () => { setTransactionToRefund(null); try { - const res = await getLockupTransaction( - swap().assetSend, - swap().id, - swap().type, - ); + const res = await getLockupTransaction(swap().id, swap().type); log.debug(`got swap transaction for ${swap().id}`); setTransactionToRefund(res.hex); } catch (error: any) { diff --git a/src/utils/boltzClient.ts b/src/utils/boltzClient.ts index 1dfe6997..4e5131cf 100644 --- a/src/utils/boltzClient.ts +++ b/src/utils/boltzClient.ts @@ -98,11 +98,6 @@ type Contracts = { }; }; -type NodeInfo = { - publicKey: string; - uris: string[]; -}; - type SwapTreeLeaf = { output: string; version: number; @@ -169,18 +164,11 @@ type ChainSwapTransaction = { type TransactionInterface = Transaction | LiquidTransaction; -export const getPairs = async (asset: string): Promise => { +export const getPairs = async (): Promise => { const [submarine, reverse, chain] = await Promise.all([ - fetcher("/v2/swap/submarine", asset), - fetcher("/v2/swap/reverse", asset), - fetcher("/v2/swap/chain", asset).catch((error) => { - // Handle API endpoints that do not have chain swaps yet gracefully - if (error.status === 404) { - return {}; - } - - throw error; - }), + fetcher("/v2/swap/submarine"), + fetcher("/v2/swap/reverse"), + fetcher("/v2/swap/chain"), ]); return { @@ -198,7 +186,7 @@ export const createSubmarineSwap = ( referralId: string, refundPublicKey?: string, ): Promise => - fetcher("/v2/swap/submarine", to, { + fetcher("/v2/swap/submarine", { from, to, invoice, @@ -217,7 +205,7 @@ export const createReverseSwap = ( claimPublicKey?: string, claimAddress?: string, ): Promise => - fetcher("/v2/swap/reverse", to, { + fetcher("/v2/swap/reverse", { from, to, invoiceAmount, @@ -239,7 +227,7 @@ export const createChainSwap = ( pairHash: string, referralId: string, ): Promise => - fetcher("/v2/swap/chain", to, { + fetcher("/v2/swap/chain", { from, to, userLockAmount, @@ -252,7 +240,6 @@ export const createChainSwap = ( }); export const getPartialRefundSignature = async ( - asset: string, id: string, type: SwapType, pubNonce: Buffer, @@ -264,7 +251,6 @@ export const getPartialRefundSignature = async ( `/v2/swap/${ type === SwapType.Submarine ? "submarine" : "chain" }/${id}/refund`, - asset, { index, pubNonce: pubNonce.toString("hex"), @@ -278,7 +264,6 @@ export const getPartialRefundSignature = async ( }; export const getPartialReverseClaimSignature = async ( - asset: string, id: string, preimage: Buffer, pubNonce: Buffer, @@ -286,7 +271,7 @@ export const getPartialReverseClaimSignature = async ( index: number, ): Promise => { checkCooperative(); - const res = await fetcher(`/v2/swap/reverse/${id}/claim`, asset, { + const res = await fetcher(`/v2/swap/reverse/${id}/claim`, { index, preimage: preimage.toString("hex"), pubNonce: pubNonce.toString("hex"), @@ -298,8 +283,8 @@ export const getPartialReverseClaimSignature = async ( }; }; -export const getSubmarineClaimDetails = async (asset: string, id: string) => { - const res = await fetcher(`/v2/swap/submarine/${id}/claim`, asset); +export const getSubmarineClaimDetails = async (id: string) => { + const res = await fetcher(`/v2/swap/submarine/${id}/claim`); return { pubNonce: Musig.parsePubNonce(res.pubNonce), preimage: Buffer.from(res.preimage, "hex"), @@ -308,42 +293,26 @@ export const getSubmarineClaimDetails = async (asset: string, id: string) => { }; export const postSubmarineClaimDetails = ( - asset: string, id: string, pubNonce: Buffer | Uint8Array, partialSignature: Buffer | Uint8Array, ) => { checkCooperative(); - return fetcher(`/v2/swap/submarine/${id}/claim`, asset, { + return fetcher(`/v2/swap/submarine/${id}/claim`, { pubNonce: Buffer.from(pubNonce).toString("hex"), partialSignature: Buffer.from(partialSignature).toString("hex"), }); }; -export const getEipRefundSignature = ( - asset: string, - id: string, - type: SwapType, -) => { +export const getEipRefundSignature = (id: string, type: SwapType) => { checkCooperative(); - return fetcher<{ signature: string }>( - `/v2/swap/${type}/${id}/refund`, - asset, - ); + return fetcher<{ signature: string }>(`/v2/swap/${type}/${id}/refund`); }; -export const getFeeEstimations = (asset: string) => - fetcher>("/v2/chain/fees", asset); - -export const getNodes = (asset: string) => - fetcher<{ - BTC: { - LND: NodeInfo; - CLN: NodeInfo; - }; - }>("/v2/nodes", asset); +export const getFeeEstimations = () => + fetcher>("/v2/chain/fees"); -export const getNodeStats = (asset: string) => +export const getNodeStats = () => fetcher<{ BTC: { total: { @@ -353,18 +322,17 @@ export const getNodeStats = (asset: string) => oldestChannel: number; }; }; - }>("/v2/nodes/stats", asset); + }>("/v2/nodes/stats"); -export const getContracts = (asset: string) => - fetcher>("/v2/chain/contracts", asset); +export const getContracts = () => + fetcher>("/v2/chain/contracts"); export const broadcastTransaction = (asset: string, txHex: string) => - fetcher<{ id: string }>(`/v2/chain/${asset}/transaction`, asset, { + fetcher<{ id: string }>(`/v2/chain/${asset}/transaction`, { hex: txHex, }); export const getLockupTransaction = async ( - asset: string, id: string, type: SwapType, ): Promise<{ @@ -380,10 +348,10 @@ export const getLockupTransaction = async ( hex: string; timeoutBlockHeight: number; timeoutEta?: number; - }>(`/v2/swap/submarine/${id}/transaction`, asset); + }>(`/v2/swap/submarine/${id}/transaction`); case SwapType.Chain: - const res = await getChainSwapTransactions(asset, id); + const res = await getChainSwapTransactions(id); return { id: res.userLock.transaction.id, hex: res.userLock.transaction.hex, @@ -396,14 +364,14 @@ export const getLockupTransaction = async ( } }; -export const getReverseTransaction = (asset: string, id: string) => +export const getReverseTransaction = (id: string) => fetcher<{ id: string; hex: string; timeoutBlockHeight: number; - }>(`/v2/swap/reverse/${id}/transaction`, asset); + }>(`/v2/swap/reverse/${id}/transaction`); -export const getSwapStatus = (asset: string, id: string) => +export const getSwapStatus = (id: string) => fetcher<{ status: string; failureReason?: string; @@ -412,17 +380,16 @@ export const getSwapStatus = (asset: string, id: string) => id: string; hex: string; }; - }>(`/v2/swap/${id}`, asset); + }>(`/v2/swap/${id}`); -export const getChainSwapClaimDetails = (asset: string, id: string) => +export const getChainSwapClaimDetails = (id: string) => fetcher<{ pubNonce: string; publicKey: string; transactionHash: string; - }>(`/v2/swap/chain/${id}/claim`, asset); + }>(`/v2/swap/chain/${id}/claim`); export const postChainSwapDetails = ( - asset: string, id: string, preimage: string, signature: { pubNonce: string; partialSignature: string }, @@ -432,18 +399,18 @@ export const postChainSwapDetails = ( return fetcher<{ pubNonce: string; partialSignature: string; - }>(`/v2/swap/chain/${id}/claim`, asset, { + }>(`/v2/swap/chain/${id}/claim`, { preimage, signature, toSign, }); }; -export const getChainSwapTransactions = (asset: string, id: string) => +export const getChainSwapTransactions = (id: string) => fetcher<{ userLock: ChainSwapTransaction; serverLock: ChainSwapTransaction; - }>(`/v2/swap/chain/${id}/transactions`, asset); + }>(`/v2/swap/chain/${id}/transactions`); export { Pairs, diff --git a/src/utils/claim.ts b/src/utils/claim.ts index 6b240420..bd6de58a 100644 --- a/src/utils/claim.ts +++ b/src/utils/claim.ts @@ -115,7 +115,6 @@ const claimReverseSwap = async ( try { const boltzSig = await getPartialReverseClaimSignature( - asset, swap.id, preimage, Buffer.from(musig.getPublicNonce()), @@ -200,10 +199,7 @@ const claimChainSwap = async ( // Sign the claim transaction of the server try { - const serverClaimDetails = await getChainSwapClaimDetails( - swap.assetSend, - swap.id, - ); + const serverClaimDetails = await getChainSwapClaimDetails(swap.id); const boltzClaimPublicKey = Buffer.from( serverClaimDetails.publicKey, @@ -259,7 +255,6 @@ const claimChainSwap = async ( try { // Post our partial signature to ask for theirs const theirPartial = await postChainSwapDetails( - swap.assetReceive, swap.id, swap.preimage, await createTheirPartialSignature(), @@ -349,7 +344,7 @@ export const createSubmarineSignature = async (swap: SubmarineSwap) => { await setup(); log.info(`creating cooperative claim signature for`, swap.id); - const claimDetails = await getSubmarineClaimDetails(swapAsset, swap.id); + const claimDetails = await getSubmarineClaimDetails(swap.id); if ( crypto.sha256(claimDetails.preimage).toString("hex") !== decodeInvoice(swap.invoice).preimageHash @@ -369,7 +364,6 @@ export const createSubmarineSignature = async (swap: SubmarineSwap) => { musig.initializeSession(claimDetails.transactionHash); await postSubmarineClaimDetails( - swapAsset, swap.id, musig.getPublicNonce(), musig.signPartial(), diff --git a/src/utils/helper.ts b/src/utils/helper.ts index 762185fe..1fcfd6b8 100644 --- a/src/utils/helper.ts +++ b/src/utils/helper.ts @@ -51,9 +51,8 @@ export const clipboard = (text: string) => { navigator.clipboard.writeText(text); }; -export const getApiUrl = (asset: string): string => { - const found = config.assets[asset]; - return chooseUrl(found?.apiUrl ?? config.apiUrl); +export const getApiUrl = (): string => { + return chooseUrl(config.apiUrl); }; export const coalesceLn = (asset: string) => (asset === LN ? BTC : asset); @@ -80,8 +79,7 @@ export const getPair = < export const fetcher = async ( url: string, - asset: string = BTC, - params: any | undefined = null, + params?: Record, ): Promise => { let opts = {}; if (params) { @@ -93,7 +91,7 @@ export const fetcher = async ( body: JSON.stringify(params), }; } - const apiUrl = getApiUrl(asset) + url; + const apiUrl = getApiUrl() + url; const response = await fetch(apiUrl, opts); if (!response.ok) { return Promise.reject(response); diff --git a/src/utils/refund.ts b/src/utils/refund.ts index fb42f9ba..bb32d85d 100644 --- a/src/utils/refund.ts +++ b/src/utils/refund.ts @@ -101,7 +101,6 @@ const refundTaproot = async ( try { const boltzSig = await getPartialRefundSignature( - swap.assetSend, swap.id, swap.type, Buffer.from(musig.getPublicNonce()), @@ -200,9 +199,7 @@ export const refund = async ( const output = decodeAddress(swap.assetSend, refundAddress); - const feePerVbyte = (await getFeeEstimations(swap.assetSend))[ - swap.assetSend - ]; + const feePerVbyte = (await getFeeEstimations())[swap.assetSend]; const lockupTransaction = getTransaction(swap.assetSend).fromHex( transactionToRefund.hex,