区块链学堂(3):Solidity

Solidity

在上一篇文章中,我们可以看到 pragma solidity 0.4.9;,

这里的Solidity,就是以太坊智能合约的核心语言Solidity,也是本教程的重点。

Solidity是什么?

Solidity是以太坊智能合约的编程语言,通过编译&部署智能合约,可以实现智能合约的Create、执行和查看,从而实现某些商业应用。

几个简单的Solidity例子

通过以下几个智能合约,我们可以将一些商业应用很好的区块链化,从而实现去中介、去信任、高度透明的商业模型。

在之后的整个教程中,我们会逐步解析Solidity编程,帮助大家快速掌握Solidity这门语言,并且将区块链落地到前端Web页面上

I 实现1+2+3+..+n的求和功能

pragma solidity 0.4.9;
contract Demo1 {
  /*计算从1到N的求和*/
  function f(uint n) returns (uint sum) {
    if (n == 0) throw; uint result = 0;
    for (uint i=0; i<=n; i++) {
      result +=i;
    }
    return result;
  }
}

II 实现一个代币功能,并自带挖矿和转移代币的功能。

pragma solidity ^0.4.0;

contract Coin {
    // The keyword "public" makes those variables
    // readable from outside.
    address public minter;
    mapping (address => uint) public balances;

    // Events allow light clients to react on
    // changes efficiently.
    event Sent(address from, address to, uint amount);

    // This is the constructor whose code is
    // run only when the contract is created.
    function Coin() {
        minter = msg.sender;
    }

    function mint(address receiver, uint amount) {
        if (msg.sender != minter) return;
        balances[receiver] += amount;
    }

    function send(address receiver, uint amount) {
        if (balances[msg.sender] < amount) return;
        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        Sent(msg.sender, receiver, amount);
    }
}

III 实现一个众筹的智能合约,各个用户可以筹款、筹款成功可以将所得转让给受益人,每个参与众筹者可以获得代币。

pragma solidity ^0.4.2;
contract token { function transfer(address receiver, uint amount){  } }

contract Crowdsale4 {
    address public beneficiary;
    uint public fundingGoal;
    uint public amountRaised;
    uint public deadline;
    uint public price;


    token public tokenReward;
    mapping(address => uint256) public balanceOf;
    bool public fundingGoalReached = false;
    event GoalReached(address beneficiary, uint amountRaised);
    event FundTransfer(address backer, uint amount, bool isContribution);
    bool public crowdsaleClosed = false;

    /* data structure to hold information about campaign contributors */

    /*  at initialization, setup the owner */
    function Crowdsale4 (
        address ifSuccessfulSendTo,
        uint fundingGoalInEthers,
        uint durationInMinutes,
        uint etherCostOfEachToken,
        token addressOfTokenUsedAsReward
    ) {
        beneficiary = ifSuccessfulSendTo;
        fundingGoal = fundingGoalInEthers * 1 ether;
        deadline = now + durationInMinutes * 1 minutes;
        price = etherCostOfEachToken * 1 ether;
        tokenReward = token(addressOfTokenUsedAsReward);
    }

    /* The function without name is the default function that is called whenever anyone sends funds to a contract */
    function () payable {
        if (crowdsaleClosed) throw;
        uint amount = msg.value;
        balanceOf[msg.sender] += amount;
        amountRaised += amount;
        tokenReward.transfer(msg.sender, amount / price);
        FundTransfer(msg.sender, amount, true);
    }

    modifier afterDeadline() { if (now >= deadline) _; }

    /* checks if the goal or time limit has been reached and ends the campaign */
    function checkGoalReached() afterDeadline {
        if (amountRaised >= fundingGoal){
            fundingGoalReached = true;
            GoalReached(beneficiary, amountRaised);
        }
        crowdsaleClosed = true;
    }


    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;
            }
        }
    }
}
Solidity的简介就到此为止了,后面我们会具体解析这些合约的奥秘
前面说过,智能合约是部署在以太坊的网络上的,那么如何搭建一个以太坊网络呢,就需要官方提供的工具Geth了。下一章会详细说明。

原文链接:http://www.ethchinese.com/?p=630



获取最新区块链咨询,请关注《以太中文网》微信公众号:以太中文网

展开阅读全文

没有更多推荐了,返回首页