Klaytn 문서 아카이브
시작하기스마트 컨트랙트노드 운영dApp 개발자
  • Klaytn 문서
  • -
    • Klaytn Overview
      • 왜 클레이튼일까요?
      • 클레이튼 디자인
        • 합의 메커니즘
        • 계정
        • 트랜잭션
          • 기본
          • 수수료 위임 트랜잭션
          • 수수료 부분 위임 트랜잭션
          • Ethereum
        • 연산
          • 클레이튼 스마트 컨트랙트
          • 실행 모델(Execution Model)
          • Computation Cost
            • 연산 비용 (구 버전 문서)
          • Klaytn 가상머신
            • 클레이튼 가상머신 (구 버전 문서)
        • 스토리지
        • 트랜잭션 비용
          • 트랜잭션 비용 (구 버전 문서)
        • 클레이튼의 네이티브 코인 - KLAY
        • 토큰 이코노미
        • 거버넌스
        • 다중 채널
        • KNI
      • 확장성 솔루션
    • Getting Started
      • Deploying Smart Contract Using Foundry
      • Deploying Smart Contract Using Hardhat
      • Deploying Smart Contract Using KEN
        • Launch an Endpoint Node
        • Top up your Account
        • Install Development Tools
        • Deploy a Smart Contract
        • Check the Deployment
        • Account Management
          • Creating Accounts
          • Managing Accounts
      • Development Environment
      • Getting KLAY
    • 스마트 컨트랙트
      • 솔리디티 - 스마트 컨트랙트 언어
      • 미리 컴파일된 컨트랙트
        • 미리 컴파일된 컨트랙트 (구 버전 문서)
      • IDE 및 도구
        • Truffle
      • 샘플 컨트랙트
        • KlaytnGreeter
        • ERC-20
          • 1. ERC-20 스마트 컨트랙트 작성
          • 2. 스마트 컨트랙트 배포
          • 3. 클레이튼 월렛에서 ERC-20 토큰 사용
        • ERC-721
          • 1. ERC-721 스마트 컨트랙트 작성
          • 2. Deploying Smart Contract
      • 테스트 가이드
      • 배포 가이드
      • 클레이튼 호환 토큰
      • 이더리움 컨트랙트 이식
    • Run a Node
      • 배포
        • Endpoint Node
          • 시스템 요구사항
          • 설치 가이드
            • 다운로드
            • Installation Guide
            • 환경설정
            • EN 실행하기
            • 설치 테스트하기
          • ken CLI 명령어
          • JSON-RPC API
        • 코어 셀
          • System Requirements
          • 네트워크 설정
          • Installation Guide
            • Download
            • 설치하기 전에
            • 컨센서스 노드 설정
              • Installation Guide
              • Configuration
              • CN 실행하기
            • 프록시 노드 설정
              • Installation Guide
              • Configuration
              • PN 실행하기
            • 코어 셀 테스트하기
          • 모니터링 설정
          • H/A 설정
        • Service Chain
          • Getting Started
            • 4개 노드 서비스 체인 설정하기
            • Connecting to Baobab
            • 크로스체인 토큰 전송
            • HA(High Availability) for ServiceChain
            • Nested ServiceChain
            • Value Transfer between Sibling ServiceChains
          • 참조 매뉴얼
            • System Requirements
            • Download
            • SCN User Guide
              • Installation
              • Configuration
              • SCN 실행 및 중지하기
              • 노드 상태 확인하기
              • kscn commands
              • homi commands
            • SPN/SEN User Guide
              • Installation
              • Configuration
              • 노드 실행 및 중지
              • Checking Node Status
            • Bridge Configuration
            • 앵커링
            • KAS 앵커링
            • 토큰 전송
            • Configuration Files
            • 로그 파일
            • Genesis JSON
            • 업그레이드 및 하드포크
          • How-To Guides
        • Download Node Packages
          • v1.11.1
          • v1.11.0
          • v1.10.2
          • v1.10.1
          • v1.10.0
          • v1.9.1
          • v1.9.0
          • v1.8.4
          • v1.8.3
          • v1.8.2
          • v1.8.1
          • v1.8.0
          • v1.7.3
          • v1.7.2
          • v1.7.1
          • v1.7.0
          • v1.6.4
          • v1.6.3
          • v1.6.2
          • v1.6.1
          • v1.6.0
          • v1.5.3
          • v1.5.2
          • v1.5.1
          • v1.5.0
          • v1.4.2
          • v1.4.1
          • v1.4.0
          • v1.3.0
          • v1.2.0
          • v1.1.1
          • v1.0.0
          • v0.9.6
          • v0.8.2
    • 운영 가이드
      • Configuration
      • 노드 로그
      • Log operation
      • 에러 및 문제 해결
      • Klaytn Command
      • Chaindata Change
      • Chaindata Migration
    • dApp Developers
      • JSON-RPC APIs
        • API references
          • eth
            • Caution
            • Account
            • Block
            • Transaction
            • Config
            • Filter
            • Gas
            • Miscellaneous
          • klay
            • Account
            • Block
            • Transaction
              • Working with Klaytn Transaction Types
            • Configuration
            • Filter
            • Gas
            • Miscellaneous
          • net
          • debug
            • Logging
            • Profiling
            • Runtime Tracing
            • Runtime Debugging
            • VM Tracing
            • VM Standard Tracing
            • Blockchain Inspection
          • admin
          • personal
          • txpool
          • governance
        • Service Chain API references
          • mainbridge
          • subbridge
        • Transaction Error Codes
      • RPC Service Providers
        • Public Endpoints
      • SDK & Libraries for interacting with Klaytn Node
        • caver-js
          • Getting Started
          • Sending a sample transaction
          • API references
            • caver.account
            • caver.wallet
              • caver.wallet.keyring
            • caver.transaction
              • Basic
              • Fee Delegation
              • Partial Fee Delegation
            • caver.rpc
              • caver.rpc.klay
              • caver.rpc.net
              • caver.rpc.governance
            • caver.contract
            • caver.abi
            • caver.kct
              • caver.kct.kip7
              • caver.kct.kip17
              • caver.kct.kip37
            • caver.validator
            • caver.utils
            • caver.ipfs
          • caver-js ~v1.4.1
            • Getting Started (~v1.4.1)
            • API references
              • caver.klay
                • Account
                • Block
                • Transaction
                  • Legacy
                  • Value Transfer
                  • Value Transfer Memo
                  • Account Update
                  • Smart Contract Deploy
                  • Smart Contract Execution
                  • Cancel
                • Configuration
                • Filter
                • Miscellaneous
              • caver.klay.net
              • caver.klay.accounts
              • caver.klay.Contract
              • caver.klay.KIP7
              • caver.klay.KIP17
              • caver.klay.abi
              • caver.utils (~v1.4.1)
            • Porting from web3.js
        • caver-java
          • Getting Started
          • API references
          • caver-java ~v1.4.0
            • Getting Started (~v1.4.0)
            • Porting from web3j
        • ethers.js
        • web3.js
      • Tutorials
        • Klaytn Online Toolkit
        • Fee Delegation Example
        • Count DApp
          • 1. Environment Setup
          • 2. Clone Count DApp
          • 3. Directory Structure
          • 4. Write Smart Contract
          • 5. Frontend Code Overview
            • 5-1. Blocknumber Component
            • 5-2. Auth Component
            • 5-3. Count Component
          • 6. Deploy Contract
          • 7. Run App
        • Klaystagram
          • 1. Environment Setup
          • 2. Clone Klaystagram DApp
          • 3. Directory Structure
          • 4. Write Klaystagram Smart Contract
          • 5. Deploy Contract
          • 6. Frontend Code Overview
          • 7. FeedPage
            • 7-1. Connect Contract to Frontend
            • 7-2. UploadPhoto Component
            • 7-3. Feed Component
            • 7-4. TransferOwnership Component
          • 8. Run App
        • Building a Buy Me a Coffee dApp
          • 1. Project Setup
          • 2. Creating a BMC Smart Contract
          • 3. Testing the contract using scripts
          • 4. Deploying BMC Smart contract
          • 5. Building the BMC Frontend with React and Web3Onboard
          • 6. Deploying Frontend code on IPFS using Fleek
          • 7. Conclusion
        • Migrating Ethereum App to Klaytn
        • Connecting MetaMask
        • Connecting Remix
        • Verifying Smart Contracts Using Block Explorers
      • Developer Tools
        • Wallets
          • Kaikas
          • Klaytn Wallet
          • Klaytn Safe
            • Klaytn Safe Design
            • Create a Safe
            • Add assets
            • Send assets
            • Contract Interaction
            • Transaction Builder
            • Points to Note
            • Frequently Asked Questions
          • Wallet Libraries
            • Web3Auth
            • Web3Modal
            • Web3-Onboard
        • Oracles
          • Orakl Network
          • Witnet
          • SupraOracles
        • Block Explorers
          • Klaytnscope
          • Klaytnfinder
        • Klaytn Contracts Wizard
    • Glossary
  • ---
    • Klaytn 하드포크
    • 클레이튼 2.0
      • 메타버스 패키지
      • 완결성과 개선 사항들
      • 이더리움 호환성
      • 거버넌스 탈중앙화
      • 대규모 에코 펀드
    • FAQ
    • 오픈 소스
    • 이용약관
    • 지원 언어
  • ℹ️최신 Klaytn 문서
