My code says Error: missing argument: passed to contract, and I want to understand how I can test that and fix my code for the future - constructor

Here is a picture of the error code that I receive when I run this code listed below:
enter image description here
import "./App.css";
import { ethers } from "ethers";
import abi from "./utils/WavePortal.json";
const App = () => {
const [currentAccount, setCurrentAccount] = useState("");
const contractAddress = "0x4AD0685b66e62f4862eBC1247d192A512D1EDEa7";
const contractABI = abi.abi;
const checkIfWalletIsConnected = async () => {
try {
const { ethereum } = window;
if (!ethereum) {
console.log("Make sure you have metamask!");
return;
} else {
console.log("We have the ethereum object", ethereum);
}
const accounts = await ethereum.request({ method: "eth_accounts" });
if (accounts.length !== 0) {
const account = accounts[0];
console.log("Found an authorized account:", account);
setCurrentAccount(account);
} else {
console.log("No authorized account found")
}
} catch (error) {
console.log(error);
}
}
/**
* Implement your connectWallet method here
*/
const connectWallet = async () => {
try {
const { ethereum } = window;
if (!ethereum) {
alert("Get MetaMask!");
return;
}
const accounts = await ethereum.request({ method: "eth_requestAccounts" });
console.log("Connected", accounts[0]);
setCurrentAccount(accounts[0]);
} catch (error) {
console.log(error)
}
}
const wave = async () => {
try {
const { ethereum } = window;
if (ethereum) {
const provider = new ethers.providers.Web3Provider(ethereum);
const signer = provider.getSigner();
const wavePortalContract = new ethers.Contract(contractAddress, contractABI, signer);
let count = await wavePortalContract.getTotalWaves();
console.log("Retrieved total wave count...", count.toNumber());
const waveTxn = await wavePortalContract.wave();
console.log("Mining...", waveTxn.hash);
await waveTxn.wait();
console.log("Mined -- ", waveTxn.hash);
count = await wavePortalContract.getTotalWaves();
console.log("Retrieved total wave count...", count.toNumber());
} else {
console.log("Ethereum object doesn't exist!");
}
} catch (error) {
console.log(error);
}
}
useEffect(() => {
checkIfWalletIsConnected();
}, [])
return (
<div className="mainContainer">
<div className="dataContainer">
<div className="header">
👋 Hey there!
</div>
<div className="bio">
Give me money please
</div>
<button className="waveButton" onClick={wave}>
Wave at Me
</button>
{/*
* If there is no currentAccount render this button
*/}
{!currentAccount && (
<button className="waveButton" onClick={connectWallet}>
Connect Wallet
</button>
)}
</div>
</div>
);
}
export default App
There is my code and the result that I get from it, if you need any other info, let me know. I have other parts of it but most of it is this part. I read that there were issues with the constructor and what all had gone through it but don't quite understand what it is. If someone is able to help and explain that would be great, thank you!

Related

Component responsible to display all my transactions are not updating after submit

