Reputation: 41
I already linked both web3 and the metamask API using script tags, and I do not seem to be getting any type of errors in my console, so why can I not find my smart contract on the etherscan.io?
My JS is as so:
var dataHandling = async function customResponse () {
const provider = await detectEthereumProvider();
if (provider) {
if (provider !== window.ethereum) {
console.error('Do you have multiple wallets installed?');
}
console.log('Access the decentralized web!');
} else {
console.log('Please install MetaMask!');
}
}
dataHandling();
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
web3 = new Web3($INFURA_LINK);
}
const SCabi = $ABI
const SCaddress = $address
async function connect(){
//Will Start the metamask extension
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
const account = accounts[0];
console.log(ethereum.selectedAddress)
var dat = {
fname: document.getElementById('name').value,
cert: document.getElementById('cert').value
}
var SC = new web3.eth.Contract(SCabi, SCaddress)
SC.methods.setMessage(JSON.stringify(dat)).call(function (err, res) {
if (err) {
console.log("An error occured", err)
}else{
console.log(SC.methods.getMessage())
return
}
})
My smart contract is as so:
contract Message {
string myMessage;
function setMessage(string x) public {
myMessage = x;
}
function getMessage() public view returns (string) {
return myMessage;
}
}
Upvotes: 0
Views: 445
Reputation: 7981
new web3.eth.Contract
does not deploy the contract. If you provide a specific address, then it is saying "I want to interact with a contract with this ABI, already deployed at this address". To deploy it, you need to use the deploy
method. You cannot choose the address you deploy to, it is returned to you when the Promise
returned from deploy
resolves.
As an aside: I assume the $
values come from PHP or something? It might be worth checking they are correct before you try deploying, if you haven't already.
Edit: assuming your contract is deployed, the problem is that setMessage
is a method that modifies the blockchain state, and as such you need to use a transaction (to pay for that change with a small amount of ETH/gas).
The way to do this with Metamask/Web3 is a bit awkward in terms of API:
// (from before)
let SC = new web3.eth.Contract(SCabi, SCaddress);
// first we get the call "data", which encodes the arguments of our call
let data = SC.methods.setMessage.getData(JSON.stringify(dat));
// then we prepare the parameters of the transaction
const params = {
data: data, // from previous line
// value: "0x0", // optional, only if you want to also pay the contract
from: account, // the USER's address
to: SCaddress // the CONTRACT's address
};
// then we start the actual transaction
ethereum.request({
method: "eth_sendTransaction",
params: [params],
}).then(txHash => console.log("transaction hash", txHash));
Upvotes: 1