Powered by GitBook
On this page
  • new contract
  • options
  • options.address
  • options.jsonInterface
  • clone
  • deploy
  • methods
  • cf) *Function signature (Function selector)
  • methods.myMethod.call
  • methods.myMethod.send
  • methods.myMethod.estimateGas
  • methods.myMethod.encodeABI
  • once
  • events
  • events.allEvents
  • getPastEvents

Was this helpful?

  1. -
  2. dApp Developers
  3. SDK & Libraries for interacting with Klaytn Node
  4. caver-js
  5. caver-js ~v1.4.1
  6. API references

caver.klay.Contract

스마트 컨트랙트와 상호작용하는 데 사용되는 caver-js 객체입니다.

The caver.klay.Contract object makes it easy to interact with smart contracts on the Klaytn blockchain. When you create a new contract object, you give it the JSON interface of the respective smart contract and caver will auto convert all calls into low level ABI calls over RPC for you.

This allows you to interact with smart contracts as if they were JavaScript objects.

new contract

new caver.klay.Contract(jsonInterface [, address] [, options])

Creates a new contract instance with all its methods and events defined in its JSON interface object.

Parameters

Name
Type
Description

jsonInterface

Object

The JSON interface for the contract to instantiate

address

String

(optional) The address of the smart contract to call. Can be added later using myContract.options.address = '0x1234..'

