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

fix: claim duplications #542

Merged
merged 5 commits into from
Mar 29, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 12 additions & 5 deletions src/components/SwapChecker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,23 @@ import {
} from "../utils/boltzClient";
import { claim, createSubmarineSignature } from "../utils/claim";
import { getApiUrl } from "../utils/helper";
import Lock from "../utils/lock";
import {
swapStatusFinal,
swapStatusPending,
swapStatusSuccess,
} from "../utils/swapStatus";

type SwapStatus = {
id: string;
status: string;
};

const reconnectInterval = 5_000;

class BoltzWebSocket {
private readonly swapClaimLock = new Lock();

private ws?: WebSocket;
private reconnectTimeout?: any;
private isClosed: boolean = false;
Expand Down Expand Up @@ -55,14 +63,13 @@ class BoltzWebSocket {
log.debug(`ws ${this.url} message`, data);

if (data.event === "update" && data.channel === "swap.update") {
const swapUpdates = data.args as {
id: string;
status: string;
}[];
const swapUpdates = data.args as SwapStatus[];
for (const status of swapUpdates) {
this.relevantIds.add(status.id);
this.prepareSwap(status.id, status);
await this.claimSwap(status.id, status);
this.swapClaimLock.acquire(() =>
this.claimSwap(status.id, status),
);
}
}
};
Expand Down
22 changes: 2 additions & 20 deletions src/status/TransactionClaimed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import LoadingSpinner from "../components/LoadingSpinner";
import { RBTC } from "../consts";
import { useGlobalContext } from "../context/Global";
import { usePayContext } from "../context/Pay";
import { getReverseTransaction } from "../utils/boltzClient";
import { claim } from "../utils/claim";

const Broadcasting = () => {
const { t } = useGlobalContext();
Expand All @@ -21,8 +19,8 @@ const Broadcasting = () => {

const TransactionClaimed = () => {
const navigate = useNavigate();
const { swap, setSwap } = usePayContext();
const { t, swaps, setSwaps } = useGlobalContext();
const { swap } = usePayContext();
const { t } = useGlobalContext();

const [claimBroadcast, setClaimBroadcast] = createSignal<
boolean | undefined
Expand All @@ -41,22 +39,6 @@ const TransactionClaimed = () => {
);
});

createEffect(async () => {
const toClaim = swap();

if (claimBroadcast() === false) {
await claim(
toClaim,
await getReverseTransaction(toClaim.asset, toClaim.id),
);
const allSwaps = swaps();
allSwaps.find((swap) => swap.id === toClaim.id).claimTx =
toClaim.claimTx;
setSwaps(allSwaps);
setSwap(toClaim);
}
});

return (
<div>
<Show when={claimBroadcast() === true} fallback={<Broadcasting />}>
Expand Down
23 changes: 23 additions & 0 deletions src/utils/lock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Lock {
private locked = false;
private readonly waiting: (() => void)[] = [];

public acquire = async (promise: () => Promise<void>) => {
while (this.locked) {
await new Promise<void>((resolve) => this.waiting.push(resolve));
}

this.locked = true;
try {
await promise();
} finally {
this.locked = false;
if (this.waiting.length > 0) {
const nextResolve = this.waiting.shift();
nextResolve();
}
}
};
}

export default Lock;
72 changes: 1 addition & 71 deletions tests/status/TransactionClaimed.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,8 @@ import { render, screen } from "@solidjs/testing-library";
import { BTC, LBTC, RBTC } from "../../src/consts";
import i18n from "../../src/i18n/i18n";
import TransactionClaimed from "../../src/status/TransactionClaimed";
import { getReverseTransaction } from "../../src/utils/boltzClient";
import { claim } from "../../src/utils/claim";
import {
TestComponent,
contextWrapper,
globalSignals,
payContext,
} from "../helper";
import { TestComponent, contextWrapper, payContext } from "../helper";

let claimPromiseResolve: (() => void) | undefined = undefined;

jest.mock("../../src/utils/claim", () => ({
claim: jest.fn().mockImplementation(
async (swap) =>
new Promise<void>((resolve) => {
claimPromiseResolve = () => {
swap.claimTx = "claimedTxId";
resolve(swap);
};
}),
),
}));
jest.mock("../../src/utils/boltzClient", () => ({
getReverseTransaction: jest.fn().mockResolvedValue({
hex: "txHex",
Expand Down Expand Up @@ -63,54 +43,4 @@ describe("TransactionClaimed", () => {
screen.findByText(i18n.en.congrats),
).resolves.not.toBeUndefined();
});

test.each`
symbol
${BTC}
${LBTC}
`(
"should trigger claim for reverse swaps to $symbol with no claim transaction",
async ({ symbol }) => {
render(
() => (
<>
<TestComponent />
<TransactionClaimed />
</>
),
{
wrapper: contextWrapper,
},
);

const swap = {
id: "swapId",
asset: symbol,
reverse: true,
};

globalSignals.setSwaps([JSON.parse(JSON.stringify(swap))]);
payContext.setSwap(swap);

await expect(
screen.findByText(i18n.en.broadcasting_claim),
).resolves.not.toBeUndefined();

claimPromiseResolve();

await expect(
screen.findByText(i18n.en.congrats),
).resolves.not.toBeUndefined();

expect(getReverseTransaction).toHaveBeenCalledTimes(1);
expect(getReverseTransaction).toHaveBeenCalledWith(
swap.asset,
swap.id,
);
expect(claim).toHaveBeenCalledTimes(1);

expect(payContext.swap().claimTx).toEqual("claimedTxId");
expect(globalSignals.swaps()[0].claimTx).toEqual("claimedTxId");
},
);
});
31 changes: 31 additions & 0 deletions tests/utils/lock.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import Lock from "../../src/utils/lock";

describe("Lock", () => {
test("should run promises sequentially", async () => {
const lock = new Lock();

let value = 0;

let firstResolve: (() => void) | undefined;
const first = () =>
new Promise<void>((resolve) => {
value = 1;
firstResolve = resolve;
});

const firstAcquire = lock.acquire(first);

expect(value).toEqual(1);
expect(lock["locked"]).toEqual(true);

const second = jest.fn().mockResolvedValue(undefined);
const secondResolve = lock.acquire(second);

expect(second).toHaveBeenCalledTimes(0);
firstResolve();
await expect(firstAcquire).resolves.toEqual(undefined);

expect(second).toHaveBeenCalledTimes(1);
await expect(secondResolve).resolves.toEqual(undefined);
});
});