I am trying to connect meta mask from nuxt.js
application
What I have done is like this
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
it makes /build/contracts/SingleNumRegister.json
4.make migrations/2_deploy_contract.js
const SingleNumRegister = artifacts.require('SingleNumRegister')
module.exports = function(deployer){
deployer.deploy(SingleNumRegister)
}
5.change truffle-cinfig.js
for my local 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
-> deployment success.
Then, I am trying to access with this script 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)
}
it shows error client.js:227 TypeError: Cannot read properties of undefined (reading 'address')
in SingleNumRegister.json
, there is no data for networks.
this file is made at process 2
and I did nothing for this.
"networks": {},
"schemaVersion": "3.4.4",
"updatedAt": "2022-01-04T08:12:18.731Z",
"devdoc": {
"kind": "dev",
"methods": {},
"version": 1
},
Is it correct? or Where should I fix???
After compiling your contract with truffle compile
run
truffle migrate
and voila! You should have something like this,
"networks": {
"1641312206935": {
"events": {},
"links": {},
"address": "0xc447AFC10846f39540EF1e2CC6F35f91903d8f94",
"transactionHash": "0x06803935f6bb461092b748953ab556cef2d9ceb610761c67193eb1cf6f07f970"
}
},
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.