options

Object

(optional) The options of the contract. See the table below for the details.

The options object contains the following:

Name
Type
Description

from

String

(optional) The address from which transactions should be made.

gasPrice

String

(optional) The gas price in peb to use for transactions.

gas

Number

(optional) The maximum gas provided for a transaction (gas limit).

data

String

(optional) The byte code of the contract. Used when the contract gets deployed.

Return Value

Type
Description

Object

The contract instance with all its methods and events.

Example

var myContract = new caver.klay.Contract([...], '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', {
      from: '0x1234567890123456789012345678901234567891', // default from address
      gasPrice: '25000000000' // default gas price in peb, 25 Gpeb in this case
});

var myContract = new caver.klay.Contract([...], 'myContract', {
      from: '0x1234567890123456789012345678901234567891', // default from address
      gasPrice: '25000000000' // default gas price in peb, 25 Gpeb in this case
});

options

myContract.options

The options object for the contract instance. from, gas and gasPrice are used as fallback values when sending transactions.

Properties

Name
Type
Description

address

String

jsonInterface

Array

data

String

The byte code of the contract. Used when the contract gets deployed.

from

String

트랜잭션이 만들어진 송신자 주소.

gasPrice

String

The gas price in peb to use for transactions.

gas

Number

The maximum gas provided for a transaction (gas limit).

