generated from gelatodigital/web3-functions-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
58 lines (47 loc) · 1.57 KB
/
index.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
import {
Web3Function,
Web3FunctionContext,
} from "@gelatonetwork/web3-functions-sdk";
import { Contract } from "@ethersproject/contracts";
import ky from "ky"; // we recommend using ky as axios doesn't support fetch by default
const AD_BOARD_ABI = [
"function postMessage(string)",
"function viewMessage(address)",
];
Web3Function.onRun(async (context: Web3FunctionContext) => {
const { userArgs, storage, multiChainProvider } = context;
const provider = multiChainProvider.default();
const adBoardAddress =
(userArgs.adBoard as string) ??
"0x28a0A1C63E7E8F0DAe5ad633fe232c12b489d5f0";
const lastPost = Number(await storage.get("lastPost")) ?? 0;
const adBoardContract = new Contract(adBoardAddress, AD_BOARD_ABI);
const nextPostTime = lastPost + 3600; // 1h
const timestamp = (await provider.getBlock("latest")).timestamp;
if (timestamp < nextPostTime) {
return { canExec: false, message: `Time not elapsed` };
}
let message = "";
try {
const randomQuoteApi = `https://zenquotes.io/api/random`;
const quote: { q: string; a: string }[] = await ky
.get(randomQuoteApi, { timeout: 5_000, retry: 0 })
.json();
message = `${quote[0].a}: ${quote[0].q}`;
console.log(message);
} catch (err) {
return { canExec: false, message: `QuoteApi call failed` };
}
await storage.set("lastPost", timestamp.toString());
return {
canExec: true,
callData: [
{
to: adBoardAddress,
data: adBoardContract.interface.encodeFunctionData("postMessage", [
message,
]),
},
],
};
});