How to conduct crowdfunding (ICO) through Ethereum smart contract

We’ve written twice about how to issue tokens, but today we’ll talk about how to use tokens for public fundraising, namely writing a fundraising contract.

Writing in the front

The tokens mentioned in this article are created using Ethereum smart contracts. Before reading this article, you should have some understanding of Ethereum and smart contracts. If you don’t already, I suggest you read what Ethereum is first

The raise

A quick word about the concept of crowdfunding: It usually goes something like this: I have a really good idea, but I don’t have the money to do it, so I send it out and I say: I need $5 million to do this, if you are interested in putting in some money, if you put in $5 million in 30 days, I will do it, and then you will all be original shareholders, and if you raise less than $5 million, you will get your money back.

Now ICO crowdfunding has been used by various tycoons to cut leek and play bad (regardless of whether or not the standard, take the money).

In fact, blockchain technology is very suitable for solving the trust problem of crowdfunding. With the help of smart contracts, when the amount of fundraising is completed, the funds can be automatically transferred to the designated account, and when the amount of fundraising is not completed, the funds can be refunded. This process does not depend on the character of the crowdfunding guru, and does not rely on third-party credit guarantees.

Tokens,

Traditional crowdfunding is usually not easy to trade after participation (it cannot be transferred to others after participation), but it is easy to trade through token participation. Participants in crowdfunding can buy and sell at any time, and when the crowdfunding project is implemented and completed, the feedback will be completely based on token holdings.

A has the technology to make A ring that can monitor health, and raises 200 million from the public. At the time of fundraising, 100 yuan corresponds to one token. It is agreed that after the ring is listed, the token holder can exchange one token for one ring. The ring’s development cycle is one year, so participants can trade their tokens at any time during the year before the ring goes on sale.

Crowdfunding smart contract code

Here’s how to implement a crowdfunded smart contract.


pragma solidity ^0.416.;

interface token {
    function transfer(address receiver, uint amount);
}

contract Crowdsale {
    address public beneficiary;  // The receiver after successful fundraising
    uint public fundingGoal;   // Amount of capital raised
    uint public amountRaised;   // Number of participants
    uint public deadline;      // Funding deadline

    uint public price;    // The exchange rate between token and Ethereum, how much is the token sold for
    token public tokenReward;   // The token to sell

    mapping(address= > uint256) public balanceOf;

    bool fundingGoalReached = false;  // Whether the crowdfunding has reached its goal
    bool crowdsaleClosed = false;   // Whether the crowdfunding is over

    /** * events can be used to track information **/
    event GoalReached(address recipient, uint totalAmountRaised);
    event FundTransfer(address backer, uint amount, bool isContribution);

    /** * constructor, set the related property */
    function Crowdsale(address ifSuccessfulSendTo, uint fundingGoalInEthers, uint durationInMinutes, uint finneyCostOfEachToken, address addressOfTokenUsedAsReward) {
            beneficiary = ifSuccessfulSendTo;
            fundingGoal = fundingGoalInEthers * 1 ether;
            deadline = now + durationInMinutes * 1 minutes;
            price = finneyCostOfEachToken * 1 finney;
            tokenReward = token(addressOfTokenUsedAsReward);   // Pass in the address of the published Token contract to create the instance
    }

    /** * Fallback function with no function name. * This function will be called */ when transferring money to contract
    function () payable {
        require(! crowdsaleClosed); uint amount = msg.value; balanceOf[msg.sender] += amount; amountRaised += amount; tokenReward.transfer(msg.sender, amount / price); FundTransfer(msg.sender, amount,true);
    }

    /** * defines a function modifier (similar to Python's decorator) * used to check for a precondition before a function is executed (the method will continue to be executed after it passes) * _ indicates code that continues to be executed **/
    modifier afterDeadline() { if (now >= deadline) _; }

    /** * This method uses the afterDeadline function modifier ** / to determine whether the crowdfunding goal has been achieved
    function checkGoalReached() afterDeadline {
        if (amountRaised >= fundingGoal) {
            fundingGoalReached = true;
            GoalReached(beneficiary, amountRaised);
        }
        crowdsaleClosed = true;
    }


    /** * When the financing target is completed, the financing fund will be sent to the receiver ** when the financing target is not completed, the refund will be executed ** /
    function safeWithdrawal() afterDeadline {
        if(! fundingGoalReached) { uint amount = balanceOf[msg.sender]; balanceOf[msg.sender] =0;
            if (amount > 0) {
                if (msg.sender.send(amount)) {
                    FundTransfer(msg.sender, amount, false);
                } else{ balanceOf[msg.sender] = amount; }}}if (fundingGoalReached && beneficiary == msg.sender) {
            if (beneficiary.send(amountRaised)) {
                FundTransfer(beneficiary, amountRaised, false);
            } else {
                //If we fail to send the funds to beneficiary, unlock funders balance
                fundingGoalReached = false; }}}}Copy the code

Deployment and Description

Before deploying this contract, we need to deploy a token contract. Please refer to the step-by-step guide to creating your own digital currency.

  1. To create a crowdfunding contract, we need to provide the following parameters: ifSuccessfulSendTo: fundingGoalInEthers: For convenience we only raise 3 ether durationInMinutes: finneyCostOfEachToken the price of each tokenUnit finneyAnd the value is: 1 (1 Mr = 1000 finney) addressOfTokenUsedAsReward: tokens contract address. Such as:

    The parameters used in this paper are:

"0xc6f9ea59d424733e8e1902c7837ea75e20abfb49", 3, 100, 1."0xad8972e2b583f580fc52f737b98327eb65d08f8c"
Copy the code
  1. Participants actually purchase crowdfunding contract tokens when investing, so they need to pre-deposit tokens into the contract. The number of tokens is: fundraising amount/price of tokens, which is: 3 * 1000/1 = 3000 (or greater than 3000 when possible). Pre-depositing tokens to the contract can be done using the MyetherWallet or by reloading the token contract in remix and performing the token contract tranfer() function to transfer tokens to the address where we created the contract. If you use MyetherWallet to transfer money, see the picture below:

  2. Investors participate in crowdfunding by transferring funds to crowdfunding contracts (sending Ethereum). When transferring funds, Fallback function (unknown function) will be executed to send corresponding tokens back to their accounts.

  3. A safe款 L () may be called by either a participant or a beneficiary. If a case is not sufficiently advanced, the participant may withdraw the funds previously invested, or if a case is sufficiently advanced, the beneficiary may withdraw all funds.

extension

It’s a very formal fundraising contract. Next, we’ll talk about two extensions to the fundraising contract, how to implement the unlimited fundraising contract and the cutting leek contract. This part of the content is exclusively published in my little column blockchain technology

How to create token issue tokens, now also recorded the corresponding video tutorial: through token science Ethereum smart contract development ** currently we are also recruiting experiential, you can click the link to learn.

If you have any problems in your study, welcome to my ** Knowledge planet ** to ask questions. As a benefit of planet members, members can join the blockchain technology paid communication group.

Reference documentation

  • Create a crowdsale

Dynamic And Simple Blockchain – Learn blockchain systematically and build the best blockchain technology blog.

Dynamic Planet Of My Knowledge answers blockchain technology questions. Welcome to join the discussion.

Aid To The Public account “Deep And Simple Blockchain Technology” To obtain blockchain technology information for the first time.