不好意思還是新手,排版可能不美
想問我用solidity在Remix上試用Remix VM部屬合約,也用了個html網頁在自己電腦的VScode,html的ABI與合約地址是Remix編譯會出現的ABI,以及合約部屬後的地址,但是都串聯不了...html會出現以下錯誤訊息
Uncaught TypeError: contractInstance.methods.admin is not a function
at contract.html:334:34
contract.html:314 Uncaught (in promise) TypeError: contractInstance.methods.deployEvi is not a function
at deployEvi (contract.html:314:44)
at HTMLButtonElement.onclick (contract.html:17:35)
想問這是什麼意思,需要修改什麼
也想問問大家有沒有html串聯solidity的參考資料,找了好久都還是串不起來 > <
感謝大家!!
html碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clinical Trial Contract Interaction</title>
<script src="https://cdn.jsdelivr.net/npm/web3@1.5.0/dist/web3.min.js"></script>
</head>
<body>
<h1>Clinical Trial Contract Interaction</h1>
<div>
<h2>Contract Information</h2>
<p><strong>Admin:</strong> <span id="adminAddress"></span></p>
<p><strong>Contract Address:</strong> <span id="contractAddress"></span></p>
</div>
<script>
// 配置 Web3 提供者
const web3 = new Web3(Web3.givenProvider || 'http://localhost:7545');
// 合約 ABI
const abi = [
// Your ABI Here
];
// 合約地址
const contractAddress = 'Your Contract Address Here';
// 初始化合約實例
const contractInstance = new web3.eth.Contract(abi, contractAddress);
// 獲取並填充合約和管理員信息
contractInstance.methods.admin().call().then(admin => {
document.getElementById('adminAddress').textContent = admin;
document.getElementById('contractAddress').textContent = contractAddress;
});
</script>
</body>
</html>
这个方法是要在合约中写入的。
contractInstance.methods.admin()
比如我有一个合约:
contract Admin {
address private owner;
function Admin() public { owner = msg.sender; }
function getOwner() public returns (address) {
return owner;
}
function transfer(address to) public {
require(msg.sender == owner);
owner = to;
}
}
然后我需要一个ABI用于映射solidity:
[
{
"constant": false,
"inputs": [],
"name": "getOwner",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "to",
"type": "address"
}
],
"name": "transfer",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}
]
最后在js中调用:
const contract = new web3.eth.Contract(abi, contractAddress);
contract.methods.getOwner().call((error, result) => {
if (!error) {
console.log("Owner address:", result);
} else {
console.error("Error:", error);
}
});
其中:getOwner
与ABI中getOwner
与合约中getOwner
是1-1映射关系。