From a7483266f4e483aad87c6be5917b26bf1e0adf4c Mon Sep 17 00:00:00 2001 From: Yash Goyal Date: Sun, 3 Dec 2023 16:24:19 +0530 Subject: [PATCH] fixed some bugs in the tests --- test/FundManager.ts | 70 ++++++++++++++------------ test/chainlink-functions-simulators.ts | 65 ++++++++++++++++-------- 2 files changed, 83 insertions(+), 52 deletions(-) diff --git a/test/FundManager.ts b/test/FundManager.ts index 625d0b5..a3e0865 100644 --- a/test/FundManager.ts +++ b/test/FundManager.ts @@ -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, @@ -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, @@ -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({ @@ -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({ @@ -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({ @@ -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: [ @@ -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: [ @@ -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); + }); }); diff --git a/test/chainlink-functions-simulators.ts b/test/chainlink-functions-simulators.ts index 2b2eea7..24bbfc2 100644 --- a/test/chainlink-functions-simulators.ts +++ b/test/chainlink-functions-simulators.ts @@ -15,9 +15,14 @@ type DecodedData = Record; const requestsPickedUp: Record = {}; const requestsHandled: Record = {}; -export async function startSimulator() { +export async function startSimulator({ + secrets, +}: { + secrets: Record; +}) { const functionsRouter = await viem.deployContract("MockFunctionsRouter"); + // const eventFilter = functionsRouter.createEventFilter.RequestCreated(); functionsRouter.watchEvent.RequestCreated({ onLogs: async (logs) => { for (const log of logs) { @@ -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"]} } @@ -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", @@ -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; }