1. Các loại giá trị
1.1. INT / UINT
uint là viết tắt của số nguyên không dấuvà bạn có thể chọn kích thước từ uint8 ĐẾN uint256
uint8bắt đầu từ0ĐẾN2 ** 8 - 1uint16bắt đầu từ0ĐẾN2 ** 16 - 1
...uint256bắt đầu từ0ĐẾN2 ** 256 - 1
uint8 public u8 = 1;
uint256 public u256 = 456;
uint public u = 123; // uint là viết tắt của uint256
số nguyên là viết tắt của số nguyênvà bạn có thể chọn kích thước từ int8 ĐẾN int256
int8bắt đầu từ-2 ** 7ĐẾN2 ** 7 - 1int16bắt đầu từ-2 ** 15ĐẾN2 ** 15 - 1...int128bắt đầu từ-2 ** 127ĐẾN2 ** 127 - 1int256bắt đầu từ-2 ** 255ĐẾN2 ** 255 - 1
int8 public i8 = -1 ; int256 public i256 = 456 ; int public i = -123 ; // int là viết tắt của int256Toán tử int và uint:
- Comparisons: <=, <, ==, !=, >=, > (returns
boolean) - Các phép toán bit: &, |, ^ (phép loại trừ bit hoặc), ~ (phép phủ định bit)
- Shifts: << (left shift), >> (right shift)
- Phép cộng, phép trừ và phép nhân:
+,-,tiêu cực -(như trongsố nguyên có dấu),*,/,%(modulo),**(lũy thừa)
Đối với một loại số nguyên biến X, bạn có thể sử dụng loại(X).min Và loại(X).max Để truy cập giá trị nhỏ nhất và lớn nhất tương ứng cho loại đó.
// Giá trị nhỏ nhất và lớn nhất của kiểu dữ liệu int:
int public minInt = type(int).min; int public maxInt = type(int).max; // Giá trị nhỏ nhất và lớn nhất của kiểu dữ liệu uint:
uint public minUint = type(uint).min; uint public maxUint = type(uint).max;1.2. BOOL
boolean có nghĩa Boolean và có 2 giá trị có thể là ĐÚNG VẬY Và SAI
bool public trueVar = true ; bool public falseVar = false ;1.3. Các toán tử:
!(phủ định logic)&&(liên từ logic, “và”)||(phép tuyển logic, “hoặc”)==(bình đẳng)!=(bất đẳng thức)
Các nhà điều hành || Và && áp dụng các quy tắc rút ngắn mạch thông thường. Điều này có nghĩa là trong biểu thức f(x) || g(y), nếu như f(x) đánh giá thành ĐÚNG VẬY, g(y) Sẽ không được đánh giá ngay cả khi có thể có tác dụng phụ.
1.4. ĐỊA CHỈ
Địa chỉlà một kiểu dữ liệu đặc biệt trong Solidity cho phép lưu trữ 20 byte (kích thước) địa chỉ của tài khoản Kaia.địa chỉ thanh toántương tự nhưĐịa chỉnhưng bổ sung thêm 2 phương pháp nữachuyển khoảnVàgửi
Địa chỉ công khai exampleAddress = 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c ; Địa chỉ phải trả công khai examplePayableAddress = 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c ;1.5. Byte
Trong Solidity, kiểu dữ liệu byte biểu thị một chuỗi các byte. Solidity có hai loại byte:
- Mảng byte có kích thước cố định
- Mảng byte với kích thước động.
Trong Solidity, từ "bytes" đại diện cho một mảng byte động. Về cơ bản, nó viết tắt cho byte[].
bytes1 a = 0xb5 ; // [10110101]
bytes1 b = 0x56 ; // [01010110]
bytes c = "abc" ; // [01100001, 01100010, 01100011]1.6. Giá trị mặc định
Các biến được khai báo mà không gán giá trị sẽ có giá trị mặc định.
bool public defaultBool; // false
uint public defaultUint; // 0
int public defaultInt; // 0
địa chỉ công khai defaultAddr; // 0x00000000000000000000000000000000000000000
bytes1 public defaultByte; // 0x001.7. HỢP ĐỒNG
hợp đồng Được sử dụng để khai báo một hợp đồng trong Solidity.
hợp đồng HelloWorld {}hợp đồng cũng có thể kế thừa từ một hợp đồng khác bằng cách sử dụng từ khóa là
Hợp đồng Mercedes là Xe hơi {}1.8. ENUM
Liệt kê là một cách để tạo kiểu dữ liệu do người dùng định nghĩa trong Solidity. Chúng có thể chuyển đổi rõ ràng sang và từ tất cả các kiểu số nguyên, nhưng không cho phép chuyển đổi ngầm định. Việc chuyển đổi rõ ràng từ số nguyên sẽ kiểm tra tại thời điểm chạy xem giá trị có nằm trong phạm vi của kiểu liệt kê hay không và gây ra lỗi. Lỗi hoảng loạn nếu không thì. Liệt kê Enum yêu cầu ít nhất một thành viên, và giá trị mặc định khi khai báo là thành viên đầu tiên. Enum không thể có nhiều hơn 256 thành viên.
Cách biểu diễn dữ liệu giống như đối với liệt kê Trong ngôn ngữ C: Các tùy chọn được biểu diễn bằng các giá trị số nguyên không dấu liên tiếp bắt đầu từ 0.
Sử dụng type(NameOfEnum).min Và type(NameOfEnum).max Bạn có thể lấy giá trị nhỏ nhất và lớn nhất tương ứng của kiểu liệt kê đã cho.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Enum {
// Enum representing shipping status
enum Status {
Pending,
Shipped,
Accepted,
Rejected,
Canceled
}
// Default value is the first element listed in
// definition of the type, in this case "Pending"
Status public status;
// Returns uint
// Pending - 0
// Shipped - 1
// Accepted - 2
// Rejected - 3
// Canceled - 4
function get() public view returns (Status) {
return status;
}
// Update status by passing uint into input
function set(Status _status) public {
status = _status;
}
// You can update to a specific enum like this
function cancel() public {
status = Status.Canceled;
}
// delete resets the enum to its first value, 0
function reset() public {
delete status;
}
}1.9. LOẠI
Kiểu giá trị do người dùng định nghĩa cho phép tạo ra một lớp trừu tượng không tốn chi phí trên một kiểu giá trị cơ bản. Điều này tương tự như một bí danh, nhưng với các yêu cầu về kiểu nghiêm ngặt hơn.
Kiểu giá trị do người dùng định nghĩa được xác định bằng cách sử dụng loại C là V, Ở đâu C là tên của loại mới được giới thiệu và V phải là một kiểu giá trị tích hợp sẵn (kiểu “cơ bản”)
// Mã định danh giấy phép SPDX: GPL-3.0
pragma solidity ^ 0.8 .8 ; // Biểu diễn kiểu dữ liệu dấu phẩy cố định 18 chữ số thập phân, 256 bit bằng cách sử dụng kiểu giá trị do người dùng định nghĩa.
kiểu UFixed256x18 là uint256;1.10. CHỨC NĂNG
chức năng Từ khóa `keyword` được sử dụng để khai báo một hàm trong Solidity.
Chúng ta có thể tuyên bố chức năng như bên dưới:
contract Counter {
uint public count;
// Function to view count variable
function get() public view returns (uint) {
return count;
}
}2. Các loại tham chiếu
2.1. Vị trí lưu trữ dữ liệu
Các biến được khai báo bằng các từ kho, ký ức hoặc dữ liệu cuộc gọi Chỉ định vị trí lưu dữ liệu.
kho- Biến này là biến trạng thái (được lưu trữ trên blockchain)ký ức- Các biến nằm trong bộ nhớ và chỉ tồn tại trong thời gian nhất định.chức năngđang chạydữ liệu cuộc gọi- Một kho dữ liệu đặc biệt chứa dữ liệu được truyền cho hàm.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract DataLocations {
uint storage varStorage
uint memory varMemory
uint calldata varCallData
}2.2. Mảng
Mảng là sự kết hợp của các yếu tố giá trị trong cùng một định dạng, tương tự như danh sách trong Python và mảng TRONG Javascript.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Array {
// Several ways to initialize an array
uint[] public arr;
uint[] public arr2 = [1, 2, 3];
// Fixed sized array, all elements initialize to 0
uint[10] public myFixedSizeArr;
function get(uint i) public view returns (uint) {
return arr[i];
}
// Solidity can return the entire array.
// But this function should be avoided for
// arrays that can grow indefinitely in length.
function getArr() public view returns (uint[] memory) {
return arr;
}
function push(uint i) public {
// Append to array
// This will increase the array length by 1.
arr.push(i);
}
function pop() public {
// Remove last element from array
// This will decrease the array length by 1
arr.pop();
}
function getLength() public view returns (uint) {
return arr.length;
}
function remove(uint index) public {
// Delete does not change the array length.
// It resets the value at index to it's default value,
// in this case 0
delete arr[index];
}
function examples() external {
// create array in memory, only fixed size can be created
uint[] memory a = new uint[](5);
}
}
2.3. Cấu trúc
Cấu trúc là một định dạng dữ liệu mà các lập trình viên khai báo để tập hợp nhiều biến có định dạng khác nhau dưới một tên duy nhất nhằm dễ dàng sử dụng trong lập trình. hợp đồng.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Todos {
struct Todo {
string text;
bool completed;
}
// An array of 'Todo' structs
Todo[] public todos;
function create(string calldata _text) public {
// 3 ways to initialize a struct
// - calling it like a function
todos.push(Todo(_text, false));
// key value mapping
todos.push(Todo({text: _text, completed: false}));
// initialize an empty struct and then update it
Todo memory todo;
todo.text = _text;
// todo.completed initialized to false
todos.push(todo);
}
// Solidity automatically created a getter for 'todos' so
// you don't actually need this function.
function get(uint _index) public view returns (string memory text, bool completed) {
Todo storage todo = todos[_index];
return (todo.text, todo.completed);
}
// update text
function updateText(uint _index, string calldata _text) public {
Todo storage todo = todos[_index];
todo.text = _text;
}
// update completed
function toggleCompleted(uint _index) public {
Todo storage todo = todos[_index];
todo.completed = !todo.completed;
}
}3. Các loại ánh xạ
Lập bản đồ
lập bản đồ có thể được sử dụng để tạo ra một bản đồ băm (tương tự như từ điển TRONG Python) giữa 1 kiểu đến một nơi khác kiểu.
Ghi chú:
Khi bạn tạo mộtlập bản đồ, tất cảchìa khóaTồn tại cùng một lúc. Điều đó có nghĩa là:
Ví dụ, bạn tạomapping(address => uint256) addressToValue;Nếu bạn chưa thiết lập bất kỳchìa khóaVàgiá trịsau đó tất cảĐịa chỉGiá trị bạn nhập vào sẽ trả về giá trị mặc định.uint256tức là 0.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Mapping {
// Mapping from address to uint
mapping(address => uint) public myMap;
function get(address _addr) public view returns (uint) {
// Mapping always returns a value.
// If the value was never set, it will return the default value.
return myMap[_addr];
}
function set(address _addr, uint _i) public {
// Update the value at this address
myMap[_addr] = _i;
}
function remove(address _addr) public {
// Reset the value to the default value.
delete myMap[_addr];
}
}
contract NestedMapping {
// Nested mapping (mapping from address to another mapping)
mapping(address => mapping(uint => bool)) public nested;
function get(address _addr1, uint _i) public view returns (bool) {
// You can get values from a nested mapping
// even when it is not initialized
return nested[_addr1][_i];
}
function set(address _addr1, uint _i, bool _boo) public {
nested[_addr1][_i] = _boo;
}
function remove(address _addr1, uint _i) public {
delete nested[_addr1][_i];
}
}4. Lưu trữ đơn giản
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract SimpleStorage {
// Declare a variable to store the name of the maintainer
string public maintainerName = "zxstim";
// Declare the version of the contract
uint8 public version = 1;
// Declare an address to receive donation
address public donationAddress = 0xe3d25540BA6CED36a0ED5ce899b99B5963f43d3F;
// Declare a Person type to store information of a person
struct Person {
string name; // name
uint8 age; // age
bool overEighteen; // Over eighteen?
address uuid; // UUID
uint256 assetValue; // asset value
int256 debtValue; // debt value
}
Person[] private listOfPeople; // this syntax means creating an array to store Person named listOfPeople
mapping(address => Person) uuidToPerson; // this syntax means creating a mapping from address to Person named uuidToPerson
// this function will store the information of a new person with name, age, overEighteen, assetValue, debtValue
function storePerson(string memory _name, uint8 _age, bool _overEighteen, uint256 _assetValue, int256 _debtValue) public returns (Person memory person) {
_assetValue *= 1e18; // Convert asset value to wei unit
_debtValue *= 1e18; // Convert debt value to wei unit
// Add information of the new person to the listOfPeople array
listOfPeople.push(Person({name: _name, age: _age, overEighteen: _overEighteen, uuid: msg.sender, assetValue: _assetValue, debtValue: _debtValue}));
// Add information of the new person to the uuidToPerson mapping
uuidToPerson[msg.sender] = Person({name: _name, age: _age, overEighteen: _overEighteen, uuid: msg.sender, assetValue: _assetValue, debtValue: _debtValue});
return Person({name: _name, age: _age, overEighteen: _overEighteen, uuid: msg.sender, assetValue: _assetValue, debtValue: _debtValue});
}
// this function will retrieve the information of a person based on the address
function retrievePerson(address _address) public view returns (Person memory person) {
return uuidToPerson[_address];
}
}