‘이더리움 댑 개발’ 세미나 14-3. Web3 공식 문서(버전 1.2.9) – API Reference 2

web3.eth.subscribe(type [, options] [, callback])

이벤트를 구독할 수 있도록 합니다.

  • 인자로 구독 유형(type)과 options와 callback을 받습니다.
  • 옵션은 구독 유형에 따라 달라집니다.
  • 구독 유형에는 다음과 같은 것들이 있습니다.
    • “pendingTransactions”
      • pending transaction incoming이벤트를 구독합니다.
    • “newBlockHeaders”
      • 블록 헤더 incoming을 구독합니다. 블록체인 상에 변경을 체크하기 위한 타이머로 사용될 수 있습니다.
    • “syncing”
      • syncing 이벤트를 구독합니다. syncing 중에는 syncing 객체를 리턴하고, syncing이 끝나면 false를 리턴합니다. syncing 객체는 isSyncing 함수에서 다루었습니다.
    • “logs”
      • logs incoming을 구독합니다.  옵션에 따라 필터링 됩니다.  옵션으로 fromBlock, address, topics를 설정합니다.
  • subscription 인스턴스를 리턴합니다. subscription 인스턴스는 다음과 같은 속성과 함수를 갖습니다.
    • id
    • arguments – subscribe할 때 사용한 인자들, 구독을 취소하고 다시 구독할 때 사용할 수 있습니다.
    • unsubscribe – 구독을 취소합니다.
    • on(“data”) – log가 incoming할 때 마다 발생, 구독 유형에 따라 다른 객체를 리턴합니다.
      • 구독 유형에 따라 리턴이 달라집니다.
        • “pendingTransactions” – 트랜잭션 해시 
        • “newBlockHeaders”- 블록헤더 객체, 블록헤더 객체는 다음과 같은 속성을 갖습니다. 
          • number, hash, parentHash, nonce, sha3Uncles, logsBloom, transactionsRoot, stateRoot, receiptsRoot, miner, extraData, gasLimit, gasUsed, timestamp
        • “syncing”
          • syncing 중에는 syncing 객체를 리턴하고, syncing이 끝나면 false를 리턴합니다. syncing 객체는 isSyncing 함수에서 다루었습니다.
    • on(“changed”) – 구독 유형에 따라 다른 객체를 리턴합니다.
      • 구독 유형이 “syncing”인 경우에는 동기화가 시작되면 true를, 동기화를 마치면 false를 리턴합니다.
      • 구독 유형이 “logs”인 경우에는 블록체인에서 로그가 제거될 때 마다 발생, 로그 객체를 리턴합니다. 로그 객체에는 “removed: true” 속성이 추가됩니다.
    • on(“error”) – 에러가 발생할 때 발생합니다. 에러 객체를 리턴합니다.
    • on(“connected”) – subscription이 성공적으로 연결될 때 발생됩니다. subscription id를 리턴합니다.

 

clearSubscriptions()

Resets subscriptions.

web3.eth.Contract

컨트랙트와 쉽게 상호작용할 수 있는 Contract 객체를 생성합니다.

new web3.eth.Contract(jsonInterface[, address][, options])

jsonInterface는 컨트랙트 abi를 기술하는 json 객체입니다.

options은 컨트랙트 함수 호출 시에 사용할 기본 값들을 설정할 수 있습니다. 다음과 같은 속성들을 포함합니다.

  • from, gasPrice, gas
  • data – 컨트랙트의 바이트 코드

Contract 클래스는 전역 속성으로 다음과 같은 것들을 포함합니다.

  • defaultAccount, defaultBlock, defaultHardfork, defaultChain, defaultCommon, transactionBlockTimeout, transactionConfirmationBlocks, transactionPollingTimeout, handleRevert

Contract 객체 생성 시에 설정한 options와 위의 전역 속성들은 Contract 속성 options를 통해서도 접근할 수 있습니다.

 

clone

현재 Contract 객체를 복제합니다.

 

deploy(options)

options 객체는 컨트랙트 바이트 코드에 해당하는 data 속성과 생성자에 전달하는 인자들에 해당하는 arguments를 포함합니다. arguments는 선택적입니다.

배포에 성공하면 Promise는 다음과 같은 속성을 포함하는 객체를 리턴합니다.

  • 함수  호출시 사용한 arguments를 속성으로 갖습니다.
  • send, estimateGas, encodeABI를 함수로 갖습니다.

 

methods

컨트랙트 함수에 접근할 수 있도록 합니다. 다음과 같은 방법들을 사용할 수 있습니다.

  • 이름
    • myContract.methods.myMethod(123)
  • 시그니처를 인덱스로 함수를 찾아 호출
    • myContract.methods[‘myMethod(uint256)’](123)
    • myContract.methods[‘0x58cf5f10’](123)

