# Solidity

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

#### Solidity是什么？

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

### 几个简单的Solidity例子

#### 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
mapping (address => uint) public balances;

// Events allow light clients to react on
// changes efficiently.

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

if (msg.sender != minter) return;
}

if (balances[msg.sender] < amount) return;
balances[msg.sender] -= amount;
}
}


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

pragma solidity ^0.4.2;

contract Crowdsale4 {
uint public fundingGoal;
uint public amountRaised;
uint public price;

token public tokenReward;
bool public fundingGoalReached = false;
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 (
uint fundingGoalInEthers,
uint durationInMinutes,
uint etherCostOfEachToken,
) {
beneficiary = ifSuccessfulSendTo;
fundingGoal = fundingGoalInEthers * 1 ether;
deadline = now + durationInMinutes * 1 minutes;
price = etherCostOfEachToken * 1 ether;
}

/* 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);
}

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

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;
}
}
}
}