【问题标题】:如何使用智能合约获得正确的余额?
【发布时间】:2022-01-18 16:03:48
【问题描述】:

我有简单的智能合约:

pragma solidity ^0.7.0;

contract Token {
    string public name = "My Hardhat Token";
    string public symbol = "MHT";
    uint256 public totalSupply = 1000000;
    address public owner;
    mapping(address => uint256) balances;

    constructor() {
        balances[msg.sender] = totalSupply;
        owner = msg.sender;
    }

    function transfer(address to, uint256 amount) external {
        require(balances[msg.sender] >= amount, "Not enough tokens");
        balances[msg.sender] -= amount;
        balances[to] += amount;
    }

    function balanceOf(address account) external view returns (uint256) {
        return balances[account];
    }
}

我接受这份合同from

我已经成功编译并上传了这个智能合约到 ropsten 测试网。我使用安全帽框架来执行此操作。 https://hardhat.org/tutorial/deploying-to-a-live-network.html

之后,我编写了一个脚本来接收余额、执行转账并创建交易。

var provider = "https://eth-ropsten.alchemyapi.io/v2/iwxxx";
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider(provider));
const abi = [{...}];
const address = "0xC1xxx";    // after deploy smart contract
const senderAddress  = "0x2bxxx";
const receiverAddress  = "0x39xxx";
const privKey = "0xf5xxx";

const token = new web3.eth.Contract(abi, address);
token.setProvider(web3.currentProvider)
token.methods.balanceOf(address).call( (err, res) => { console.log("Address Balance: ", res); }); // 0
token.methods.balanceOf(senderAddress).call((err, res) => { console.log("SenderAddress Balance: ", res); }); // 0

token.methods.transfer(receiverAddress, "1").send({ "from": address }, (err, res) => {
    if (err) {console.log("Error occured ! ", err);return}
    console.log("Hash transaction: " + res);
});

send_tr();
async function send_tr(){
    let transactionNonce = await web3.eth.getTransactionCount(senderAddress);
    let raw = {"to":receiverAddress, "value":"1", "gas":2000000, "nonce":web3.utils.toHex(transactionNonce)};
    const signedTx = await web3.eth.accounts.signTransaction(raw, privKey);
    await web3.eth.sendSignedTransaction(signedTx.rawTransaction, (err, ret) => {
        if (err) {console.log("An error occurred", err);return;}
        console.log("Success, txHash is: ", ret);
    });
}

问题是为什么我的余额为零,即使合约部署不足?

最后交易成功(据我了解,需要交易才能使从地址转移到地址的代币转移成功)

【问题讨论】:

    标签: javascript ethereum smartcontracts web3js hardhat


    【解决方案1】:

    在solidity 构造函数中,您设置的是部署者地址的余额,而不是合约地址的余额。

    constructor() {
        balances[msg.sender] = totalSupply;
        owner = msg.sender;
    }
    

    但是在 JS 脚本中,你是在询问合约地址的余额。

    const token = new web3.eth.Contract(abi, address);
    token.methods.balanceOf(address)
    

    【讨论】:

    • 它不工作,仍然平衡 0
    • @alex10 你做了什么改变,但仍然没有工作?
    • 对不起,它的工作,谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2023-01-19
    • 1970-01-01
    • 2018-07-22
    • 2022-06-14
    相关资源
    最近更新 更多