1. 단위
1.1. 일반적인 단위
웨이이더리움의 가장 작은 단위입니다 (1웨이== 1)gwei가스 가격을 나타내는 데 흔히 사용되는 단위입니다 (1gwei== 1e9)이더단위 (1)이더== 1e18)
참고:
Solidity에서는 계산에 정수를 사용하며, 이 언어는부동유형. 부동 소수점 표현 방식의 문제로 인해 반올림 오류가 발생합니다 (반올림)로 인해 공격의 빌라구가 발생합니다.
1.2. 시간 단위
- 1 == 1
초 - 1
회의록== 60초 - 1
시간== 60회의록 - 1
일== 24시간 - 1
주== 7일
예시
function f(uint start, uint daysAfter) public { if (block.timestamp >= start + daysAfter * 1 days) { // ...
}
}2. 전역 변수
2.1. 블록 및 트랜잭션 속성
blockhash(uint blockNumber) returns (bytes32): 주어진 블록의 해시 값블록 번호최근 256개 블록 중 하나일 경우 반환하고, 그렇지 않으면 0을 반환합니다block.basefee (uint): 현재 블록의 기본 수수료block.chainid (uint): 현재 체인 IDblock.coinbase (지급 주소): 현재 블록 채굴자의 주소block.gaslimit (uint): 현재 블록의 가스 한도블록 번호 (uint): 현재 블록 번호block.timestamp (uint): 현재 블록 타임스탬프(유닉스 에포크 기준 초 단위)gasleft()는 (uint256)을 반환합니다.: 잔여 가스msg.data (바이트 단위 호출 데이터): 전체 호출 데이터msg.sender (주소): 메시지 발신자 (현재 통화)msg.sig (4바이트): 호출 데이터의 첫 4바이트(즉, 함수 식별자)msg.value (uint): 메시지와 함께 전송된 위(wei)의 수tx.gasprice (uint): 거래의 가스 비용tx.origin (주소): 거래의 발신자 (전체 호출 체인)
2.2. 오류 처리
assert(bool condition): 조건이 충족되지 않을 경우 Panic 오류를 발생시켜 상태 변경을 되돌립니다. 내부 오류 처리용으로 사용됩니다.require(bool condition): 조건이 충족되지 않으면 원래 상태로 되돌림 - 입력값이나 외부 구성 요소의 오류 발생 시 사용됩니다.require(bool 조건, string 메모리 메시지): 조건이 충족되지 않으면 원래 상태로 되돌립니다. 입력값이나 외부 구성 요소의 오류 처리 시 사용합니다. 또한 오류 메시지도 제공합니다.되돌리기(): 실행을 중단하고 상태 변경을 원상 복구합니다revert(문자열, 메모리, 이유): 실행을 중단하고 상태 변경 사항을 원상 복구하며, 설명 문구를 제공합니다
2.3. 주소 유형의 구성원
<address>.balance (uint256): 위나라에서의 연설의 나머지 부분<address>.code (bytes memory): 주소의 코드 (비워둘 수 있음)<address>.codehash (bytes32): 주소의 코드 해시<address payable>.transfer(uint256 amount): 지정된 양의 Wei를 주소로 전송하며, 실패 시 롤백되고, 2300 가스를 지원금으로 지급하며, 이 값은 조정할 수 없습니다.<address payable>.send(uint256 amount) returns (bool): 지정한 양의 Wei를 주소로 전송하며, 실패 시 false를 반환하고, 2300 가스를 자동으로 지급하며, 이 값은 조정할 수 없습니다.<address>.call(bytes memory) returns (bool, bytes memory): 지정된 페이로드를 사용하여 저수준 CALL을 실행하고, 성공 여부와 반환 데이터를 반환하며, 사용 가능한 모든 가스를 전달하고, 조정 가능<address>.delegatecall(bytes memory) returns (bool, bytes memory): 지정된 페이로드를 사용하여 저수준 DELEGATECALL을 호출하고, 성공 여부와 반환 데이터를 반환하며, 사용 가능한 모든 가스를 전달하고, 조정 가능<address>.staticcall(bytes memory) returns (bool, bytes memory): 지정된 페이로드를 사용하여 저수준 STATICCALL을 호출하고, 성공 여부와 반환 데이터를 반환하며, 사용 가능한 모든 가스를 전달하고, 조정 가능
2.4. 계약 관련 키워드
이것: 현재 계약은 명시적으로 Address로 전환 가능합니다최고: 상속 계층 구조에서 한 단계 위의 계약selfdestruct(수취인 주소): 현재 계약을 파기하고, 자금을 지정된 주소로 전송한 후 실행을 종료합니다. selfdestruct는 EVM에서 유래한 몇 가지 특이점이 있다는 점에 유의하십시오:- 수신 계약의 receive 함수가 실행되지 않습니다.
- 계약은 실제로 거래가 종료될 때만 파기되며, 리버트(revert)는 이러한 파기 과정을 “되돌릴” 수 있습니다.
3. 표현식과 제어 구조
3.1. 지원되는 키워드
다음과 같은 것이 있습니다: 만약, 그렇지 않으면, ~하는 동안, ~하다, ~을 위해, 중단, 계속, 돌아가기, 해봐/잡다 C나 자바스크립트에서 익숙한 일반적인 의미론과 마찬가지로.
3.2. 함수 호출
우리는 ~라고 부를 수 있습니다 함수 1 중 계약 다른 곳에서 계약. 아래에는 2개의 계약이 포함된 예시가 있습니다 발신자 그리고 칼리.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Callee {
uint public x;
uint public value;
function setX(uint _x) public returns (uint) {
x = _x;
return x;
}
function setXandSendEther(uint _x) public payable returns (uint, uint) {
x = _x;
value = msg.value;
return (x, value);
}
}
contract Caller {
function setX(Callee _callee, uint _x) public {
uint x = _callee.setX(_x);
}
function setXFromAddress(address _addr, uint _x) public {
Callee callee = Callee(_addr);
callee.setX(_x);
}
function setXandSendEther(Callee _callee, uint _x) public payable {
(uint x, uint value) = _callee.setXandSendEther{value: msg.value}(_x);
}
}3.3. 키워드를 사용하여 새 계약 생성 새로움
우리는 키워드를 사용할 수 있습니다 새로움 새 계약을 생성하려면. AdvancedStorage.sol 다음 예시를 통해 이에 대해 더 자세히 설명하겠습니다.
4. 고급 스토리지
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract AdvancedStorage {
// Declare the address of a vault manager
address public vaultManager;
// Declare an error type for unauthorized access
error OwnableUnauthorizedAccount(address account);
// Constructor is a function that runs when the contract is initialized
constructor() {
// Assign the address of the deployer to the vault manager variable
vaultManager = msg.sender;
}
// Declare the InvestmentVault Struct data type
struct InvestmentVault {
uint256 investmentDuration; // Thời gian đầu tư
int256 returnOnInvestment; // % lãi suất trả về
bool initialized; // Đã khởi tạo
address identityCard; // Địa chỉ thẻ thông tin
}
// Declare a variable with the InvestmentVault type
InvestmentVault private investmentVault;
// This function initializes the investment vault
function setInitialInvestmentVault(uint256 daysAfter, int256 _returnOnInvestment, address _vaultOwner) public {
// We check if the initiator is the vaultManager
if (msg.sender != vaultManager) {
// This reverts all actions and reverts the transaction
revert OwnableUnauthorizedAccount(msg.sender);
}
// Declare the investment duration
uint256 _investmentDuration = block.timestamp + daysAfter * 1 days;
// Create a new identity card for the customer
CustomerIdentityCard customerIdentityCard = new CustomerIdentityCard(_vaultOwner);
// Assign the address of the vault owner/customer to the mapping with the vault information
investmentVault = InvestmentVault({investmentDuration: _investmentDuration, returnOnInvestment: _returnOnInvestment, initialized: true, identityCard: address(customerIdentityCard)});
}
// Function to change the return on investment
function editReturnOnInvestment(int256 _newReturnOnInvestment) public {
// require keyword works similarly to if and revert above
require (msg.sender == vaultManager, "Unauthorized Manager");
// Change the value of the interest rate
investmentVault.returnOnInvestment = _newReturnOnInvestment;
}
// Function to return investmentVault information
function retrieveInvestmentVault() public view returns (InvestmentVault memory _investmentVault) {
return investmentVault;
}
// Function to return the address of the IdentityCard
function retrieveCustomerInformation() public view returns (address) {
return CustomerIdentityCard(investmentVault.identityCard).customer();
}
}
// Contract that stores the address of the vault owner
contract CustomerIdentityCard {
// declares a variable to store the address of the customer
address public customer;
// initialize the contract and assign the address of the customer
constructor(address _customer) {
customer = _customer;
}
}