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

Web3

web3.js 라이브러리의 메인 클래스

  • var Web3 = require(‘web3’);

 

Web3.modules

하위 모듈들에 대한 클래스를 갖는 객체를 리턴합니다. 수동적으로 하위 모듈들에 대한 인스턴스를 생성할 수 있습니다.

 

Web3 Instance

Web3 인스턴스를 생성할 때 하위 모듈들에 대한 인스턴스들도 자동 생성됩니다. web3 객체를 통해 하위 모듈 객체들에 접근할 수 있습니다.

  • version
  • provider 설정
    • 어떤 네트워크에 연결할 지는 provider로 설정합니다.
    • web3 인스턴스를 생성할 때 provider 정보를 인자로 전달할 수도 있고, setProvider로 설정할 수 도 있습니다.
  • providers
    • provider 클래스를 포함한 객체를 리턴합니다. 이 클래스들을 사용해서 provider를 생성할 수 있습니다.
  • setProvider
    • provider가 다른 하위 모듈이 있는 경우 하위 모듈 별로 provider를 설정할 수 있습니다.
      • bzz는 항상 별도로 provider를 설정해야 합니다.
    • provider 설정을 좀 더 세부적으로 할 수 있습니다.
  • givenProvider
    • 이더리움 호환 브라우저에 의해 설정되는 provider. 없는 경우 null을 리턴합니다. web3 인스턴스가 생성되기 전에 설정되어야 하기 때문에 전역 함수입니다.
  • currentProvider
  • BatchRequest
    • 배치 요청을 생성하고 실행할 수 있는 클래스
    • add(request)
      • To add a request object to the batch call.
    • execute()
      • Will execute the batch request.
    • extend
      • web3에 하위 모듈을 추가하는 함수입니다. 추가된 모듈 객체를 리턴합니다.
      • methods 객체를 매개변수로 갖습니다. methods 객체는 String 타입 property와 Array 타입 methods를 속성으로 갖습니다.
        • property
          • eth나 utils와 같은 모듈에 추가되는 속성 이름
        • methods
          • name  – 함수 이름
          • call – RPC 함수 이름
          • params – 매개변수 갯수
          • inputFormatter – input formatter 함수들에 대한 배열
          • outputFormatter – output formatter 함수

 

web3.eth

이더리움 블록체인과 컨트랙트와 상호작용을 지원합니다.

이더리움 블록체인은 이더리움 주소의 유효성을 검증하기 위해 checksum 주소를 지원합니다. checksum 주소는 대소문자를 구분하고 주소에 대소문자를 가지고 주소의 유효성을 검증합니다.

eth 모듈 함수들은 checksum 주소를 사용합니다. eth 모듈 함수를 호출할 때 checksum 주소 유효성 검증을 거치지 않도록 하려면 모두 소문자이거나 모두 대문자인 이더리움 주소를 사용해야 합니다.

