Adding a return function to Truffles Pet Shop - solidity

I am following the Truffle tutorials, and am on https://www.trufflesuite.com/tutorials/pet-shop. I would like to add a return function that sets the adopters[PetId] in the solidity contract back to the 0 address. I currently have:
function returnPet(uint petId) public returns (uint) {
require(petId >= 0 && petId <= 15);
adopters[petId] = msg.sender;
return petId;
}
in my Adoption.sol
and in my app.js is:
handleReturn: function(event) {
event.preventDefault();
var petId = parseInt($(event.target).data('id'));
var adoptionInstance;
web3.eth.getAccounts(function(error, accounts) {
if (error) {
console.log(error);
}
var account = accounts[0];
App.contracts.Adoption.deployed().then(function(instance) {
adoptionInstance = instance;
return adoptionInstance.returnPet(petId);
}).then(function(result) {
return App.markAdopted();
}).catch(function(err) {
console.log(err.message);
});
});
but it hits the catch and returns: invalid address.
In short:
How do I zero out an address in an array of addresses?emphasized text

Your current code in returnPet() sets the adopters[petId] value to msg.sender, which means "the caller address".
I would like to add a return function that sets the adopters[PetId] in the solidity contract back to the 0 address
You can do it by setting the value to address(0).
So your function will then look like
function returnPet(uint petId) public returns (uint) {
require(petId >= 0 && petId <= 15);
adopters[petId] = address(0);
return petId;
}

Related

VM Exception while processing transaction: reverted with reason string 'message'

I don't understand what's wrong, why I am getting this error on function testing.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "#openzeppelin/contracts/utils/Address.sol";
contract Voting {
address public owner;
uint public counter;
uint public minCandidates = 2;
uint public maxCandidates;
uint public immutable Comission;
struct Candidate {
uint balance;
bool isExistOnThisVoting;
}
struct _Voting {
bool started;
address Winner;
uint StartDate;
uint WinnerBalance;
uint Bank;
uint Period;
mapping(address => Candidate) Candidates;
}
mapping(uint => _Voting) private Votings;
modifier onlyOwner() {
require(msg.sender == owner, "Sorry, but you are not an owner!");
_;
}
constructor(uint _maxCandidates, uint _comission) {
owner = msg.sender;
Comission = _comission;
maxCandidates = _maxCandidates;
}
function addVoting(address[] calldata _candidates, uint _period) public onlyOwner {
require(minCandidates <= _candidates.length && _candidates.length < maxCandidates,
"The number of candidates must comply with the voting rules!"
);
Votings[counter].Period = _period;
for( uint i = 0; i < _candidates.length; i++) {
addCandidate(counter, _candidates[i]);
}
emit votingDraftCreated(counter);
counter++;
}
function editVotingPeriod(uint _id, uint _newPeriod) public onlyOwner {
require(Votings[_id].started = false, "The voting has already begun!");
Votings[_id].Period = _newPeriod;
}
function addCandidate(uint _id, address _candidate) public onlyOwner {
require(address(_candidate) != address(0), "This candidate with zero address!");
require(Address.isContract(_candidate) == false, "A contract can't be a candidate!");
require(Votings[_id].started, "The voting has already begun!");
Votings[_id].Candidates[_candidate].isExistOnThisVoting = true;
emit candidateInfo(_id, _candidate, true);
}
function deleteCandidate(address _candidate, uint _id) public onlyOwner {
require(Votings[_id].started, "The voting has already begun!");
Votings[_id].Candidates[_candidate].isExistOnThisVoting = false;
emit candidateInfo(_id, _candidate, false);
}
function startVoting(uint _id) public onlyOwner {
Votings[_id].started = true;
Votings[_id].StartDate = block.timestamp;
emit votingStarted(_id, block.timestamp);
}
function takePartInVoting(uint _id, address _candidate) public payable {
require(Address.isContract(msg.sender) == false, "A contract can't vote!");
require(Votings[_id].started, "The voting doesn't start!");
require(Votings[_id].StartDate + Votings[_id].Period > block.timestamp, "The voting has ended!");
require(checkCandidate(_id, _candidate), "This candidates does not exist in this voting!");
Votings[_id].Candidates[_candidate].balance += msg.value;
Votings[_id].Bank += msg.value;
if (Votings[_id].Candidates[_candidate].balance > Votings[_id].WinnerBalance) {
Votings[_id].WinnerBalance = Votings[_id].Candidates[_candidate].balance;
Votings[_id].Winner = _candidate;
}
}
function withDrawPrize(uint _id) public {
require(Votings[_id].started, "The voting doesn't start!");
require(Votings[_id].StartDate + Votings[_id].Period < block.timestamp, "The voting is not ended yet!");
require(msg.sender == Votings[_id].Winner, "You are not a winner!");
require(Votings[_id].Bank > 0, "You have already receive your prize!");
uint amount = Votings[_id].Bank;
uint ownerComission = (Comission * amount) / 100;
uint clearAmount = amount - ownerComission;
Votings[_id].Bank = 0;
payable(owner).transfer(ownerComission);
payable(msg.sender).transfer(clearAmount);
}
function checkCandidate(uint _id, address _candidate) public view returns(bool) {
return(Votings[_id].Candidates[_candidate].isExistOnThisVoting);
}
function getVotingInfo(uint256 _id) public view returns (
bool,
uint256,
uint256,
uint256,
uint256,
address
) {
return(
Votings[_id].started,
Votings[_id].StartDate,
Votings[_id].WinnerBalance,
Votings[_id].Bank,
Votings[_id].Period,
Votings[_id].Winner);
}
function setMaxCandidates(uint _maxCandidates) public onlyOwner {
require(minCandidates <= _maxCandidates, "Minimum number of candidates is 2");
maxCandidates = _maxCandidates;
}
event candidateInfo(uint indexed id, address indexed candidate, bool existOnThisVoting);
event votingDraftCreated(uint indexed id);
event votingStarted(uint indexed id, uint startDate);
}
Here is the contract and the test for it:
const { time, loadFixture } = require("#nomicfoundation/hardhat-network-helpers");
const { ethers } = require("hardhat");
const { expect } = require("chai");
describe("Voting", function () {
async function deploy() {
const [owner, user] = await ethers.getSigners();
const Voting = await ethers.getContractFactory("Voting");
const myVoting = await Voting.deploy(5, 10);
return { myVoting, owner, user };
}
it("An owner can change voting's period", async function () {
const { myVoting, owner } = await loadFixture(deploy);
await myVoting.connect(owner).editVotingPeriod(0, 200);
const _votingInfo = await myVoting.getVotingInfo(0);
expect(_votingInfo[2]).to.equal(200);
});
it("Owner can create another voting", async function () {
const { myVoting, owner, user } = await loadFixture(deploy);
const counter_before = await myVoting.counter();
let candidates = new Array();
for (i = 1; i < 4; i++) candidates.push(owner.address);
await myVoting.connect(owner).addVoting(candidates, 100);
const is_candidate = await myVoting.checkCandidate(counter_before, user.address);
expect(is_candidate).to.equal(false);
});
And only two tests are failing with message -> Error: VM Exception while processing transaction: reverted with reason string 'The voting has already begun!'
Could somebody help me to understand why did I get this error?
I don't understand why I got this error.
I found a bug in the solidity code. You're using = instead of == in this line:
require(Votings[_id].started = false, "The voting has already begun!");
I'm not sure this alone will fix your problem, but try again!

Solidity Compilations: UnimplementedFeature

I am getting an Error in the IDE:
UnimplementedFeatureError: Copying of type struct ChatGroups.Message memory[] memory to storage not yet supported.
And I really don't know what to do with everything that I made ( It's commented in French )
There is the full code, and I really tried to find how can I implement what do I want with a different approach if someone could help for that and if I can preserv this code.
Thanks a lot for the people that are going to help !
pragma solidity ^0.6.12;
contract ChatGroups {
struct Group {
string name;
address[] members;
Message[] messages;
}
struct Message {
uint id;
string text;
address author;
bool deleted;
}
Group[] groups;
address[] users;
event GroupCreated(uint groupId, string groupName);
event MessagePublished(uint groupId, uint messageId, string messageText, address messageAuthor);
event MessageDeleted(uint groupId, uint messageId);
event UserAddedToGroup(uint groupId, address user);
event UserRemovedFromGroup(uint groupId, address user);
function createGroup(string memory groupName) public {
require(isUser(msg.sender), "Unauthorized user");
groups.push(Group({
name: groupName,
members: new address[](1),
messages: new Message[](0)
}));
groups[groups.length - 1].members[0] = msg.sender;
emit GroupCreated(groups.length, groupName);
}
function publishMessage(uint groupId, string memory messageText) public {
require(isUser(msg.sender), "Unauthorized user");
Group storage group = groups[groupId - 1];
require(isMember(group, msg.sender), "Unauthorized user");
group.messages.push(Message({
id: group.messages.length + 1,
text: messageText,
author: msg.sender,
deleted: false
}));
emit MessagePublished(groupId, group.messages[group.messages.length - 1].id, messageText, msg.sender);
}
function deleteMessage(uint groupId, uint messageId) public {
require(isUser(msg.sender), "Unauthorized user");
Group storage group = groups[groupId - 1];
require(isMember(group, msg.sender) && group.messages[messageId - 1].author == msg.sender, "Unauthorized user");
group.messages[messageId - 1].deleted = true;
emit MessageDeleted(groupId, messageId);
}
function removeUser(uint groupId, address user) public {
require(isUser(msg.sender), "Unauthorized user");
Group storage group = groups[groupId - 1];
require(isAdmin(group, msg.sender), "Unauthorized user");
require(isMember(group, user), "Unauthorized user");
uint index = getMemberIndex(group, user);
group.members[index] = group.members[group.members.length - 1];
group.members.length--;
emit UserRemovedFromGroup(groupId, user);
}
function addUser(uint groupId, address user) public {
require(isUser(msg.sender), "Unauthorized user");
Group storage group = groups[groupId - 1];
require(isAdmin(group, msg.sender), "Unauthorized user");
require(!isMember(group, user), "User already member of group");
group.members.push(user);
emit UserAddedToGroup(groupId, user);
}
function isUser(address user) private view returns (bool) {
for (uint i = 0; i < users.length; i++) {
if (users[i] == user) {
return true;
}
}
return false;
}
function isMember(Group memory group, address user) public view returns (bool) {
if (group.members[0] == user) {
return true;
}
for (uint i = 1; i < group.members.length; i++) {
if (group.members[i] == user) {
return true;
}
}
return false;
}
function isAdmin(Group memory group, address user) public view returns (bool) {
if (group.members[0] == user) {
return true;
}
for (uint i = 1; i < group.members.length; i++) {
if (group.members[i] == user) {
return true;
}
}
return false;
}
function getMemberIndex(Group storage group, address user) private view returns (uint) {
for (uint i = 0; i < group.members.length; i++) {
if (group.members[i] == user) {
return i;
}
}
return group.members.length;
}
}
While compiling it, I'm getting this error, and I really have no solutions in my mind...
In your smart contract, there are some issues related to your logic in different operation. Thought, the main issue that you shared in this thread refers to a struct inside another struct (in this case, I say about Message[] struct).
The error say that you cannot pass a struct array initializing at runtime because this object is memorized inside storage space.
In details, you have to change the implementation for valorized attribute related to group struct (method: createGroup(string memory groupName)). The change to make is:
Group storage group = groups.push();
group.name = groupName;
group.members = new address[](1);
group.members[0] = msg.sender;
In this way, you create before a space into storage memory array, and then you fill it with the variable (if them has been valorized). At this point, you have to change the method called publishMessage() changing this line:
Group storage group = groups[groupId - 1];
with:
Group storage group = groups[groupId];
This same improvement you have to do in: deleteMessage() and addUser().
In following lines, I put your smart contract with my changes:
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
contract ChatGroups {
struct Group {
string name;
address[] members;
Message[] messages;
}
struct Message {
uint id;
string text;
address author;
bool deleted;
}
Group[] groups;
address[] users;
event GroupCreated(uint groupId, string groupName);
event MessagePublished(uint groupId, uint messageId, string messageText, address messageAuthor);
event MessageDeleted(uint groupId, uint messageId);
event UserAddedToGroup(uint groupId, address user);
event UserRemovedFromGroup(uint groupId, address user);
function createGroup(string memory groupName) public {
require(isUser(msg.sender), "Unauthorized user");
// NOTE: I changed at this point your original implementation
Group storage group = groups.push();
group.name = groupName;
group.members = new address[](1);
group.members[0] = msg.sender;
emit GroupCreated(groups.length, groupName);
}
function publishMessage(uint groupId, string memory messageText) public {
require(isUser(msg.sender), "Unauthorized user");
Group storage group = groups[groupId];
require(isMember(group, msg.sender), "Unauthorized user");
group.messages.push(Message({
id: group.messages.length + 1,
text: messageText,
author: msg.sender,
deleted: false
}));
emit MessagePublished(groupId, group.messages[group.messages.length - 1].id, messageText, msg.sender);
}
function deleteMessage(uint groupId, uint messageId) public {
require(isUser(msg.sender), "Unauthorized user");
Group storage group = groups[groupId];
require(isMember(group, msg.sender) && group.messages[messageId - 1].author == msg.sender, "Unauthorized user");
group.messages[messageId - 1].deleted = true;
emit MessageDeleted(groupId, messageId);
}
function removeUser(uint groupId, address user) public {
require(isUser(msg.sender), "Unauthorized user");
Group storage group = groups[groupId - 1];
require(isAdmin(group, msg.sender), "Unauthorized user");
require(isMember(group, user), "Unauthorized user");
uint index = getMemberIndex(group, user);
group.members[index] = group.members[group.members.length - 1];
// NOTE: The attribute length() is only read-only, you cannot modify or handle the length of array using in this way!
group.members.length;
emit UserRemovedFromGroup(groupId, user);
}
function addUser(uint groupId, address user) public {
require(isUser(msg.sender), "Unauthorized user");
Group storage group = groups[groupId];
require(isAdmin(group, msg.sender), "Unauthorized user");
require(!isMember(group, user), "User already member of group");
group.members.push(user);
emit UserAddedToGroup(groupId, user);
}
function isUser(address user) private view returns (bool) {
for (uint i = 0; i < users.length; i++) {
if (users[i] == user) {
return true;
}
}
return false;
}
function isMember(Group memory group, address user) public view returns (bool) {
if (group.members[0] == user) {
return true;
}
for (uint i = 1; i < group.members.length; i++) {
if (group.members[i] == user) {
return true;
}
}
return false;
}
function isAdmin(Group memory group, address user) public view returns (bool) {
if (group.members[0] == user) {
return true;
}
for (uint i = 1; i < group.members.length; i++) {
if (group.members[i] == user) {
return true;
}
}
return false;
}
function getMemberIndex(Group storage group, address user) private view returns (uint) {
for (uint i = 0; i < group.members.length; i++) {
if (group.members[i] == user) {
return i;
}
}
return group.members.length;
}
}
P.S.: I think that you have to integrate users before call the various method inside users array. Although, the smart contract logic give you this error: "Unauthorized user". I think you should think better about this aspect

Error: value out-of-bounds on callbackGasLimit variable

i have written a simple contract in solidity as seen below
/**
* #title Lottery
* #notice Enter lottery by paying some amount
* #notice pick a random number( verifiably random)
* #notice winner be selected every xtimes
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "#chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
import "#chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "#chainlink/contracts/src/v0.8/interfaces/KeeperCompatibleInterface.sol";
// ============= Errors ====================
error Lottery__NotEnoughFunds();
error Lottery__TransferFailed();
error Lottery__NotOpen();
error Raffle__UpkeepNotNeeded(uint256 currentBalance, uint256 numPlayers, uint256 raffleState);
contract Lottery is VRFConsumerBaseV2, KeeperCompatibleInterface {
// ============= Type declaration ===========
enum LotteryState {
OPEN,
CALCULATING
}
// ======== state variables ============
uint256 private immutable i_entranceFee;
address payable[] private s_players;
bytes32 private immutable i_gasLane;
uint64 private immutable i_subscriptionId;
uint32 private immutable i_callbackGasLimit;
uint16 private constant REQUEST_CONFIRMATION = 3;
uint32 private constant NUM_WORDS = 1;
VRFCoordinatorV2Interface private immutable i_vrfCoordinator;
address private s_recentwinner;
LotteryState private s_lotteryState;
uint256 private s_lastTimeStamp;
uint256 private immutable i_interval;
// ========== Events ==================
event LotteryEnter(address indexed player);
event RandomwinnerRequest(uint256 indexed requestId);
event WinnerPicked(address indexed winner);
// ========= constructor ============
constructor(
address vrfCoordinatorV2,
uint256 entranceFee,
uint32 callbackGasLimit,
uint256 interval,
bytes32 gasLane,
uint64 subscriptionId
) VRFConsumerBaseV2(vrfCoordinatorV2) {
i_entranceFee = entranceFee;
i_vrfCoordinator = VRFCoordinatorV2Interface(vrfCoordinatorV2);
i_gasLane = gasLane;
i_subscriptionId = subscriptionId;
i_callbackGasLimit = callbackGasLimit;
s_lotteryState = LotteryState.OPEN;
i_interval = interval;
s_lastTimeStamp = block.timestamp;
}
// ========== functions ============
function enterLottery() public payable {
if (msg.value < i_entranceFee) {
revert Lottery__NotEnoughFunds();
}
if (s_lotteryState != LotteryState.OPEN ) {
revert Lottery__NotOpen();
}
s_players.push(payable(msg.sender));
emit LotteryEnter(msg.sender);
}
function checkUpkeep(
bytes memory /* checkData */
)
public
view
override
returns (
bool upkeepNeeded,
bytes memory /* performData */
)
{
bool isOpen = LotteryState.OPEN == s_lotteryState;
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?
}
function performUpkeep( bytes calldata /* performData */) external override {
( bool upKeepNeeded, ) = checkUpkeep("");
if(!upKeepNeeded){
revert Raffle__UpkeepNotNeeded(
address(this).balance,
s_players.length,
uint256(s_lotteryState)
);
}
// Request a random number
// Once we get it , do something with it
s_lotteryState = LotteryState.CALCULATING;
uint256 requestId = i_vrfCoordinator.requestRandomWords(
i_gasLane,
i_subscriptionId,
REQUEST_CONFIRMATION,
i_callbackGasLimit,
NUM_WORDS
);
emit RandomwinnerRequest(requestId);
}
function fulfillRandomWords(uint256 /*requestId*/, uint256[] memory randomWords) internal override {
// Modulo function
uint256 winnerIndex = randomWords[0] % s_players.length;
address payable recentWinner = s_players[winnerIndex];
s_recentwinner = recentWinner;
s_lotteryState = LotteryState.OPEN;
s_players = new address payable[](0);
s_lastTimeStamp = block.timestamp;
(bool success, ) = recentWinner.call{value: address(this).balance}("");
if (!success) {
revert Lottery__TransferFailed();
}
emit WinnerPicked(recentWinner);
}
// =============== View /Pure functions =============
function getEntraceFee() public view returns (uint256) {
return i_entranceFee;
}
function getPlayers(uint256 index) public view returns (address) {
return s_players[index];
}
function getRecentWinner() public view returns (address) {
return s_recentwinner;
}
function getRaffleState() public view returns (LotteryState) {
return s_lotteryState;
}
function getNumWords() public pure returns (uint256) {
return NUM_WORDS;
}
function getRequestConfirmations() public pure returns (uint256) {
return REQUEST_CONFIRMATION;
}
function getLastTimeStamp() public view returns (uint256) {
return s_lastTimeStamp;
}
function getInterval() public view returns (uint256) {
return i_interval;
}
function getNumberOfPlayers() public view returns (uint256) {
return s_players.length;
}
}
and it deploy script
const { network, ethers } = require("hardhat");
const {
developmentChains,
networkConfig,
VERIFICATION_BLOCK_CONFIRMATIONS,
} = require("../helper-hardhat-config");
const { verify } = require("../utils/verify");
const VR_FUND_AMOUNT = ethers.utils.parseEther("4");
module.exports = async function ({ getNamedAccounts, deployments }) {
const { deploy, log } = deployments;
const { deployer } = await getNamedAccounts();
const chainId = network.config.chainId;
let vrfCoordinatorV2Address, subscriptionId;
if (developmentChains.includes(network.name)) {
const vrfCoordinatorV2Mock = await ethers.getContract(
"VRFCoordinatorV2Mock"
);
vrfCoordinatorV2Address = vrfCoordinatorV2Mock.address;
const transactionResponse = await vrfCoordinatorV2Mock.createSubscription();
const transactionReceipt = await transactionResponse.wait(1);
subscriptionId = transactionReceipt.events[0].args.subId;
// fund the subscription
await vrfCoordinatorV2Mock.fundSubscription(subscriptionId, VR_FUND_AMOUNT);
} else {
vrfCoordinatorV2Address = networkConfig[chainId]["vrfCoordinatorV2"];
subscriptionId = networkConfig[chainId]["subscriptionId"];
}
const entranceFee = networkConfig[chainId]["entranceFee"];
const gasLane = networkConfig[chainId]["gasLane"];
const callbackGasLimit = networkConfig[chainId]["callbackGasLimit"];
const interval = networkConfig[chainId]["interval"];
const args = [
vrfCoordinatorV2Address,
entranceFee,
gasLane,
subscriptionId,
callbackGasLimit,
interval,
];
const lottery = await deploy("Lottery", {
from: deployer,
args: args,
log: true,
waitConfirmations: network.config.blockConfirmations || 1,
});
if (
!developmentChains.includes(network.name) &&
process.env.ETHERSCAN_API_KEY
) {
log("Verifying.....");
await verify(lottery.address, args);
}
log("-----------------------------------");
};
module.exports.tags = ["all", "lottery"];
mock deploy script
const { network } = require("hardhat")
const { developmentChains } = require("../helper-hardhat-config")
const BASE_FEE = ethers.utils.parseEther("0.25") // 0.25 is this the premium in LINK?
const GAS_PRICE_LINK = 1e9 // link per gas, is this the gas lane? // 0.000000001 LINK per gas
module.exports = async function ({ getNamedAccounts, deployments }) {
const { deploy, log } = deployments
const { deployer } = await getNamedAccounts()
const chainId = network.config.chainId
const args =[BASE_FEE, GAS_PRICE_LINK]
// If we are on a local development network, we need to deploy mocks!
if(developmentChains.includes(network.name)){
log("Local Network Detected! Deploying mocks...")
// deploy a mock vrfCoordinator
await deploy("VRFCoordinatorV2Mock",{
from:deployer,
log:true,
args:args,
})
log("Mocks Deployed!")
log("------------------------------------------")
}
}
module.exports.tags = ["all", "mocks"]
and helper configuration
const { ethers } = require("hardhat")
const networkConfig = {
5:{
name:"goerli",
vrfCoordinatorV2:"0x2Ca8E0C643bDe4C2E08ab1fA0da3401AdAD7734D",
entranceFee: ethers.utils.parseEther("0.01"),
gasLane:"0x79d3d8832d904592c0bf9818b621522c988bb8b0c05cdc3b15aea1b6e8db0c15",
subscriptionId:"0",
callbackGasLimit:"500000",
interval:"30"
},
31337:{
name:"hardhat",
entranceFee: ethers.utils.parseEther("0.01"),
gasLane:"0x79d3d8832d904592c0bf9818b621522c988bb8b0c05cdc3b15aea1b6e8db0c15",
callbackGasLimit:"500000",
interval:"30"
}
}
const developmentChains = ["hardhat", "localhost"]
module.exports = {
networkConfig,
developmentChains
}
when run yarn hardhat deploy, i encounter an error
as below
An unexpected error occurred:
Error: ERROR processing C:\Users\amoko\Desktop\blockchain\lottery\deploy\01-deploy-lottery.js:
Error: value out-of-bounds (argument="callbackGasLimit", value="0x79d3d8832d904592c0bf9818b621522c988bb8b0c05cdc3b15aea1b6e8db0c15", code=INVALID_ARGUMENT, version=abi/5.7.0)
at Logger.makeError (C:\Users\amoko\Desktop\blockchain\lottery\node_modules\#ethersproject\logger\src.ts\index.ts:269:28)
at Logger.throwError (C:\Users\amoko\Desktop\blockchain\lottery\node_modules\#ethersproject\logger\src.ts\index.ts:281:20)
at Logger.throwArgumentError (C:\Users\amoko\Desktop\blockchain\lottery\node_modules\#ethersproject\logger\src.ts\index.ts:285:21)
at NumberCoder.Coder._throwError (C:\Users\amoko\Desktop\blockchain\lottery\node_modules\#ethersproject\abi\src.ts\coders\abstract-coder.ts:68:16)
at NumberCoder.encode (C:\Users\amoko\Desktop\blockchain\lottery\node_modules\#ethersproject\abi\src.ts\coders\number.ts:35:18)
at C:\Users\amoko\Desktop\blockchain\lottery\node_modules\#ethersproject\abi\src.ts\coders\array.ts:71:19
at Array.forEach (<anonymous>)
at pack (C:\Users\amoko\Desktop\blockchain\lottery\node_modules\#ethersproject\abi\src.ts\coders\array.ts:54:12)
at TupleCoder.encode (C:\Users\amoko\Desktop\blockchain\lottery\node_modules\#ethersproject\abi\src.ts\coders\tuple.ts:54:20)
at AbiCoder.encode (C:\Users\amoko\Desktop\blockchain\lottery\node_modules\#ethersproject\abi\src.ts\abi-coder.ts:111:15)
at DeploymentsManager.executeDeployScripts (C:\Users\amoko\Desktop\blockchain\lottery\node_modules\hardhat-deploy\src\DeploymentsManager.ts:1222:19)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at runNextTicks (node:internal/process/task_queues:65:3)
at listOnTimeout (node:internal/timers:528:9)
at processTimers (node:internal/timers:502:7)
at DeploymentsManager.runDeploy (C:\Users\amoko\Desktop\blockchain\lottery\node_modules\hardhat-deploy\src\DeploymentsManager.ts:1052:5)
at SimpleTaskDefinition.action (C:\Users\amoko\Desktop\blockchain\lottery\node_modules\hardhat-deploy\src\index.ts:438:5)
at Environment._runTaskDefinition (C:\Users\amoko\Desktop\blockchain\lottery\node_modules\hardhat\src\internal\core\runtime-environment.ts:308:14)
at Environment.run (C:\Users\amoko\Desktop\blockchain\lottery\node_modules\hardhat\src\internal\core\runtime-environment.ts:156:14)
at SimpleTaskDefinition.action (C:\Users\amoko\Desktop\blockchain\lottery\node_modules\hardhat-deploy\src\index.ts:584:32)
error Command failed with exit code 1.
i need help on figuring out why is it is propagting this error and how to fix it
I have tried changing the callbackgasLimit but it still brings the error. i expect the contract to get deployed on my localhost network when i run yarn hardhat deploy
i discovered that i had used a wrong variable(raffleState) in defining the event "Raffle__UpkeepNotNeeded" so it was leading to a significant increase in gas fees which were exceeding the max gas limit set for the testnet hence the error

Whats this function returns Boolean?

I don't understand why these types of functions have to return a Boolean.
function becomeRichest() public payable returns (bool) {
if (msg.value > mostSent) {
richest = msg.sender;
mostSent = msg.value;
amount += msg.value;
players++;
return true;
} else {
amount += msg.value;
players++;
return false;
}
}
It depends on how are you going to interact with it. For example, if you are interacting with this contract by using truffle, then you could see something like this:
let richest = await contractInstance.becomeRichest({ value: 1000 })
As you can see, it returns the return value in that function.

Java.lang.String errors & not printing to error file

For this project the end result was for there to be 2 error reports sent to an error file at as well as a listing of account summary information printed out. While i can get a majority of the account information printed out such as Balance before transaction and transaction to the account or if there were insufficient funds for the transaction, that's all that will print out as it should be. I'm receiving no errors or exceptions so i'm in all honesty not too sure where the issue at hand may be. I was hoping a second pair of eyes on my code could possibly point out where my issue may be, below is my code of the Account.java, CheckingAccount.java CreditCard.java and lastly D4.java which contains the main method.
Account.java
public class Account {
protected String accountNo, institution, name;
protected double balance;
public Account (String accountNo, String name, String institution, double balance) {
this.name = name;
this.accountNo = accountNo;
this.balance = balance;
this.institution = institution;
}
public String getAccount() {
return accountNo;
}
public boolean debitAccount(double amt) {
return false;
}
public boolean creditAccount(double amt) {
return false;
}
}
CheckingAccount.java
public class CheckingAccount extends Account {
public CheckingAccount(String acctNo, String name, String inst, double balance) {
super(acctNo, name, inst, balance);
this.name = name;
this.accountNo = acctNo;
this.balance = balance;
this.institution = institution;
}
public double getBalance()
{
return balance;
}
public boolean debitAccount(double amt) {
balance += amt;
return false;
}
public boolean creditAccount(double amt) {
balance -= amt;
return false;
}
}
CreditCard.java
public class CreditCard extends Account {
private double creditLimit;
private double availableCredit;
public CreditCard(String acctNo, String name, String inst, double limit, double balance) {
super(acctNo, name, inst, 0);
this.creditLimit = creditLimit;
this.availableCredit = availableCredit;
this.balance = balance;
}
public boolean debitAccount(double amt) {
balance -= amt;
return false;
}
public double getCreditLimit(){
return creditLimit;
}
public double getBalance()
{
return balance;
}
public boolean creditAccount(double amt) {
balance += amt;
return false;
}
}
D4.java
import java.io.*;
import java.util.*;
public class D4 {
public static void main(String[] args) throws FileNotFoundException
{
Boolean valid;
String transactionFile = args[0];
String theaccount, transaction;
File transactions = new File(transactionFile);
Scanner infile = new Scanner(transactions);
File errorFile = new File(args[1]);
PrintWriter error = new PrintWriter(errorFile);
Vector<Account> account = new Vector<Account>();
while(infile.hasNext())
{
transaction = infile.nextLine();
valid = performTrans(account, transaction, error, errorFile);
}
}
private static Account findAccount(Vector<Account> a, String acctNo) {
for(int index = 0; index < a.size(); index ++)
{
if (a.elementAt(index).getAccount().equals(acctNo))
{
return a.elementAt(index);
}
}
return null;
}
private static boolean Checkingacct(Account a)
{
if(a instanceof CheckingAccount)
{
return true;
}
else
{
return false;
}
}
private static boolean Creditcrd(Account a)
{
if(a instanceof CreditCard)
{
return true;
}
else
{
return false;
}
}
private static String errorLog(Vector<Account> a, String transaction)
{
String[] trans = transaction.split(":");
String error;
if(findAccount(a, trans[1])==null)
{
error = ("Invalid account: " + transaction);
System.out.println(error);
return error;
}
else
{
Account acc = findAccount(a, trans[1]);
if( trans[0] == "debit")
{
error = ("Transaction denied: " + transaction);
System.out.println(error);
return error;
}
else
{
return null;
}
}
}
private static boolean performTrans(Vector<Account> account, String transaction, PrintWriter log, File errorFile)
{
String[] pieces = transaction.split(":");
String trans = pieces[0];
System.out.println(pieces);
if(trans.equals("create"))
{
if( pieces[1].equals("checking"))
{
CheckingAccount checking = new CheckingAccount(pieces[2], pieces[3], pieces[4], Double.parseDouble(pieces[5]));
account.add(checking);
return true;
}
else if (pieces[1].equals("credit"))
{
CreditCard creditCard = new CreditCard(pieces[2], pieces[3], pieces[4], 0, Double.parseDouble(pieces[5]));
account.add(creditCard);
return true;
}
else
{
System.out.println("not sure what to put here");
return false;
}
}
else if(trans.equals("debit"))
{
if(findAccount(account, pieces[1]) == null)
{
return false;
}
else
{
Account a = findAccount(account, pieces[1]);
double amount = Double.parseDouble(pieces[2]);
if(Checkingacct(a) == true)
{
CheckingAccount checking = (CheckingAccount) a;
System.out.println("Balance before transaction: " + checking.getBalance());
checking.creditAccount(amount);
System.out.println("Transaction to account: " + amount);
System.out.println("Balance after transaction: " + checking.getBalance() + "\n");
return true;
}
else if(Creditcrd(a) == true)
{
CreditCard creditCard = (CreditCard) a;
System.out.println("Balance before transaction: " + creditCard.getBalance());
System.out.println("Transaction to account: " + amount);
if(amount + creditCard.getBalance() > creditCard.getCreditLimit())
{
System.out.println("Insufficient funds for transaction");
return false;
}
else
{
creditCard.creditAccount(amount);
return true;
}
}
}
}
else if(trans.equals("credit"))
{
if(findAccount(account, pieces[1]) == null)
{
System.out.println("Print Error Message");
return false;
}
else
{
Account a = findAccount(account, pieces[1]);
double amount = Double.parseDouble(pieces[2]);
if(Creditcrd(a) == true)
{
CheckingAccount checking = (CheckingAccount) a;
System.out.println("Balance before transaction: " + checking.getBalance());
checking.debitAccount(amount);
System.out.println("Transaction to account: " + amount);
System.out.println("Balance after transaction: " + checking.getBalance() + "\n");
return true;
}
else if(Creditcrd(a) == true)
{
CreditCard creditCard = (CreditCard) a;
System.out.println(creditCard.getBalance());
return true;
}
}
}
else if(trans.equals("report"))
{
return true;
}
return false;
}
}
The text file im attempting to read from is called D4.txt and the information inside of it is
create:checking:10-3784665:Chase:Joe Holder:2000
create:credit:1234567898765432:First Card:Bob Badger:4000
create:checking:11-3478645:Dime:Melissa Martin:1000
report
debit:10-3784665:523.67
debit:1234567898765432:3500
credit:10-3784665:50
credit:11-3478645:30
debit:10-839723:200
debit:1234567898765432:600
report
The two errors im supposed to be able to print out and see in the errorFile.txt or whatever you choose to call it is and is where the main problem is as this information for some reason is not being processed and printed onto the outputfle.
Invalid account: debit:10839723:200
Transaction denied: debit:1234567898765432:600
The information printed to the console is supposed to look like
Account Summary:
Checking account #103784665
Bank: Chase
Name on account: Joe Holder
Balance: 1526.33
Credit Account #1234567898765432
Bank: First Card
Issued to: Bob Badger
Credit Limit: 4000
Balance: 3500.00
Available credit: 500.00
Checking account #113478645
Bank: Dime
Name on account: Melissa Martin
Balance: 1030.00
End account summary.
But this is also a part of the issue as currently when i run the code whats being printed out to the console is
run D4 d4.txt errorFile.txt
[Ljava.lang.String;#1d540a51
[Ljava.lang.String;#b31c562
[Ljava.lang.String;#3db12bab
[Ljava.lang.String;#4ff0c6b8
[Ljava.lang.String;#4d40d320
Balance before transaction: 2000.0
Transaction to account: 523.67
Balance after transaction: 1476.33
[Ljava.lang.String;#2c9cc42e
Balance before transaction: 4000.0
Transaction to account: 3500.0
Insufficient funds for transaction
[Ljava.lang.String;#2bb07c61
[Ljava.lang.String;#483b594b
[Ljava.lang.String;#31470572
[Ljava.lang.String;#20aedee
Balance before transaction: 4000.0
Transaction to account: 600.0
Insufficient funds for transaction
[Ljava.lang.String;#2ea4aa4d
I know this is a lot of information to sort through and i just want to thank anyone and everyone in advance for your help and hope its something simple that im just overlooking!