I'm using redux toolkit with react and have a basic setup because I'm building a simple expense tracker, so I have two operations: get all transactions and add a new transaction. That's it.
My problem: When I create a new transaction the component responsible for displaying my data does not update and I can only see the changes after refreshing the page.
Below you can see my transactionSlice file:
const initialState = {
transactions: [],
loading: false,
error: null,
}
export const getTransactions = createAsyncThunk(
"transactions/getTransactions",
async () => {
const res = await axios.get('http://localhost:8000/transactions')
return res.data
}
)
export const addTransaction = createAsyncThunk(
"transaction/addTransaction",
async(data) => {
const res = await axios.post('http://localhost:8000/transactions', data);
return res.data
}
)
const transactionsSlice = createSlice({
name: 'transactions',
initialState,
reducers: {},
extraReducers: {
[getTransactions.pending]: (state) => {
state.loading = true;
},
[getTransactions.fulfilled]: (state, {payload}) => {
console.log(payload);
state.loading = false;
state.transactions = payload;
state.error = ''
},
[getTransactions.rejected]: (state) => {
state.loading = false;
state.error = state.error.message;
},
[addTransaction.pending]: (state) => {
state.loading = true;
},
[addTransaction.fulfilled]: (state) => {
state.loading = false;
},
[addTransaction.rejected]: (state) => {
state.loading = false;
state.error = state.error.message;
}
}
});
and here is the code from the component where I'm displaying all transactions
const { transactions, loading } = useSelector(selectAllTransactions);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getTransactions());
}, [dispatch]);
but when I make a post request my state with all transactions doesn't update immediately. I can only see the changes if I update the page and I'm doing it manually. I'm wondering why is this happening if I have useEffect watching for changes?
AddTransaction.js file :
const [transactionName, setTransactionName] = useState('');
const [amount, setAmount] = useState('');
const dispatch = useDispatch();
const handleSubmit = (e) => {
e.preventDefault();
const data = {
transactionName,
amount
}
if(transactionName && amount){
dispatch(addTransaction(data));
dispatch(getTransactions());
setTransactionName('')
setAmount('');
}
}
I've tried to google it but it seems my doubt is so silly that I can't even find an answer for that.
Here is my server file:
app.post('/transactions',(req, res) => {
const {transactionName, amount} = req.body;
const query = `INSERT INTO transactions (title, amount)
VALUES ("${transactionName}", "${amount}")`
db.query(query, (err, result) => {
if(err){
console.log(err)
}
res.send(result)
})
});
Am I missing something? Could someone explain to me why the component responsible to display all transactions are not updating after submit, please?
Try executing getTransactions once addTransaction(data) is finished, not at the same time:
const handleSubmit = (e) => {
e.preventDefault();
const data = {
transactionName,
amount
}
if(transactionName && amount){
dispatch(addTransaction(data))
.then(() => {
dispatch(getTransactions())
setTransactionName('')
setAmount('')
}
}
}

Change number of servings on click (React Hooks - API)

I'm working on a recipe site using API from a third party and want to change the number of servings (which is output from the API data) when clicking the + & - button. I tried assigning the output serving amount <Servings>{recipe.servings}</Servings> in a variable and useState to update it but it kept showing errors. I would appreciate any help (preferably using react Hooks). Thanks :)
Here is my code:
const id = 716429;
const apiURL = `https://api.spoonacular.com/recipes/${id}/information`;
const apiKey = "34ac49879bd04719b7a984caaa4006b4";
const imgURL = `https://spoonacular.com/cdn/ingredients_100x100/`;
const {
data: recipe,
error,
isLoading,
} = useFetch(apiURL + "?apiKey=" + apiKey);
const [isChecked, setIsChecked] = useState(true);
const handleChange = () => {
setIsChecked(!isChecked);
};
return (
<Section>
<h2>Ingredients</h2>
<ServingsandUnits>
{recipe && (
<ServingsIncrementer>
<p>Servings: </p>
<Minus />
<Servings>{recipe.servings}</Servings>
<Plus />
</ServingsIncrementer>
)}
<ButtonGroup>
<input
type="checkbox"
id="metric"
name="unit"
checked={isChecked}
onChange={handleChange}
/>
<label htmlFor="male">Metric</label>
</ButtonGroup>
</ServingsandUnits>
</Section>
};
My custom hook is called useFetch:
const useFetch = (url) => {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortCont = new AbortController();
fetch(url, { signal: abortCont.signal })
.then((res) => {
if (!res.ok) {
// error coming back from server
throw Error("Could not fetch the data for that resource");
}
return res.json();
})
.then((data) => {
setIsLoading(false);
setData(data);
setError(null);
})
.catch((err) => {
if (err.name === "AbortError") {
console.log("Fetch aborted");
} else {
// auto catches network / connection error
setIsLoading(false);
setError(err.message);
}
});
return () => {
abortCont.abort();
};
}, [url]);
return { data, isLoading, error };
};
export default useFetch;

cannot connect client app with web3js to metamask

