This repository was archived by the owner on Mar 16, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathuseContractApproval.ts
More file actions
65 lines (59 loc) · 2.32 KB
/
useContractApproval.ts
File metadata and controls
65 lines (59 loc) · 2.32 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
import { useQuery } from "@tanstack/react-query";
import { AGENT_ACCOUNT_APPROVAL_TYPES } from "@aibtc/types";
async function fetchApprovals(
agentAccountId: string,
contractIds: string[],
type: (typeof AGENT_ACCOUNT_APPROVAL_TYPES)[keyof typeof AGENT_ACCOUNT_APPROVAL_TYPES] = AGENT_ACCOUNT_APPROVAL_TYPES.TOKEN,
bustCache: boolean = false
) {
const [agentAddr, agentName] = agentAccountId.split(".");
if (!agentAddr || !agentName) throw new Error("Invalid agent account id");
const results = await Promise.all(
contractIds.map(async (targetContractId) => {
const res = await fetch(
// `${process.env.NEXT_PUBLIC_CACHE_URL}/contract-calls/read-only/${agentAddr}/${agentName}/is-approved-contract`,
`https://aibtcdev-cache-preview.hosting-962.workers.dev/contract-calls/read-only/${agentAddr}/${agentName}/get-agent-permissions`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
functionArgs: [
{
type: "principal",
value: targetContractId,
},
{
type: "uint",
value: type.toString(),
},
],
senderAddress: agentAddr,
network: process.env.NEXT_PUBLIC_STACKS_NETWORK,
cacheControl: { bustCache }, // Add cache busting here
}),
}
);
if (!res.ok) return { id: targetContractId, approved: false };
const data = await res.json();
const result = data?.success ? data?.data : false;
return {
id: targetContractId,
approved: result === true,
};
})
);
return Object.fromEntries(results.map((r) => [r.id, r.approved]));
}
export function useBatchContractApprovals(
agentAccountId: string | null,
contractIds: string[],
type: (typeof AGENT_ACCOUNT_APPROVAL_TYPES)[keyof typeof AGENT_ACCOUNT_APPROVAL_TYPES] = AGENT_ACCOUNT_APPROVAL_TYPES.TOKEN
) {
return useQuery({
queryKey: ["batch-approvals", agentAccountId, contractIds, type],
queryFn: () => fetchApprovals(agentAccountId!, contractIds, type, true), // Always bust cache on refetch
enabled: !!agentAccountId && contractIds.length > 0,
staleTime: 5 * 60 * 1000,
gcTime: 5 * 60 * 1000, // Cache the results for 5 minutes
});
}