如何将Solidity合约定义为javascript对象



我正在制作一个简单的应用程序,作为智能合约的前端。契约有一个公共字符串属性message,我希望它能够通过newContract.methods.message().call()访问。

我定义了对showMessage()函数的onclick调用,该函数应将消息属性记录到控制台,但当我单击带有onclick事件的按钮时,我会在本文底部收到错误消息。

新合约对象实例化下面的检查表明该类型没有定义,但我仍然收到一个undefined错误。

编辑:
删除了无关的ABI部分并添加了智能合约源代码。

问题似乎与newContract对象的范围有关。尽管它是用var声明的,但不能通过showMessage()函数内的全局window对象访问它。正确的范围是什么?

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.3.5/web3.min.js" integrity="sha512-S/O+gH5szs/+/dUylm15Jp/JZJsIoWlpSVMwT6yAS4Rh7kazaRUxSzFBwnqE2/jBphcr7xovTQJaopiEZAzi+A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script type="text/javascript">

let web3js;
function startApp() {            
var address = "...";
const jsoninterface = [

{
"inputs": [
{
"internalType": "string",
"name": "_newMessage",
"type": "string"
}
],
"name": "setMessage",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},

{
"inputs": [],
"name": "message",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
}
]
var newContract = new web3js.eth.Contract(jsoninterface, address);
if (typeof newContract === 'object' && typeof newContract !== 'undefined' && newContract !== null){
console.log("contract created")
} else {
console.log("contract not created")
}
}
window.addEventListener('load', function() {
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
// Use Mist/MetaMask's provider
web3js = new Web3(web3.currentProvider);
} else {
alert("Please install Metamask to continue");
// Handle the case where the user doesn't have Metamask installed
// Probably show them a message prompting them to install Metamask
}
// Now you can start your app & access web3 freely:
startApp();
console.log('startapp finished')
})
function showMessage(){
var retval = window.newContract.methods.message().call();
console.log(retval);
}
</script>
</head>
<body>
<!-- the content goes here -->
<button onclick="showMessage()">click here</button>
</body>
</html>

以下是控制台的输出:

contract created
startapp finished
Uncaught TypeError: Cannot read property 'message' of undefined
at showMessage ((index):132)
at HTMLButtonElement.onclick ((index):140)
showMessage @ (index):132
onclick @ (index):140

以下是智能合约代码:

pragma solidity >=0.7.0 <0.9.0;

contract HelloWorld {
string public message = "Hello World";
uint public counter = 0;

function setMessage(string calldata _newMessage) public {
message = _newMessage;
}

function incrementCounter() public {
counter++;
}
}

ABI JSON定义了一个setMessage()函数,但没有message属性(或函数(。如果您的合同中有message属性(或函数(,则它必须是externalpublic才能在合同之外可读。

在将属性或函数设置为外部或公共之后,您还需要重新生成ABI JSON。

问题确实是合同变量的范围,做出下面箭头所示的两个更改使我能够解决问题。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.3.5/web3.min.js" integrity="sha512-S/O+gH5szs/+/dUylm15Jp/JZJsIoWlpSVMwT6yAS4Rh7kazaRUxSzFBwnqE2/jBphcr7xovTQJaopiEZAzi+A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script type="text/javascript">

let web3js;
---------> var newContract;
function startApp() {            
var address = "...";
const jsoninterface = [

{
"inputs": [
{
"internalType": "string",
"name": "_newMessage",
"type": "string"
}
],
"name": "setMessage",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},

{
"inputs": [],
"name": "message",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
}
]
---------> window.newContract = new web3js.eth.Contract(jsoninterface, address);
if (typeof newContract === 'object' && typeof newContract !== 'undefined' && newContract !== null){
console.log("contract created")
} else {
console.log("contract not created")
}
}
window.addEventListener('load', function() {
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
// Use Mist/MetaMask's provider
web3js = new Web3(web3.currentProvider);
} else {
alert("Please install Metamask to continue");
// Handle the case where the user doesn't have Metamask installed
// Probably show them a message prompting them to install Metamask
}
// Now you can start your app & access web3 freely:
startApp();
console.log('startapp finished')
})
function showMessage(){
var retval = window.newContract.methods.message().call();
console.log(retval);
}
</script>
</head>
<body>
<!-- the content goes here -->
<button onclick="showMessage()">click here</button>
</body>
</html>

最新更新