javascript - 为什么我没有看到我的智能合约进入区块链?
问题描述
我已经使用脚本标签链接了 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
return fromdeploy
解析时它会返回给你。
顺便说一句:我假设这些$
值来自 PHP 之类的?在您尝试部署之前检查它们是否正确可能是值得的,如果您还没有。
编辑:假设您的合约已部署,问题在于这setMessage
是一种修改区块链状态的方法,因此您需要使用交易(用少量的 ETH/gas 支付该更改)。
使用 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));
推荐阅读
- javascript - 如何生成特定真实世界大小的图像
- angular - 带有 ResizeObserver 的 ViewContainerRef 在角度中无法正常工作
- angular - 当另一个发射时运行一个可观察的,返回两个结果
- django - Django 模型 - 使用两个外键值
- php - 如何回显同一表中 2 列的结果 - PHP
- excel - 查找最后一个不匹配值的地址
- wpf - WPF Tabcontrol DataTemplate 和子用户控件初始化
- javascript - 从字符串数组创建对象
- sql - 如何按列式数据库删除重复数据
- node.js - 无法监听个位数的端口号?节点js