forked from Prompt-Hash-Stellar/prompt-hash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseAccountSequenceNumber.ts
More file actions
65 lines (57 loc) · 2.03 KB
/
Copy pathuseAccountSequenceNumber.ts
File metadata and controls
65 lines (57 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/only-throw-error */
/* eslint-disable @typescript-eslint/no-unsafe-argument */
import { MuxedAccount, StrKey } from "@stellar/stellar-sdk";
import { useQuery } from "@tanstack/react-query";
import { NetworkHeaders } from "../types/types";
export const useAccountSequenceNumber = ({
publicKey,
horizonUrl,
headers,
uniqueId,
enabled = false,
}: {
publicKey: string;
horizonUrl: string;
headers: NetworkHeaders;
uniqueId?: string;
enabled?: boolean;
}) => {
const query = useQuery({
queryKey: ["accountSequenceNumber", { publicKey, uniqueId }],
queryFn: async () => {
let sourceAccount = publicKey;
if (StrKey.isValidMed25519PublicKey(publicKey)) {
const muxedAccount = MuxedAccount.fromAddress(publicKey, "0");
sourceAccount = muxedAccount.baseAccount().accountId();
}
try {
const response = await fetch(
`${horizonUrl}/accounts/${sourceAccount}`,
{ headers },
);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const responseJson = await response.json();
if (responseJson?.status === 0) {
throw `Unable to reach server at ${horizonUrl}.`;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
if (responseJson?.status?.toString()?.startsWith("4")) {
if (responseJson?.title === "Resource Missing") {
throw "Account not found. Make sure the correct network is selected and the account is funded/created.";
}
throw (
responseJson?.extras?.reason ||
responseJson?.detail ||
"Something went wrong when fetching the transaction sequence number. Please try again."
);
}
return (BigInt(responseJson.sequence) + BigInt(1)).toString();
} catch (e: unknown) {
throw `${e as Error}. Check network configuration.`;
}
},
enabled,
});
return query;
};