智能合约Solidity学习(第一课)

@@@数学运算

加(+),减(-),乘(*),除(/), 取模(%),求方(**)

例子:

a ** b;  //a的b次方


@@@数组

分为固定数组与动态数组


// Array with a fixed length of 2 elements:

uint[2] fixedArray;

// another fixed Array, can contain 5 strings:

string[5] stringArray;

// a dynamic Array - has no fixed size, can keep growing:

uint[] dynamicArray;


@@@结构体struct

struct Person {

uint age;
string name;
}


//数组定义
Person[] public people;

//创建一个结构体实例
Person satoshi = Person(172, "tester");
//将实例元素加入数组中
people.push(tester);


@@@ 函数修饰符

public :  提供给合约外部调用,当然内部也可以调用

private : 合约内部调用,外部不可访问。


@@@ function 修改符 

view  :方法体里只是查看合约内的数据,不会进行任何修改

pure :方法体里既不修改也不查看合约内的数据,只是进行非合约数据相关的操作

例如:

function sayHello() public  view returns (string) {}

function _multiply(uint a, uint b) private  pure returns (uint) {
  return a * b;
}

@@@数据类型转换

uint8 a = 5;

uint b = 6;

// throws an error because a * b returns a uint, not uint8:
uint8 c = a * b;

// we have to typecast b as a uint8 to make it work:
uint8 c = a * uint8(b);


@@@ 以太坊内置hash函数 keccak256 

 实现是一种SHA3算法,生成一个256bit长度(32字节)的值。

例如:

keccak256("aaaab");

计算结果为:6e91ec6b618bb462a4a6ee5aa2cb0e9cf30f7a052bb467b0ba58b8748c00d2e5

@@@ function定义

以function关键字起头,参数名通常以下划线(_)开头,用于区分合约变量

例如:

function eatHamburgers(string _name, uint _amount) {

}

方法调用 :

eatHamburgers("aaa",10);


@@@创建合约,关键字contract

pragma solidity ^0.4.19;

contract Example {

// This will be stored permanently in the blockchain

uint myUnsignedInteger = 100; //uint 是uint256 的别称

}

@@@事件通知event

一种合约与前端通讯的方式

例子:

// declare the event

event IntegersAdded(uint x, uint y, uint result);

function add(uint _x, uint _y) public {
  uint result = _x + _y;
  // fire an event to let the app know the function was called:
  IntegersAdded(_x, _y, result);
  return result;

}


总体例子:(引自:https://cryptozombies.io

pragma solidity ^0.4.19;

contract ZombieFactory {

    event NewZombie(uint zombieId, string name, uint dna);

    uint dnaDigits = 16;
    uint dnaModulus = 10 ** dnaDigits;

    struct Zombie {
        string name;
        uint dna;
    }

    Zombie[] public zombies;

    // declare mappings here

    function _createZombie(string _name, uint _dna) private {
        uint id = zombies.push(Zombie(_name, _dna)) - 1;
        NewZombie(id, _name, _dna);
    } 

    function _generateRandomDna(string _str) private view returns (uint) {
        uint rand = uint(keccak256(_str));
        return rand % dnaModulus;
    }

    function createRandomZombie(string _name) public {
        uint randDna = _generateRandomDna(_name);
        _createZombie(_name, randDna);
    }

}



猜你喜欢

转载自blog.csdn.net/dongshengliao/article/details/80931249