Example

> myContract.options;
{
    address: '0x1234567890123456789012345678901234567891',
    jsonInterface: [...],
    from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
    gasPrice: '10000000000000',
    gas: 1000000
}

> myContract.options.from = '0x1234567890123456789012345678901234567891'; // default from address
> myContract.options.gasPrice = '25000000000000'; // default gas price in peb
> myContract.options.gas = 5000000; // provide as fallback always 5M gas

options.address

myContract.options.address

The address used for this contract instance myContract. All transactions generated by caver-js from this contract will contain this address as the "to". 주소는 소문자로 저장됩니다.

Property

Name
Type
Description

address

String \

null

Example

>  myContract.options.address;
'0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae'

// set a new address
>  myContract.options.address = '0x1234FFDD...';

options.jsonInterface

myContract.options.jsonInterface

The JSON interface object derived from the ABI of this contract myContract.

Property

Name
Type
Description

jsonInterface

Array

The JSON interface for this contract. Re-setting this will regenerate the methods and events of the contract instance.

Example

> myContract.options.jsonInterface;
[{
      "type":"function",
      "name":"foo",
      "inputs": [{"name":"a","type":"uint256"}],
      "outputs": [{"name":"b","type":"address"}]
 },{
      "type":"event",
      "name":"Event"
      "inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"bytes32","indexed":false}],
 }]

// set a new interface
> myContract.options.jsonInterface = [...];

clone

myContract.clone()

Clones the current contract instance.

Parameters

None

Return Value

Type
Description

Object

The new cloned contract instance.

Example

> var contract1 = new caver.klay.Contract(abi, address, {gasPrice: '12345678', from: fromAddress});
> var contract2 = contract1.clone();
> contract2.options.address = address2;
> (contract1.options.address !== contract2.options.address);
true

deploy

myContract.deploy(options)

컨트랙트를 Klaytn 블록체인에 배포합니다. After successful deployment, the promise will be resolved with a new contract instance.

Parameters

options: 배포에 사용되는 옵션 객체:

Name
Type
Description

data

String

The byte code of the contract.

arguments

Array

(optional) The arguments that get passed to the constructor on deployment.

Return Value

Object: 트랜잭션 객체:

Type
Description

Array

arguments: 이전에 메소드에 전달되었던 인자. 이들은 변경될 수 있습니다.

Function

Function

Function

Example

> myContract.deploy({
      data: '0x12345...',
      arguments: [123, 'My String']
  })
  .send({
      from: '0x1234567890123456789012345678901234567891',
      gas: 1500000,
      value: 0,
  }, function(error, transactionHash) { ... })
  .on('error', function(error) { ... })
  .on('transactionHash', function(transactionHash) { ... })
  .on('receipt', function(receipt) {
     console.log(receipt.contractAddress) // contains the new contract address
   })
  .then(function(newContractInstance) {
      console.log(newContractInstance.options.address) // instance with the new contract address
  });

// When the data is already set as an option to the contract itself
> myContract.options.data = '0x12345...';

> myContract.deploy({
        arguments: [123, 'My String']
  })
  .send({
      from: '0x1234567890123456789012345678901234567891',
      gas: 1500000,
      value: 0,
  })
  .then(function(newContractInstance) {
      console.log(newContractInstance.options.address) // instance with the new contract address
  });

// Simply encoding
> myContract.deploy({
      data: '0x12345...',
      arguments: [123, 'My String']
  })
  .encodeABI();
'0x12345...0000012345678765432'

