我有簡單的智能合約:
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];
}
}
我把這份合同從
我已經成功編譯并上傳了這個智能合約到 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);
});
}
問題是為什么即使合同部署不足,我的余額仍然為零?
最后交易成功(據我了解,需要交易才能使地址到地址的代幣轉移成功)
uj5u.com熱心網友回復:
在solidity建構式中,您設定的是部署者地址的余額——而不是合約地址的余額。
constructor() {
balances[msg.sender] = totalSupply;
owner = msg.sender;
}
但是在 JS 腳本中,您詢問的是合約地址的余額。
const token = new web3.eth.Contract(abi, address);
token.methods.balanceOf(address)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/381601.html
標籤:javascript 以太坊 智能合约 web3js 安全帽
上一篇:JavaScript排序多個陣列
