This repository has been archived by the owner on Feb 14, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuse-handle-feed.ts
108 lines (92 loc) · 2.72 KB
/
use-handle-feed.ts
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import { BASE_URL, EXP_PER_FEED, EXP_PER_LEVEL } from "@/app/config";
import {
createPlugin,
fetchAssetV1,
updatePluginV1,
updateV1,
} from "@metaplex-foundation/mpl-core";
import {
setComputeUnitLimit,
setComputeUnitPrice,
} from "@metaplex-foundation/mpl-toolbox";
import {
type RpcConfirmTransactionResult,
type Umi,
publicKey,
transactionBuilder,
} from "@metaplex-foundation/umi";
import { useMutation } from "@tanstack/react-query";
interface Input {
umi: Umi;
assetPublicKey: string;
}
interface Output {
signature: Uint8Array;
result: RpcConfirmTransactionResult;
}
export const useHandleFeed = () => {
const mutation = useMutation<Output, Error, Input>({
mutationFn: async ({ umi, assetPublicKey }: Input): Promise<Output> => {
console.log(`Feeding for ${assetPublicKey}`);
const asset = await fetchAssetV1(umi, publicKey(assetPublicKey));
const attributeList = asset.attributes?.attributeList;
const expAttribute = attributeList?.find((attr) => attr.key === "Exp");
const newExpValue = expAttribute
? Number.parseInt(expAttribute.value) + EXP_PER_FEED
: EXP_PER_FEED;
const level = Math.floor(newExpValue / EXP_PER_LEVEL);
const newUri = getUriForLevel(level);
const dateUnix = Math.floor(Date.now() / 1000).toString();
let transactions = transactionBuilder();
if (asset.uri !== newUri) {
transactions = transactions.add(
updateV1(umi, {
asset: asset.publicKey,
newName: asset.name,
newUri,
}),
);
}
transactions = transactions.add(
updatePluginV1(umi, {
asset: asset.publicKey,
plugin: createPlugin({
type: "Attributes",
data: {
attributeList: [
{ key: "Exp", value: newExpValue.toString() },
{
key: "Last Fed Time",
value: dateUnix,
},
],
},
}),
}),
);
transactions = transactions.prepend(
setComputeUnitPrice(umi, { microLamports: 1_000_000 }),
);
transactions = transactions.prepend(
setComputeUnitLimit(umi, { units: 800_000 }),
);
const result = await transactions.sendAndConfirm(umi, {
send: {
commitment: "finalized",
},
confirm: {
commitment: "finalized",
},
});
return result;
},
});
return mutation;
};
function getUriForLevel(level: number): string {
// Replace this with your own logic to get the URI for a given level
if (level >= 3) {
return `${BASE_URL}/assets/3.json`;
}
return `${BASE_URL}/assets/${level}.json`;
}