// Gas estimation
> myContract.deploy({
      data: '0x12345...',
      arguments: [123, 'My String']
  })
  .estimateGas(function(err, gas) {
      console.log(gas);
  });

methods

myContract.methods.myMethod([param1 [, param2 [, ...]]])

Creates a transaction object for that method, which then can be called, sent, estimated or ABI encoded.

이 스마트 컨트랙트의 메소드는 다음을 통해 이용할 수 있습니다:

  • 이름: myContract.methods.myMethod(123)

  • 매개변수가 있는 이름: myContract.methods['myMethod(uint256)'](123)

  • The signature*: myContract.methods['0x58cf5f10'](123)

This allows calling functions with the same name but different parameters from the JavaScript contract object.

cf) *Function signature (Function selector)

The first four bytes of the call data for a function call specifies the function to be called. It is the first (left, high-order in big-endian) four bytes of the Keccak-256 (SHA-3) hash of the signature of the function.

The function signature can be made by 2 different methods. 1. caver.klay.abi.encodeFunctionSignature('funcName(paramType1,paramType2,...)') 2. caver.utils.sha3('funcName(paramType1,paramType2,...)').substr(0, 10)

ex)

caver.klay.abi.encodeFunctionSignature('myMethod(uint256)')
> 0x58cf5f10

caver.utils.sha3('myMethod(uint256)').substr(0, 10)
> 0x58cf5f10

Parameters

모든 메소드의 매개변수는 JSON 인터페이스에 정의된 스마트 컨트랙트 메소드에 의존합니다.

Return Value

Object: The transaction object:

Type
Description

Array

arguments: The arguments passed to the method before. They can be changed.

Function

Function

Function

Function

Example

// calling a method
> myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}, function(error, result) {
      ...
  });

// or sending and using a promise
> myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
  .then(function(receipt) {
    // receipt can also be a new contract instance, when coming from a "contract.deploy({...}).send()"
  });

// or sending and using the events
> myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
  .on('transactionHash', function(hash) {
      ...
  })
  .on('receipt', function(receipt) {
      ...
  })
  .on('error', console.error);

methods.myMethod.call

myContract.methods.myMethod([param1 [, param2 [, ...]]]).call(options [, callback])

Will call a "constant" method and execute its smart contract method in the Klaytn Virtual Machine without sending any transaction. Note that calling cannot alter the smart contract state.

Parameters

Name
Type
Description

options

Object

(optional) The options used for calling. See the table below for the details.

callback

Function

(optional) This callback will be fired with the result of the smart contract method execution as the second argument, or with an error object as the first argument.

The options object can contain the following:

Name
Type
Description

from

String

(optional) The address the call “transaction” should be made from.

gasPrice

String

(optional) The gas price in peb to use for this call "transaction".

gas

Number

(optional) The maximum gas provided for this call "transaction" (gas limit).

Return Value

Promise returns Mixed: The return value(s) of the smart contract method. If it returns a single value, it is returned as it is. If it has multiple return values, they are returned as an object with properties and indices.

Example

// using the callback
> myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}, function(error, result) {
      ...
  });

// using the promise
> myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
  .then(function(result) {
      ...
  });
// Solidity: MULTI-ARGUMENT RETURN
contract MyContract {
    function myFunction() returns(uint256 myNumber, string myString) {
        return (23456, "Hello!%");
    }
}
> var MyContract = new caver.klay.Contract(abi, address);
> MyContract.methods.myFunction().call().then(console.log);
Result {
      myNumber: '23456',
      myString: 'Hello!%',
      0: '23456', // these are here as fallbacks if the name is not known or given
      1: 'Hello!%'
}
// Solidity: SINGLE-ARGUMENT RETURN
contract MyContract {
    function myFunction() returns(string myString) {
        return "Hello!%";
    }
}
> var MyContract = new caver.klay.Contract(abi, address);
> MyContract.methods.myFunction().call().then(console.log);
"Hello!%"

