Skip to content

Commit

Permalink
fix: timeout on the wallet getInscriptions method (#57)
Browse files Browse the repository at this point in the history
  • Loading branch information
jrwbabylonlab authored Aug 8, 2024
2 parents 63c9a12 + dbc2bbb commit cace884
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
18 changes: 16 additions & 2 deletions src/utils/utxo/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { postVerifyUtxoOrdinals, UtxoInfo } from "@/app/api/postFilterOrdinals";

import { InscriptionIdentifier, UTXO } from "../wallet/wallet_provider";

const LOW_VALUE_UTXO_THRESHOLD = 10000;
export const LOW_VALUE_UTXO_THRESHOLD = 10000;
export const WALLET_FETCH_INSRIPTIONS_TIMEOUT = 3000; // 3 seconds

/**
* Filters out UTXOs that contain ordinals.
Expand Down Expand Up @@ -34,7 +35,20 @@ export const filterOrdinals = async (
// try to get the ordinals from the wallet first, if the wallet supports it
// otherwise fallback to the Babylon API
try {
const inscriptions = await getInscriptionsFromWalletCb();
const inscriptions = await Promise.race([
getInscriptionsFromWalletCb(),
new Promise<InscriptionIdentifier[]>((_, reject) =>
setTimeout(
() =>
reject(
new Error(
"Request timed out when fetching inscriptions from wallet",
),
),
WALLET_FETCH_INSRIPTIONS_TIMEOUT,
),
),
]);
// filter out the utxos that contains ordinals
return utxos.filter(
(utxo) =>
Expand Down
27 changes: 26 additions & 1 deletion tests/utils/utox/utxo.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { postVerifyUtxoOrdinals } from "@/app/api/postFilterOrdinals";
import { filterOrdinals } from "@/utils/utxo";
import { filterOrdinals, WALLET_FETCH_INSRIPTIONS_TIMEOUT } from "@/utils/utxo";
import { InscriptionIdentifier, UTXO } from "@/utils/wallet/wallet_provider";

// Mock the dependencies
Expand Down Expand Up @@ -109,4 +109,29 @@ describe("filterOrdinals", () => {

expect(result).toEqual(mockUtxos);
});

it("should filter UTXOs using the API fallback when wallet callback times out", async () => {
const mockApiResponse = [
{ txid: "txid1", vout: 0, inscription: true },
{ txid: "txid2", vout: 1, inscription: false },
{ txid: "txid3", vout: 2, inscription: false },
];
const getInscriptionsFromWalletCb = jest.fn().mockImplementation(() => {
return new Promise((resolve) =>
setTimeout(resolve, WALLET_FETCH_INSRIPTIONS_TIMEOUT + 1000),
);
});

(postVerifyUtxoOrdinals as jest.Mock).mockResolvedValue(mockApiResponse);

const result = await filterOrdinals(
mockUtxos,
address,
getInscriptionsFromWalletCb,
);

expect(getInscriptionsFromWalletCb).toHaveBeenCalledTimes(1);
expect(postVerifyUtxoOrdinals).toHaveBeenCalledWith(mockUtxos, address);
expect(result).toEqual([mockUtxos[1], mockUtxos[2]]);
});
});

0 comments on commit cace884

Please sign in to comment.