vite+reacr 实现 web3 的 DAPP项目(1)-项目初始化

发布时间 2023-09-03 00:27:55作者: to人间值得

安装 React 及 Hardhat

mkdir ArtistStudio 
cd ArtistStudio

pnpm create vite artist-studio --template react
cd artist-studio

npx hardhat
# 剩下的默认回车

使用 React 及 Hardhat

npx hardhat node # 启动本地 hardhat 网络

# 另开命令行页面执行
npx hardhat compile # 编译
npx hardhat test --network localhost # 执行测试,在本地网络
npx hardhat run ./scripts/deploy.js  --network localhost # 部署合约,在本地网络

# 运行 react 项目
npm run dev 

连接钱包

/src/App.jsx

```jsx
import { BrowserProvider } from 'ethers'
import './App.css'

function App() {
  const connectWallet = async () => {
    if (!window.ethereum) {``
      alert('Please install MetaMask')
      return
    }

    const provider = new BrowserProvider(window.ethereum)
    const signer = provider.getSigner()
  }
  return (
    <>
      <button onClick={connectWallet}>Connect Wallet</button>
    </>
  )
}

export default App
```

点击 `Connect Wallet` 后,选择账号连接

![](https://img2023.cnblogs.com/blog/1502439/202309/1502439-20230903001859564-490817114.png)