Skip to content

Commit

Permalink
fixed some bugs in the tests
Browse files Browse the repository at this point in the history
  • Loading branch information
yashgo0018 committed Dec 3, 2023
1 parent 9b4079c commit a748326
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 52 deletions.
70 changes: 38 additions & 32 deletions test/FundManager.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import {
time,
loadFixture,
} from "@nomicfoundation/hardhat-toolbox-viem/network-helpers";
import { expect } from "chai";
import hre, { viem } from "hardhat";
import { getAddress, parseGwei } from "viem";
import {
WalletClient,
PublicClient,
Expand Down Expand Up @@ -55,7 +50,11 @@ describe("Fund Manager", function () {
if (wallet.account) accounts.push(wallet.account);
}

functionsRouterAddress = await startSimulator();
functionsRouterAddress = await startSimulator({
secrets: {
pinataAPIKey: process.env.PINATA_API_KEY || "",
},
});

fundManager = await viem.deployContract("FundManager", [
functionsRouterAddress,
Expand All @@ -69,31 +68,18 @@ describe("Fund Manager", function () {
stringToHex(donId, { size: 32 }),
]);

await fundManager.write.setGasLimit([gasLimit]);
await fundManager.write.setGasLimitForPriceFetchFunction([gasLimit]);

await fundManager.write.setSubscriptionId([BigInt(subscriptionId)]);

// await fundManager.write.setEncryptedSecretUrls([stringToHex("")]);
});

it("Should make a request", async () => {
const functionSourceCode = fs.readFileSync(
"./chainlinkFunctions/fetchPastPrices.js"
);
const hash = await fundManager.write.makeRequest([
functionSourceCode.toString(),
]);

await waitForRequestHandling(publicClient, fundManager.address, hash);

console.log(await fundManager.read.result());
});

it("Should add a token in the contract", async () => {
await fundManager.write.addToken([accounts[1].address, "ethereum"]);

const tokenList = JSON.parse(
await fundManager.read.getJSONTokenSymbolList()
(await fundManager.read.getJSONTokenSymbolList([10n]))[0]
);

expect(tokenList).to.deep.eq({
Expand All @@ -110,20 +96,16 @@ describe("Fund Manager", function () {
it("Should remove a token from the contract", async () => {
await fundManager.write.removeToken([accounts[1].address]);

const tokenList = JSON.parse(
await fundManager.read.getJSONTokenSymbolList()
);

expect(tokenList).to.deep.eq({
tokens: [],
});
expect(
(await fundManager.read.getJSONTokenSymbolList([10n])).length
).to.be.eq(0);
});

it("Should be able to add a token in the contract after it was removed", async () => {
await fundManager.write.addToken([accounts[1].address, "ethereum"]);

const tokenList = JSON.parse(
await fundManager.read.getJSONTokenSymbolList()
(await fundManager.read.getJSONTokenSymbolList([10n]))[0]
);

expect(tokenList).to.deep.eq({
Expand All @@ -142,7 +124,7 @@ describe("Fund Manager", function () {
}

const tokenList = JSON.parse(
await fundManager.read.getJSONTokenSymbolList()
(await fundManager.read.getJSONTokenSymbolList([10n]))[0]
);

expect(tokenList).to.deep.eq({
Expand All @@ -162,7 +144,9 @@ describe("Fund Manager", function () {
it("Should remove one token and add another", async () => {
await fundManager.write.removeToken([accounts[1].address]);

let tokenList = JSON.parse(await fundManager.read.getJSONTokenSymbolList());
let tokenList = JSON.parse(
(await fundManager.read.getJSONTokenSymbolList([10n]))[0]
);

expect(tokenList).to.deep.eq({
tokens: [
Expand All @@ -183,7 +167,9 @@ describe("Fund Manager", function () {
supportedTokens[0].symbol,
]);

tokenList = JSON.parse(await fundManager.read.getJSONTokenSymbolList());
tokenList = JSON.parse(
(await fundManager.read.getJSONTokenSymbolList([10n]))[0]
);

expect(tokenList).to.deep.eq({
tokens: [
Expand All @@ -198,4 +184,24 @@ describe("Fund Manager", function () {
],
});
});

it("Should update the price fetch source code", async () => {
const functionSourceCode = fs.readFileSync(
"./chainlinkFunctions/fetchPastPrices.js"
);

await fundManager.write.setPriceFetchSourceCode([
functionSourceCode.toString("utf-8"),
]);

expect(await fundManager.read.priceFetchSourceCode()).to.be.eq(
functionSourceCode.toString("utf-8")
);
});

it("Should initiate proportion refresh", async () => {
const hash = await fundManager.write.initiateProportionRefresh();

await waitForRequestHandling(publicClient, fundManager.address, hash);
});
});
65 changes: 45 additions & 20 deletions test/chainlink-functions-simulators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,14 @@ type DecodedData = Record<string, any>;
const requestsPickedUp: Record<string, boolean> = {};
const requestsHandled: Record<string, boolean> = {};

export async function startSimulator() {
export async function startSimulator({
secrets,
}: {
secrets: Record<string, string>;
}) {
const functionsRouter = await viem.deployContract("MockFunctionsRouter");

// const eventFilter = functionsRouter.createEventFilter.RequestCreated();
functionsRouter.watchEvent.RequestCreated({
onLogs: async (logs) => {
for (const log of logs) {
Expand All @@ -43,15 +48,31 @@ export async function startSimulator() {
static encodeString(s) {
return [["string"], [s]]
}
static async makeHttpRequest({url, method, data, headers}) {
try {
const response = await fetch(url, {method: method || "GET", body: data ? JSON.stringify(data) : undefined, headers: headers || undefined});
return {
error: response.status >= 400,
data: await response.json()
}
} catch (err) {
return {error: true}
}
}
}
const secrets = ${JSON.stringify(secrets)};
${
decodedData["args"]
? `const args = ${JSON.stringify(decodedData["args"])}`
: ""
}
function main() {
async function main() {
${decodedData["source"]}
}
Expand All @@ -61,6 +82,8 @@ export async function startSimulator() {
try {
const [types, values] = await eval(code);

console.log(values);

const result = encodePacked(types, values);
await functionsRouter.write.fulfill([
requestId || "0x",
Expand All @@ -86,30 +109,32 @@ export async function waitForRequestHandling(
) {
const receipt = await client.getTransactionReceipt({ hash });
const topicId = keccak256(stringToBytes("RequestSent(bytes32)"));
const log = receipt.logs.filter(
const logs = receipt.logs.filter(
(log) => log.address === contractAddress && log.topics[0] === topicId
)[0];
);

if (!log) throw "functions request not sent";
for (const log of logs) {
if (!log) throw "functions request not sent";

const requestId = log.topics[1];
if (!requestId) throw "invalid event emitted";
const requestId = log.topics[1];
if (!requestId) throw "invalid event emitted";

let pickedUp = false;
let pickedUp = false;

await new Promise((resolve, reject) => {
const interval = setInterval(() => {
if (!pickedUp && requestsPickedUp[requestId]) {
pickedUp = true;
console.log(`Request id ${requestId} is picked up by the node`);
}
await new Promise((resolve, reject) => {
const interval = setInterval(() => {
if (!pickedUp && requestsPickedUp[requestId]) {
pickedUp = true;
console.log(`Request id ${requestId} is picked up by the node`);
}

if (requestsHandled[requestId]) {
clearInterval(interval);
resolve(null);
}
}, 50);
});
if (requestsHandled[requestId]) {
clearInterval(interval);
resolve(null);
}
}, 50);
});
}

return;
}

0 comments on commit a748326

Please sign in to comment.