Data Types

Arrays

1
2
3
4
5
uint[5] arr;// similar to std::array
uint[] vec;// similar to std::vector

uint newLength = vec.push(); // similar to .push_back()
vec.length; // similar to .size()

Mappings / Dictionary

1
2
3
4
5
mapping(K => V) map; // similar to std::map<K, V>

delete map[k]; // delete a specific key, similar to .erase()
delete map; // .clear()
//

Address

address 的本质是一个 20 byte 的值,指向一个 Ethereum Address. 如果额外添加关键词 payable 则表示这个 address 可以进行交易(自动拥有 transfer()send() 方法)


Contract

Contract 的生态位

实际上我认为在设计代码架构的时候,还是应该将 Contract 视为 Class 进行处理. 不仅从逻辑上来说不叫相近,实现上也比较相近。

Important GLOBAL Variables

我们主要认识一下 msg 全局变量,msg 就是当前 contract 收到的消息,包含发送者、发送的金额等信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
/* msg - Current message received by the contract */
msg.sender; // address of the sender
msg.value; // amount of ETH sent (in `wei`). Should be marked as [payable]
msg.data; // bytes, complete call data
msg.gas; // remaining gas

/* tx - this transaction */
tx.origin; // address of the sender of the transaction.
tx.gasprice; // Gas price

/* block - this block */
block.timestamp;
block.number;

Function Modifiers

Grammar to Define a Function

1
2
3
4
5
6
// function [NAME]([ARGUMENTS])
// [VISIBILITY] [PAYABLE?] returns ([RETURN TYPE] [RETURN NAME]) {
// }
function someFunction(uint amount) public payable returns (uint remaining) {
// do something here......
}
Function Visibility Explanation
public All other functions/contracts (including internal or external) can call this function
private Only this contract can call this function
external Can only be called from externally. If an internal one want to call, have to use this keyword
internal Can only be called from internally.
  • payable: this function can receive & send ETH.