1. 단위
1.1. 공통 단위
웨이(wei)는 이더(Ether)의 가장 작은 하위 단위입니다(1웨이(wei)== 1)그웨이(gwei)는 가스 가격을 나타내는 데 주로 사용되는 하위 단위입니다(1그웨이(gwei)== 1e9)이더(ether)단위(1이더(ether)== 1e18)
참고:
Solidity에서는 연산에 정수(integer)를 사용하며 해당 언어는부동소수점타입을 지원하지 않습니다. 부동소수점 표현 방식은 반올림 오류(반올림)를 유발하여 공격에 악용될 수 있는 논리적 허점을 만듭니다.
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): 지정된 블록의 해시 값 (조건:blocknumber가장 최근의 256개 블록 중 하나인 경우; 그 외에는 0 반환)block.basefee (uint): 현재 블록의 기본 수수료(base fee)block.chainid (uint): 현재 체인 IDblock.coinbase (address payable): 현재 블록 생성자의 주소block.gaslimit (uint): 현재 블록의 가스 한도(gas limit)block.number (uint): 현재 블록 번호block.timestamp (uint): 유닉스 에포크 이후의 초 단위로 나타낸 현재 블록 타임스탬프gasleft() returns (uint256): 남은 가스 양msg.data (bytes calldata): 전체 캘데이터(calldata)msg.sender (address): 메시지 발신자(현재 호출)msg.sig (bytes4): 캘데이터의 처음 4바이트(즉, 함수 식별자)msg.value (uint): 메시지와 함께 전송된 웨이(wei) 수tx.gasprice (uint): 트랜잭션의 가스 가격tx.origin (address): 트랜잭션 발신자(전체 호출 체인)
2.2. 오류 처리
assert(bool condition): 조건이 충족되지 않으면 패닉(Panic) 오류를 발생시키고 상태 변경을 롤백함 - 내부 오류에 사용됨.require(bool condition): 조건이 충족되지 않으면 롤백함 - 입력값 또는 외부 컴포넌트의 오류에 사용됨.require(bool condition, string memory message): 조건이 충족되지 않으면 롤백함 - 입력값 또는 외부 컴포넌트의 오류에 사용됨. 오류 메시지도 함께 제공함.revert(): 실행을 중단하고 상태 변경을 롤백함revert(string memory reason): 실행을 중단하고 상태 변경을 롤백하며, 설명 문자열을 제공함
2.3. 주소 타입의 멤버
<address>.balance (uint256): 해당 주소의 웨이(Wei) 단위 잔액<address>.code (bytes memory): 해당 주소의 코드(비어 있을 수 있음)<address>.codehash (bytes32): Address의 코드 해시<address payable>.transfer(uint256 amount): 지정된 양의 Wei를 Address로 전송하며, 실패 시 롤백되고, 2300 가스 수수료를 선전송하며 조정할 수 없음<address payable>.send(uint256 amount) returns (bool): 지정된 양의 Wei를 Address로 전송하며, 실패 시 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. 컨트랙트 관련 키워드
this: 현재 컨트랙트이며, Address로 명시적 변환이 가능함super: 상속 계층 구조에서 한 단계 위에 있는 컨트랙트selfdestruct(address payable recipient): 현재 계약을 파기하고, 해당 자금을 지정된 주소로 전송한 후 실행을 종료합니다. selfdestruct는 EVM 에서 물려받은 몇 가지 특이점이 있다는 점에 유의하십시오:- 수신 컨트랙트의 receive 함수가 실행되지 않습니다.
- 컨트랙트는 트랜잭션이 끝날 때 실제로 파괴되며, 롤백을 통해 파괴가 "취소"될 수 있습니다.
3. 표현식 및 제어 구조
3.1. 지원되는 키워드
다음 항목이 존재합니다: if, else, while, do, 위한, break, continue, return, try/catch C 또는 JavaScript에서 잘 알려진 일반적인 의미론을 따릅니다.
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. 키워드를 사용하여 새 컨트랙트 생성 new
키워드를 사용할 수 있습니다 new 를 사용하여 새로운 컨트랙트를 생성합니다. 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;
}
}
학습 목표
이번 강의를 마치면 다음 내용을 이해하게 됩니다: