如何解决为什么我看不到智能合约进入区块链?
我已经使用脚本标签链接了web3和Metamask 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与合同进行交互”。要部署它,您需要使用deploy
方法。您无法选择要部署到的地址,当Promise
返回的deploy
解析后,地址会返回给您。
顺便说一句:我假设$
值来自PHP之类的东西?如果尚未尝试,则可能需要在尝试部署之前检查它们是否正确。
编辑:假设您的合同已部署,则问题在于setMessage
是一种修改区块链状态的方法,因此您需要使用交易(为此支付费用)少量的ETH /气体就可以改变它。)
使用Metamask / Web3进行此操作的方式在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));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。