methods.myMethod.send

myContract.methods.myMethod([param1 [, param2 [, ...]]]).send(options [, callback])

스마트 컨트랙트에 트랜잭션을 보내고 그 메소드를 실행합니다. Note that this can alter the smart contract state.

Parameters

Name
Type
Description

options

Object

The options used for sending. See the table below for the details.

callback

Function

(optional) This callback will be fired first with the "transactionHash", or with an error object as the first argument.

The options object can contain the following:

Name
Type
Description

from

String

The address from which the transaction should be sent.

gasPrice

String

(optional) The gas price in peb to use for this transaction.

gas

Number

The maximum gas provided for this transaction (gas limit).

value

Number \

String | BN | BigNumber

Return Value

callback은 32바이트 트랜잭션 해시를 반환합니다.

PromiEvent: 프로미스(promise)가 조합된 이벤트 이미터(event emitter). Will be resolved when the transaction receipt is available, or if this send() is called from a someContract.deploy(), then the promise will be resolved with the new contract instance. 추가로 다음과 같은 이벤트를 사용할 수 있습니다:

Name
Type
Description

transactionHash

String

트랜잭션이 전송된 직후 및 트랜잭션 해시를 사용할 수 있을 때 발생합니다.

receipt

Object

error

Error

전송 중 오류가 발생하면 발생됩니다. On an out-of-gas error, the second parameter is the receipt.

Example

// using the callback
> myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}, function(error, transactionHash) {
    ...
  });

// using the promise
> myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
  .then(function(receipt) {
    // receipt can also be a new contract instance, when coming from a "contract.deploy({...}).send()"
  });


// using the event emitter
> myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
  .on('transactionHash', function(hash) {
    ...
  })
  .on('receipt', function(receipt) {
    console.log(receipt);
  })
  .on('error', console.error); // If there is an out-of-gas error, the second parameter is the receipt.

// receipt example
{
   "transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
   "transactionIndex": 0,
   "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
   "blockNumber": 3,
   "contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
   "gasUsed": 30234,
   "events": {
     "MyEvent": {
       returnValues: {
         myIndexedParam: 20,
         myOtherIndexedParam: '0x123456789...',
         myNonIndexParam: 'My String'
       },
       raw: {
         data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
         topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
       },
       event: 'MyEvent',
       signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
       logIndex: 0,
       transactionIndex: 0,
       transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
       blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
       blockNumber: 1234,
       address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
    },
    "MyOtherEvent": {
      ...
    },
    "MyMultipleEvent":[{...}, {...}] // If there are a multiple of the same events, they will be in an array.
  }
}

methods.myMethod.estimateGas

myContract.methods.myMethod([param1 [, param2 [, ...]]]).estimateGas(options [, callback])

Will estimate the gas that a method execution will take when executed in the Klaytn Virtual Machine. The estimation can differ from the actual gas used when later sending a transaction, as the state of the smart contract can be different at that time.

Parameters

Name
Type
Description

options

Object

(optional) The options used for calling. See the table below for the details.

callback

Function

(optional) This callback will be fired with the result of the gas estimation as the second argument, or with an error object as the first argument.

The options object can contain the following:

Name
Type
Description

from

String

(optional) The address from which the call "transaction" should be made.

gas

Number

(optional) The maximum gas provided for this call "transaction" (gas limit). Setting a specific value helps to detect out of gas errors. If all gas is used, it will return the same number.

value

Number \

String | BN | BigNumber

Return Value

Promise는 Number를 반환합니다 - 모의 호출/트랜잭션에 사용된 가스.

Example

// using the callback
> myContract.methods.myMethod(123).estimateGas({gas: 5000000}, function(error, gasAmount) {
    if(gasAmount == 5000000)
      console.log('Method ran out of gas');
  });

