timeout exceeded for raffle unit tests #5510
-
const { assert, expect } = require("chai")
const { network, getNamedAccounts, deployments, ethers } = require("hardhat")
const { developmentChains, networkConfig } = require("../../helper-hardhat-config")
!developmentChains.includes(network.name)
? describe.skip
: describe("raffle unit test", function () {
let raffle, vrfCoordinatorV2Mock, raffleEntranceFee, deployer, interval
const chainId = network.config.chainId
beforeEach(async function () {
deployer = (await getNamedAccounts()).deployer
await deployments.fixture(["all"])
raffle = await ethers.getContract("Raffle", deployer)
vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock", deployer)
raffleEntranceFee = await raffle.GetEntranceFee()
interval = await raffle.getInterval()
})
describe("constructor", function () {
it("initializes the raffle correctly ", async function () {
const raffleState = await raffle.getRaffleState()
assert.equal(raffleState.toString(), "0")
assert.equal(interval.toString(), networkConfig[chainId]["interval"])
})
})
describe("enterRaffle", function () {
it("reverts when you dont pay enough", async function () {
await expect(raffle.enterRaffle()).to.be.revertedWith(
"Raffle__SendMoreToEnterRaffle"
)
})
it("records player when they enter", async function () {
await raffle.enterRaffle({ value: raffleEntranceFee })
const playerFromContract = await raffle.getPlayer(0)
assert.equal(playerFromContract, deployer)
})
it("emits an event", async function () {
await expect(raffle.enterRaffle({ value: raffleEntranceFee })).to.emit(
raffle,
"RaffleEnter"
)
})
it("doesnt allows entrance when raffle is calculating", async function () {
await raffle.enterRaffle({ value: raffleEntranceFee })
await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
await network.provider.send("evm_mine", [])
await raffle.performUpkeep([])
await expect(raffle.enterRaffle({ value: raffleEntranceFee })).to.be.revertedWith(
"Raffle__NotOpen"
)
})
})
describe("checkUpkeep", function () {
it("returns false if people haven't sent any ETH", async () => {
await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
await network.provider.request({ method: "evm_mine", params: [] })
const { upKeepNeeded } = await raffle.callStatic.checkUpkeep("0x") // upkeepNeeded = (timePassed && isOpen && hasBalance && hasPlayers)
assert(!upKeepNeeded)
})
it("returns false if raffle isn't open", async () => {
await raffle.enterRaffle({ value: raffleEntranceFee })
await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
await network.provider.request({ method: "evm_mine", params: [] })
await raffle.performUpkeep([]) // changes the state to calculating
const raffleState = await raffle.getRaffleState() // stores the new state
const { upKeepNeeded } = await raffle.callStatic.checkUpkeep("0x") // upkeepNeeded = (timePassed && isOpen && hasBalance && hasPlayers)
assert.equal(raffleState.toString() == "1", upKeepNeeded == false)
})
it("returns false if enough time hasn't passed", async () => {
await raffle.enterRaffle({ value: raffleEntranceFee })
await network.provider.send("evm_increaseTime", [interval.toNumber() - 5]) // use a higher number here if this test fails
await network.provider.request({ method: "evm_mine", params: [] })
const { upKeepNeeded } = await raffle.callStatic.checkUpkeep("0x") // upkeepNeeded = (timePassed && isOpen && hasBalance && hasPlayers)
assert(!upKeepNeeded)
})
it("returns true if enough time has passed, has players, eth, and is open", async () => {
await raffle.enterRaffle({ value: raffleEntranceFee })
await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
await network.provider.request({ method: "evm_mine", params: [] })
const { upKeepNeeded } = await raffle.callStatic.checkUpkeep("0x") // upkeepNeeded = (timePassed && isOpen && hasBalance && hasPlayers)
assert(upKeepNeeded)
})
})
describe("performUpkeep", function () {
it("it can only run if checkupkeep is true", async function () {
await raffle.enterRaffle({ value: raffleEntranceFee })
await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
await network.provider.request({ method: "evm_mine", params: [] })
const tx = await raffle.performUpkeep("0x")
assert(tx)
})
it("reverts if checkup is false", async () => {
await expect(raffle.performUpkeep("0x")).to.be.revertedWith(
"Raffle__UpKeepNotNeeded"
)
})
it("updates the raffle state and emits a requestId", async () => {
// Too many asserts in this test!
await raffle.enterRaffle({ value: raffleEntranceFee })
await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
await network.provider.request({ method: "evm_mine", params: [] })
const txResponse = await raffle.performUpkeep("0x") // emits requestId
const txReceipt = await txResponse.wait(1) // waits 1 block
const raffleState = await raffle.getRaffleState() // updates state
const requestId = txReceipt.events[1].args.requestId
assert(requestId.toNumber() > 0)
assert(raffleState == 1) // 0 = open, 1 = calculating
})
})
describe("fulfillRandomWords", function () {
beforeEach(async () => {
await raffle.enterRaffle({ value: raffleEntranceFee })
await network.provider.send("evm_increaseTime", [interval.toNumber() + 1])
await network.provider.request({ method: "evm_mine", params: [] })
})
it("can only be called after performupkeep", async () => {
await expect(
vrfCoordinatorV2Mock.fulfillRandomWords(0, raffle.address) // reverts if not fulfilled
).to.be.revertedWith("nonexistent request")
await expect(
vrfCoordinatorV2Mock.fulfillRandomWords(1, raffle.address) // reverts if not fulfilled
).to.be.revertedWith("nonexistent request")
})
it("picks a winner,resets the lottery and sends money", async function () {
const additionalEntrants = 3
const startingAccountIndex = 1
const accounts = await ethers.getSigners()
for (i = startingAccountIndex; i < startingAccountIndex + additionalEntrants; i++) {
const accountConnectedRaffle = raffle.connect(accounts[i])
await accountConnectedRaffle.enterRaffle({ value: raffleEntranceFee })
}
const startingTimeStamp = await raffle.getLastTimeStamp()
await new Promise(async (resolve, reject) => {
raffle.once("WinnerPicked", async () => {
console.log("found the event")
try {
const recentWinner = await raffle.getRecentWinner()
const raffleState = await raffle.getRaffleState()
const endingTimeStamp = await raffle.getLatestTimeStamp()
const numPlayers = await raffle.getNumberOfPlayers()
console.log(recentWinner)
console.log(accounts[2].address)
console.log(accounts[0].address)
console.log(accounts[1].address)
assert.equal(numPlayers.toString(), "0")
assert.equal(raffleState.toString(), "0")
assert(endingTimeStamp > startingTimeStamp)
resolve()
} catch (e) {
reject(e)
}
})
const txResponse = await raffle.performUpkeep("0x") // emits requestId
const txReceipt = await txResponse.wait(1)
await vrfCoordinatorV2Mock.fulfillRandomWords(txReceipt.events[1].args.requestId)
})
})
})
})// SPDX-License-Identifier: MIT
pragma solidity >=0.8.18;
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AutomationCompatibleInterface.sol";
error Raffle__SendMoreToEnterRaffle();
error Raffle__TransferFailed();
error Raffle__NotOpen();
error Raffle__UpKeepNotNeeded(uint256 currentBalance, uint256 numPlayers, uint256 raffleState);
contract Raffle is VRFConsumerBaseV2, AutomationCompatibleInterface {
enum RaffleState {
OPEN,
CALCULATING
}
uint256 private immutable i_entranceFee;
address payable[] private s_players;
VRFCoordinatorV2Interface private immutable i_vrfCoordinator;
bytes32 private immutable i_gasLane;
uint64 private immutable i_subscriptionId;
uint32 private immutable i_callbackGasLimit;
uint16 private constant REQUEST_CONFIRMATIONS = 3;
uint32 private constant NUM_WORDS = 1;
address private s_recentWinner;
RaffleState private s_raffleState;
uint256 private s_lastTimeStamp;
uint256 private immutable i_interval;
event RaffleEnter(address indexed player);
event RequestedRaffleWinner(uint256 indexed requestId);
event WinnerPicked(address indexed winner);
constructor(
address vrfCoordinatorV2,
uint256 entranceFee,
bytes32 gasLane,
//uint256 interval,
uint64 subscriptionId,
uint32 callbackGasLimit,
uint256 interval
) VRFConsumerBaseV2(vrfCoordinatorV2) {
i_entranceFee = entranceFee;
i_vrfCoordinator = VRFCoordinatorV2Interface(vrfCoordinatorV2);
i_gasLane = gasLane;
i_subscriptionId = subscriptionId;
i_callbackGasLimit = callbackGasLimit;
s_raffleState = RaffleState.OPEN;
s_lastTimeStamp = block.timestamp;
i_interval = interval;
}
function enterRaffle() public payable {
if (msg.value < i_entranceFee) {
revert Raffle__SendMoreToEnterRaffle();
}
if (s_raffleState != RaffleState.OPEN) {
revert Raffle__NotOpen();
}
s_players.push(payable(msg.sender));
emit RaffleEnter(msg.sender);
}
function checkUpkeep(
bytes memory /*checkData*/
) public override returns (bool upKeepNeeded, bytes memory /*performData */) {
bool isOpen = (RaffleState.OPEN == s_raffleState);
bool timePassed = ((block.timestamp - s_lastTimeStamp) > i_interval);
bool hasPlayers = (s_players.length > 0);
bool hasBalance = address(this).balance > 0;
upKeepNeeded = (isOpen && timePassed && hasBalance && hasPlayers);
}
function performUpkeep(bytes calldata /*performData */) external override {
(bool upKeepNeeded, ) = checkUpkeep("");
if (!upKeepNeeded) {
revert Raffle__UpKeepNotNeeded(
address(this).balance,
s_players.length,
uint256(s_raffleState)
);
}
s_raffleState = RaffleState.CALCULATING;
uint256 requestId = i_vrfCoordinator.requestRandomWords(
i_gasLane,
i_subscriptionId,
REQUEST_CONFIRMATIONS,
i_callbackGasLimit,
NUM_WORDS
);
emit RequestedRaffleWinner(requestId);
}
function fulfillRandomWords(
uint256 /*requestId*/, //bcoz function needs this paramter but we dont use it
uint256[] memory randomWords
) internal override {
uint256 indexOfWinner = randomWords[0] % s_players.length;
address payable recentWinner = s_players[indexOfWinner];
s_recentWinner = recentWinner;
s_raffleState = RaffleState.OPEN;
s_players = new address payable[](0);
s_lastTimeStamp = block.timestamp;
(bool success, ) = recentWinner.call{value: address(this).balance}("");
if (!success) {
revert Raffle__TransferFailed();
}
emit WinnerPicked(recentWinner);
}
function GetEntranceFee() public view returns (uint256) {
return i_entranceFee;
}
function GetRecentwinner() public view returns (address) {
return s_recentWinner;
}
function getRaffleState() public view returns (RaffleState) {
return s_raffleState;
}
function getNumWords() public pure returns (uint256) {
return NUM_WORDS;
}
function getRequestConfirmations() public pure returns (uint256) {
return REQUEST_CONFIRMATIONS;
}
function getPlayer(uint256 index) public view returns (address) {
return s_players[index];
}
function getLastTimeStamp() public view returns (uint256) {
return s_lastTimeStamp;
}
function getInterval() public view returns (uint256) {
return i_interval;
}
}i have also tried by extending time limit to 500s |
Beta Was this translation helpful? Give feedback.
Answered by
HarshDev56
May 19, 2023
Replies: 1 comment 1 reply
-
|
@Sanyam2103 in your unit tests file you forgot to add await vrfCoordinatorV2Mock.fulfillRandomWords(txReceipt.events[1].args.requestId)you need to change that to this await vrfCoordinatorV2Mock.fulfillRandomWords(
txRecipt.events[1].args.requestId,
raffle.address
) |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
Sanyam2103
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

@Sanyam2103 in your unit tests file you forgot to add
raffle.addressin the last linechange this line
you need to change that to this