일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 이더리움
- Safe mode is ON
- hadoop safe mode
- code=0)
- hive beeline
- mac hive
- 자소서 시간 줄이기
- 자소서 빨리 쓰는 법
- mac hadoop 3
- 카카오 2020 코딩테스트
- 이더리움 #ethereum
- Failed to connect to localhost:10000
- is not allowed to impersonate hive (state=08S01
- 자소서 너무 오래 걸림
- hive beeline 에러
- Could not open client transport with JDBC Uri: jdbc:hive2://localhost:10000
- Resources are low on NN
- 기업 조사 빨리 하는 법
- 도커 교과서
- 자소서 빨리
- hive beeline 실행
- 카카오 2020 코테
- 백준 18428
- hadoop safe mode leave
- 카카오 자물쇠와 열쇠
- mac hadoop 설정
- mac hive 3
- hive beeline 설정
- mac hadoop
- mac hadoop 설치
- Today
- Total
A seeker after truth
투표 dapp 강의(작성중) 본문
수강한 강의: https://www.inflearn.com/course/ethereum-solidity-%ED%88%AC%ED%91%9C-dapp/dashboard
- web3JS 라이브러리가 RPC 역할을 함. 블록체인은 node.js와 RPC로 통신할 수밖에 없다. 나중에 리액트, 앵귤러 등을 이용할 수 있다.
투표앱에 필요한 세 가지
1. 각 후보자들 초기화
2. 후보자에 대한 투표
3. 득표수 확인
1번을 위해 후보자들을 생성자로 만든 뒤, 이름을 인수로 전달.
컨트랙트를 만들기 위한 브라우저 remix 이용. -> remix.ethereum.org
코드는 아래와 같다.
///Must write the version of compiler you'll use | |
pragma solidity ^0.6.2; | |
///contract == class! | |
contract voting { | |
/// "Constructor to initialize candidates" | |
/// solidity doesn't support string or array so use byte stream | |
bytes32[] public candidateList; | |
/// keep track of the number of votes | |
mapping (bytes32 => uint8) public votesReceived; | |
/// this constructor is invoked only once when this contract is deployed | |
constructor(bytes32[] memory candidateNames) public { | |
candidateList = candidateNames; | |
} | |
/// "Vote for candidates" | |
function voteForCandidate(bytes32 candidate) public { | |
/**Look back when the contract is initialized, this is by default set to zero. | |
So you don't have to assign it to zero to begin with.*/ | |
require(validCandidate(candidate)); | |
votesReceived[candidate] += 1; | |
} | |
/// "Get count of votes for each candidate" | |
/// this F doesn't change the state(maybe value?), mark as "view" which means "read only F" | |
function totalVotesFor(bytes32 candidate) view public returns(uint8) { | |
require(validCandidate(candidate)); | |
return votesReceived[candidate]; | |
} | |
function validCandidate(bytes32 candidate) view public returns (bool) { | |
for(uint i=0; i < candidateList.length; i++) { | |
if (candidateList[i] == candidate) { | |
return true; | |
} | |
} | |
return false; | |
} | |
} |
여기서 pragma에 나오는 솔리디티 컴파일러 버전은 당연히 깔려있는 버전과 일치해야 함.
- 해당 스마트컨트랙트가 배포될 때, 생성자는 한번만 초기화되며, 여러번 배포하면 배포할 때마다 이 컨트랙트의 인스턴스를 만들 것이다.
그래서 이 컨트랙트가 한번 만들어지면 변경될 수 없고, overwritten 될수도 없다.
- mapping = 연관배열. 다른 언어에서는 해시라고 함.
- byte code는 블록체인 상에 배포되는 코드를 말하고, abi는 ~
solc로 컴파일을 마치고 해당 폴더에 있는 파일들을 보면 아래와 같다.
$ node_modules voting.sol voting_sol_voting.bin package-lock.json voting_sol_voting.abi
하지만 막힌다. 일단 지금까지 경과를 설명하자면
node_modules/.bin/solcjs --bin --abi voting.sol (컴파일)
node(node console 킴)
> Web3 = require('web3')
> web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"))
> bytecode = fs.readFileSync('./voting_sol_voting.bin').toString()
> abi = fs.readFileSync('./voting_sol_voting.abi').toString()
> abi = JSON.parse(fs.readFileSync('./voting_sol_voting.abi').toString())
> deployedContract = new web3.eth.contract(abi)
> deployedContract.deploy({
... data: bytecode,
... arguments: [['Rama', 'Nick', 'Jose'].map(name => web3.toAscii(name))] <-여기서 web3.util.asciiToHex는 안된다! 이거 이제 지원 안된다고 함. 정확히 몇 버전부터 안되는지 그건 안찾아봐서 모르겠
... }).send({
... from: '0xc8f07cfa13707d5456f950d4be8e7891ec7df1d615d985fee733f7f5fc80c544',
... gas: 1500000,
... gasPrice: web3.utils.toWei('0.00003', 'ether')
... }).then((newContractInstance) => {
... deployedContract.options.address = newContractInstance.options.address;
... })
Uncaught TypeError: deployedContract.deploy is not a function
여기부터 미치겠다.
https://web3js.readthedocs.io/en/v1.2.0/web3-eth-contract.html#deploy
https://web3js.readthedocs.io/en/v1.2.0/web3-eth-contract.html#methods-mymethod-send
이거 참고해봐도 모르겠고.... 에러메시지 그대로 구글 검색해서해봐도 모르겠고... 왜 저걸 통째로 함수로 인식하는건지 당최... 저 링크에 나오는 예시 코드 참고해서
deployedContract.deploy({
data: bytecode,
arguments: [['Rama', 'Nick', 'Jose'].map(name => web3.toAscii(name))]
}).send({
from: '0xc8f07cfa13707d5456f950d4be8e7891ec7df1d615d985fee733f7f5fc80c544',
gas: 1500000,
gasPrice: web3.utils.toWei('0.00003', 'ether')
}).then(function(newContractInstance){
deployedContract.options.address = newContractInstance.options.address;
})
이렇게 해봐도 같은 에러메시지...
그리고 해당 강의 맨밑에 나와있는대로 하는 법도 모르겠다.
> Web3 = require('web3') > web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
> abiDefinition = JSON.parse(compiledCode.contracts[':Voting'].interface)
> VotingContract = web3.eth.contract(abiDefinition) > byteCode = compiledCode.contracts[':Voting'].bytecode
> deployedContract = VotingContract.new(['Rama','Nick','Jose'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000})
> deployedContract.address '0x0396d2b97871144f75ba9a9c8ae12bf6c019f610' <- Your address will be different
여기에 해당하는 내용인데, 여기서 두번째 줄 명령어의 compiledCode 부분에에 어떻게 내가 작성한 코드를 넣을지 모르겠다. 뒷부분인 contracts[':Voting'].interface 부분도 무슨 말인지 모르겠다. 이렇게 하면 실행되는게 맞는지 그걸 모르겠단 것. 문법을 몰라서 더더욱...
음... web3.js 에서 막히면 자스의 이벤트 처리 부분을 공부해보는건 어떨까 싶다.
'Blockchain' 카테고리의 다른 글
이더리움과 솔리디티(7) - 암호경제학 (0) | 2019.10.11 |
---|---|
이더리움과 솔리디티 입문(6) - 이더 채굴 (0) | 2019.10.11 |
이더리움과 솔리디티 입문(5) - 스마트 계약과 토큰 (0) | 2019.10.11 |
이더리움과 솔리디티 입문(4) - 솔리디티 (0) | 2019.10.11 |
이더리움과 솔리디티 입문(3) - EVM (0) | 2019.10.10 |