繁体   English   中英

如何连接松露合约与 ReactJS?

[英]How to connect truffle contract with ReactJS?

我已经签订了一个彩票合同,现在我想将它连接到我将使用 ReactJS 创建的前端。 我已经使用 Truffle 框架来部署和测试我的合同。

      npm i @truffle/contract

然后在 utils/loadContract 中:

import contract from "@truffle/contract"

export const loadContract = async (name, provider) => {
  // in truffle, contracts are in "contracts" directory
  const res = await fetch(`/contracts/${name}.json`)
  const Artifact = await res.json()
  const _contract = contract(Artifact)
  _contract.setProvider(provider)

  let deployedContract = null
  try {
    deployedContract = await _contract.deployed()
  } catch {
    console.error("You are connected to the wrong network")
  }
  return deployedContract
}

然后在 app.jsx 中加载合约。 第一的:

  npm i @metamask/detect-provider

然后在 app.js 中编写你的代码

import detectEthereumProvider from '@metamask/detect-provider'
import { loadContract } from "./utils/load-contract";
import {useEffect, useState } from "react";


 const [web3Api, setWeb3Api] = useState({
    provider: null,
    isProviderLoaded: false,
    web3: null,
    contract: null
  })

 // call this function inside useEFfect, if user connects to different account, you will update it
 const setAccountListener = provider => {
    provider.on("accountsChanged", _ => window.location.reload())
    provider.on("chainChanged", _ => window.location.reload())
  }

// useEffect is called before your component loaded
// load the contract, set the state, so when your compoent loaded, your state will be ready
useEffect(() => {
    const loadProvider = async () => {
      // if Metamask installed, this will detect its provider
      const provider = await detectEthereumProvider()
      // load the contract if provider exists
      if (provider) {
        // Lottery is not name of the file, it is NAME OF CONTRACT
        const contract = await loadContract("Lottery", provider)
        setAccountListener(provider)
        setWeb3Api({
          web3: new Web3(provider),
          provider:provider,
          // Now you set the contract. 
          // when your app.js loaded you will be able to call contract methods
          contract:contract,
          isProviderLoaded: true
        })
      } else {
        setWeb3Api(api => ({...api, isProviderLoaded: true}))
        console.error("Please, install Metamask.")
      }
    }

    loadProvider()
  }, [])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM