블록체인 개발 #1

반영환·2023년 5월 8일
0

BlockChainDev

목록 보기
1/11
post-thumbnail

Solidity

학습 환경

remix.ethereum.org : 웹브라우저에서 사용가능한 솔리디티 IDE

특정 변수

msg.sender : 메시지를 보낸 주소

msg.value : 메시지에 있는 값

스마트컨트랙트 구조

pragma solidity 0.4.23;
// 1. 컨트랙트 선언
contract Sample {
	// 2. 상태 변수 선언
	uint256 data;
    address owner;
    
    // 3. 이벤트 정의
    event logData(uint256 dataToLog);
    
    // 4. 함수 변경자 정의 ( 함수를 실행시키는 조건!!)
    modifier onlyOwner() {
    	require(msg.sender == owner);
        _;
    }
    
    // 5. 생성자
    constructor (uint256 initData, address initOwner) public {
    	data = initData;
        owner = initOwner;
    }
    // 6. 메서드 정의
    function getData() public view returns (uint256 returned) {
    	return data
    }
    function setData(uint256 newData) public onlyOwner {
    	emit logData(newData);
        data = newData;
    }
}

솔리디티 데이터 타입

contract Sample {
	string public myString = "wow"; // utf-8 로 인코딩돼 알아보기쉽게 표현
    bytes12 public myRawString = "wowowo"; 
    
    mapping (address => string) myMap; // key와 value의 데이터구조
    constructor(string value) public {
    	myMap[msg.sender= = value
    }
    
    uinit[] myDynamicArray = [0,0]; // 동적 배열
    uint[3] myStaticArray = [1,1,0]; // 정적 배열
    
    
}

interface Token {
	function transfer(address recipient, uint amout) external;
}

데이터 위치

스토리지 / 메모리

  • 스토리지 - 전역변수 (블록체인내 저장)
  • 메모리 - 로컬변수 ( 사용 후 휘발됨 )

솔리디티 문법

if, else, while, for, break, continue, return , ? 모두 지원함.

가시성

누가 접근할 수있는지 정의

external

다른 컨트랙트나 트랜젝션을 통해서만 호출 가능
f() X , this.f() O

public

모든 방법으로 접근 가능

internal

내부적으로만 접근 가능
접근을 위해 this를 사용 X
상속된 컨트랙트에서는 접근 가능

private

인터널과 비슷하지만 상속된 컨트랙트에서는 접근할 수 없다.

가스

EVM에서 무언가실행될때 사용되는 수수료

가스리밋

가스리밋은 수수료의 한계치.

가스리밋을 낮게 설정하면 일이 끝나기 전에 가스를 다쓰게된다. 이는 돌려주지 않는데 채굴자들이 일을 하는데 가스를 이미 사용했기 때문

가스 프라이스

가스프라이스는 가스당 가격. 이 가격이 비싸지면 채굴자는 수수료를 많이 받기 때문에 비싼 가스프라이스가 먼저 채굴된다.

즉 가스프라이스 * 사용량이 수수료가 된다.

에러

TypeError: Data location must be "memory" or "calldata" for parameter in function, but none was given.
  --> Vote.sol:23:28:
   |
23 |     function addCandidator(string _name) public {
   |                            ^^^^^^^^^^^^

이 오류는 Solidity에서 함수 매개 변수에 대한 데이터 위치가 지정되지 않은 경우 발생합니다.

함수 매개 변수를 저장하기 위해 두 가지 위치가 있습니다. "memory" 또는 "calldata"입니다. 일반적으로 매개 변수가 상태 변수에 저장되는 것이 아니라 함수 호출의 일부로 전달되는 경우 "calldata"가 사용됩니다. 그러나 매개 변수가 함수 내부에서만 사용되는 경우 "memory"를 사용합니다.

따라서 addCandidator 함수에서 문자열 _name에 대한 데이터 위치를 지정해야 합니다. 함수에서 _name 매개 변수를 상태 변수에 저장하지 않고 사용하려는 것으로 추정됩니다. 그래서 "memory" 데이터 위치를 사용해야 합니다. 이를 위해서는 _name 매개 변수 선언을 다음과 같이 수정해야 합니다.

function addCandidator(string memory _name) public {
    // 함수 본문
}

이제 함수가 예상대로 작동할 것입니다.

라이브 코딩 내용

이정도면 간단한 계약은 설계 가능할 듯

// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

contract Vote {

    // structure
    struct candidator {
        string name;
        uint upVote;
    }
    // variable
    address owner; 
    bool live;
    candidator[] public candidatorList;
    // mapping
    mapping(address => bool) Voted;
    // event
    event AddCandidator(string name);
    event UpVote(string candidator, uint upVote);
    event FinishVote(bool live);
    event Voting(address owner);
    // modifier
    modifier onlyOwner {
        require(msg.sender == owner);
        _; // 이후 함수 모두 실행해라 란 뜻뜻
    }

    //constructor
    constructor() public {
        owner = msg.sender;
        live = true;
        
        emit Voting(owner);
    }

    // candidator
    function addCandidator(string memory _name) public onlyOwner {
        require(live == true);
        // 후보자 수 제한
        require(candidatorList.length < 5); // 조건이 만족하지 않으면 아래 함수가 실행되지 않아 gas 사용을 절감할 수 있있음
        
        candidatorList.push(candidator(_name, 0));

        // emit event
        emit AddCandidator(_name);
    }
    // get candidator
    
    // voting
    function upVote(uint _indexOfCandidator) public {
        require(live == true);
        require(_indexOfCandidator < candidatorList.length );
        require(Voted[msg.sender] == false);
        
        candidatorList[_indexOfCandidator].upVote++;
        Voted[msg.sender] = true;

        emit UpVote(candidatorList[_indexOfCandidator].name, candidatorList[_indexOfCandidator].upVote);

    }
    // finish vote
    function finishVote() public onlyOwner {
        live = false;

        emit FinishVote(live);
    }
}




profile
최고의 오늘을 꿈꾸는 개발자

0개의 댓글

관련 채용 정보