Cannot Enter Raffle and run getEntranceFee Function #5579
-
I am currently at 17:50:00 trying to follow along with the video and Connect the EnterRaffle Function with the frontend , a Please let me know if there is some mistake in the code I have provided helper-hardhat-config for the values import {abi , contractAddress} from "../constants";
import {useMoralis , isWeb3Enabled, useWeb3Contract} from "react-moralis"
import { useEffect , useState} from "react";
import {ethers} from "ethers";
export default function LotteryEntrance(){
const {chainId : chainIdHex} = useMoralis; // this line will remove chainID object from useMoralis and rename it to chainId hex (chainId in useMoralis is in Hexform)
const chainId = parseInt(chainIdHex) // it will create a new variable chainId and its value will be integer form of chainIdHex
const [entranceFee, setEntranceFee] = useState("0")
const raffleAddresses = chainId ? contractAddress[chainId][0] : null
const {runContractFunction : enterRaffle } = useWeb3Contract({
abi: abi,
contractAddress: raffleAddresses,
functionName: "enterRaffle" ,
params: {},
msgValue: entranceFee,
})
const {runContractFunction : getEntranceFee } = useWeb3Contract({
abi: abi,
contractAddress: raffleAddresses,
functionName: "getEntranceFee" ,
params: {},
})
async function updateUIValues() {
// Another way we could make a contract call:
// const options = { abi, contractAddress: raffleAddress }
// const fee = await Moralis.executeFunction({
// functionName: "getEntranceFee",
// ...options,
// })
const entranceFeeFromCall = (await getEntranceFee()).toString()
// const numPlayersFromCall = (await getPlayersNumber()).toString()
// const recentWinnerFromCall = await getRecentWinner()
setEntranceFee(entranceFeeFromCall)
// setNumberOfPlayers(numPlayersFromCall)
// setRecentWinner(recentWinnerFromCall)
}
useEffect(() => {
if (isWeb3Enabled) {
updateUIValues()
}
}, [isWeb3Enabled])
let displayentrancefeee = ethers.utils.formatUnits(entranceFee, "ether")
return (
<div>
{raffleAddresses ? (
<div>
<button className="enterraffle_button" onClick={async function(){
await enterRaffle()
}}> Enter Raffle </button>
Hi from Lottery Entrance Fee :{displayentrancefeee} {entranceFee} ETH
</div>
) : (
<div> no raffle address doesn't exists</div>
)}
</div> )
} Helper-hardhat-config.jsconst { ethers } = require("hardhat")
const networkConfig = {
default: {
name: "hardhat",
keepersUpdateInterval: "30",
},
31337: {
name: "localhost",
subscriptionId: "588",
gasLane: "0x474e34a077df58807dbe9c96d3c009b23b3c6d0cce433e59bbf5b34f823bc56c", // 30 gwei
keepersUpdateInterval: "30",
raffleEntranceFee: ethers.utils.parseEther("0.01"), // 0.01 ETH
callbackGasLimit: "500000", // 500,000 gas
},
11155111: {
name: "sepolia",
subscriptionId: "6926",
gasLane: "0x474e34a077df58807dbe9c96d3c009b23b3c6d0cce433e59bbf5b34f823bc56c", // 30 gwei
keepersUpdateInterval: "30",
raffleEntranceFee: ethers.utils.parseEther("0.01"), // 0.01 ETH
callbackGasLimit: "500000", // 500,000 gas
vrfCoordinatorV2: "0x8103B0A8A00be2DDC778e6e7eaa21791Cd364625",
},
1: {
name: "mainnet",
keepersUpdateInterval: "30",
},
}
const developmentChains = ["hardhat", "localhost"]
const VERIFICATION_BLOCK_CONFIRMATIONS = 6
const frontEndContractsFile = "../nextjs-smartcontract-lottery-fcc/constants/contractAddresses.json"
const frontEndAbiFile = "../nextjs-smartcontract-lottery-fcc/constants/abi.json"
module.exports = {
networkConfig,
developmentChains,
VERIFICATION_BLOCK_CONFIRMATIONS,
frontEndContractsFile,
frontEndAbiFile,
} Raffle.sol // SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AutomationCompatibleInterface.sol";
import "hardhat/console.sol";
/* Errors */
error Raffle__UpkeepNotNeeded(uint256 currentBalance, uint256 numPlayers, uint256 raffleState);
error Raffle__TransferFailed();
error Raffle__SendMoreToEnterRaffle();
error Raffle__RaffleNotOpen();
/**@title A sample Raffle Contract
* @author Patrick Collins
* @notice This contract is for creating a sample raffle contract
* @dev This implements the Chainlink VRF Version 2
*/
contract Raffle is VRFConsumerBaseV2, AutomationCompatibleInterface {
/* Type declarations */
enum RaffleState {
OPEN,
CALCULATING
}
/* State variables */
// Chainlink VRF Variables
VRFCoordinatorV2Interface private immutable i_vrfCoordinator;
uint64 private immutable i_subscriptionId;
bytes32 private immutable i_gasLane;
uint32 private immutable i_callbackGasLimit;
uint16 private constant REQUEST_CONFIRMATIONS = 3;
uint32 private constant NUM_WORDS = 1;
// Lottery Variables
uint256 private immutable i_interval;
uint256 private immutable i_entranceFee = 0.1;
uint256 private s_lastTimeStamp;
address private s_recentWinner;
address payable[] private s_players;
RaffleState private s_raffleState;
/* Events */
event RequestedRaffleWinner(uint256 indexed requestId);
event RaffleEnter(address indexed player);
event WinnerPicked(address indexed player);
/* Functions */
constructor(
address vrfCoordinatorV2,
uint64 subscriptionId,
bytes32 gasLane, // keyHash
uint256 interval,
uint256 entranceFee,
uint32 callbackGasLimit
) VRFConsumerBaseV2(vrfCoordinatorV2) {
i_vrfCoordinator = VRFCoordinatorV2Interface(vrfCoordinatorV2);
i_gasLane = gasLane;
i_interval = interval;
i_subscriptionId = subscriptionId;
i_entranceFee = entranceFee;
s_raffleState = RaffleState.OPEN;
s_lastTimeStamp = block.timestamp;
i_callbackGasLimit = callbackGasLimit;
}
function enterRaffle() public payable {
// require(msg.value >= i_entranceFee, "Not enough value sent");
// require(s_raffleState == RaffleState.OPEN, "Raffle is not open");
if (msg.value < i_entranceFee) {
revert Raffle__SendMoreToEnterRaffle();
}
if (s_raffleState != RaffleState.OPEN) {
revert Raffle__RaffleNotOpen();
}
s_players.push(payable(msg.sender));
// Emit an event when we update a dynamic array or mapping
// Named events with the function name reversed
emit RaffleEnter(msg.sender);
}
/**
* @dev This is the function that the Chainlink Keeper nodes call
* they look for `upkeepNeeded` to return True.
* the following should be true for this to return true:
* 1. The time interval has passed between raffle runs.
* 2. The lottery is open.
* 3. The contract has ETH.
* 4. Implicity, your subscription is funded with LINK.
*/
function checkUpkeep(
bytes memory /* checkData */
)
public
view
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 = (timePassed && isOpen && hasBalance && hasPlayers);
return (upkeepNeeded, "0x0"); // can we comment this out?
}
/**
* @dev Once `checkUpkeep` is returning `true`, this function is called
* and it kicks off a Chainlink VRF call to get a random winner.
*/
function performUpkeep(
bytes calldata /* performData */
) external override {
(bool upkeepNeeded, ) = checkUpkeep("");
// require(upkeepNeeded, "Upkeep not needed");
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
);
// Quiz... is this redundant?
emit RequestedRaffleWinner(requestId);
}
/**
* @dev This is the function that Chainlink VRF node
* calls to send the money to the random winner.
*/
function fulfillRandomWords(
uint256, /* requestId */
uint256[] memory randomWords
) internal override {
// s_players size 10
// randomNumber 202
// 202 % 10 ? what's doesn't divide evenly into 202?
// 20 * 10 = 200
// 2
// 202 % 10 = 2
uint256 indexOfWinner = randomWords[0] % s_players.length;
address payable recentWinner = s_players[indexOfWinner];
s_recentWinner = recentWinner;
s_players = new address payable[](0);
s_raffleState = RaffleState.OPEN;
s_lastTimeStamp = block.timestamp;
(bool success, ) = recentWinner.call{value: address(this).balance}("");
// require(success, "Transfer failed");
if (!success) {
revert Raffle__TransferFailed();
}
emit WinnerPicked(recentWinner);
}
/** Getter Functions */
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 getRecentWinner() public view returns (address) {
return s_recentWinner;
}
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;
}
function getEntranceFee() public view returns (uint256) {
return i_entranceFee;
}
function getNumberOfPlayers() public view returns (uint256) {
return s_players.length;
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
Hello @Bhavik-punmiya It is probably problem with your constants or json mapping. Show us your repository, so we can help you. You can also import correct contract address like below: Take deployed contract from deployments folder from your backend. This file should have same name as your contract and It looks like below: You will see that it is json and it contains all necessary data you need. To import abi and address just do following in your js script: import contract from "../contracts/DigitalRightsMaykr.json"
const contractAddress = contract.address
const abi = contract.abi It is much more efficient than showed in course imo |
Beta Was this translation helpful? Give feedback.
@Bhavik-punmiya
Please deploy it on sepolia swap abi and address and try running your front on it.