无法从智能合约获取客户端中的状态变量



我正在学习使用以太坊区块链构建ICO。我已经为代币销售编写了智能合约,它运行良好。我也为它写了测试,但当我试图在客户端网站上获得状态变量的值时,它会给我错误

我的代币销售代码:

pragma solidity ^0.4.24;
import './KhananiToken.sol';
contract KhananiTokenSale {
address admin;
KhananiToken public tokenContract;
uint256 public tokenPrice;
uint256 public tokensSold;
event Sell(
address   _buyer,
uint256  _amount
);
constructor (KhananiToken _tokenContract, uint256 _tokenPrice ) public {
//Assign an Admin
admin = msg.sender; //address of person how deployed the contract
tokenContract = _tokenContract;
tokenPrice = _tokenPrice;
}
function multiply(uint x, uint y) internal pure returns(uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function buyTokens(uint256 _numberOfTokens) public payable {
require(msg.value == multiply(_numberOfTokens , tokenPrice));
require(tokenContract.balanceOf(this) >= _numberOfTokens);        
require(tokenContract.transfer(msg.sender, _numberOfTokens));        
tokensSold += _numberOfTokens;
Sell(msg.sender, _numberOfTokens);
}
}

我的迁移代码:

module.exports = function(deployer) {
var tokenSupply = 1000000;
var tokenPrice = 1000000000000000; // is 0.001 Ehter
deployer.deploy(KhananiToken, tokenSupply).then(function(TokenAddress){
return  deployer.deploy(KhananiTokenSale, TokenAddress.address, tokenPrice);
}); //1000000 it the inital token supply
};

我的客户端代码:

App.contracts.KhananiTokenSale.deployed().then(function(instance){
khananiTokenSaleInstance = instance;
return instance.tokenPrice();
}).then(function(tokenPrice){
console.log('tokenPrice',tokenPrice)
console.log('tokenPrice',App.tokenPrice)
App.tokenPrice = tokenPrice;
//$('.token-price').html(App.tokenPrice)
})

在重新运行instance.tokenPrice((后,代码没有进入.then函数,因此console.log('tokenPrice',tokenPrice(不起作用。在铬我得到这个错误

MetaMask-RPC错误:内部JSON-RPC错误。{代码:-32603,消息:"内部JSON-RPC错误。"}未捕获(承诺中(错误:内部JSON-RPC错误。在Object.InvalidResponse(inpage.js:1(

在MetaMask中,我得到了这个错误

错误:[ethjs-rpc]rpc错误,带有有效负载{"id":1913523409875,"jsonrpc":"2.0","params":["0xf8920785174876e8008307a12094ab306a5cb13cca96bb50864e34ad92b3462af4b28711c37937e008000a36107240000000000000000000000000000000000000000000005822d45a0ad3178b0e1121d7dac39a7a90481fd87644eb07e67f0c638b2566827051a08ca03ee4cc4c432bbf02fbbdf9a02737c9d65d11a0e98376c86bf8621a343a3b41a"],"method":"eth_sendRawTransaction"}错误:正在尝试运行调用约定函数的事务,但收件人地址0xab306a5cb13cca96bb50864e34ad92b3462af4b2为不是合同地址

试试这个:

App.contracts.KhananiTokenSale.deployed().then(function(instance){
khananiTokenSaleInstance = instance;
return instance.tokenPrice.call();
}).then(function(tokenPrice){
console.log("tokenPrice", tokenPrice);
})

这是一条简单的规则:

  • 当您想进行交易,即更改区块链中的数据时,请使用instance.functionName()
  • 当您只想在不更改任何数据的情况下从区块链读取数据时,请使用instance.getterFunctionOrVariableName.call();

最新更新