// using the promise
> myContract.methods.myMethod(123).estimateGas({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
  .then(function(gasAmount) {
    ...
  })
  .catch(function(error) {
    ...
  });

methods.myMethod.encodeABI

myContract.methods.myMethod([param1 [, param2[, ...]]]).encodeABI()

Encodes the ABI for this method. This can be used to send a transaction, call a method, or pass it into another smart contract method as arguments.

Parameters

None

Return Value

Type
Description

String

The encoded ABI byte code to send via a transaction or call.

Example

> myContract.methods.myMethod(123).encodeABI();
'0x58cf5f1000000000000000000000000000000000000000000000000000000000000007B'

once

myContract.once(event [, options], callback)

Subscribes to an event and unsubscribes immediately after the first event or error. Will only fire for a single event.

Parameters

Name
Type
Description

event

String

컨트랙트, 또는 모든 이벤트를 받기 위한 "allEvents"에서의 이벤트 이름.

options

Object

(optional) The options used for deployment. See the table below for the details.

callback

Function

The options object can contain the following:

Name
Type
Description

filter

Object

(optional) Lets you filter events by indexed parameters, e.g., {filter: {myNumber: [12,13]}} means all events where "myNumber" is 12 or 13.

topics

Array

(optional) This allows you to manually set the topics for the event filter. 필터 특성 및 이벤트 서명이 제공되면, topic[0] 가 자동으로 설정되지 않습니다.

Return Value

undefined

Example

> myContract.once('MyEvent', {
    filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
  }, function(error, event) { console.log(event); });

// event output example
{
    returnValues: {
        myIndexedParam: 20,
        myOtherIndexedParam: '0x123456789...',
        myNonIndexParam: 'My String'
    },
    raw: {
        data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
        topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
    },
    event: 'MyEvent',
    signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
    logIndex: 0,
    transactionIndex: 0,
    transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
    blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
    blockNumber: 1234,
    address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
}

events

myContract.events.MyEvent([options][, callback])

이벤트를 구독합니다.

Parameters

Name
Type
Description

options

Object

(optional) The options used for deployment. See the table below for the details.

callback

Function

(optional) This callback will be fired for each event as the second argument, or an error as the first argument.

The options object can contain the following:

Name
Type
Description

filter

Object

(optional) Lets you filter events by indexed parameters, e.g., {filter: {myNumber: [12,13]}} means all events where "myNumber" is 12 or 13.

fromBlock

Number

(optional) The block number from which to get events on.

topics

Array

(optional) This allows to manually set the topics for the event filter. If given the filter property and event signature, topic[0] will not be set automatically.

Return Value

EventEmitter: 이벤트 이미터는 다음 이벤트를 가집니다:

Name
Type
Description

data

Object

이벤트 객체를 인수로 각 수신 이벤트를 발생합니다.

error

Object

구독 오류가 발생하면 발생합니다.

반환된 이벤트 Object의 구조는 다음과 같습니다:

Name
Type
Description

event

String

이벤트 이름.

signature

String \

null

address

String

이 이벤트가 발생한 주소.

returnValues

Object

The return values coming from the event, e.g., {myVar: 1, myVar2: '0x234...'}.

logIndex

Number

블록에서 이벤트 인덱스 위치의 정수값.

transactionIndex

Number

이벤트가 생성된 트랜잭션의 인덱스 위치의 정수값.

transactionHash

32-byte String

이 이벤트가 생성된 블록의 해시. 아직 보류 중인 경우 null.

blockHash

32-byte String

Hash of the block this event was created in. null when it is still pending.

blockNumber

Number

이 로그가 생성된 블록 번호. 아직 보류 중인 경우 null.

raw.data

String

색인화되지 않은 로그 매개변수를 포함하는 데이터.

raw.topics

Array

최대 4개의 32바이트 주제를 가진 배열, 주제 1-3은 이벤트의 색인화된 매개변수가 포함됩니다.

id

String

로그 식별자. It is made through concatenating "log_" string with keccak256(blockHash + transactionHash + logIndex).substr(0, 8)

Example

> myContract.events.MyEvent({
    filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
    fromBlock: 0
  }, function(error, event) { console.log(event); })
  .on('data', function(event){
      console.log(event); // same results as the optional callback above
  })
  .on('error', console.error);

// event output example
{
    returnValues: {
        myIndexedParam: 20,
        myOtherIndexedParam: '0x123456789...',
        myNonIndexParam: 'My String'
    },
    raw: {
        data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
        topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
    },
    event: 'MyEvent',
    signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
    logIndex: 0,
    transactionIndex: 0,
    transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
    blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
    blockNumber: 1234,
    address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
    id: 'log_41d221bc',
}

events.allEvents

myContract.events.allEvents([options] [, callback])

getPastEvents

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

이 컨트랙트의 이전 이벤트를 가져옵니다.

Parameters

Name
Type
Description

event

String

The name of the event in the contract, or "allEvents" to get all events.

options

Object

(optional) The options used for deployment. See the table below for the details.

callback

Function

(optional) This callback will be fired with an array of event logs as the second argument, or an error as the first argument.

옵션 개체에는 다음이 포함됩니다:

Name
Type
Description

filter

Object

(optional) Lets you filter events by indexed parameters, e.g., {filter: {myNumber: [12,13]}} means all events where "myNumber" is 12 or 13.

fromBlock

Number

(optional) The block number from which to get events on.

toBlock

Number

(optional) The block number to get events up to (defaults to "latest").

topics

Array

(optional) This allows manually setting the topics for the event filter. If given the filter property and event signature, topic[0] will not be set automatically.

Return Value

Promise returns Array: An array with the past event objects, matching the given event name and filter.

Example

> myContract.getPastEvents('MyEvent', {
      filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
      fromBlock: 0,
      toBlock: 'latest'
  }, function(error, events) { console.log(events); })
  .then(function(events) {
      console.log(events) // same results as the optional callback above
  });

[{
    returnValues: {
        myIndexedParam: 20,
        myOtherIndexedParam: '0x123456789...',
        myNonIndexParam: 'My String'
    },
    raw: {
        data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
        topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
    },
    event: 'MyEvent',
    signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
    logIndex: 0,
    transactionIndex: 0,
    transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
    blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
    blockNumber: 1234,
    address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
},{
      ...
}]
Previouscaver.klay.accountsNextcaver.klay.KIP7

Last updated 2 years ago

Was this helpful?

The address where the contract is deployed. Also see .

The JSON interface of the contract. Also see .

: Will deploy the contract. 프로미스는 영수증 대신 새 컨트랙트 인스턴스를 반환할 것입니다.

: Will estimate the gas used for the deployment.

: Encodes the ABI of the deployment, which is contract data + constructor parameters.

: Will call the "constant" method and execute its smart contract method in the Klaytn Virtual Machine without sending a transaction (cannot alter the smart contract state).

: Will send a transaction to the smart contract and execute its method (can alter the smart contract state).

: Will estimate the gas used when the method would be executed on the blockchain.

: Encodes the ABI for this method. 트랜잭션을 사용하여 메소드를 호출하거나 인수로써 다른 스마트 컨트랙트 메소드에 전달될 수 있습니다.

트랜잭션 영수증을 사용할 수 있을 때 발생합니다. 컨트랙트의 영수증에는 logs 속성이 없지만, 대신 이벤트 이름을 키로, 이벤트를 속성으로 하는 events 속성이 있습니다. See for details about the returned event object.

This callback will be fired for the first event as the second argument, or an error as the first argument. See for details about the event structure.

Same as but receives all events from this smart contract. 선택적으로 filter 속성은 해당 이벤트를 필터링할 수 있습니다.

events
options.address
options.jsonInterface
send
estimateGas
encodeABI
call
send
estimateGas
encodeABI
getPastEvents return values
getPastEvents return values