我开始从事一个简单的项目,我在区块链方面没有太多经验。我想使用JavaScript连接到Solidity合约。连接合同并获取地址是可行的,但当我调用getInfo时,我会收到以下错误:
Uncaught (in promise) Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.
以下是代码。合同:
pragma solidity ^0.8.0; contract NFT { uint256 id; string name; string description; address owner; constructor(uint256 _id, string memory _name, string memory _description) public { id = _id; name = _name; description = _description; owner = msg.sender; } function transfer(address newOwner) public { require(msg.sender == owner, "Only the owner can transfer the NFT"); owner = newOwner; } function getInfo() public view returns (uint256, string memory, string memory, address) { return (id, name, description, owner); } function getAddress() external view returns(address) { return address(this); } }
JavaScript代码:
const connectContract = async () => { const contractAbi = [ { "inputs": [ { "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "transfer", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "_id", "type": "uint256" }, { "internalType": "string", "name": "_name", "type": "string" }, { "internalType": "string", "name": "_description", "type": "string" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [], "name": "getAddress", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "getInfo", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" }, { "internalType": "string", "name": "", "type": "string" }, { "internalType": "string", "name": "", "type": "string" }, { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" } ]; // the ABI of the NFT contract const contractAddress = "0xd9145CCE52D386f254917e481eB44e9943F39138"; // the address of the deployed NFT contract window.web3 = await new Web3(window.ethereum); window.contract = await new window.web3.eth.Contract(contractAbi, contractAddress); document.getElementById("contractArea").innerHTML = "Connected to Contract"; web3.eth.getAccounts(console.log); } const getInfo = async () => { const info = await contract.methods.getInfo().call().then(console.log); } async function main() { const contract = new web3.eth.Contract(contractAbi, contractAddress); // Transfer the NFT to a new owner const newOwner = "0x9F0cF368555c299184735EE48Ca2e7ae51b324E5"; const receipt = await contract.methods.transfer(newOwner).send({ from: web3.eth.defaultAccount }); console.log(receipt); }
这是与智能合约连接的正确方式吗?我错过了什么?