基於區塊鏈開發的畢業設計衆籌DAPP核心源碼

 

pragma solidity >=0.4.21 <0.7.0;


contract Crowdfunding {
    // author
    address public author;

    // joined amount
    mapping(address => uint) public joined;

    // crowdfunding target
    uint constant Target = 10 ether;

    uint public endTime;

    // record current crowdfunding price
    uint public price  = 0.02 ether ;

    // end crowdfunding, after author withdraw funds
    bool public closed = false;

    // address[] joinAccouts;
    event Join(address indexed user, uint price);

    constructor() public {
        author = msg.sender;
        endTime = now + 30 days;
    }

    // update price
    function updatePrice() internal {
        uint rise = address(this).balance / 1 ether * 0.002 ether;
        price = 0.02 ether + rise;
    }

    function () external payable {
        require(now < endTime && !closed  , "衆籌已結束");
        require(joined[msg.sender] == 0 , "你已經參與過衆籌");

        require (msg.value >= price, "出價太低了");
        joined[msg.sender] = msg.value;
        
        updatePrice();
        
        emit Join(msg.sender, msg.value);     //  48820  gas
        // joinAccouts.push(msg.sender);   // 88246  gas 
    } 

    // author withdraw funds
    function withdrawFund() external {
        require(msg.sender == author, "你不是作者");
        require(address(this).balance >= Target, "未達到衆籌目標");
        closed = true;   
        msg.sender.transfer(address(this).balance);
    }

    // reader withdraw funds
    function withdraw() external {
        require(now > endTime, "還未到衆籌結束時間");
        require(!closed, "衆籌達標,衆籌資金已提取");
        require(Target > address(this).balance, "衆籌達標,你沒法提取資金");
        
        msg.sender.transfer(joined[msg.sender]);
    }

}
<template>
<div class="content">
  <h3> 新書衆籌</h3>
  <span>以最低的價格獲取我的新書 </span>

  <!-- 衆籌的總體狀態  -->
  <div class="status">
    <div v-if="!closed">已衆籌資金:<b>{{ total }} ETH </b></div>
    <div v-if="closed"> 衆籌已完成 </div>
    <div>衆籌截止時間:{{ endDate }}</div>
  </div>

  <!-- 當讀者參與過,顯示如下div  -->
  <div v-if="joined" class="card-bkg">
    <div class="award-des">
      <span> 參與價格 </span>
      <b> {{ joinPrice }} ETH </b>
    </div>

    <button :disabled="closed" @click="withdraw">贖回</button>
  </div>

  <!--  當讀者還未參與時,顯示如下div  -->
  <div v-if="!joined" class="card-bkg">
    <div class="award-des">
      <span> 當前衆籌價格 </span>
      <b> {{ price }} ETH </b>
    </div>

    <button :disabled="closed" @click="join">參與衆籌</button>
  </div>

  <!--  如果是創作者,顯示 -->
  <div class="box" v-if="isAuthor">
    <div >
      <p v-bind:key="item" v-for="item in joinList" >
        <label> 地址:{{ item.address.substring(0, 30) + "..."  }} </label>
        金額:<b> {{ item.price }} </b>
      </p>
    </div>

    <button :disabled="closed" @click="withdrawFund"> 提取資金</button>
  </div>

</div>
</template>

<script>
import Web3 from "web3";
import contract from "truffle-contract";
import crowd from '../../build/contracts/Crowdfunding.json';
import axios from 'axios'

export default {
  name: 'CrowdFund',
  // 定義上面HTML模板中使用的變量
  data() {
    return {
      price: null,
      total: 0,
      closed: true,
      joinPrice: null,
      joined: false,
      endDate: "null",
      isAuthor: true,

      joinList: [],
    }
  },

    // 當前Vue組件被創建時回調的hook 函數
  async created() {
    await this.initWeb3Account()
    await this.initContract()
    await this.getCrowdInfo()
    this.getJoins()
  },

  methods: {

    // 初始化 web3及賬號
    async initWeb3Account() {
      if (window.ethereum) {
        this.provider = window.ethereum;
        try {
          await window.ethereum.enable();
        } catch (error) {
          //   console.log("User denied account access");
        }
      } else if (window.web3) {
        this.provider = window.web3.currentProvider;
      } else {
        this.provider = new Web3.providers.HttpProvider("http://127.0.0.1:7545");
      }
      this.web3 = new Web3(this.provider);

      this.web3.eth.getAccounts().then(accs  => {
        this.account = accs[0]
      })
    },

    //  初始化合約實例
    async initContract() {
      const crowdContract = contract(crowd)
      crowdContract.setProvider(this.provider)
      this.crowdFund = await crowdContract.deployed()
    },

    // 獲取合約的狀態信息
    async getCrowdInfo() {

      // 獲取合約的餘額
      this.web3.eth.getBalance(this.crowdFund.address).then(
        r => {
          this.total = this.web3.utils.fromWei(r)
        }
      )

      // 獲取讀者的參與金額, joined 在合約中是public 的狀態變量,自動生成相應的訪問器函數
      this.crowdFund.joined(this.account).then(
        r => {
          if (r > 0) {
            this.joined = true
            this.joinPrice = this.web3.utils.fromWei(r)
          }
        }
      )

     // 獲取合約的關閉狀態
      this.crowdFund.closed().then(
        r => this.closed = r
      )

      // 獲取當前的衆籌價格
      this.crowdFund.price().then(
        r => this.price = this.web3.utils.fromWei(r)
      )

      // 獲取衆籌截止時間
      this.crowdFund.endTime().then(r => {
        var endTime = new Date(r * 1000)
        // 把時間戳轉化爲本地時間
        this.endDate = endTime.toLocaleDateString().replace(/\//g, "-") + " " + endTime.toTimeString().substr(0, 8);
      })

      // 獲取衆籌創作者地址
      this.crowdFund.author().then(r => {
        if (this.account == r) {
          this.isAuthor = true
        } else {
          this.isAuthor = false
        }
      })

    },

    // 讀者點擊參與衆籌時調用
    join() {
      this.web3.eth.sendTransaction({
        from: this.account,
        to: this.crowdFund.address,
        value: this.web3.utils.toWei(this.price)
      }).then(() =>
        this.getCrowdInfo()
      )
    },

    withdraw() {
      this.crowdFund.withdraw({
        from: this.account
      }).then(() => {
        this.getCrowdInfo()
      })
    },

    withdrawFund() {
      this.crowdFund.withdrawFund({
        from: this.account
      }).then(() => {
        this.getCrowdInfo()
      })
    },

    // 獲取衆籌列表
    getJoins() {
      axios.get('http://localhost:3000/joins')
        .then(response => {
          this.joinList = response.data
        })
        .catch(function (error) { // Ajax請求失敗處理
          console.log(error);
        });
    },

  }
}
</script>

<style scoped>
.content {
  font-size: 187 px;
}

.status {
  margin: 20px;
}

.card-bkg {
  margin: 10px;
  display: flex;
  justify-content: space-between;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  border-radius: 5px;
  padding: 11px;
}


.award-des {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.award-des span {
  font-size: 12px;
}

.award-des b {
  font-size: 16px;
}

button {
  display: inline-block;
  line-height: 1;
  border-radius: 4px;
  padding: 12px 20px;
  white-space: nowrap;
  font-weight: 500;
  border: 1px solid #dcdfe6;
}

.box {
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  border-radius: 5px;
  padding: 11px;
  margin: 10px;
}


</style>

安裝依賴庫

yarn install

Compiles and hot-reloads for development

yarn serve

Compiles and minifies for production

yarn build

Lints and fixes files

yarn lint

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章