I am a dapp beginner. This is a demo app for a todolist
I am unable to get a connection to the blockchain in web3js. Websocket connection error
localhost is localhost:8545
using web3js CDN : https://cdn.jsdelivr.net/npm/web3#latest/dist/web3.min.js
this is my app.js
App = {
loading: false,
contracts: {},
load: async () => {
console.log('app loading ...')
console.log(web3);
await App.loadWeb3()
await App.loadAccount()
// await App.loadContract()
// await App.render()
},
// https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8
loadWeb3: async () => {
let web3 = new Web3('ws://localhost:8545');
if (typeof web3 !== 'undefined') {
App.web3Provider = web3.currentProvider
web3.setProvider('ws://localhost:8546');
web3.eth.getAccounts().then(console.log);
} else {
window.alert("Please connect to Metamask.")
}
// Modern dapp browsers...
if (window.ethereum) {
window.web3 = new Web3(ethereum)
try {
// Request account access if needed
await ethereum.enable()
// Acccounts now exposed
web3.eth.sendTransaction({/* ... */})
console.log('MetaMask is installed!');
} catch (error) {
// User denied account access...
}
}
// Legacy dapp browsers...
else if (window.web3) {
App.web3Provider = web3.currentProvider
window.web3 = new Web3(web3.currentProvider)
// Acccounts always exposed
web3.eth.sendTransaction({/* ... */})
}
// Non-dapp browsers...
else {
console.log('Non-Ethereum browser detected. You should consider trying MetaMask!')
}
},
loadAccount: async () => {
// Set the current blockchain account
App.account = web3.eth.accounts[0]
console.log(App.account)
// web3 set up by loadWeb3, includes all accounts, loading first one via MetaMask
},
loadContract: async () => {
// Create a JavaScript version of the smart contract
const todoList = await $.getJSON('TodoList.json')
App.contracts.TodoList = TruffleContract(todoList)
App.contracts.TodoList.setProvider(App.web3Provider)
// Hydrate the smart contract with values from the blockchain
App.todoList = await App.contracts.TodoList.deployed()
},
render: async () => {
// Prevent double render
if (App.loading) {
return
}
// Update app loading state
App.setLoading(true)
// Render Account
$('#account').html(App.account)
// Render Tasks
await App.renderTasks()
// Update loading state
App.setLoading(false)
},
renderTasks: async () => {
// Load the total task count from the blockchain
const taskCount = await App.todoList.taskCount()
const $taskTemplate = $('.taskTemplate')
// Render out each task with a new task template
for (var i = 1; i <= taskCount; i++) {
// Fetch the task data from the blockchain
const task = await App.todoList.tasks(i)
const taskId = task[0].toNumber()
const taskContent = task[1]
const taskCompleted = task[2]
// Create the html for the task
const $newTaskTemplate = $taskTemplate.clone()
$newTaskTemplate.find('.content').html(taskContent)
$newTaskTemplate.find('input')
.prop('name', taskId)
.prop('checked', taskCompleted)
.on('click', App.toggleCompleted)
// Put the task in the correct list
if (taskCompleted) {
$('#completedTaskList').append($newTaskTemplate)
} else {
$('#taskList').append($newTaskTemplate)
}
// Show the task
$newTaskTemplate.show()
}
},
createTask: async () => {
App.setLoading(true)
const content = $('#newTask').val()
await App.todoList.createTask(content)
window.location.reload()
},
toggleCompleted: async (e) => {
App.setLoading(true)
const taskId = e.target.name
await App.todoList.toggleCompleted(taskId)
window.location.reload()
},
setLoading: (boolean) => {
App.loading = boolean
const loader = $('#loader')
const content = $('#content')
if (boolean) {
loader.show()
content.hide()
} else {
loader.hide()
content.show()
}
}
}
$(() => {
$(window).load(() => {
App.load()
})
})
I get this error in the console :
Again I am a total newbie, any help is appreciated.
Any source of info did not help
Hey after metamask update , it no longer injects web3 .
You can check the blog below , It has shown how to connect metamask with our project .
https://dapp-world.com/blogs/01/how-to-connect-metamask-with-dapp--1616927367052
Only thing is its web application , you can relate it with your project .
Hope it works !