모듈 수준에서 제공해야 하는 provider 관련, BatchRequest, extend를 지원합니다.

  • defaultAccount
    • from을 요구하는 eth 모듈 함수에서 from을 명시하지 않고 기본 값을 사용하도록 할 수 있습니다. defaultAccount를 설정합니다. defaultAccount 초기 값은 undefined입니다. 
      • 서명이 필요한 함수인 경우 기본 계정으로 설정된 주소에 대한 개인키나 키스토어를 노드에 포함하고 있어야 합니다. 메타마스크를 사용하는 경우는 메타마스크에 해당 계정이 등록되어 있어야 합니다.
  • defaultBlock
    • 블록 정보가 필요한 eth 모듈 함수에서 블록 정보를 명시하지 않고 기본 값을 사용하도록 할 수 있습니다. defaultBlock을 설정합니다. defaultBlock의 초기 값은 “latest” 입니다. 
      • defaultBlock 값은 블록 번호를 나타내는 숫자나 “genesis”, “latest”, “pending”, “earliest”를 사용할 수 있습니다.
        • “genesis”, “earliest” – The genesis block
        • “latest” – The latest block (current head of the blockchain)
        • “pending” – The currently mined block (including pending transactions)
  • defaultHardfork, defaultChain, defaultCommon
    • is used for signing transactions locally.
      •  defaultHardfork로 설정 가능한 값은 “chainstart”, “homestead”, “dao”, “tangerineWhistle”, “spuriousDragon”, “byzantium”, “constantinople”, “petersburg”, “istanbul” 입니다. 초기 값은 “petersburg” 입니다.
      • defaultChain로 설정 가능한 값은 “mainnet”, “goerli”, “kovan”, “rinkeby”, “ropsten” 입니다. 초기 값은 “mainnet” 입니다.
    • defaultCommon는 customChain, baseChain, hardfork 속성을 갖는 객체입니다.
      • customChain은 custom 체인에 대한 정보를 설정할 수 있는 name, networkId, chainId 속성을 갖는 객체입니다.
  • transactionBlockTimeout
    • The transactionBlockTimeout is used over socket-based connections. This option defines the amount of new blocks it should wait until the first confirmation happens, otherwise the PromiEvent rejects with a timeout error. 기본 값은 50입니다.
  • transactionConfirmationBlocks
    • This defines the number of blocks it requires until a transaction is considered confirmed. 기본 값은 24입니다.
  • transactionPollingTimeout
    • The transactionPollingTimeout is used over HTTP connections. This option defines the number of seconds Web3 will wait for a receipt which confirms that a transaction was mined by the network. If this method times out, the transaction may still be pending. 기본 값은 750입니다.
  • handleRevert
    • revert 이유를 리턴할 것인지를 설정합니다.
  • maxListenersWarningThreshold
    •  This defines the threshold above which a warning about the number of event listeners attached to a provider which supports sockets subscriptions will be written to the console. You may see this warning if you call setProvider on large numbers of Web3 contract objects. 기본 값은 100입니다.
  • getProtocolVersion –  Promise – String
    • Promise를 리턴하는 함수는 인자로 callback 함수를 선택적으로 가질 수 있습니다. 이후 Promise를 리턴하는 함수는 이 내용을 명시하지 않겠습니다.
    • 노드의 이더리움 프로토콜 버전을 리턴합니다.
  • isSyncing – Promise – Object | Boolean
    • 노드가 현재 동기화 중인지 체크합니다. 동기화되지 않은 경우는 false를 리턴하고, 동기화된 경우는 다음과 같은 속성들을 갖는 객체를 리턴합니다.
      • startingBlock, currentBlock, highestBlock, knownStates, pulledStates
  • getCoinbase – Promise – String
    • 노드에 설정된 코인 베이스 주소를 리턴합니다.
  • isMining – Promise – Boolean
    • 노드가 채굴 중인지 여부를 리턴합니다.
  • getHashrate – Promise – Number
    • 노드의 채굴 중인 경우 초당 해시레이트를 리턴합니다.
  • getGasPrice – Promise – String
    • 평균 가스 가격을 리턴합니다.
  • getAccounts – Promise – Array
    • 노드가 컨트롤하는 계정 목록을 리턴합니다.
  • getBlockNumber – Promise – Number
    • 현재 블록 넘버를 리턴합니다.
  • getBalance – Promise – String
    • 인자로 블록 번호와 주소와 블록 번호를 사용합니다. 블록 번호는 생략 가능합니다. 생략하는 경우 defaultBlock을 사용합니다.
    • 블록을 기준으로 주소의 잔고를 리턴합니다.
  • getStorageAt – Promise – String
    • 인자로 주소와 인덱스와 블록 번호를 사용합니다. 블록 번호는 생략 가능합니다.
    • 주소의 인덱스 위치의 storage 값을 리턴합니다.
  • getCode – Promise – String
    • 인자로 주소와 블록 번호를 사용합니다. 블록 번호는 생략 가능합니다.
    • 주소의 코드를 리턴합니다.
  • getBlock – Promise – Object
    • 인자로 블록 번호 또는 블록 해시 값과 블록에 모든 트랜잭션을 객체로 포함할 것인지, 트랜잭션 해시만 포함할 것인지 여부를 사용합니다.
    • 블록 번호 또는 블록 해시 값에 해당하는 블록을 리턴합니다. 블록 객체는 다음과 같은 속성을 포함합니다.
      • number, hash, nonce, logsBloom – 블록의 로그에 대한 블룸 필터
        • pending 블록인 경우 null
      • parentHash, sha3Uncles
      • transactionsRoot, stateRoot
      • miner
        • 채굴 보상을 받는 주소
      • difficulty, totalDifficulty, extraData
      • size – 블록의 바이트 크기
      • gasLimit, gasUsed, timestamp
      • transactions
      • uncles – uncle 해시 목록 배열
  • getBlockTransactionCount – Promise – Number
    • 인자로 블록 번호 또는 블록 해시 값을 사용합니다.
    • 블록의 트랜잭션 갯수를 리턴합니다.
  • getBlockUncleCount – Promise – Number
    • 인자로 블록 번호 또는 블록 해시 값을 사용합니다.
    • 블록의 uncle 갯수를 리턴합니다.
  • getUncle – Promise – Object
    • 인자로 블록 번호 또는 블록 해시 값과 인덱스를 사용합니다.
    • 블록의 uncle들 중 인덱스 위치의 uncle을 리턴합니다. getBlock과 같이 블록 객체를 리턴합니다.
  • getTransaction – Promise – Object
    • 인자로 트랜잭션 해시를 사용합니다.
    • 트랜잭션 해시에 해당하는 트랜잭션 객체를 리턴합니다. 트랜잭션 객체는 다음과 같은 속성들을 포함합니다.
      • hash, nonce, blockHash, blockNumber, transactionIndex
      • from, to, value
      • gasPrice, gas
      • input – The data sent along with the transaction.
  • getPendingTransactions – Promise – Object[]
    • pending 트랜잭션들을 리턴합니다. 트랜잭션 객체 배열을 리턴합니다.
  • getTransactionFromBlock – Promise – Object
    • 인자로 블록 번호 또는 블록 해시 값과 인덱스를 사용합니다.
    • 블록의 트랜잭션들 중 인덱스 위치에 해당하는 트랜잭션을 리턴합니다. 트랜잭션 객체를 리턴합니다.
  • getTransactionReceipt – Promise – Object
    • 인자로 트랜잭션 해시 값을 사용합니다.
    • 트랜잭션 해시에 해당하는 transaction receipt을 리턴합니다. transaction receipt 객체를 리턴합니다. transaction receipt 객체는 다음과 같은 속성을 포함합니다.
      • status
        • 트랜잭션이 성공하면 true, 트랜잭션이 revert되면 false
      • blockHash, blockNumber, transactionHash, transactionIndex
      • from, to
      • contractAddress
      • cumulativeGasUsed
        • The total amount of gas used when this transaction was executed in the block.
      • gasUsed
        • The amount of gas used by this specific transaction alone.
      • logs
        • Array of log objects, which this transaction generated.
  • getTransactionCount – Promise – Number
    • 인자로 주소와 블록 번호를 사용합니다. 블록 번호는 생략가능합니다.
    • 주소로 보내진 트랜잭션 갯수를 리턴합니다.
  • sendTransaction
    • 인자로 트랜잭션 객체를 사용합니다. 트랜잭션 객체는 다음과 같은 속성을 갖습니다.
      • from, to, value
      • gasPrice, gas
      • data – 컨트랙트 함수 호출을 위한 데이터를 포함하는 ABI 바이트 문자열 또는 컨트랙트 생성 트랜잭션의 경우 초기화 코드
      • nonce, chain, hardfork, common
    • callback 함수 hash 값을 리턴합니다.
    • 다음과 같은 이벤트들에 접근할 수 있습니다.
      • “sending”
        • 트랜잭션 요청이 transmitting되기 전에 발생, payload 객체를 리턴
      • “sent”
        • request body가 작성되었지만 트랜잭션 해시를 받기 전에 발생, payload 객체를 리턴
      • “transactionHash”
        • 트랜잭션 해시가 가용할 때 발생, 트랜잭션 해시를 리턴
      • “receipt”
        • transaction receipt이 가용할 때 발생, receipt 객체를 리턴
      • “confirmation”
        • 12번째 까지 매 확정 시마다 발생, 확정 수와 receipt 객체를 리턴, 확정 수가 0인 경우는 채굴되었을 때를 나타냅니다.
      • “error”
        • 에러가 발생했을 때 발생, Error 객체를 리턴
  • sendSignedTransaction – Promise – String
    • 인자로 서명된 트랜잭션 데이터를 사용합니다.
    • 서명된 트랜잭션을 전송합니다. sendTransaction과 리턴이 같습니다.
  • sign – Promise – String
    • 인자로 서명 대상 데이터와 주소를 사용합니다.
      • 데이터가 문자열이면  web3.utils.utf8ToHex를 사용해서 16진수로 변환할 수 있습니다. 
    • 서명을 리턴합니다.
  • signTransaction – Promise – Object
    • 트랜잭션 데이터 객체와 주소를 인자로 받습니다.
    • RLP 인코딩된 트랜잭션 객체를 리턴합니다. 이 객체는 속성으로 tx와 raw를 갖습니다. raw 속성 값을 사용해서 sendSignedTransaction로 트랜잭션을 전송할 수 있습니다. 
  • call – Promise – String
    • 인자로 call 객체와 블록 번호를 사용합니다. 블록 번호는 생략가능합니다.
    •  EVM에서 실행되지만 블록체인으로 채굴되지 않는 message call 트랜잭션을 실행합니다.
    • call에서 리턴된 데이터를 리턴합니다.
  • estimateGas – Promise – Number
    • 인자로 call 객체를 사용합니다.
    • message call 이나 transaction 실행을 모의하고 사용된 가스를 리턴합니다.
  • getPastLogs – Promise – Array
    • 인자로 옵션 객체를 사용합니다. 옵션 객체는 다음과 같은 속성을 포함합니다.
      • fromBlock, toBlock, address
      • topics
        • An array of values which must each appear in the log entries. The order is important, if you want to leave topics out use null.  You can also pass an array for each topic with options for that topic.
    • 옵션에 매칭되는 과거 로그 객체 배열을 리턴합니다. 객체는 다음과 같은 속성을 갖습니다.
      • address
      • data, topics
      • logIndex, transactionIndex, transactionHash, blockHash, blockNumber
  • getWork – Promise – Array
    • Gets work for miners to mine on. Returns the hash of the current block, the seedHash, and the boundary condition to be met (“target”).
  • submitWork – Promise – Boolean
    • Used for submitting a proof-of-work solution.
  • requestAccounts – Promise – Array
    • This method will request/enable the accounts from the current environment. This method will only work if you’re using the injected provider from a application like Metamask. It doesn’t work if you’re connected to a node with a default Web3.js provider (WebsocketProvider, HttpProvidder and IpcProvider).
  • getChainId – Promise – Number
    • 노드에 연결된 체인 id를 리턴합니다.
  • getNodeInfo – Promise – String
    • 클라이언트 버전을 리턴합니다.
  • getProof – Promise – Object
    • Returns the account and storage-values of the specified account including the Merkle-proof as described in EIP-1186.
    • 리턴되는 계정 객체는 다음과 같은 속성을 포함합니다.
      • address, balance, codeHash, nonce
      • storageHash
        • SHA3 of the StorageRoot. All storage will deliver a MerkleProof starting with this rootHash.
      • accountProof
        • Array of rlp-serialized MerkleTree-Nodes, starting with the stateRoot-Node, following the path of the SHA3 (address) as key.
      • storageProof
        • Array of storage-entries as requested.
          • key – The requested storage key.
          • value – The storage value.
About the Author
(주)뉴테크프라임 대표 김현남입니다. 저에 대해 좀 더 알기를 원하시는 분은 아래 링크를 참조하세요. http://www.umlcert.com/kimhn/

Leave a Reply

*