Comment on page
caver.contract
The
caver.contract
object makes it easy to interact with smart contracts on the Klaytn blockchain platform. When you create a new contract object, you have to provide the JSON interface for that smart contract and caver-js will automatically convert all calls with the contract object in javascript into low-level ABI calls over RPC for you.This allows you to interact with smart contracts as if they were JavaScript objects.
caver.contract.create(jsonInterface [, address] [, options])
Creates a new contract instance with all its methods and events defined in its JSON interface object. This function works the same as new caver.contract.
Parameters
Return Value
Example
const contract = caver.contract.create([
{
constant: true,
inputs: [{ name: 'interfaceId', type: 'bytes4' }],
name: 'supportsInterface',
outputs: [{ name: '', type: 'bool' }],
payable: false,
stateMutability: 'view',
type: 'function',
},
...
], '0x{address in hex}')
new caver.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. |
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. |
Return Value
Type | Description |
---|---|
object | The contract instance with all its methods and events. |
Example
const myContract = new caver.contract([...], '0x{address in hex}', { gasPrice: '25000000000' })
myContract.options
The
options
object for the contract instance. from
, gas
, gasPrice
, feePayer
and feeRatio
are used as fallback values when sending transactions.Properties
Name | Type | Description |
---|---|---|
address | string | The address where the contract is deployed. |
jsonInterface | Array | The JSON interface of the contract. |
from | string | The default address from which the contract deployment/execution transaction is sent. If the from address is not defined when creating the transaction, this myContract.options.from is always used to create the transaction. |
gasPrice | string | The gas price in peb to use for transactions. |
gas | number | The maximum gas provided for a transaction (gas limit). |
data | string | The byte code of the contract. 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. |
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
The address used for this contract instance
myContract
. All transactions generated by caver-js from this contract will contain this address as the to
of the transaction.Property
Name | Type | Description |
---|---|---|
address | string | null | The address for this contract or null if it is not yet set. |
Example
> myContract.options.address
'0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae'
// set a contract address
> myContract.options.address = '0x1234FFDD...'
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
[
{
constant: true,
inputs: [ { name: 'interfaceId', type: 'bytes4' } ],
name: 'supportsInterface',
outputs: [ { name: '', type: 'bool' } ],
payable: false,
stateMutability: 'view',
type: 'function',
signature: '0x01ffc9a7',
},
...
{
anonymous: false,
inputs: [
{ indexed: true, name: 'owner', type: 'address' },
{ indexed: true, name: 'spender', type: 'address' },
{ indexed: false, name: 'value', type: 'uint256' }
],
name: 'Approval',
type: 'event',
signature: '0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925',
},
]
// set a new jsonInterface
> myContract.options.jsonInterface = [...]
myContract.clone([contractAddress])
Clones the current contract instance.
Parameters
Name | Type | Description |
---|---|---|
contractAddress | String | (optional) The address of the new contract. If omitted, it will be set to the address in the original instance (e.g., myContract.options.address ). |
Return Value
Type | Description |
---|---|
object | The new cloned contract instance. |
Example
> myContract.clone()
Contract {
currentProvider: [Getter/Setter],
...
_keyrings: KeyringContainer { ... }
}
myContract.deploy(options, byteCode [, param1 [, param2 [, ...]]])
Deploys the contract to the Klaytn network. After a successful deployment, the promise will be resolved with a new contract instance. Unlike the usability of the existing myContract.deploy function, this function sends a transaction directly to the Klaytn network. You don't need to call
send()
with the returned object.NOTE
caver.wallet
must contains keyring instances corresponding to from
and feePayer
in options
or myContract.options
to make signatures.Parameters
Name | Type | Description |
---|---|---|
options | object | |
byteCode | string | The byte code of the contract. |
parameters | Mixed | (optional) The parameters that get passed to the constructor on deployment. |
Return Value
Promise
returning PromiEvent
: The promise will be resolved with the new contract instance.Type | Description |
---|---|
PromiEvent | A promise combined event emitter. It will be resolved when the transaction receipt is available. If send() is called from a myContract.deploy() , then 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 isstring
.receipt
: It is fired when the transaction receipt is available. See caver.rpc.klay.getTransactionReceipt for more details. Its type isobject
.error
: It is fired if an error occurs during sending. On an out-of-gas error, the second parameter is the receipt. Its type isError
.
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(options)
Returns the object used when deploying the smart contract to the Klaytn. You can send the smart contract deploy transaction via calling
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 | The options object used for deployment. See the below table to find the description. |
The options object can contain the following:
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
Type | Description |
---|---|
object | An object in which arguments and functions for contract distribution are defined. See the below table to find the description. |
The object contains the following:
Name | Type | Description |
---|---|---|
arguments | Array | The arguments passed in options.arguments . |
function | The function that will deploy the contract to the Klaytn. The promise as the result of this function will be resolved with the new contract instance. | |
function | The function that will sign a smart contract deploy transaction as a sender. The sign function will return signed transaction. | |
function | The function that will sign a smart contract deploy transaction as a fee payer. The signAsFeePayer function will return signed transaction. | |
function | The function that will estimate the gas used for the deployment. The execution of this function does not deploy the contract. | |
function | 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. |
NOTE
myContract.deploy({ data, arguments }).sign(options)
and myContract.deploy({ data, arguments }).signAsFeePayer(options)
are supported since caver-js v1.6.1.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)
})
myContract.send(options, methodName [, param1 [, param2 [, ...]]])
Submits a transaction to execute the function of the smart contract. This can alter the smart contract state.
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 myContract.send
, feeDelegation
and feePayer
should be set properly.feeDelegation
is defined totrue
, butfeePayer
is not defined : Throws an error.feeDelegation
is defined totrue
andfeePayer
is defined, butfeeRatio
is not defined: FeeDelegatedSmartContractExecutionfeeDelegation
is defined totrue
andfeePayer
andfeeRatio
are defined: FeeDelegatedSmartContractExecutionWithRatio
NOTE
caver.wallet
must contains keyring instances corresponding to from
and feePayer
in options
or myContract.options
to make signatures.Parameters
Name | Type | Description |
---|---|---|
options | object | |
methodName | string | The method name of the contract function to execute. |
parameters | Mixed | (optional) The parameters that get passed to the smart contract function. |
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 isstring
.receipt
: It is fired when the transaction receipt is available. See caver.rpc.klay.getTransactionReceipt for more details. Its type isobject
.error
: It is fired if an error occurs during sending. On an out-of-gas error, the second parameter is the receipt. Its type isError
.
Example
// Send a SmartContractExecution and use the promise
> myContract.send({ from: '0x{address in hex}', gas: 1000000 }, 'methodName', 123).then(console.log)
{
blockHash: '0x294202dcd1d3c422880e2a209b9cd70ce7036300536c78ab74130c5717cb90da',
blockNumber: 16342,
contractAddress: null,
from: '0x69c3a6e3485446118d8081063dcef2e65b69ae91',
gas: '0xf4240',
gasPrice: '0x5d21dba00',
gasUsed: 47411,
input: '0x983b2...',
logsBloom: '0x00800...',
nonce: '0x1cd',
senderTxHash: '0xe3f50d2bab2c462ef99379860d2b634d85a0c9fba4e2b189daf1d96bd4bbf8ff',
signatures: [ { V: '0x4e43', R: '0x2ba27...', S: '0x50d37...' } ],
status: true,
to: '0x361870b50834a6afc3358e81a3f7f1b1eb9c7e55',
transactionHash: '0xe3f50d2bab2c462ef99379860d2b634d85a0c9fba4e2b189daf1d96bd4bbf8ff',
transactionIndex: 0,
type: 'TxTypeSmartContractExecution',
typeInt: 48,
value: '0x0',
events: {...}
}
// Send a SmartContractExecution and use the event emitter
> myContract.send({ from: '0x{address in hex}', gas: 1000000 }, 'methodName', 123)
.on('transactionHash', function(hash) {
...
})
.on('receipt', function(receipt) {
console.log(receipt)
})
.on('error', console.error)
// Send a FeeDelegatedSmartContractExecution
> myContract.send({
from: '0x{address in hex}',
gas: 1000000,
feeDelegation: true,
feePayer: '0x{address in hex}',
}, 'methodName', 123).then(console.log)
{
blockHash: '0x149e36f279577c306fccb9779a0274e802501c32f7054c951f592778bd5c168a',
blockNumber: 16458,
contractAddress: null,
feePayer: '0x69c3a6e3485446118d8081063dcef2e65b69ae91',
feePayerSignatures: [ { V: '0x4e43', R: '0x48c28...', S: '0x18413...' } ],
from: '0x69c3a6e3485446118d8081063dcef2e65b69ae91',
gas: '0xf4240',
gasPrice: '0x5d21dba00',
gasUsed: 57411,
input: '0x983b2d5600000000000000000000000022bb89bd35e7b12bd25bea4165cf0f9330032f8c',
logsBloom: '0x00800...',
nonce: '0x1f5',
senderTxHash: '0x5b06ca5046229e066c11dfc0c74fcbc98509294370981f9b142378a8f2bd5fe8',
signatures: [ { V: '0x4e44', R: '0xfb707...', S: '0x641c6...' } ],
status: true,
to: '0x361870b50834a6afc3358e81a3f7f1b1eb9c7e55',
transactionHash: '0x0e04be479ad06ec87acbf49abd44f16a56390c736f0a7354860ebc7fc0f92e13',
transactionIndex: 1,
type: 'TxTypeFeeDelegatedSmartContractExecution',
typeInt: 49,
value: '0x0',
events: {...}
}
// Send a FeeDelegatedSmartContractExecutionWithRatio
> myContract.send({
from: '0x{address in hex}',
gas: 1000000,
feeDelegation: true,
feePayer: '0x{address in hex}',
feeRatio: 30,
}, 'methodName', 123).then(console.log)
{
blockHash: '0x8f0a0137cf7e0fea503c818910140246437db36121871bc54b2ebc688873b3f3',
blockNumber: 16539,
contractAddress: null,
feePayer: '0x69c3a6e3485446118d8081063dcef2e65b69ae91',
feePayerSignatures: [ { V: '0x4e43', R: '0x80db0...', S: '0xf8c7c...' } ],
feeRatio: '0x1e',
from: '0x69c3a6e3485446118d8081063dcef2e65b69ae91',
gas: '0xf4240',
gasPrice: '0x5d21dba00',
gasUsed: 62411,
input: '0x983b2d560000000000000000000000007ad1a538041fa3ba1a721f87203cb1a3822b8eaa',
logsBloom: '0x00800...',
nonce: '0x219',
senderTxHash: '0x14c7b674a0e253b31c85c7be8cbfe4bf9d86e66e940fcae34b854e25eab1ce15',
signatures: [ { V: '0x4e43', R: '0xd57ef...', S: '0xe14f3...' } ],
status: true,
to: '0x361870b50834a6afc3358e81a3f7f1b1eb9c7e55',
transactionHash: '0xfbf00ec189aeb0941d554384f1660ffdac7768b3af2bb1526bcb3983215c1183',
transactionIndex: 0,
type: 'TxTypeFeeDelegatedSmartContractExecutionWithRatio',
typeInt: 50,
value: '0x0',
events: {...}
}
myContract.sign(options, methodName [, param1 [, param2 [, ...]]])
Signs a smart contract transaction as a sender to deploy the smart contract or execute the function of the smart contract.
If a smart contract is deployed, 'constructor' can be entered in the methodName, such as
myContract.sign({ from, ... }, 'constructor', byteCode, ...)
.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 myContract.sign
, feeDelegation
should be defined as true
.feeDelegation
is defined totrue
, butfeeRatio
is not defined: FeeDelegatedSmartContractDeploy / FeeDelegatedSmartContractExecutionfeeDelegation
is defined totrue
andfeeRatio
is defined: FeeDelegatedSmartContractDeployWithRatio / FeeDelegatedSmartContractExecutionWithRatio
NOTE
caver.wallet
must contains keyring instances corresponding to from
in options
or myContract.options
to make signatures.Parameters
Name | Type | Description |
---|---|---|
options | object | |
methodName | string | 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
Example
// Sign a SmartContractDeploy
> myContract.sign({ from: '0x{address in hex}', gas: 1000000 }, 'constructor', byteCode, 123).then(console.log)
SmartContractDeploy {
_type: 'TxTypeSmartContractDeploy',
_from: '0x69c3a6e3485446118d8081063dcef2e65b69ae91',
_gas: '0xf4240',
_signatures: [ SignatureData { _v: '0x4e43', _r: '0xeb6b5...', _s: '0x5e4f9...' } ],
_to: '0x',
_value: '0x0',
_input: '0x60806...',
_humanReadable: false,
_codeFormat: '0x0',
_chainId: '0x2710',
_gasPrice: '0x5d21dba00',
_nonce: '0x2a5'
}
// Sign a FeeDelegatedSmartContractDeploy
> myContract.sign({ from: '0x{address in hex}', feeDelegation: true, gas: 1000000 }, 'constructor', byteCode, 123).then(console.log)
FeeDelegatedSmartContractDeploy {
_type: 'TxTypeFeeDelegatedSmartContractDeploy',
_from: '0x69c3a6e3485446118d8081063dcef2e65b69ae91',
_gas: '0xf4240',
_signatures: [ SignatureData { _v: '0x4e43', _r: '0xee0f5...', _s: '0x31cbf...' } ],
_feePayer: '0x0000000000000000000000000000000000000000',
_feePayerSignatures: [ SignatureData { _v: '0x01', _r: '0x', _s: '0x' } ],
_to: '0x',
_value: '0x0',
_input: '0x60806...',
_humanReadable: false,
_codeFormat: '0x0',
_chainId: '0x2710',
_gasPrice: '0x5d21dba00',
_nonce: '0x320'
}
// Sign a FeeDelegatedSmartContractDeployWithRatio
> myContract.sign({ from: keyring.address, feeDelegation: true, feeRatio: 30, gas: 1000000 }, 'constructor', byteCode, 123).then(console.log)
FeeDelegatedSmartContractDeployWithRatio {
_type: 'TxTypeFeeDelegatedSmartContractDeployWithRatio',
_from: '0x69c3a6e3485446118d8081063dcef2e65b69ae91',
_gas: '0xf4240',
_signatures: [ SignatureData { _v: '0x4e44', _r: '0x4c2b0...', _s: '0x47df8...' } ],
_feePayer: '0x0000000000000000000000000000000000000000',
_feePayerSignatures: [ SignatureData { _v: '0x01', _r: '0x', _s<