method 객체를 리턴합니다. method 객체는 다음과 같은 속성과 함수를 포함합니다.

  • arguments
  • call(options [, defaultBlock] [, callback])
    • Will call the “constant” method and execute its smart contract method in the EVM without sending a transaction (Can’t alter the smart contract state).
    • callback에는 컨트랙트 함수 실행 결과가 전달됩니다.
    • Promise는 컨트랙트 함수 실행 결과를 리턴합니다.
  • send(options[, callback])
    • Will send a transaction to the smart contract and execute its method (Can alter the smart contract state).
    • callback에는 트랜잭션 해시 값이 전달됩니다.
    • Promise는 컨트랙트 함수 실행 결과를 리턴합니다.

 

once(event[, options], callback)

  • Subscribes to an event and unsubscribes immediately after the first event or error. Will only fire for a single event.한 번만 이벤트 발생을 구독
  • 컨트랙트 이벤트 이름(event)과 options와 callback을 인자로 받습니다.
    • 이벤트 이름이 “allEvents”인 경우 모든 이벤트에 해당합니다.
  • options 객체는 다음과 같은 속성을 갖습니다.
    • filter
      • Lets you filter events by indexed parameters, e.g. {filter: {myNumber: [12,13]}} means all events where “myNumber” is 12 or 13.
    • topics
      • This allows you to manually set the topics for the event filter. If given the filter property and event signature, (topic[0]) will not be set automatically.

 

events

이벤트 구독을 위해 event 객체에 접근할 수 있도록 합니다.

  • 구체적인 이벤트 이름을 사용해서 개별 이벤트를 구독할 수 있도록 합니다.
    • MyEvent([options][, callback])
      • options는 filter, topics, defaultBlock 속성을 갖습니다.
    • 다음과 같은 이벤트 객체들을 갖는 event emitter를 리턴합니다.
      • “data”, “changed”, “error”, “connected”
    • 이벤트 객체는 다음과 같은 속성을 갖습니다.
      • event – 이벤트 이름
      • signature
      • address – Address this event originated from
      • returnValues – The return values coming from the event, e.g. {myVar: 1, myVar2: ‘0x234…’}
      • logIndex – Integer of the event index position in the block.
      • transactionIndex, transactionHash, blockHash, blockNumber
      • raw.data – The data containing non-indexed log parameter
      • raw.topics -An array with max 4 32 Byte topics, topic 1-3 contains indexed parameters
  • allEvents([options][, callback])
    • 모든 이벤트를 구독하도록 합니다.

 

getPastEvents(event[, options][, callback])

과거 이벤트들을 얻을 수 있도록 합니다.

  • options는 다음과 같은 속성을 갖습니다.
    • filter, fromBlock, toBlock, topics
  • Promise는 이벤트 객체 배열을 리턴합니다.

web3.eth.accounts

계정을 생성하고, 트랜잭션과 데이터에 서명하는 기능을 제공합니다.

 

create([entropy]);

개인키와 공개키를 갖는 계정 객체를 생성합니다.

  • entropy
    • A random string to increase entropy. If given it should be at least 32 characters. If none is given a random string will be generated using randomhex.
  • 계정 객체는 다음과 같은 속성과 함수를 갖습니다.
    • address, privateKey, publicKey
    • signTransaction(tx [, callback]), sign(data)

 

privateKeyToAccount(privateKey [, ignoreLength ])

개인키로 계정 객체를 생성합니다.

 

signTransaction(tx, privateKey [, callback])

트랜잭션에 서명합니다. 트랜잭션 객체(tx)는 다음과 같은 속성을 갖습니다.

  • nonce, chainId, to, data, value, gasPrice, gas, chain, hardfork, common

Promise는 트랜잭션 서명 객체를 리턴합니다. 트랜잭션 서명 객체는 다음과 같은 속성을 갖습니다.

  • messageHash, r, s, v, rawTransaction, transactionHash

 

recoverTransaction(rawTransaction)

서명하는데 사용된 주소를 리턴합니다.

 

hashMessage(message)

메시지 해시 값을 리턴합니다.

 

sign(data, privateKey)

데이터에 서명합니다.

Promise는 데이터 서명 객체를 리턴합니다. 데이터 서명 객체는 다음과 같은 속성을 갖습니다.

  • messageHash, r, s, v

 

recover

데이터에 서명한 주소를 리턴합니다.

인자로 서명 객체를 사용하거나, raw RLP encoded signature를 사용하거나, r, s, v 값을 사용합니다.

 

encrypt(privateKey, password)

개인키와 암호를 사용해서 암호화해서 키스토어를 생성합니다.

 

decrypt(keystore, password)

키스토어와 암호를 가지고 개인키를 복호화 합니다.

 

wallet

다수의 계정을 갖는 in memory wallet을 포함하는 객체에 접근할 수 있도록 합니다.

  • create(numberOfAccounts [, entropy])
    • 다수의 계정을 생성합니다.
  • add(account), remove(account), clear()
    • 계정을 추가, 삭제, 모두 삭제 합니다.
  • encrypt(password), decrypt(keystoreArray, password);
    • 지갑의 모든 계정에 대해 암호화하여 키스토어를 생성하거나 복호화합니다.
  • save(password [, keyName]), load(password [, keyName])
    • 지갑을 저장하고, 로드 합니다.
    • keyName
      • The key used for the local storage position, defaults to “web3js_wallet”.

 

