caver.contract 객체는 Klaytn 블록체인과 스마트 컨트랙트 간의 상호작용을 쉽게 만들어 줍니다. 새 컨트랙트 객체를 생성할 때 해당 스마트 컨트랙트를 위해 JSON 인터페이스를 제공해야 하는데, 이때 caver-js가 자바스크립트로 작성된 컨트랙트 객체와의 모든 호출을 RPC를 통해 하위 수준의 ABI 호출로 자동 변환시켜줍니다.
이를 통해 스마트 컨트랙트가 마치 자바스크립트 객체인 것처럼 스마트 컨트랙트와 상호작용할 수 있습니다.
Creates a new contract instance with all its methods and events defined in its JSON interface object.
Parameters
Name
Type
Description
jsonInterface
object
컨트랙트를 인스턴스화하기 위한 JSON 인터페이스
address
string
(선택 사항) 호출할 스마트 컨트랙트의 주소. myContract.options.address = '0x1234..'를 사용하여 나중에 추가할 수 있습니다.
options
object
(선택 사항) 컨트랙트 옵션. 자세한 내용은 아래 표를 참조하세요.
옵션 개체에는 다음이 포함됩니다:
Name
Type
Description
from
string
(선택 사항) 트랜잭션이 만들어진 송신자 주소.
gasPrice
string
(선택 사항) 트랜잭션에 사용할 peb 단위의 가스 가격.
gas
number
(선택 사항) 트랜잭션에 규정된 최대 가스 (가스 제한).
data
string
(선택 사항) 컨트랙트의 바이트 코드. 컨트랙트가 배포될 때 사용됩니다.
feeDelegation
boolean
(선택 사항) 수수료 위임 트랜잭션 사용 여부를 나타냅니다.
feePayer
string
(선택 사항) 트랜잭션 수수료를 부담하는 수수료 납부자의 주소입니다. feeDelegation이 true일 때, 값은 트랜잭션의 feePayer 필드에 설정됩니다.
feeRatio
string
(optional) Fee payer가 부담하게될 트랜잭션 수수료의 비율입니다. feeDelegation이 true이며, feeRatio가 유효한 값으로 설정되었을 경우, 부분 수수료 위임 트랜잭션이 사용됩니다. 유효한 범위는 1에서 99 사이입니다. 0이나 100 이상의 값은 허용되지 않습니다.
Return Value
Type
Description
object
모든 메소드와 이벤트가 있는 컨트랙트 인스턴스.
Example
constmyContract=newcaver.contract([...],'0x{address in hex}', { gasPrice:'25000000000' })
myContract.options
myContract.options
컨트랙트 인스턴스에 대한 options 객체. from, gas, gasPrice, feePayer 그리고 feeRatio는 트랜잭션 전송시 대체값으로 사용됩니다.
속성
Name
Type
Description
address
string
컨트랙트가 배포된 주소.
jsonInterface
Array
The JSON interface of the contract.
from
string
컨트랙트 배포/실행 트랜잭션을 전송하는 기본 주소입니다. 트랜잭션 생성시 from 주소가 정의되어 있지 않다면, 트랜잭션 생성시 항상 myContract.options.from가 사용됩니다.
gasPrice
string
트랜잭션에 사용할 peb 단위의 가스 가격.
gas
number
트랜잭션에 제공된 최대 가스 (가스 제한).
data
string
컨트랙트의 바이트 코드. Used when the contract gets deployed.
feeDelegation
boolean
(optional) Whether to use fee delegation transaction.
feePayer
string
(optional) The address of the fee payer paying the transaction fee. When feeDelegation is true, the value is set to the feePayer field in the transaction.
feeRatio
string
(optional) The ratio of the transaction fee the fee payer will be burdened with. If feeDelegation is true and feeRatio is set to a valid value, a partial fee delegation transaction is used. The valid range of this is between 1 and 99. The ratio of 0, or 100 and above are not allowed.
참고feeDelegation, feePayer, 그리고 feeRatio는 caver-js v1.6.1 이후부터 지원됩니다.
Example
>myContract.options{ address: [Getter/Setter], jsonInterface: [Getter/Setter], from: [Getter/Setter], feePayer: [Getter/Setter], feeDelegation: [Getter/Setter], feeRatio: [Getter/Setter], gasPrice: [Getter/Setter], gas: [Getter/Setter], data: [Getter/Setter]}>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>myContract.options.feeDelegation =true// use fee delegation transaction>myContract.options.feePayer ='0x1234567890123456789012345678901234567891'// default fee payer address>myContract.options.feeRatio =20// default fee ratio when send partial fee delegation transaction
myContract.options.address
myContract.options.address
이 컨트랙트 인스턴스 myContract에 사용된 주소. 해당 컨트랙트에서 caver-js에 의해 생성된 모든 트랜잭션에 이 주소가 to로서 포함될 것입니다.
속성
Name
Type
Description
address
string \
null
Example
>myContract.options.address'0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae'// 컨트랙트 주소 설정>myContract.options.address ='0x1234FFDD...'
myContract.options.jsonInterface
myContract.options.jsonInterface
이 컨트랙트 myContract의 ABI에서 파생된 JSON 인터페이스 객체.
Property
Name
Type
Description
jsonInterface
Array
이 컨트랙트의 JSON 인터페이스. 이를 재설정하면 컨트랙트 인스턴스의 메소드 및 이벤트가 재생성됩니다.
컨트랙트를 Klaytn 네트워크에 배포합니다. 성공적으로 배포된 후, Promise는 새로운 컨트랙트 인스턴스와 함께 해결(resolved)될 것입니다. Unlike the usability of the existing myContract.deploy function, this function sends a transaction directly to the Klaytn network. 반환된 객체와 함께 send()를 호출할 필요가 없습니다.
NOTE 서명을 하기 위해서는 caver.wallet가 options나 myContract.options의 from와 feePayer에 해당하는 키링 인스턴스를 포함해야 합니다.
Promise는 PromiEvent를 반환: Promise가 새로운 컨트랙트 인스턴스와 함께 해결(resolved)됩니다.
Type
Description
PromiEvent
프로미스(promise)가 조합된 이벤트 이미터(event emitter). 트랜잭션 영수증이 준비되면 해결(resolve)됩니다. myContract.deploy()에서 send()가 호출될 경우, Promise는 새로운 컨트랙트 인스턴스와 함께 해결(resolved)됩니다.
PromiEvent에서는 다음 이벤트가 발생할 수 있습니다.
"transactionHash": 트랜잭션이 전송되고 트랜잭션 해시가 준비된 직후에 발생합니다. 타입은 string입니다.
error: 전송 중 에러가 발생하면 발생합니다. 가스 부족 에러(out-of-gas)가 발생한 경우 두 번째 인자는 트랜잭션 영수증입니다. 타입은 error입니다.
Example
// Deploy a smart contract without constructor arguments>myContract.deploy({ from:'0x{address in hex}', gas:1500000, },'0x{byte code}').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 })// Deploy a smart contract with constructor arguments>myContract.deploy({ from:'0x{address in hex}', gas:1500000, },'0x{byte code}','keyString',...).on('error',function(error) { ... }).on('transactionHash',function(transactionHash) { ... }).on('receipt',function(receipt) {console.log(receipt.contractAddress) }).then(function(newContractInstance) {console.log(newContractInstance.options.address) })// Deploy a smart contract with fee delegation transaction (TxTypeFeeDelegatedSmartContractDeploy)>myContract.deploy({ from:'0x{address in hex}', feeDelegation:true, feePayer:'0x{address in hex}', gas:1500000, },'0x{byte code}').on('error',function(error) { ... }).on('transactionHash',function(transactionHash) { ... }).on('receipt',function(receipt) {console.log(receipt.contractAddress) }).then(function(newContractInstance) {console.log(newContractInstance.options.address) })// Deploy a smart contract with partial fee delegation transaction (TxTypeFeeDelegatedSmartContractDeployWithRatio)>myContract.deploy({ from:'0x{address in hex}', feeDelegation:true, feePayer:'0x{address in hex}', feeRatio:30, gas:1500000, },'0x{byte code}').on('error',function(error) { ... }).on('transactionHash',function(transactionHash) { ... }).on('receipt',function(receipt) {console.log(receipt.contractAddress) }).then(function(newContractInstance) {console.log(newContractInstance.options.address) })
myContract.deploy
myContract.deploy(options)
Klaytn에 스마트 컨트랙트를 배포할 때 사용되는 객체를 반환합니다. myContract.deploy({ data, arguments }).send(options)를 호출함으로써 스마트 컨트랙트 배포 트랜잭션을 전송할 수 있습니다. After a successful deployment, the promise will be resolved with a new contract instance.
Parameters
Name
Type
Description
options
object
배포에 사용되는 옵션 객체입니다. 자세한 내용은 아래 표를 참조하세요.
옵션 개체에는 다음이 포함됩니다:
Name
Type
Description
data
string
The byte code of the contract.
arguments
Array
(선택 사항) 배포시 생성자에게 전달되는 인자입니다.
Return Value
Type
Description
object
An object in which arguments and functions for contract distribution are defined. See the below table to find the description.
The function that encodes the ABI of the deployment, which is contract data + constructor parameters. The execution of this function does not deploy the contract.
>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) })
A promise combined event emitter. It will be resolved when the transaction receipt is available. The promise will be resolved with the new contract instance.
For PromiEvent, the following events are available:
"transactionHash": 트랜잭션이 전송되고 트랜잭션 해시가 준비된 직후에 발생합니다. Its type is string.
스마트 컨트랙트 배포 또는 스마트 컨트랙트 함수 실행을 위해 발신자로서 스마트 컨트랙트 트랜잭션에 서명합니다.
스마트 컨트랙트가 배포되었다면 myContract.sign({ from, ... }, 'constructor', byteCode, ...)와 같이 'constructor'를 methodName에 입력할 수 있습니다.
The transaction type used for this function depends on the options or the value defined in myContract.options. myContract.sign를 통해 수수료 위임 트랜잭션을 사용하고 싶다면, feeDelegationdl true로 정의되어야 합니다.
스마트 컨트랙트 배포 또는 스마트 컨트랙트 함수 실행을 위해 수수료 납부자로서 스마트 컨트랙트 트랜잭션에 서명합니다.
스마트 컨트랙트가 배포되었다면 myContract.signAsFeePayer({ from, feeDelegation: true, feePayer, ... }, 'constructor', byteCode, ...)와 같이 methodName에 'constructor'를 입력할 수 있습니다.
The transaction type used for this function depends on the options or the value defined in myContract.options. signAsFeePayer는 트랜잭션 수수료 납부자로서 서명하는 함수이기 때문에 feeDelegation 필드는 true로 정의되어야 합니다. 수수료 납부자의 주소 또한 feePayer 필드에 정의되어 있어야 합니다.
The method name of the contract function to execute. If you want to sign a transaction for deploying the smart contract, use 'constructor' string instead of method name.
parameters
Mixed
(optional) The parameters that get passed to the smart contract function. If you want to sign a smart contract deploy transaction, pass the byteCode and constructor parameters.
Return Value
Promise returning Transaction - The signed smart contract transaction.
이를 통해 자바스크립트 컨트랙트 객체로부터 이름은 같지만 매개변수가 다른 함수를 호출할 수 있습니다.
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 given via 2 different methods.
1. caver.abi.encodefunctionSignature('funcName(paramType1,paramType2,...)')2. caver.utils.sha3('funcName(paramType1,paramType2,...)').substr(0, 10)
The function that will call and execute a constant method in its smart contract on Klaytn Virtual Machine without sending a transaction (cannot alter the smart contract state).
The function that encodes the ABI for this method. This can be sent using a transaction, calling the method, or passing into another smart contract method as its argument.
// Calling a method>myContract.methods.methodName(123).call({ ... },function(error, result) { ... })>myContract.methods.methodName(123).call({ ... }).then((result) => { ... })// Sending basic transaction and using the promise>myContract.methods.methodName(123).send({ from:'0x{address in hex}',... }).then(function(receipt) {// receipt can also be a new contract instance, when coming from a "contract.deploy({...}).send()" })// Sending basic transaction and using the eventEmitter>myContract.methods.methodName(123).send({ from:'0x{address in hex}',... }).on('transactionHash',function(hash) {... }).on('receipt',function(receipt) {... }).on('error',console.error)// Sending fee delegation transaction and using the promise>myContract.methods.methodName(123).send({ from:'0x{address in hex}', feePayer:'0x{fee-payer address}', feeDelegation:true,f... }).then(function(receipt) {// receipt can also be a new contract instance, when coming from a "contract.deploy({...}).send()" })// Sending partial fee delegation transaction and using the promise>myContract.methods.methodName(123).send({ from:'0x{address in hex}', feePayer:'0x{fee-payer address}', feeDelegation:true, feeRatio:30,... }).then(function(receipt) {// receipt can also be a new contract instance, when coming from a "contract.deploy({...}).send()" })// sign the basic transaction>myContract.methods.methodName(123).sign({ from:'0x{address in hex}', feeDelegation:true,... }).then(function(signedTx) { ... })// sign the fee delegation transaction>myContract.methods.methodName(123).sign({ from:'0x{address in hex}', feeDelegation:true,... }).then(function(signedTx) { ... })// sign the partial fee delegation transaction>myContract.methods.methodName(123).sign({ from:'0x{address in hex}', feeDelegation:true, feeRatio:30,... }).then(function(signedTx) { ... })// sign the fee delegation transaction as a fee payer>myContract.methods.methodName(123).signAsFeePayer({ from:'0x{address in hex}', feePayer:'0x{fee-payer address}', feeDelegation:true,... }).then(function(signedTx) { ... })// sign the partial fee delegation transaction as a fee payer>myContract.methods.methodName(123).signAsFeePayer({ from:'0x{address in hex}', feePayer:'0x{fee-payer address}', feeDelegation:true, feeRatio:30,... }).then(function(signedTx) { ... })
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. It is recommended to use myContract.call provided as a short-cut function.
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 which calling contract methods should be made from.
gasPrice
string
(optional) The gas price in peb to use for this call.
gas
number
(optional) The maximum gas provided for this call (gas limit).
Return Value
Promise returning 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, it returns an object with properties and indices.
Will send a transaction to deploy the smart contract or execute the function of the smart contract. This can alter the smart contract state. It is recommended to use myContract.send provided as a short-cut function.
If a smart contract is deployed, 'constructor' can be entered in the methodName, such as myContract.methods.constructor or myContract.methods['constructor'], but it is recommended to use the myContract.deploy function.
The transaction type used for this function depends on the options or the value defined in myContract.options. If you want to use a fee-delegated transaction through methods.methodName.send, feeDelegation and feePayer should be set properly.
NOTEcaver.wallet must contains keyring instances corresponding to from and feePayer in options or myContract.options to make signatures.
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
트랜잭션을 보낼 송신자 주소. If omitted, myContract.options.from will be used.
gas
number
The maximum gas provided for this transaction (gas limit).
gasPrice
string
(선택 사항) 트랜잭션에 사용할 peb 단위의 가스 가격.
value
number \
string | BN | Bignumber
feeDelegation
boolean
(optional, default false) 수수료 위임 트랜잭션 사용 여부를 나타냅니다. If omitted, myContract.options.feeDelegation will be used.
feePayer
string
(optional) The address of the fee payer paying the transaction fee. When feeDelegation is true, the value is set to the feePayer field in the transaction. If omitted, myContract.options.feePayer will be used.
feeRatio
string
(optional) The ratio of the transaction fee the fee payer will be burdened with. If feeDelegation is true and feeRatio is set to a valid value, a partial fee delegation transaction is used. The valid range of this is between 1 and 99. The ratio of 0, or 100 and above are not allowed. If omitted, myContract.options.feeRatio will be used.
NOTEfeeDelegation, feePayer and feeRatio are supported since caver-js v1.6.1.
Return Value
Promise returns PromiEvent
Type
Description
PromiEvent
A promise combined event emitter. It will be resolved when the transaction receipt is available. The promise will be resolved with the new contract instance.
For PromiEvent, the following events are available:
transactionHash: It is fired right after the transaction is sent and a transaction hash is available. Its type is string.
error: It is fired if an error occurs during sending. On an out-of-gas error, the second parameter is the receipt. Its type is Error.
Example
// using the promise>myContract.methods.methodName(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.methodName(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": {"eventName": { returnValues: { myIndexedParam:20, myOtherIndexedParam:'0x123456789...', myNonIndexParam:'My string' }, raw: { data:'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
}, event:'eventName', signature:'0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', logIndex:0, transactionIndex:0, transactionHash:'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', blockHash:'0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', blocknumber:1234, address:'0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe' },"MyOtherEvent": {... },"MyMultipleEvent":[{...}, {...}] // If there are multiples of the same events, they will be in an array. }}// Deploy the contract> myContract.methods.constructor('0x{byte code}', 123).send({ from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', gas: 1000000 })
> myContract.methods['constructor']('0x{byte code}', 123).send({ from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', gas: 1000000 })
Signs a smart contract transaction as a sender to deploy the smart contract or execute the function of the smart contract. It is recommended to use myContract.sign provided as a short-cut function.
If a smart contract is deployed, 'constructor' can be entered in the methodName, such as myContract.methods.constructor or myContract.methods['constructor'].
The transaction type used for this function depends on the options or the value defined in myContract.options. If you want to use a fee-delegated transaction through methods.methodName.sign, feeDelegation should be defined as true.
Signs a smart contract transaction as a fee payer to deploy the smart contract or execute the function of the smart contract. It is recommended to use myContract.signAsFeePayer provided as a short-cut function.
If a smart contract is deployed, 'constructor' can be entered in the methodName, such as myContract.methods.constructor or myContract.methods['constructor'].
The transaction type used for this function depends on the options or the value defined in myContract.options. The signAsFeePayer is a function that signs as a transaction fee payer, so feeDelegation field must be defined as true. Also, the address of the fee payer must be defined in the feePayer field.
feeDelegation is not defined : Throws an error.
feeDelegation is defined, but feePayer is not defined : Throws an error.
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 calling the contract method should be made.
gas
number
(optional) The maximum gas provided for this call (gas limit). 특정 값을 설정하면 가스 부족 오류를 감지하는 데 도움이 됩니다. 모든 가스가 사용되면 같은 숫자를 반환합니다.
Subscribes to an event and unsubscribes immediately after the first event or error. 단일 이벤트에 대해서만 발생합니다.
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 subscription. See the table below for the details.
callback
function
이 콜백은 첫 번째 이벤트를 두 번째 인수로, 또는 오류를 첫 번째 인수로 하여 발생됩니다. See myContract.getPastEvents for details about the event structure.
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. Given the filter property and event signature, topic[0] would not be set automatically.
Return Value
Promise returns object - An event object. For more detail about event object, please refer to myContract.getPastEvents.
Example
>myContract.once('eventName', { 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:'eventName', signature:'0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', logIndex:0, transactionIndex:0, transactionHash:'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', blockHash:'0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', blocknumber:1234, address:'0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}
You can unsubscribe an event by calling the unsubscribe function of the subscription object returned by the subscribe function.
NOTEmyContract.subscribe is supported since caver-js v1.9.1-rc.1.
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 subscription. See the table below for the details.
callback
function
This callback will be fired for the first event as the second argument, or an error as the first argument. See myContract.getPastEvents for details about the event structure.
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. Given the filter property and event signature, topic[0] would not be set automatically.
Return Value
Promise returns object - An event object. For more detail about event object, please refer to myContract.getPastEvents.
Example
>constsubscription=myContract.subscribe('eventName', { filter: {myIndexedParam: [20,23], myOtherIndexedParam:'0x123456789...'},// Using an array means OR: e.g. 20 or 23 },function(error, event) { console.log(event) }){ returnValues: { myIndexedParam:20, myOtherIndexedParam:'0x123456789...', myNonIndexParam:'My string' }, raw: { data:'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', topics: ['0xfd43a...','0x7f9fa...'] }, event:'eventName', signature:'0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', logIndex:0, transactionIndex:0, transactionHash:'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385', blockHash:'0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', blocknumber:1234, address:'0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}>subscription.unsubscribe() // unsubscribe the event
(optional) The options used for subscription. 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.
topics
Array
(optional) This allows you to manually set the topics for the event filter. Given the filter property and event signature, topic[0] would not be set automatically.
Return Value
EventEmitter: The event emitter has the following events:
Name
Type
Description
data
object
Fires on each incoming event with the event object as an argument.
connected
string
Fires once after the subscription successfully connected. It returns the subscription ID.
The name of the event in the contract, or "allEvents" to get all events.
options
object
(optional) The options used for subscription. 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.
To 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.
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. Given the filter property and event signature, topic[0] would not be set automatically.
Return Value
Promise returns Array - An array with the past event objects, matching the given event name and filter.
An event object can contain the following:
Name
Type
Description
event
string
The event name.
signature
string \
null
address
string
Address this event originated from.
returnValues
object
The return values coming from the event, e.g. {myVar: 1, myVar2: '0x234...'}.
logIndex
number
The event index position in the block.
transactionIndex
number
The transaction’s index position the event was created in.
transactionHash
string
The hash of the transaction this event was created in.
blockHash
string
The hash of the block this event was created in. null when it’s still pending.
blockNumber
number
The block number this log was created in. null when still pending.
raw
object
An object defines data and topic. raw.data containing non-indexed log parameter. raw.topic is an array with a maximum of four 32 Byte topics, and topic 1-3 contains indexed parameters of the event.
Example
> myContract.getPastEvents('eventName', {
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: 'eventName',
signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
logIndex: 0,
transactionIndex: 0,
transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blocknumber: 1234,
address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
},{
...
}]