Skip to content

Commit

Permalink
Add autocheck network and write method for deploying contract
Browse files Browse the repository at this point in the history
  • Loading branch information
riadelimemmedov committed Mar 5, 2024
1 parent e17e9f4 commit 7a01c4f
Show file tree
Hide file tree
Showing 6 changed files with 131 additions and 30 deletions.
2 changes: 0 additions & 2 deletions blockchain/contracts/PetAdoption.sol
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

// import "hardhat/console.sol"; //If you want use console.log inside the smart contract you need to install hardhat

contract PetAdoption {
address public owner;
uint public petIndex = 0;
Expand Down
4 changes: 3 additions & 1 deletion blockchain/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@
"lint": "eslint",
"test": "npx hardhat test",
"coverage": "npx hardhat coverage",
"compile": "npx hardhat compile"
"compile": "npx hardhat compile",
"run_node": "npx hardhat node",
"deploy_localhost": "npx hardhat run scripts/deploy.js --network localhost"
},
"dependencies": {
"ganache-cli": "^6.12.2"
Expand Down
45 changes: 45 additions & 0 deletions blockchain/scripts/deploy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/* eslint-disable no-undef */
const hre = require("hardhat")
const fs = require("fs")

// !main
async function main(){
console.log("Deployment started...")

const [deployer] = await hre.ethers.getSigners()
const address = await deployer.getAddress()

console.log(`Deploying the contract with the account ${address}`)

const PETS_COUNT = 5
const PetAdoption = await hre.ethers.getContractFactory("PetAdoption")
const contract = await PetAdoption.deploy(PETS_COUNT)

//Get sender user addresss,well you know who deploy that is contract
const receipt = await contract.deployTransaction.wait()// Line of code is waiting for the deployment transaction to be included in six blocks on the Ethereum blockchain. This is done to ensure that the transaction has sufficient confirmations, which helps to ensure the transaction will not be reversed.

// Set essential contract information to json file
await setDeployContract(contract.interface.format("json"),contract.address,hre.network.name,receipt.from)
}

// ?call the main function and check contract is successfully deployed or not
main().catch(error => {
console.error(error)
process.exitCode = 1
})


//!setDeployContract
async function setDeployContract(abi,address,network,receipt) {
const contractData = {abi,address,"network":hre.network.name,"deployer":receipt}
if(network == "localhost"){
const filePath = "../frontend/contract-ui/contracts/PetLocal.json"
fs.writeFileSync(filePath,JSON.stringify(contractData))
console.log("Our contract deployed --- LOCALHOST ---")
}
else{
const filePath = "../frontend/contract-ui/contracts/PetProd.json"
fs.writeFileSync(filePath,JSON.stringify(contractData))
console.log("Our contract deployed --- PROD ---")
}
}
1 change: 1 addition & 0 deletions frontend/contract-ui/contracts/PetLocal.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"abi":"[{\"type\":\"constructor\",\"payable\":false,\"inputs\":[{\"type\":\"uint256\",\"name\":\"initialPetIndex\"}]},{\"type\":\"function\",\"name\":\"addPet\",\"constant\":false,\"payable\":false,\"inputs\":[],\"outputs\":[]},{\"type\":\"function\",\"name\":\"addToCart\",\"constant\":false,\"payable\":false,\"inputs\":[{\"type\":\"uint256\",\"name\":\"_petId\"},{\"type\":\"string\",\"name\":\"_petName\"},{\"type\":\"string\",\"name\":\"_petColor\"},{\"type\":\"uint256\",\"name\":\"_petPrice\"},{\"type\":\"string\",\"name\":\"_petPhoto\"}],\"outputs\":[]},{\"type\":\"function\",\"name\":\"adoptPet\",\"constant\":false,\"payable\":false,\"inputs\":[{\"type\":\"uint256\",\"name\":\"adoptIdx\"}],\"outputs\":[]},{\"type\":\"function\",\"name\":\"allAdoptedPets\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[{\"type\":\"uint256\"}],\"outputs\":[{\"type\":\"uint256\"}]},{\"type\":\"function\",\"name\":\"getAllAdoptedPets\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"uint256[]\"}]},{\"type\":\"function\",\"name\":\"getAllAdoptedPetsByOwner\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"uint256[]\"}]},{\"type\":\"function\",\"name\":\"getCartItems\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"tuple[]\",\"components\":[{\"type\":\"uint256\",\"name\":\"id\"},{\"type\":\"string\",\"name\":\"name\"},{\"type\":\"string\",\"name\":\"color\"},{\"type\":\"uint256\",\"name\":\"price\"},{\"type\":\"string\",\"name\":\"photo\"}]}]},{\"type\":\"function\",\"name\":\"getOwner\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"address\"}]},{\"type\":\"function\",\"name\":\"owner\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"address\"}]},{\"type\":\"function\",\"name\":\"ownerAddressToPetList\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[{\"type\":\"address\"},{\"type\":\"uint256\"}],\"outputs\":[{\"type\":\"uint256\"}]},{\"type\":\"function\",\"name\":\"petIdxToOwnerAddress\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[{\"type\":\"uint256\"}],\"outputs\":[{\"type\":\"address\"}]},{\"type\":\"function\",\"name\":\"petIndex\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"uint256\"}]}]","address":"0x8A791620dd6260079BF849Dc5567aDC3F2FdC318","network":"localhost","deployer":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"}
92 changes: 78 additions & 14 deletions frontend/contract-ui/src/Dapp.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,88 @@ import reactLogo from './assets/react.svg'
import { PetItem } from './components/Petitem'
import { TxError } from './components/TxError'
import { Navbar } from './components/Navbar'
import { toast } from 'react-toastify'

// HARDHAT_NETWORK_ID
const HARDHAT_NETWORK_ID = Number(import.meta.env.VITE_VUE_HARDHAT_NETWORK_ID)

//*Dapp
function Dapp() {
//return jsx to client
return (
<>
<div className="container">
{/*<TxError/>*/}
<br />
<div className="navbar-container">
<Navbar/>
</div>
<div className="items">
<PetItem/>
const [selectedAddress,setSelectedAddress] = useState(null)

// ?isAuthenticated
const isAuthenticated = async () => {
const provider = window.ethereum
if (typeof provider !== 'undefined') {
let accounts = await provider.request({method: "eth_requestAccounts"})
return true
} else {
toast.error("MetaMask is not installed");
return false
}
}

// ?checkNetwork
const checkNetwork = async () => {
if (window.ethereum.networkVersion !== HARDHAT_NETWORK_ID.toString()) {
if (await switchNetwork()) {
return true;
} else {
return false;
}
}
return true
}


// ?switchNetwork
const switchNetwork = async () => {
const chainIdHex = `0x${HARDHAT_NETWORK_ID.toString(16)}` //Convert to 16 based hexadecimal chainIdHex number
if(await isAuthenticated()){
try {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: chainIdHex }],//Only accept hex number
})
return true
} catch (error) {
toast.error("Switching to the network failed")
return false
}
}
else{
return false
}
}

