区块链投票应用:使用solidity+truffle+metamsk开发Dapp应用

本文档记录了学习Dapp开发的过程,包括安装Ganache和Truffle,编写投票智能合约,创建项目,部署合约,修改迁移脚本,编译和部署合约,设置网络配置,编写前端界面并实现与区块链的交互。同时,介绍了如何使用Metamask进行账户管理和投票操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考教程:https://www.bilibili.com/video/BV14z4y1Z7Jd?p=8
本博客是学习Dapp开发过程的笔记,感谢令狐一冲老师精彩讲解。上述是老师B站视频链接。

Ganache

ganache是一个本地区块链环境,每次启动后会在内存中模拟一个区块链。

1.环境安装

1.安装Node.js

2.安装 ganache-cli(ganache也可以)

3.运行ganache

ganache-cli

!!Truffle

安装truffle

sudo npm install -g truffle

安装过程中可能出错,可能解决方式

//升级node.js
sudo npm install -g n
sudo n stable

安装完成之后检查安装

truffle -v  //版本

开发DApp(投票为例)

1.编写智能合约

投票合约

// SPDX-License-Identifier: SimPL-2.0
pragma solidity >=0.4.18 <0.8.0;

contract Voting{
   
    bytes32[] public candodateList;
    mapping(bytes32 => uint8) public votesReceived;
    
    
    constructor(bytes32[] memory _candidateListName) public {
   
        candodateList = _candidateListName;
    }
    
    function validateCan(bytes32 _candidate) internal view returns(bool) {
   
        for(uint8 i = 0; i< candodateList.length; i++) {
   
            if(candodateList[i] == _candidate)
                return true;
        }
        return false;
    }
     
    function voteForCan(bytes32 _candidate) public {
   
        votesReceived[_candidate] += 1;
    }
    
    function totalVotes(bytes32 _candidate)public view returns(uint8) {
   
        return votesReceived[_candidate];
    }
}

2.创建项目

mkdir Voting
cd Voting

truffle unbox webpack
//webpack 可以换成其他的模板文件,也可以换成init不用模板

//遇到问题了,
/*
✔ Preparing to download box
✖ Downloading
Unbox failed!
✖ Downloading
Unbox failed!
Error: Error connecting to github.com. Please check your internet connection and try again.
*/
//也可以通过如下方式获取
git clone https://github.com/truffle-box/webpack-box.git
$ cd truffle-init-webpack

3.修改合约部署脚本

1.启动ganache

删除模板里其他合约,将自己的合约部署到ganache上

2.修改合约部署脚本

修改migration中的2_deploy+contract.js(照着葫芦画瓢)

// const ConvertLib = artifacts.require("ConvertLib");
// const MetaCoin = artifacts.require("MetaCoin");
const Voting = artifacts.require("Voting"
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值