为什么我没有看到我的智能合约进入区块链



我已经使用脚本标记链接了web3和元任务API,而且我的控制台中似乎没有任何类型的错误,所以为什么我不能在etherscan.io上找到我的智能合约?

我的JS是这样的:

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
}
})

我的智能合约是这样的:


contract Message {
string myMessage;
function setMessage(string x) public {
myMessage = x;
}
function getMessage() public view returns (string) {
return myMessage;
}
}

new web3.eth.Contract不部署合约。如果你提供了一个特定的地址,那么它就是在说";我想与这个ABI进行交互,这个ABI已经部署在这个地址";。要部署它,您需要使用deploy方法。您不能选择部署到的地址,当从deploy返回的Promise解析时,它会返回给您。

顺便说一句:我假设$值来自PHP或其他什么?如果您还没有尝试部署,那么在尝试部署之前,检查它们是否正确可能是值得的。


编辑:假设您的合同已部署,问题是setMessage是一种修改区块链状态的方法,因此您需要使用交易(用少量ETH/gas支付更改费用(。

在API:方面,使用Metamask/Web3的方法有点尴尬

// (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));