【区块链】以太坊truffle+web3+ganache简单实践

以太坊truffle+web3+ganache简单实践

安装

  • 下载最新版nodejs
  • npm install -g truffle
  • 下载ganache

帮助文档

https://www.trufflesuite.com/docs/truffle/getting-started/installation
https://web3js.readthedocs.io/en/v1.2.9/web3-eth-abi.html
https://github.com/ethereum/web3.js

结构

在这里插入图片描述

代码

solidity代码


pragma solidity ^0.5.0;

contract Auction {
    // 受益者
    address payable public benefitAddr;

    // 拍卖时间
    uint public startTime;
    uint public endTime;
    uint public remainTime;

    // 是否结束
    bool public hasBid = false;

    // 现在的最高价
    string public bidderId = "";
    uint public highestPrice;
    address public highestBidder;

    // 当前商品
    string public currentBid = "";

    // 存储历史出价记录
    mapping(address => uint) pendingResults;

    function startAuction(string memory bidName) public returns(bool) {
        // 检查现在是否正在拍卖
        require(hasBid != true);

        uint _bidTime = 300000;

        benefitAddr = msg.sender;

        // 设定时间
        startTime = now;
        startTime = now + _bidTime;
        remainTime = _bidTime;
        // 设定拍卖品
        currentBid = bidName;

        // 设定当前拍卖价格
        highestPrice = 0;
        highestBidder = address(0);

        hasBid = true;

        return true;
    }

    function bid(string memory _bidderId) public payable{
        // 如果出价最高就执行拍卖
        require(msg.value > highestPrice);

        highestBidder = msg.sender;
        highestPrice = msg.value;

        bidderId = _bidderId;

        if(highestPrice != 0){
            pendingResults[highestBidder] += highestPrice;
        }

    }

    function endAuction() public {
        // 合约是没有定时的
        // 验证拍卖时间,谁可以结束拍卖
        hasBid = false;
        currentBid = '';

        benefitAddr.transfer(highestPrice);

    }

    function getInfo() public view returns (string memory, uint){
        return (bidderId, highestPrice);
    }


    // 没拍到的退款
    function withdraw() public returns (bool){
        uint amount = pendingResults[msg.sender];
        require(amount > 0);

        if(amount > 0){
            pendingResults[msg.sender] = 0;

            if (!msg.sender.send(amount)){
                pendingResults[msg.sender] = amount;
                return false;
            }
        }
        return true;
    }
}

html

<html>
<head>
    <title>第一个智能合约</title>
    <meta charset="UTF-8">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
</head>
<body>
用户id: <input type="text" id="userId" value="2"/> <br/>
账户: <input type="text" id="account" value="0xCFE84e7D2262fedb2C5Dd30D2d9746a211CD5Abd"/> <br/>
出价:<input type="text" id="ethe" value="3"/> <br/>
<button id="setInfo">设定</button><br/>
<button id="getInfo">获取</button><br/>
当前值: <div id="curInfo"></div>
</body>

<script>
    $(function() {
        var currentProvider = new Web3.providers.HttpProvider('http://localhost:7545');
        var web3 = new Web3(currentProvider);

        // var fs = require('fs');

        // var squadJSON = JSON.parse(fs.readFileSync('./build/contracts/Auction.json', 'utf8'));
        // var abi = squadJSON.abi;
        // console.log(abi);
        var address = '0xCFE84e7D2262fedb2C5Dd30D2d9746a211CD5Abd';

        // console.log(Auction);

        var simpleAuction = new web3.eth.Contract(<你得编译后的合约>, '0x44B5E9f98d61eC4B7918fDAC8C9bC57e360d57EA');
        // 注意这个合约的地址不是什么账户地址,migrate后的地址
        simpleAuction.setProvider(currentProvider);


        simpleAuction.methods.startAuction("华为手机").send({from:address,gas:200000});


        $("#setInfo").click(function() {
            var userId = String($("#userId").val());
            var acc1 = String($("#account").val());
            var ethe = String($("#ethe").val());

            console.log(ethe);
            // simpleAuction.methods.bid(2).call({from:acc1});
            simpleAuction.methods.bid(userId).send({from:acc1, value:web3.utils.toWei(ethe,"ether"), gas:200000});
            // simpleAuction.methods.bid(userId).send({from:acc1, value:ethe, gas:200000});
            // simpleAuction.methods.bid().send({from:'0x90ba5323772524c7E423184545b9dE72B9Bd65D3', value:web3.utils.toWei(ethe,"ether")});

            // simpleAuction.methods.getInfo().call({gas:1000000}).then(function(result){
            //     console.log(result);
            //     $("#curInfo").text("highestPrice =>" + result);
            // });
            // simpleAuction.methods.getInfo().send({from:acc1, gas:1000000}).then(console.log());


        });
        $("#getInfo").click(function() {
            simpleAuction.methods.getInfo().call({gas:200000}).then(function(result){
                console.log(result);
                $("#curInfo").text("highestPrice =>" + web3.utils.fromWei(result[1],"ether"));
            })
        });
    });



</script>
</html>

注意

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue + Truffle是一种常用的组合,用于创建以太坊Dapp(去中心化应用程序)。Vue是一个流行的JavaScript框架,用于构建用户界面,而Truffle是一个用于开发以太坊智能合约的开发框架。结合使用Vue和Truffle可以轻松地构建具有交互性和响应性的以太坊Dapp。 以下是使用Vue + Truffle创建以太坊Dapp的步骤: 1. 安装TruffleGanacheTruffle是一个用于开发以太坊智能合约的开发框架,而Ganache是一个用于在本地开发和测试以太坊应用程序的个人区块链。 ```shell npm install -g truffle npm install -g ganache-cli ``` 2. 创建一个新的Truffle项目: 在命令行中,进入你想要创建项目的目录,并执行以下命令: ```shell truffle init ``` 3. 创建一个新的Vue项目: 在命令行中,进入你想要创建项目的目录,并执行以下命令: ```shell vue create my-dapp ``` 4. 配置Truffle项目: 在Truffle项目的根目录下,打开truffle-config.js文件,并进行以下配置: - 配置网络:将网络配置为连接到Ganache个人区块链。 - 配置合约:将合约编译和部署到以太坊网络。 5. 编写智能合约: 在Truffle项目的contracts目录下,编写你的智能合约。 6. 编写Vue组件: 在Vue项目的src目录下,编写你的Vue组件,用于与智能合约进行交互。 7. 部署智能合约: 在命令行中,进入Truffle项目的根目录,并执行以下命令来部署智能合约: ```shell truffle migrate ``` 8. 运行Vue项目: 在命令行中,进入Vue项目的根目录,并执行以下命令来运行Vue项目: ```shell npm run serve ``` 现在,你已经成功地使用Vue + Truffle创建了一个以太坊Dapp。你可以在Vue组件中调用智能合约的方法,并与以太坊网络进行交互。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值