Hi @gabba
It worked, thank you!
Cemil
OK, so I tried those steps, I had to mess around a bit with some permissions, but it’s working, thank you
Hi, anyone knows how to solve the problem here:
I have already tried the solution from this link, but it does not seem to work:
https://forumtest.ivanontech.com/t/introduction-to-unit-testing/10052/42
I have node version 10.18.0, Truffle 0.5.16, Web3.js 1.2.1.
Any help would be appreciated!
Hi @gabba
here is the code, it is from the People Project lectures. I want to create person directly in truffle console, deployed the contract without problem, then I used:
let instance = await People.delpoyed()
instance
instance.createPerson(dave, 180, 55)
just realized that I put age and height in wrong positions, but that should return error, not “dave is not defined” ?
contract People is Ownable{
struct Person {
uint id;
string name;
uint age;
uint height;
bool senior;
}
event personCreated(string name, bool senior);
event personDeleted(string name, bool senior, address deletedBy);
uint public balance;
modifier costs(uint cost){
require(msg.value >= cost);
_;
}
mapping (address => Person) private people;
address[] private creators;
function createPerson(string memory name, uint age, uint height) public payable costs(1 ether){
require(age < 150, "Age needs to be below 150");
require(msg.value >= 1 ether);
balance += msg.value;
//This creates a person
Person memory newPerson;
newPerson.name = name;
newPerson.age = age;
newPerson.height = height;
if(age >= 65){
newPerson.senior = true;
}
else{
newPerson.senior = false;
}
insertPerson(newPerson);
creators.push(msg.sender);
assert(
keccak256(
abi.encodePacked(
people[msg.sender].name,
people[msg.sender].age,
people[msg.sender].height,
people[msg.sender].senior
)
)
==
keccak256(
abi.encodePacked(
newPerson.name,
newPerson.age,
newPerson.height,
newPerson.senior
)
)
);
emit personCreated(newPerson.name, newPerson.senior);
}
function insertPerson(Person memory newPerson) private {
address creator = msg.sender;
people[creator] = newPerson;
}
function getPerson() public view returns(string memory name, uint age, uint height, bool senior){
address creator = msg.sender;
return (people[creator].name, people[creator].age, people[creator].height, people[creator].senior);
}
}
Hi @Golden_Pig_Coin
Your bug is in your test file not in your contract can you share your test file ?
Hi @gabba, here is the test file:
const People = artifacts.require("People");
const truffleAssert = require("truffle-assertions");
contract ("People", async function(accounts){
let instance;
before (async function(){
instance = await People.deployed()
});
it("shouldn't create a person with age over 150 years", async function(){
await truffleAssert.fails(instance.createPerson("Bob", 200, 190, {value: web3.utils.toWei("1", "ether")}), truffleAssert.ErrorType.REVERT);
});
it("shouldn't create a person without payment", async function(){
await truffleAssert.fails(instance.createPerson("Bob", 50, 190, {value: 1000}), truffleAssert.ErrorType.REVERT);
});
it("should set senior status correctly", async function(){
await instance.createPerson("Bob", 65, 190, {value: web3.utils.toWei("1", "ether")});
let result = await instance.getPerson();
assert(result.senior === true, "Senior level not set");
});
it("should set age correctly", async function(){
let result = await instance.getPerson();
assert(result.age == 65, "Age not set correctly");
});
it("should not allow other account except the owner to delete people", async function(){
await instance.createPerson("Lisa", 35, 170, {from: accounts[1], value: web3.utils.toWei("1", "ether")});
await truffleAssert.fails(instance.deletePerson(accounts[1], {from: accounts[1], value: web3.utils.toWei("1", "ether")}), truffleAssert.ErrorType.REVERT);
});
it("should only allow owner to delete people", async function(){
await truffleAssert.passes(instance.deletePerson(accounts[1], {from: accounts[0]}));
});
it("should decrease owner's balance after adding people", async function(){
let instance = await People.new();
let initialBalance = parseInt(await web3.eth.getBalance(accounts[0]));
await instance.createPerson("David", 38, 175,{from: accounts[0], value: web3.utils.toWei("1", "ether")});
let newBalance = parseInt(await web3.eth.getBalance(accounts[0]));
assert(newBalance < initialBalance, "owner's balance did not decrease");
});
it("should not be able to withdraw the contract fund except the owner", async function(){
await truffleAssert.fails(instance.withdrawAll({from: accounts[1]}), truffleAssert.ErrorType.REVERT);
});
it("should only allow the contract owner to withdraw the contract funds", async function(){
await truffleAssert.passes(instance.withdrawAll({from: accounts[0]}));
});
});
Hi again @Golden_Pig_Coin ^^
Ohhh my bad i didn’t read well, you try to do it in the truffle console…
You need to do
instance.createPerson("dave", 200, 190)
with double quotes, or define dave as a variable
let dave = "dave";
instance.createPerson(dave, 200, 190)
Hi @gabba
thank you very much!
That explains why it worked on the previous day! I need to screenshot everything that I did correctly from now on!
In his example @filip codes:
assert(result.senior === true, "senior level not set");
I cannot see why he is using === rather than == given that senior is of type bool. I used == and it worked as intended.
Am I missing something?
hey all my code is running fine but when i am using “instance.setMessage()” i am getting following error @filip
================================================================================
truffle(ganache)> instance.setMessage(“hey !!”)
Uncaught Error: Returned error: VM Exception while processing transaction: revert
at evalmachine.:0:10
at sigintHandlersWrap (vm.js:258:15)
at Script.runInContext (vm.js:138:14)
at runScript (C:\Users\gandh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\console.js:222:1)
at Console.interpret (C:\Users\gandh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\console.js:237:1)
at ReplManager.interpret (C:\Users\gandh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\repl.js:129:1)
at bound (domain.js:429:14)
at REPLServer.runBound [as eval] (domain.js:442:12)
at REPLServer.onLine (repl.js:792:10)
at REPLServer.emit (events.js:315:20)
at REPLServer.EventEmitter.emit (domain.js:485:12)
at REPLServer.Interface._onLine (readline.js:337:10)
at REPLServer.Interface._line (readline.js:666:8)
at REPLServer.Interface._ttyWrite (readline.js:1006:14)
at REPLServer.self._ttyWrite (repl.js:882:9)
at ReadStream.onkeypress (readline.js:213:10)
at ReadStream.emit (events.js:315:20)
at ReadStream.EventEmitter.emit (domain.js:485:12)
at emitKeys (internal/readline/utils.js:335:14)
at emitKeys.next () {
hijackedStack: ‘Error: Returned error: VM Exception while processing transaction: revert\n’ +
’ at Object.ErrorResponse (C:\Users\gandh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\node_modules\web3-core-helpers\src\errors.js:29:1)\n’ +
’ at C:\Users\gandh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\node_modules\web3-core-requestmanager\src\index.js:140:1\n’ +
’ at C:\Users\gandh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\provider\wrapper.js:112:1\n’ +
’ at XMLHttpRequest.request.onreadystatechange (C:\Users\gandh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\node_modules\web3-providers-http\src\index.js:96:1)\n’ +
’ at XMLHttpRequestEventTarget.dispatchEvent (C:\Users\gandh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\node_modules\xhr2-cookies\dist\xml-http-request-event-target.js:34:1)\n’ +
’ at XMLHttpRequest._setReadyState (C:\Users\gandh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\node_modules\xhr2-cookies\dist\xml-http-request.js:208:1)\n’ +
’ at XMLHttpRequest._onHttpResponseEnd (C:\Users\gandh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\node_modules\xhr2-cookies\dist\xml-http-request.js:318:1)\n’ +
’ at IncomingMessage. (C:\Users\gandh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\node_modules\xhr2-cookies\dist\xml-http-request.js:289:47)\n’ +
’ at IncomingMessage.emit (events.js:327:22)\n’ +
’ at IncomingMessage.EventEmitter.emit (domain.js:547:15)\n’ +
’ at endReadableNT (_stream_readable.js:1224:12)\n’ +
’ at processTicksAndRejections (internal/process/task_queues.js:84:21)’
}
Hi @Kiki
=== is comparing the type and the value
== is just comparing the value.
it’s always safer to user ===
2=="2"
true
2==="2"
false
It’s important because it could leads to other errors later in your code for example in this case
2+"2"
"22"
2+2
4
Hi @Gandharv_dalal
Can you show use the code of your smart contract. If you have a revert it means that a require didn’t pass.
Also try
truffle migrate --reset
Maybe your contract wasn’t updated with the correct parameters
this is my code @gabba thanks for reaching out,but it is still showing error
pragma solidity 0.5.12;
contract Helloworld{
string message =“hello world !”;
function getMessage() public view returns(string memory){
return message;
}
function setMessage(string memory newMessage) public {
message=newMessage;
}
}
Hummm it’s weird you code is ok, can you call the getMessage function ?
Did you leave truffle console, enter truffle migrate --reset then go back in the console deployed a new contract and try again ?
Yeah now it worked after restarting my project again thanks for helping
Hi @filip
I am having a hard time getting truffle onto my terminal every time I try to enter truffle init, it return command not found. I even tried to confirm the version I installed and it still returns command not found
Macintosh-10:~ CalvinCutlass$ npm install [email protected]
[email protected] postinstall /Users/CalvinCutlass/node_modules/truffle
node ./scripts/postinstall.js
npm WARN saveError ENOENT: no such file or directory, open ‘/Users/CalvinCutlass/package.json’
npm WARN enoent ENOENT: no such file or directory, open ‘/Users/CalvinCutlass/package.json’
npm WARN CalvinCutlass No description
npm WARN CalvinCutlass No repository field.
npm WARN CalvinCutlass No README data
npm WARN CalvinCutlass No license field.
added 1 package from 1 contributor and audited 36 packages in 16.304s
found 4 low severity vulnerabilities
run npm audit fix
to fix them, or npm audit
for details
Macintosh-10:~ CalvinCutlass$ npm audit fix
npm ERR! code EAUDITNOPJSON
npm ERR! audit No package.json found: Cannot audit a project without a package.json
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/CalvinCutlass/.npm/_logs/2020-05-24T18_03_03_685Z-debug.log
Macintosh-10:~ CalvinCutlass$ truffle version
-bash: truffle: command not found
Hi @mjwatson10
You need to do
npm init
then install truffle
But you can also instal truffle globaly with the option ‘-g’
@gabba I am still running into command not found when i try truffle init
CalvinCutlass@Macintosh-10 ~ % npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See npm help json
for definitive documentation on these fields
and exactly what they do.
Use npm install <pkg>
afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (calvincutlass) turffle
version: (1.0.0)
description:
entry point: (index.js)
test command: (mocha)
git repository:
keywords: truffle
author: me
license: (ISC)
About to write to /Users/CalvinCutlass/package.json:
{
“name”: “turffle”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“dependencies”: {},
“devDependencies”: {},
“scripts”: {
“test”: “mocha”
},
“keywords”: [
“truffle”
],
“author”: “me”,
“license”: “ISC”
}
Is this OK? (yes)
CalvinCutlass@Macintosh-10 ~ % npm install -g [email protected]
npm WARN deprecated [email protected]: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
/Users/CalvinCutlass/npm-global/bin/truffle -> /Users/CalvinCutlass/npm-global/lib/node_modules/truffle/build/cli.bundled.js
[email protected] postinstall /Users/CalvinCutlass/npm-global/lib/node_modules/truffle
node ./scripts/postinstall.js
added 27 packages from 439 contributors in 23.024s
CalvinCutlass@Macintosh-10 ~ % truffle init
zsh: command not found: truffle
CalvinCutlass@Macintosh-10 ~ %
Hi @mjwatson10 you had installed truffle globally (-g) not locally and i think that you can’t call it because it’s not in your PATH.
When you are calling a binary your shell in looking in every folder in your path
echo $PATH
Truffle has been installed here
/Users/CalvinCutlass/npm-global/bin/truffle
can you try this
/Users/CalvinCutlass/npm-global/bin/truffle -v
if you want you can add the npm global folder in your path
export /Users/CalvinCutlass/npm-global/bin/:$PATH
This command will add the bin folder to you path, and you will be able to call truffle directly.
This new path will only be available in your current shell
When a shell start it loads all his default environment variables.
I see that your are using zsh so i guess you know all this stuff and you will be able to change your default path in ~/.zshrc