consensys solidity simple bank exercise [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 days ago.
Improve this question
i'm currently passing 7 of 8 #openzeppelin/test-helpers when i run $ truffle test on my clone of the consensys simple-bank-exercise
why am i getting the following error and does it relate to the code below?
should log a deposit event when a deposit is made:
TypeError: Cannot read properties of undefined (reading 'toNumber')
SimpleBank.sol
function deposit() public payable returns(uint) {
require(enrolled[msg.sender] == true, "User is not enrolled."); /// #notice deposit ether into bank
balances[msg.sender] += msg.value;
emit LogDepositMade(msg.sender, msg.value);
return balances[msg.sender]; /// #return the balance of the user after the deposit is made
}
simpleBank.test.js
it("should log a deposit event when a deposit is made", async () => {
await instance.enroll({ from: alice });
const result = await instance.deposit({ from: alice, value: deposit });
const expectedEventResult = { accountAddress: alice, amount: deposit };
const logAccountAddress = result.logs[0].args.accountAddress;
const logDepositAmount = result.logs[0].args.amount.toNumber();
// const logDepositAmount = result.logs[0].args.depositAmount.toNumber();
assert.equal(expectedEventResult.accountAddress, logAccountAddress, "LogDepositMade event accountAddress property not emitted, check deposit method",);
assert.equal(expectedEventResult.amount, logDepositAmount, "LogDepositMade event amount property not emitted, check deposit method",);
});
thanks!

Related

I want to call a single document from my Angular Firestore [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I'm facing a problem in my project, I'm using Nested Children Routing to show data in my project, I want the data of this specific item to be shown once I click the button on it, I did the routing right, it's just I can't get the proper function for the items.
Here's my service
PostsService.service.ts
getPostById(id: string){
let docId = this.afs.collection('posts').doc(id).get()
.subscribe( doc => {
if(doc.exists){
console.log('Document Id => ', doc.id)
console.log('Document data => ', doc.data())
}else {
console.log('Document not found')
}
});
return docId;
}
and Here's my TS function for the single item
.component.ts
posts: Posts[] = [];
post!:any;
constructor(
private PostsService: PostsService,
private route: ActivatedRoute
) {}
ngOnInit(): void {
let id = this.route.snapshot.params['id']
this.PostsService.getPostById(id);
}
You're attempting the get the whole collection with getPostById() and then trying to find a single document from the results. Getting the whole colletion means you will read n amount of times for n amount of documents - which is wasteful and slow.
If you ask something with getPostById() then you should do something with the return as well. Right now your asking, but not doing anything with the return.
How about we just get the single document? It will return an Observable, so we can keep monitoring the document, or just use the face value as it is.
getPostById(id: string) {
const itemDoc = this.afs.doc<any>('posts/' + id);
return itemDoc.valueChanges();
}
And in your component, don't forget to unsubscribe from the Observable.
ngOnInit() {
let id = this.route.snapshot.params['id'];
this.PostsService.getPostById(id).subscribe(post => {
console.log(post);
})
}

TypeError: Cannot read properties of undefined (reading 'equal') [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
I have created 2 TESTS --
In 2nd TEST, I have enclosed owner, addr1, addr2 in [] as per the Official Hardhat Documentation, like this const [owner,addr1,addr2] = await ethers.getSigners();,
But the problem is when I use [] bracket, it shows me the error TypeError: Cannot read properties of undefined (reading 'equal') and the test also failed,
Here is the Code --->
const { expect } = require('chai');
// const { ethers } = require('hardhat');
describe('Token contract', function () {
//1st TEST
it('Deployment should assign the total supply of the tokens to the owner', async function () {
const [owner] = await ethers.getSigners();
const Token = await ethers.getContractFactory('Token');
const hardhatToken = await Token.deploy();
const ownerBalance = await hardhatToken.balanceOf(owner.address);
expect(await hardhatToken.totalSupply()).to.equal(ownerBalance);
});
//2nd TEST
it('Should Transfer Tokens between accounts', async function () {
const [owner,addr1,addr2] = await ethers.getSigners();
const Token = await ethers.getContractFactory('Token');
const hardhatToken = await Token.deploy();
//Transfer 10 tokens from Owner to addr1
await hardhatToken.transfer(addr1.address,10);
expect(await hardhatToken.balanceOf(addr1.address).to.equal(10));
//Transfer 5 tokens from addr1 to addr2
await hardhatToken.connect(addr1).transfer(addr2.address,5);
expect(await hardhatToken.balanceOf(addr2.address).to.equal(5))
});
});
But if U see in the 1st TEST, I haven't used [], for owner, so the test passed.
Below is the Official Hardhat documentation if U want to check the code --->
https://hardhat.org/tutorial/testing-contracts.html
Please help me to solve this Problem
Thanks
enter image description here
You didn't close the parenthesis around the expect calls in the second test correctly. You're accessing .to on the number returned by .balanceOf.
Replace with:
expect(await hardhatToken.balanceOf(addr1.address)).to.equal(10);
// ...
expect(await hardhatToken.balanceOf(addr2.address)).to.equal(5);

How can I run a function at a particular point in the future? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a schedule option in my API what I did with Expressjs and NodeJS. Our backend calls this API with two parameters (userID & timestamp). The goal is to delete user informations (folders, documents, etc) at the specified time (..or few minutes later). The timestamp can be 5 minutes to 2 days from now.
When it happened the job is done and the API is waiting for an other call. The API can receive 1000 calls per day, so the performance is very important. What's the best way to run the function in the future?
async function scheduledAction(userId, timestamp) {
var actionInFuture = await checkDate(timestamp);
if(actionInFuture) {
console.log('Action triggered');
}
}
async function checkDate(timestamp) {
await new Promise(resolve => {
setTimeout(resolve, 1000)
});
// timestamp = 1627311533000
if(Date.now() >= timestamp) {
return true;
} else {
return checkDate(timestamp);
}
}
app.get('/action', (req, res) => {
scheduledAction(req.query.userId, req.query.timestamp);
}
scheduledAction(req.query.userId, req.query.timestamp);
You can use Node Schedule package, https://www.npmjs.com/package/node-schedule
For example:
var schedule = require('node-schedule');
const date = new Date(1627309531*1000);
var j = schedule.scheduleJob(date, function(){
console.log('Action triggered');
});

null value for firestore [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So basically, I can't display the collection on my html. I get a null value error for gamesList. But when I log it to the console, I can see the contents just fine, no problems there.
// get data
db.collection('games').get().then(snapshot => {
setupGames(snapshot.docs);
});
// DOM elements
const gamesList = document.querySelector('.games');
// setup games
const setupGames = (data) => {
let html = '';
data.forEach(doc => {
const game = doc.data();
const li = `
<li>
<div class="collapsible-header grey lighten-4">${game.title}</div>
<div class="collapsible-body white">${game.content}</div>
`;
html += li
});
gamesList.innerHTML = html;
}
So here something goes wrong and for the life of me I can't figure it out.
but when I use this the data does display correctly in the console, title and content:
// setup guides
const setupGames = (data) => {
let html = '';
data.forEach(doc => {
const game = doc.data();
console.log(game);
});
}
I think, when you use get() function on a collection, it already returns you the document list, so you don't need to call snapshot.docs
There's an example here:
https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_collection
If you want to use real time data with snapshots, try it this way:
db.collection('games').onSnapshot(snapshot => {
setupGames(snapshot.docs);
});

Why are my variables not being correctly defined in my if...else statement? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
In the code below, I've defined a function called checkPassword(), which takes in a single argument, passwordCorrect, which will be either true or false.
I've also defined two variables, accessGranted and message, which currently have no values (they're undefined) and will be overwritten and defined by your if statement if you've written it correctly.
I need to write an if statement inside the function that updates the two variables, accessGranted (a boolean), and message (a string), to meet the requirements below
Requirements:
1) If passwordCorrect is true, accessGranted should have a value of true and message should have a value of 'Welcome to the admin panel!'
2) In any other case, accessGranted should have a value of false and message should have a value of 'Wrong password.'
var accessGranted;
var message;
function checkPassword(passwordCorrect) {
if passwordCorrect == true {
accessGranted = true;
message = "Welcome to the admin panel!";
}
else {
accessGranted = false;
message = "Wrong password."
}
}
console.log('Access Granted:', accessGranted);
console.log('Message:', message);
You need to call the function and fix your syntax error. If statements need parentheses in javascript.
let accessGranted;
let message;
function checkPassword(passwordCorrect) {
if (passwordCorrect) {
accessGranted = true;
message = "Welcome to the admin panel!";
}
else {
accessGranted = false;
message = "Wrong password."
}
}
checkPassword(true)
console.log('Access Granted:', accessGranted);
console.log('Message:', message);

Categories