首页 > 解决方案 > 为什么我没有看到我的智能合约进入区块链?

问题描述

我已经使用脚本标签链接了 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;
    }
}

标签: javascriptblockchainethereumsmartcontracts

解决方案


new web3.eth.Contract不部署合约。如果您提供特定地址,则表示“我想与已部署在此地址的此 ABI 的合同进行交互”。要部署它,您需要使用该deploy方法。你不能选择你部署到的地址,当Promisereturn 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));

推荐阅读