【发布时间】:2022-01-04 08:26:51
【问题描述】:
我正在尝试从nuxt.js 应用程序连接元掩码
我做的是这样的
1.yarn truffle init
2.make contract/SingleNumRegister.sol
pragma solidity ^0.8.10;
contract SingleNumRegister{
struct StoreNumber{
address from;
uint256 number;
}
StoreNumber[] public storeNumbers;
function set(uint256 num) public {
storeNumbers.push(StoreNumber(msg.sender,num));
}
function get() public view returns(uint256){
uint256 index = storeNumbers.length -1;
return storeNumbers[index].number;
}
}
3.yarn truffle build 它使/build/contracts/SingleNumRegister.json
4.make migrations/2_deploy_contract.js
const SingleNumRegister = artifacts.require('SingleNumRegister')
module.exports = function(deployer){
deployer.deploy(SingleNumRegister)
}
5.将truffle-cinfig.js更改为我的本地Ganache
networks: {
development: {
host: "127.0.0.1", // Localhost (default: none)
port:7545, // Standard Ethereum port (default: none)
network_id: "*", // Any network (default: none)
},
6.yarn truffle deploy -> 部署成功。
然后,我正在尝试使用此脚本plugins/web3.js 访问。
import Web3 from "web3"
import artifacts from "~~/build/contracts/SingleNumRegister.json"
export default async function(context,inject){
let web3;
if (typeof window != 'undefined' && typeof window.ethereum != 'undefined'){
web3 = new Web3(window.ethereum)
window.ethereum.enable().catch((error) =>{
console.log(error)
})
}else if (
typeof window !== 'undefined' &&
typeof window.web3 !== 'undefined'
){
web3 = new Web3(window.web3.currentProvider)
}else {
const httpEndpoint = "http://127.0.0.1:7545"
web3 = new Web3(new Web3.providers.HttpProvider(httpEndpoint))
inject('web3',web3)
}
let networkId = await web3.eth.net.getId()
console.log("networkId:"+ networkId);
let contract = new web3.eth.Contract(
artifacts.abi,
artifacts.networks[networkId].address
)
inject('web3',web3)
inject('contract',contract)
}
它显示错误client.js:227 TypeError: Cannot read properties of undefined (reading 'address')
在SingleNumRegister.json 中,没有网络数据。
这个文件是在进程2 上创建的,我没有为此做任何事情。
"networks": {},
"schemaVersion": "3.4.4",
"updatedAt": "2022-01-04T08:12:18.731Z",
"devdoc": {
"kind": "dev",
"methods": {},
"version": 1
},
正确吗?或者我应该在哪里修复???
【问题讨论】:
标签: javascript nuxt.js blockchain smartcontracts metamask