// ?initializeDapp
const initializeDapp = async (address) => {
if (await isAuthenticated()) {
setSelectedAddress(address)
const contract = await initContract()
}
}

// ?initContract
const initContract = async () => {
toast.success("I should init the contract !")
}

//return jsx to client
return (
<>
<div className="container">
{/*<TxError/>*/}
<br />
<div className="navbar-container">
<Navbar/>
</div>
<div className="items">
<PetItem isAuthenticated={isAuthenticated} checkNetwork={checkNetwork}/>
</div>
</div>
</div>
</>
)
</>
)
}

export default Dapp
17 changes: 4 additions & 13 deletions frontend/contract-ui/src/components/Petitem.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ToastContainer, toast } from 'react-toastify';
import InfiniteScroll from 'react-infinite-scroll-component';

//*PetItem
export function PetItem(){
export function PetItem({isAuthenticated,checkNetwork}){
const [petData,setPetData] = useState([])
const [hasMore,setHasMore] = useState(true)
const [page,setPage] = useState(1)
Expand All @@ -18,6 +18,7 @@ export function PetItem(){
}, 1500);
},[page])


// ?getPetData
const getPetData = async () => {
const apiUrl = `${url}/pets/?page=${page}`
Expand All @@ -40,21 +41,11 @@ export function PetItem(){
}
}

// ?isAuthenticated
const isAuthenticated = async () => {
const provider = window.ethereum
if (typeof provider !== 'undefined') {
let accounts = await provider.request({method: "eth_requestAccounts"})
return true
} else {
toast.error("MetaMask is not installed");
return false
}
}

//? addToCart
const addToCart = async () => {
const is_auth = await isAuthenticated()
const is_auth = await checkNetwork()
console.log("Add to carttt ", is_auth)
if (is_auth){
toast.success('Added to cart successfully')
}
Expand Down

0 comments on commit 7a01c4f

Please sign in to comment.