web3.eth.personal

다음과 같은 모듈 공통 속성과 함수를 갖습니다.

  • provider 관련,  BatchRequest, extend

계정 관련 속성과 함수를 갖습니다.

  • newAccount(password, [callback])
  • sign(data, address, password [, callback])
  • ecRecover(message, signature [, callback])
  • signTransaction(transaction, password [, callback])
  • sendTransaction(transactionOptions, password [, callback])

 

unlockAccount(address, password, unlockDuraction [, callback])

서명하려면 해당 계정이 unlock 되어 있어야 합니다. unlockDuration 동안 unlock 됩니다.

lockAccount(address [, callback])

계정을 lock 합니다.

 

getAccounts([callback])

노드가 제어하는 계정 목록을 리턴합니다.

 

importRawKey(privateKey, password)

개인키를 암호를 사용해서 키스토어로 임포트합니다.

web3.utils

블룸 필터 관련 다음과 같은 함수들을 제공합니다.

  • isBloom, isUserEthereumAddressInBloom, isContractAddressInBloom, isTopic, isTopicInBloom, isInBloom

 

randomHex(size)

주어진 바이트 크기에 해당하는 암호학적으로 강력한 pseudo-random HEX 문자열을 생성합니다.

 

underscore 라이브러리를 제공합니다.

 

BN(mixed)

자바스크립트 big number를 계산하기 위해 BN.js 라이브러리를 사용합니다. library for calculating with big numbers in JavaScript.

 

isBN, isBigNumber

BN.js 인스턴스 인지,  BigNumber.js 인스턴스 인지 체크합니다.

 

sha3(string), sha3Raw(string), soliditySha3(param1 [, param2, …]), soliditySha3Raw(param1 [, param2, …])

sha3 해시 값을 리턴합니다. sha3Raw는 null 대신 해시 값을 리턴합니다. solditySha3은 솔리디티에서 하는 방법과 같은 방법으로 sha3 해시 값을 계산합니다.

 

isHex, isHexStrict

16진수인지를 체크합니다. isHexStrict는 0x로 시작하는 16진수 문자열에 대해서만 true를 리턴합니다.

 

toHex

16진수 문자열로 변환합니다.

 

isAddress, checkAddressChecksum

주소인지, 체크섬 주소 인지를 체크합니다.

 

toChecksumAddress

체크섬 주소로 변환합니다.

 

toBN, hexToNumberString, hexToNumber, numberToHex, hexToUtf8, hexToAscii, utf8ToHex, asciiToHex, hexToBytes, bytesToHex

 

toWei(number [, unit]),  fromWei(number [, unit])

단위에 해당하는 값을 웨이로, 웨이를 단위에 해당하는 값으로 변환합니다. unit의 기본 값은 ether입니다.

 

unitMap

이더 단위들을 웨이 크기로 제공합니다.

 

padLeft(string, characterAmount [, sign]), padRight(string, characterAmount [, sign])

sign에 해당하는 문자로, 전체 길이가 characterAmount가 되도록 string을 채워줍니다. sign의 기본 값은 “0”입니다.

 

toTwosComplement(number)

음수를 2의 보수로 변환합니다.

web3.eth.abi

abi를 인코딩하고 디코딩하는 기능을 제공합니다.

 

encodeFunctionSignature(functionName)

함수 abi에 대한 sha3 해시 값의 첫 번째 4바이트를 리턴합니다.

 

encodeEventSignature(eventName)

이벤트 abi에 대한 sha3 해시 값을 리턴합니다.

 

encodeParameter(type, parameter), encodeParameters(typesArray, parameters)

매개변수 타입과 인자에 대한 abi를 인코딩합니다.

encodeFunctionCall(jsonInterface, parameters)

함수 호출에 대한 abi를 인코딩합니다.

 

decodeParameter(type, hexString), decodeParameters(typesArray, hexString)

 

decodeLog(inputs, hexString, topics)

인코딩된 log data와 indexed topic data를 디코딩합니다.

  • inputs
    • A JSON interface inputs array.
  • hexString
    • The ABI byte code in the data field of a log.
  • topics
    • An array with the index parameter topics of the log, without the topic[0] if its a non-anonymous event, otherwise with topic[0].

web3.*.net

노드 네트워크 속성과 상호작용할 수 있는 기능을 제공합니다.

 

getId([callback])

현재 네트워크 id를 리턴합니다.

isListening([callback])

노드가 peers들을 리스닝하고 있는지를 체크합니다.

 

getPeerCount([callback])

연결된 peers 갯수를 리턴합니다.

About the Author
(주)뉴테크프라임 대표 김현남입니다. 저에 대해 좀 더 알기를 원하시는 분은 아래 링크를 참조하세요. http://www.umlcert.com/kimhn/

Leave a Reply

*