튼튼한 기초
12009 단어 blockchainweb3beginners
본문에서 우리는 견고한 기초 지식을 배울 것이다.Solidity는 새로운 고급 프로그래밍 언어로 이더리움 블록체인에서 스마트 계약을 실시하는 데 전문적으로 사용된다.
카탈로그
Features of Solidity
견고성 특징
액세스 수정 함수
There are four basic access modifiers used by variables and functions
contract MyContract {
uint256 public myPublicVar;
function getVar() public view returns(uint) {
return myPublicVar;
}
}
contract MyContract {
uint256 external externalVar;
function getVar() external view returns(uint) {
return externalVar;
}
}
contract MyContract {
uint256 internal internalVar;
function getVar() internal view returns(uint) {
return internalVar;
}
}
contract MyContract {
uint256 private privateVar;
function getVar() private view returns(uint) {
return privateVar;
}
}
메모리 및 스토리지
우리는 메모리를 램으로, 메모리를 하드디스크로 볼 수 있다.메모리 변수에 저장된 모든 값은 임시적이며 실행이 중지되면 지워지고 저장 변수의 값은 블록체인에 영구적으로 저장되며 새로 실행된 후에도 변수는 이전에 저장된 값을 가지게 됩니다.계약이 체결된 후 스토리지 구조는 영원히 바꿀 수 없지만 그 가치는 바꿀 수 있다.
메모리가 소모되는 기체는 상대적으로 적다.
메모리는 방법에서만 사용할 수 있고 계약 단계(상태 변수)에서는 사용할 수 없습니다.
메모리는 변수의 새 복사본을 만들고 저장은 같은 위치를 가리키며 원시 변수의 값을 변경할 수 있습니다.
Example
pragma solidity >=0.8.7;
// Creating a contract
contract MemoryContract
{
// state variable (always in storage)
uint[] public numbers;
function addNumbers() public {
numbers.push(1);
numbers.push(2);
// numbers = [1, 2]
//1. Creating a new memory instance
uint[] memory myMemoryNumbers = numbers;
myMemoryNumbers[0] = 10;
// myMemoryNumber = [10, 2]
// numbers = [1, 2]
//2. Creating a new storage instance
uint[] storage myStorageNumbers = numbers;
myStorageNumbers[0] = 10;
// myStorageNumbers = [10, 2]
// numbers = [10, 2]
}
}
기본 유형
Example
// specify the version of solidity
pragma solidity >=0.8.7;
// Creating a contract
contract BasicTypes {
// Boolean value
bool public myBoolean = false;
// Integer variable
int32 public myInt = -60313;
// unsigned Integer
uint public myUInt = 60313; // alias for uint256
// String variable
string public myStr = "Saurabh";
// Byte string (uses less gas)
bytes32 public myByteString = "Bomble";
// Byte variable
bytes1 public b = "a";
// Defining an enumerator
enum myEnum { ACCEPTED, PENDING, REJECTED }
}
변량
구문
<type> <access modifier> <variable name>;
변수 유형
Example
pragma solidity >=0.8.7;
contract VariableType {
// State variables => stored on blockchain
uint myUint = 1;
//160-bit ethereum address
address public myAddress = 0xE9Bc4d002161aA50E15728ba19aDC3aA34a91D98;
constructor() {
// msg is global variable
myAddress = msg.sender // address of user who deployed the contract
}
function getValue() public pure returns(uint) {
myAddress = msg.sender // address of current caller
uint value = 1; // local variable
return value;
}
}
데이터 구조
Example
pragma solidity >=0.8.7;
contract DataStructure {
// Array
uint[] public myIntArray = [1, 2, 3];
string[] public myStringArray = ["apple", "banana"];
uint[][] public array2D = [ [1,2,3], [4,5,6] ];
function addValue(string memory _value) public {
myStringArray.push(_value);
}
function valueCount() public view returns(uint) {
return myStringArray.length;
}
// Mapping (key-value store)
mapping(uint => string) public names;
constructor() {
names[1] = "Saurabh";
names[2] = "John";
names[3] = "Doe";
}
struct Book {
string title;
string author;
}
mapping(uint => Book) books; // key = id of book(unit), value = Book
// Nested mapping
mapping(address => mapping(uint => Book)) public myBooks;
function addBook(uint _id, string memory _title, string memory _author) public {
books[_id] = Book(_title, _author);
}
function getBook(uint _id) public view returns(string memory, string memory){
string memory _title = books[_id].title;
string memory _author = books[_id].author;
return (_title, _author);
}
function addMyBook(uint _id, string memory _title, string memory _author) public {
myBooks[msg.sender][_id] = Book(_title, _author);
}
}
조건문과 순환
Example
pragma solidity >=0.8.7;
contract ConditionalsLoops {
// Loop
uint[] public numbers = [1,2,3,4,5];
address public owner;
constructor() {
owner = msg.sender;
}
function countEven() public view returns(uint count) {
count = 0;
for(uint i = 0; i < numbers.length; i++) {
count += isEven(numbers[i]) ? 1 : 0;
}
}
// Conditionals (just like js)
function isEven(uint _value) public pure returns(bool) {
return _value % 2 == 0;
}
function isOwner() public view returns(bool) {
if(msg.sender == owner) return true;
return false;
}
}
기능
Example
pragma solidity >=0.8.7;
contract FunctionContract {
uint myUint = 1;
function getValue() public pure returns(uint) {
uint value = 1;
return value;
}
function getMyUint() public view returns(uint) {
return myUint;
}
}
오류 처리
Example
if(currentStatus == Status.VACANT) {
revert("Currently occupied");
}
Example
require(currentStatus == Status.VACANT, "Currently occupied");
상속권
계승은 대상을 대상으로 프로그래밍하는 언어의 가장 중요한 특성 중의 하나다.그것은 코드를 신축성, 중용성, 조직성을 가지게 한다.부계약을 기본계약이라고 하고, 기본계약 상속 방법과 속성의 계약을 파생계약이라고 한다.
pragma solidity >=0.8.7;
contract BaseContract {
uint public a;
uint public b;
// Wrong defination to be corrected in derived
function getDiff() public view virtual returns(uint) {
return(a*b);
}
}
// Defining child contract
contract DerivedContract is BaseContract{
constructor(uint _a, uint _b) {
a = _a;
b = _b;
super;
}
// Correct defination with same signature
function getDiff() public view virtual override returns(uint) {
return(a-b);
}
}
// Defining calling contract
contract CallerContract {
DerivedContract derivedContract;
constructor(uint _val1, uint _val2) {
derivedContract = new DerivedContract(_val1, _val2);
}
function getDiffAandB() public view returns(uint) {
return derivedContract.getDiff();
}
}
결론
읽어주셔서 감사합니다.🙏. 이 장은 여기까지입니다.우리는solidity의 대부분 기본 개념을 배워서 스마트 계약을 작성하기 시작했다.
dev.to에서 따라오세요.
Reference
이 문제에 관하여(튼튼한 기초), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/saurabh619/basics-of-solidity-3fhb텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)