본문 바로가기
Ethereum/부동산 Dapp

부동산Dapp_(5)event

by rooney-l3 2019. 9. 24.

[STEP1]

 

SmartContract 작성

pragma solidity ^0.4.23;

contract RealEstate {
    //매입자 정보 구조체
    struct Buyer {
        address buyerAddress;
        bytes32 name;
        uint age;
    }
    //매물의 아이디를 key값으로 하여 매입자의 정보를 불러오는 구조
    mapping (uint => Buyer) public buyerInfo;
    
    address public owner;
    address[10] public buyers;
    
    //어떤 이벤트가 생성되었을때 이벤트의 내용도 블록체인안에 저장된다
    event LogBuyRealEstate(
        address _buyer,
        uint _id
    );
   
    constructor() public {
        owner = msg.sender;
    } 

    function buyRealEstate(uint _id, bytes32 _name, uint _age)public payable {
        //매물 유효성 검사
        require(_id >= 0 && _id <=9);
        //매개변수로 받은 id를 인덱스값으로 써서 구매자의 주소를 배열에 저장
        buyers[_id] = msg.sender;
        //매물의 아이디를 key값으로 하여 매입자의 정보를 구조체의 value값으로 저장
        buyerInfo[_id] = Buyer(msg.sender, _name, _age);
        //eth를 계정과 계정으로 이동할때 transfer함수 사용
        //msg.value는 Wei만 허용, owner에게 eth를 전송
        owner.transfer(msg.value);
        //이벤트를 발생
        emit LogBuyRealEstate(msg.sender, _id);
   }
}

 

[STEP2]

1. 수정된 컨트랙트 재배포

 

truffle migrate --compile-all --reset --network ganache

2. truffle 콘솔 접속 및 전역변수에 instance 저장

RealEstate.deployed().then(function(instance) { app = instance ; } )

 

3. 이벤트 초기화

우리가 만든 LogBuyRealEstate를 사용하기위해서는 파라미터를 명시해야합니다. 첫 번째 파라미터{}는 필터이고, 두번째 파라미터 {fromBlock: 0, toBlock: 'latest'} 는 범위 입니다. 

watch는 앞에서 필터링한 부분과 범위를 정해준 부분을 감지하고 콜백으로 error와 event를 받습니다.그리고 받은 이벤트를 콘솔에 보여주도록합니다. 

app.LogBuyRealEstate({}, {fromBlock: 0, toBlock: 'latest'}).watch(function(error, event) console.log(event); })

4. 매물구입 후 이벤트 작동 확인

밑에 logs 부분이 생긴것을 확인 할 수 있습니다. 

이벤트에 관한 모든 정보를 담고 있고 이 정보드를 블록체인에 저장하였습니다. 

args 부분에 우리가 명시한 주소와 id값이 나오는 것을 확인 할 수 있습니다. 

댓글