generated from gelatodigital/web3-functions-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
70 lines (61 loc) · 2.23 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
59
60
61
62
63
64
65
66
67
68
69
70
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 ORACLE_ABI = [
"function lastUpdated() external view returns(uint256)",
"function updatePrice(uint256)",
];
Web3Function.onRun(async (context: Web3FunctionContext) => {
const { userArgs, multiChainProvider } = context;
const provider = multiChainProvider.default();
// Retrieve Last oracle update time
const oracleAddress =
(userArgs.oracle as string) ?? "0x71B9B0F6C999CBbB0FeF9c92B80D54e4973214da";
let lastUpdated;
let oracle;
try {
oracle = new Contract(oracleAddress, ORACLE_ABI, provider);
lastUpdated = parseInt(await oracle.lastUpdated());
console.log(`Last oracle update: ${lastUpdated}`);
} catch (err) {
return { canExec: false, message: `Rpc call failed` };
}
// Check if it's ready for a new update
const nextUpdateTime = lastUpdated + 300; // 5 min
const timestamp = (await provider.getBlock("latest")).timestamp;
console.log(`Next oracle update: ${nextUpdateTime}`);
if (timestamp < nextUpdateTime) {
return { canExec: false, message: `Time not elapsed` };
}
// Get current price on coingecko
const currency = (userArgs.currency as string) ?? "ethereum";
let price = 0;
try {
// Get api from secrets
const coingeckoApi = await context.secrets.get("COINGECKO_API");
if (!coingeckoApi)
return { canExec: false, message: `COINGECKO_API not set in secrets` };
const coingeckoSimplePriceApi = `${coingeckoApi}/simple/price?ids=${currency}&vs_currencies=usd`;
console.log(coingeckoSimplePriceApi);
const priceData: { [key: string]: { usd: number } } = await ky
.get(coingeckoSimplePriceApi, { timeout: 5_000, retry: 0 })
.json();
price = Math.floor(priceData[currency].usd);
} catch (err) {
return { canExec: false, message: `Coingecko call failed` };
}
console.log(`Updating price: ${price}`);
// Return execution call data
return {
canExec: true,
callData: [
{
to: oracleAddress,
data: oracle.interface.encodeFunctionData("updatePrice", [price]),
},
],
};
});