首页 > 解决方案 > 将已部署的智能合约连接到 JavaScript 时出现问题。Remix + JS + Infura + Ropsten(使用 Metamask)

问题描述

我是 DApps 的初学者,并且仍在学习大多数概念。最近,我在 Remix IDE 中编写了一个智能合约,我使用注入的 web3 和 metamask 将其部署在 ropsten 测试网络中。合同中的功能可以正常工作并且符合预期。这是合同:

pragma solidity >=0.7.0 <0.9.0;

contract details {
    uint count=0;
   struct empDetails {
        uint date;
        string bank;
        uint BPay;
        uint allw;
        uint spallw;
        string status;
    }
    mapping (string => empDetails) AllDetails;


    function SetUserInfo(uint _date, string memory _empID, string memory _bank, string memory _status,
    uint _BPay, uint _allw, uint _spallw) public {
        AllDetails[_empID].date = _date;
        AllDetails[_empID].bank = _bank;
        AllDetails[_empID].BPay = _BPay;
        AllDetails[_empID].allw = _allw;
        AllDetails[_empID].spallw = _spallw;
        AllDetails[_empID].status = _status;
}


    function GetUserInfo(string memory _empID) public view returns (uint,string memory,uint,uint,uint,string memory)
    {
        return (AllDetails[_empID].date,AllDetails[_empID].bank,AllDetails[_empID].BPay, AllDetails[_empID].allw,
        AllDetails[_empID].spallw,AllDetails[_empID].status);
    }

}

我尝试使用 web3 将它连接到我正在创建的简单前端。在使用 Ropsten 之前,我尝试在 Ganache 客户端上部署它,它运行良好。在 Ropsten 中执行相同的代码时,我遇到了很多错误,我使用本论坛中的其他帖子作为参考解决了这些错误。这是最终代码:

const Web3 = require("web3");
const Tx= require("ethereumjs-tx").Transaction;

web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/MY_ROPSTEN_API"));
  
var UserContract = new web3.eth.Contract(ABI, CONTRACT_ADDRESS);

var privatekey= new Buffer.from(PRIVATE_KEY, 'hex');

async function Submit(){

const myData= UserContract.methods.SetUserInfo(144447,"E102","ASBI","Working",30000,4060,5020).encodeABI();
const mynonce = await web3.utils.toHex(web3.eth.getTransactionCount(ACCOUNT_ADDRESS)) 
const txObject={from:ACCOUNT_ADDRESS,
gasPrice:100,
gasLimit:gasLimitHex = 300000,
nonce:mynonce,data:myData};

var tx= new Tx(txObject,{'chain':'ropsten'});
tx.sign(privatekey);
const serializedTx= tx.serialize();
const raw='0x'+serializedTx.toString('hex');
const transaction=web3.eth.sendSignedTransaction(raw,(err,txr)=>{
    
    if(err)
    {
        console.log(err);
    }
    else{
        console.log("It is Working "+txr);
    }
})

}
Submit();

我现在只对输入参数值进行了硬编码。当我尝试运行 Submit() 函数时,我收到一条成功消息“它正在工作”以及我假设的其他一些值是事务哈希。

示例输出:它正在工作 0x39418c22fc32c1670fcad9f9eba991976434b64bcf8a8ba0cf49ee1799efa90a

但我在 Metamask 或 Etherscan 上没有看到任何变化。我还尝试在我硬编码的数据上使用 remix 自己的环境在solidity 合约中运行getter 函数,但我只得到一组空值。有人可以帮助我了解发生了什么以及我做错了什么吗?

标签: javascriptblockchainethereumsolidityweb3

解决方案


推荐阅读