ipfs.add is not working for ipfs client v44.3.0 how can I resolve this?

This is my code in App.js, and its always returning an "Unhandeled Rejection Type error saying that ipfs.add(...). then is not a function.
import React, { Component } from 'react';
import './App.css';
var ipfsAPI = require('ipfs-http-client')
var ipfs = ipfsAPI({host: 'localhost', port: '5001', protocol:'http'})
class App extends Component {
saveTestBlobOnIpfs = (blob) => {
return new Promise(function(resolve, reject) {
const descBuffer = Buffer.from(blob, 'utf-8');
ipfs.add(descBuffer).then((response) => {
console.log(response)
resolve(response[0].hash);
}).catch((err) => {
console.error(err)
reject(err);
})
})
}
render() {
return (
<div className="App">
<h1>IPFS Pool</h1>
<input
ref = "ipfs"
style = {{width: 200, height: 50}}/>
<button
onClick = {() => {
console.log("Upload Data to IPFS");
let content = this.refs.ipfs.value;
console.log(content);
this.saveTestBlobOnIpfs(content).then((hash) => {
console.log("Hash of uploaded data: " + hash)
});
}}
style = {{height: 50}}>Upload Data to IPFS</button>
</div>
);
}
}
export default App;
Do I need to add an async function or something, I'm fairly new to js so any help would greatly appreciated. I just don't know how to change the ipfs.add to make my code work.
I have also followed the same tutorial and ran into the same problem. The ipfs.add function does not accept a call function anymore. More information on that here: https://blog.ipfs.io/2020-02-01-async-await-refactor/
The solution is turn your saveTestBlobOnIpfs function into an async/await function. Like this:
saveTestBlobOnIpfs = async (event) => {
event.preventDefault();
console.log('The file will be Submitted!');
let data = this.state.buffer;
console.log('Submit this: ', data);
if (data){
try{
const postResponse = await ipfs.add(data)
console.log("postResponse", postResponse);
} catch(e){
console.log("Error: ", e)
}
} else{
alert("No files submitted. Please try again.");
console.log('ERROR: No data to submit');
}
}

cloud function for sending fcm notifications to a collection of tokens

I am trying to send a notification whenever a new update to my database takes place. I have the onUpdate side working but I am new to FCM and I am stuck at the sending the notification.
The structure of the devices collection is:
+devices/
+tokenId/
-tokenId:njurhvnlkdnvlksnvlñaksnvlkak
-userId:nkjnjfnwjfnwlknlkdwqkwdkqwdd
The function that I have right now that gets stuck with an empty value of token is:
const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
const settings = { timestampsInSnapshots: true };
db.settings(settings);
.....
exports.fcmSend = functions.firestore
.document(`chats/{chatId}`).onUpdate((change, context) => {
const messageArray = change.after.data().messages;
const message = messageArray[(messageArray.length-1)].content
if (!change.after.data()) {
return console.log('nothing new');
}
const payload = {
notification: {
title: "nuevo co-lab",
body: message,
}
};
return admin.database().ref(`/devices`)
.once('value')
.then(token => token.val())
.then(userFcmToken => {
console.log("Sending...", userFcmToken);
return admin.messaging().sendToDevice(userFcmToken, payload)
})
.then(res => {
console.log("Sent Successfully", res);
})
.catch(err => {
console.log("Error: ", err);
});
});
I am not able to get the token from the database. It is null or undefined. Can anyone help me with this second part of the function?
Thanks a lot in advance!
Thanks Frank for the tip!
I managed to solve the problem with this code in case anybody needs it:
const payload = {
notification: {
title: "nuevo mensaje de co-lab",
body: message,
}
};
// Get the list of device tokens.
const allTokens = await admin.firestore().collection('devices').get();
const tokens = [];
allTokens.forEach((tokenDoc) => {
tokens.push(tokenDoc.id);
});
if (tokens.length > 0) {
// Send notifications to all tokens.
return await admin.messaging().sendToDevice(tokens, payload);
}else {
return null;
}