SDK

This page introduces KAS SDK(caver-js-ext-kas/caver-java-ext-kas) section.

KAS SDK (Software Development Kit) is a development tool provided to easily use KAS in various development environments. KAS SDK is an extension library of Caver and supports JavaScript and Java environment like Caver. If you develop BApp with KAS SDK, you can use both KAS function and existing Caver function through a single library.

KAS SDK(caver-js extension) and KAS SDK(caver-java extension) are the extended libraries ofcaver-js and caver-java respectively. You can use the existing caver-js/caver-java features, as well as the Node API, TokenHistory API, Wallet API, Anchor API, KIP-17 API and KIP-7 API of KAS.

KAS SDK Prerequisites

KAS SDK (caver-js extension)

To use KAS SDK (caver-js extension) you need the following packages.

KAS SDK (caver-js extension) works in the Node.js version below.

KAS SDK (caver-java extension)

To use KAS SDK (caver-java extension) you need Java 8 or higher version to be pre-installed. For inquires about this document or KAS, please visit Developer Forum.

How to install KAS SDK

KAS SDK (caver-js extension)

KAS SDK (caver-js extension) can be installed using the command below.

$ npm install caver-js-ext-kas

If you want to install a specific version of KAS SDK (caver-js extension), use the command below.

$ npm install caver-js-ext-kas@X.X.X

KAS SDK (caver-java extension)

KAS SDK (caver-java extension) requires Java 8 or higher, and can be installed by the following environment.

maven

<dependency>
  <groupId>xyz.groundx.caver</groupId>
  <artifactId>caver-java-ext-kas</artifactId>
  <version>X.X.X</version>
  <type>pom</type>
</dependency>

In maven project, you can installed Anroid KAS SDK(caver-java extension) by writing as follow.

<dependency>
  <groupId>xyz.groundx.caver</groupId>
  <artifactId>caver-java-ext-kas</artifactId>
  <version>X.X.X-android</version>
  <type>pom</type>
</dependency>

gradle

implementation 'xyz.groundx.caver:caver-java-ext-kas:X.X.X

In gradle project, you can installed Android KAS SDK(caver-java extension) by writing as follow.

implementation 'xyz.groundx.caver:caver-java-ext-kas:X.X.X-android

You can find the latest KAS SDK (caver-java extension) in Release Page.

For inquires about this document or KAS, please visit Developer Forum.

Hello World

KAS SDK (caver-js extension)

In order to use KAS API with KAS SDK (caver-js extension), you need to set up "chain id" and "authentication key". You can initialize the setting to use KAS API service as shown below:

const caver = new CaverExtKAS(chainId, accessKeyId, secretAccessKey)

Passing chainId, accessKeyId and secretAccessKey to the constructor will internally call the caver.initKASAPI function, which initializes the authentication keys used in Node API, Wallet API, Token History API, Anchor API, KIP-17 and KIP-7. The initialization method for each KAS API service is as follows. You can optionally pass endpoint URL as the Endpoint URL. If a separate URL is not passed, the KAS Production URL will be set as default as shown below.

KAS Production URL

  • Node API: https://node-api.klaytnapi.com

  • Wallet API: https://wallet-api.klaytnapi.com

  • Anchor API: https://anchor-api.klaytnapi.com

  • Token History API: https://th-api.klaytnapi.com

  • KIP-17 API: https://kip17-api.klaytnapi.com

  • KIP-7 API: https://kip7-api.klaytnapi.com

// Initializing Node API
caver.initNodeAPI(chainId, accessKeyId, secretAccessKey [, useHttp] [, url])

// Initializing Wallet API
caver.initWalletAPI(chainId, accessKeyId, secretAccessKey [, url])

// Initializing TokenHistory API
caver.initTokenHistoryAPI(chainId, accessKeyId, secretAccessKey [, url])

// Initializing Anchor API
caver.initAnchorAPI(chainId, accessKeyId, secretAccessKey [, url])

// Initializing KIP-17 API
caver.initKIP17API(chainId, accessKeyId, secretAccessKey [, url])

// Initializing KIP-7 API
caver.initKIP7API(chainId, accessKeyId, secretAccessKey [, url])

You can fetch the latest block information with KAS' Node API when using KAS SDK (caver-js extension) as shown below:

For the caver.initNodeAPI function, you can assign a provider for calling KAS Node API using the parameter useHttp. For more details, please refer to Calling KAS Node API using WebSocket Provider.

const CaverExtKAS = require('caver-js-ext-kas')
onst caver = new CaverExtKAS(chainId, accessKeyId, secretAccessKey)

const blockNumber = await caver.rpc.klay.getBlockNumber()
console.log(blockNumber)

When the above codes are executed, the latest block number will be displayed as shown below:

0x26b0736

Here's how to create an account using KAS' Wallet API using KAS SDK (caver-js extension):

const CaverExtKAS = require('caver-js-ext-kas')
const caver = new CaverExtKAS(chainId, accessKeyId, secretAccessKey)

const account = await caver.kas.wallet.createAccount()
console.log(account)

When the above code is executed, the information of the account will be created in KAS as shown below.

Account {
  address: '0x4d6de1Fe6a281306C54AD81b79a0c137b13872DC',
  chainId: 1001,
  createdAt: 1602124416,
  keyId: 'krn:1001:wallet:9c42dff5-d317-4abd-a7ab-576aad12ea07:account-pool:default:0x975fa77efbde347b0c471f0f29ba73c1281521f69485d650c8c10125e37b57fc',
  krn: 'krn:1001:wallet:9c42dff5-d317-4abd-a7ab-576aad12ea07:account-pool:default',
  publicKey: '0x0433f1b15d33e821155988408e949d21d5bd0d053d9f2ed90f3df57e96f0ce7a766ba36617f43f2ad1e0f3caca5bdb431a88c51c1bdaab8dc781589b1658e646f1',
  updatedAt: 1602124416
}

You can retrieve NFT contract list with KAS TokenHistory API when using KAS SDK (caver-js extension).

const CaverExtKAS = require('caver-js-ext-kas')
const caver = new CaverExtKAS(chainId, accessKeyId, secretAccessKey)


// Query parameters are optional, so `caver.kas.tokenHistory.getNFTContractList` can be executed without query parameters.
const query = { size: 1 }
const nftContractList = await caver.kas.tokenHistory.getNFTContractList(query)
console.log(nftContractList)

Executing the above code will print the list of NFT contracts as shown below:

PageableNftContractDetails {
  items: [ 
    NftContractDetail {
      address: '0x44b12eea91acb7866737e5157f1525503a3c7d11',
      name: 'YouTube Thumbnail Token',
      symbol: 'YTT',
      totalSupply: '0x3',
      createdAt: 1601417429,
      updatedAt: 1601417429,
      deletedAt: 0,
      type: 'KIP-17',
      status: 'completed'
    }
  ],
  cursor: 'omYpAQ8xGDrlz5O3akAbYDPolJ1r7kx3ZWg2L5mwDQ5GAk7ONYdpzXW0LBZVq2n60WRJKPg8469bvxMl1rmoaew3EQVa6Gq8KpeEdzB0O9vMX4NE1X9eb206gBNLJ7qW'
}

Here's how to use KAS SDK (caver-js extension) for sending anchoring data using KAS's Anchor API:

const CaverExtKAS = require('caver-js-ext-kas')
const caver = new CaverExtKAS()

const operator = '0x{address in hex}'
const payload = { id: '12837851', customField: 'custom test' }
const anchoringResult = await caver.kas.anchor.sendAnchoringData(operator, payload)
console.log(anchoringResult)

When the above codes are executed, the result of the anchoring data transmission will be displayed as shown below:

AnchorBlockStatus { status: 'succeed' }

Here is how you can deploy KIP-17 contracts with KIP-17 API using KAS SDK (caver-js extension):

const CaverExtKAS = require('caver-js-ext-kas')
const caver = new CaverExtKAS(chainId, accessKeyId, secretAccessKey)

const name = 'Jasmine'
const symbol = 'JAS'
const alias = 'jasmine-alias'
const result = await caver.kas.kip17.deploy(name, symbol, alias)
console.log(result)

When the above codes are executed, the result of the KIP-17 DeployContract API will be displayed as shown below:

{
    status: 'Submitted',
    transactionHash: '0x4707420eeda479477eae0c73878d9186150c153a9e2cbfe43e9d37750b64a4ec',
}

Below is a demonstration of how to deploy a KIP-7 contract with KAS KIP-7 API while using KAS SDK (caver-js extension).

const caver = new CaverExtKAS(chainId, accessKeyId, secretAccessKey)

const CaverExtKAS = require('caver-js-ext-kas')
const caver = new CaverExtKAS(chainId, accessKeyId, secretAccessKey)
const name = 'Jasmine'
const symbol = 'JAS'
const decimals = 18
const initialSupply = '1000000000000000000'
const alias = 'jasmine-alias'
const result = await caver.kas.kip7.deploy(name, symbol, decimals, initialSupply, alias)
console.log(result)

Executing the above code will return the following results of calling the KIP-7 contract:

{
    status: 'Submitted',
    transactionHash: '0xf4a9c11fb3e5148050ac2a19ab221be72bebfea95078317dda01a1c207f6f779',
}

KAS SDK (caver-java extension)

In order to use KAS API with KAS SDK (caver-java extension), you need to set up "chain id" and "authentication key". You can initialize the setting to use KAS API service as shown below:

CaverExtKAS caver = new CaverExtKAS();
caver.initKASAPI(chainId, accessKeyId, secretAccessKey)

Using the above caver.initKASAPI function initializes the authentication keys used in Node API, Wallet API, Token History API, and Anchor API at the same time. The initialization method for each KAS API service is shown below. You can optionally pass the Endpoint URL as the last parameter. If a separate URL is not passed, the KAS Production URL described below will be set as the default.

KAS Production URL

  • Node API: https://node-api.klaytnapi.com

  • Wallet API: https://wallet-api.klaytnapi.com

  • Anchor API: https://anchor-api.klaytnapi.com

  • Token History API: https://th-api.klaytnapi.com

  • KIP-17 API: https://kip17-api.klaytnapi.com

// Initialize Node API
caver.initNodeAPI(chainId, accessKeyId, secretAccessKey [, url])
// Initialize Wallet API
caver.initWalletAPI(chainId, accessKeyId, secretAccessKey [, url])
// Initialize TokenHistory API
caver.initTokenHistoryAPI(chainId, accessKeyId, secretAccessKey [, url])
// Initialize Anchor API
caver.initAnchorAPI(chainId, accessKeyId, secretAccessKey [, url])
// KIP-17 API Initial Setting
caver.initKIP17API(chainId, accessKeyId, secretAccessKey [, url])

The following demonstrates how to fetch the latest block information with KAS' Node API when using KAS SDK (caver-java extension):

import com.klaytn.caver.methods.response.Quantity;
import xyz.groundx.caver_ext_kas.CaverExtKAS;
import java.io.IOException;

public class HelloKAS {
    public static void getBlockNumber() throws IOException {
        CaverExtKAS caver = new CaverExtKAS();
        caver.initKASAPI(chainId, accessKeyId, secretAccessKey);
        Quantity response = caver.rpc.klay.getBlockNumber().send();
        System.out.println(response.getResult());
    }

    public static void main(String[] args) throws IOException {
        getBlockNumber();
    }
}

When the above code is executed, the latest block number is displayed as shown below.

0x26b0736

Here's how to create an account using KAS' Wallet API using KAS SDK (caver-java extension).

import xyz.groundx.caver_ext_kas.CaverExtKAS;
import xyz.groundx.caver_ext_kas.rest_client.io.swagger.client.ApiException;
import xyz.groundx.caver_ext_kas.rest_client.io.swagger.client.api.wallet.model.Account;

public class HelloKAS {
    public static void createAccount() throws ApiException {
        CaverExtKAS caver = new CaverExtKAS();
        caver.initKASAPI(chainId, accessKeyId, secretAccessKey);

        Account account = caver.kas.wallet.createAccount();
        System.out.println(account);
    }

    public static void main(String[] args) throws ApiException {
        createAccount();
    }
}

When the above code is executed, the information of the account created in KAS is displayed as below.

class Account {
    address: 0x0BA67C887F922AF3d0D781dD940c6d0C80D395DE
    chainId: 1001
    createdAt: 1602550121
    keyId: krn:1001:wallet:d5c346f5-bb80-4f45-9093-57e25205cdc8:account-pool:pool:0xbedefad10db4df3488aaf1669b9164549c1aebe7c326f4b19ba6c6ce0f330fa5
    krn: krn:1001:wallet:d5c346f5-bb80-4f45-9093-57e25205cdc8:account-pool:pool
    publicKey: 0x041d56cbe46915854600c9d3c4ef614906f27473abe948cf587d990dcbce030d5989f4458bc470e44b2916d75194729102bb60e1e6a27c01030de84208a13232c2
    updatedAt: 1602550121
    multiSigKeys: null
    threshold: null
}

The following is how to retrieve NFT contract list using KAS' TokenHistory API using KAS SDK (caver-java extension).

import xyz.groundx.caver_ext_kas.CaverExtKAS;
import xyz.groundx.caver_ext_kas.kas.tokenhistory.TokenHistoryQueryOptions;
import xyz.groundx.caver_ext_kas.rest_client.io.swagger.client.ApiException;
import xyz.groundx.caver_ext_kas.rest_client.io.swagger.client.api.tokenhistory.model.PageableNftContractDetails;

public class HelloKAS {

    public static void getNFTContractList() throws ApiException {
        CaverExtKAS caver = new CaverExtKAS();
        caver.initKASAPI(chainId, accessKeyId, secretAccessKey);

        // Query parameters are optional, so `caver.kas.tokenHistory.getNFTContractList` can be executed without query parameters.
        TokenHistoryQueryOptions options = new TokenHistoryQueryOptions();
        options.setSize((long)1);

        PageableNftContractDetails result = caver.kas.tokenHistory.getNFTContractList(options);
        System.out.println(result);
    }

    public static void main(String[] args) throws ApiException {
        getNFTContractList();
    }
}

Executing the above code will output the list of NFT contracts as shown below.

class PageableNftContractDetails {
    items: [class NftContractDetail {
        address: 0x1d15887950aa821814b793ed4a4cfa38937df5da
        name: KIP17
        symbol: KIP17
        totalSupply: 0x0
        createdAt: 1602495497
        updatedAt: 1602495497
        deletedAt: 0
        type: KIP-17
        status: completed
    }]
    cursor: owN0deEJPGMZ69Q3L5V34MAgJ5xpNmrQ9lWk0EDvxv7bkQq1aLX58AZz0GlgNEyd1kRwK94JBdVP6rm3eopO2DMWYz6BKoXPYbdOewaGqZ1728La7rbx8YDBgW2lkqAK
}

Here's how to use KAS SDK (caver-java extension) to send anchoring data using KAS's Anchor API:

import xyz.groundx.caver_ext_kas.CaverExtKAS;
import xyz.groundx.caver_ext_kas.rest_client.io.swagger.client.ApiException;
import xyz.groundx.caver_ext_kas.rest_client.io.swagger.client.api.anchor.model.AnchorBlockPayload;
import xyz.groundx.caver_ext_kas.rest_client.io.swagger.client.api.anchor.model.AnchorBlockStatus;

public class HelloKAS {
    public void sendAnchoringData() throws ApiException {
        CaverExtKAS caver = new CaverExtKAS();
        caver.initKASAPI(chainId, accessKeyId, secretAccessKey);

        String operatorID = "operatorId";

        AnchorBlockPayload payload = new AnchorBlockPayload();
        payload.put("id", "12837851");
        payload.put("field", "1");
        payload.put("filed2", 4);

        AnchorBlockStatus status = caver.kas.anchor.sendAnchoringData(operatorID, payload);
        System.out.println();
    }

    public static void main(String[] args) throws ApiException {
        sendAnchoringData();
    }
}

When the above code is executed, the result of transmitting the anchoring data is displayed as below:

class AnchorBlockStatus {
    status: succeed
}

Here is how you can deploy KIP-17 contracts with KAS KIP-17 API when using KAS SDK (caver-java extension).

String name = "My First KIP-17";
String symbol = "MFK";
String alias = "my-first-kip17";
Kip17TransactionStatusResponse res = caver.kas.kip17.deploy(name, symbol, alias);
System.out.println(res);

When the above codes are executed, the results of the KIP-17 DeployContract API will be displayed:

class Kip17TransactionStatusResponse {
    status: Submitted
    transactionHash: 0x....
}

Using Smart Contracts with a Klaytn Account in KAS Wallet API

From KAS SDK v1.0.2, KASWallet, a wallet that operates using KAS Wallet API, is provided in caver. With this, you can use the caver.contract package and caver.kct using the Klaytn account of the KAS Wallet API.

Using caver.contract with a Klaytn Account in KAS Wallet API

caver.contract uses caver.wallet to deploy a smart contract to Klaytn and execute pre-deployed contracts. Since the caver.wallet of KAS SDK is a wallet that uses the KAS Wallet API, you can easily deploy or execute a smart contract on Klaytn by using the caver.contract in KAS SDK with the Klaytn account in KAS Wallet API.

Using caver.contract with a Klaytn account in KAS Wallet API is the same as the method to use the existing caver.contract of Caver. This section describes a simple example of deploying and executing a smart contract. Here, the Klaytn account used to deploy and run smart contracts is the Klaytn account managed by the KAS Wallet API, and this Klaytn account must own enough KLAY to send transactions.

KAS SDK(caver-js extension)

How to deploy a smart contract using caver-js-ext-kas is as follows.

// caver-js-ext-kas
const CaverExtKAS = require('caver-js-ext-kas')

const chainId = 1001
const accessKeyId = '{access key ID of your KAS account}'
const secretAccessKey = '{secret access key of your KAS account}'

const caver = new CaverExtKAS(chainId, accessKeyId, secretAccessKey)

const abi = [
    {
        constant: true,
        inputs: [{ name: 'key', type: 'string' }],
        name: 'get',
        outputs: [{ name: '', type: 'string' }],
        payable: false,
        stateMutability: 'view',
        type: 'function',
    },
    {
        constant: false,
        inputs: [{ name: 'key', type: 'string' }, { name: 'value', type: 'string' }],
        name: 'set',
        outputs: [],
        payable: false,
        stateMutability: 'nonpayable',
        type: 'function',
    },
]
const byteCode =
    '0x608060405234801561001057600080fd5b5061051f806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c8063693ec85e1461003b578063e942b5161461016f575b600080fd5b6100f46004803603602081101561005157600080fd5b810190808035906020019064010000000081111561006e57600080fd5b82018360208201111561008057600080fd5b803590602001918460018302840111640100000000831117156100a257600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192905050506102c1565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610134578082015181840152602081019050610119565b50505050905090810190601f1680156101615780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102bf6004803603604081101561018557600080fd5b81019080803590602001906401000000008111156101a257600080fd5b8201836020820111156101b457600080fd5b803590602001918460018302840111640100000000831117156101d657600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192908035906020019064010000000081111561023957600080fd5b82018360208201111561024b57600080fd5b8035906020019184600183028401116401000000008311171561026d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192905050506103cc565b005b60606000826040518082805190602001908083835b602083106102f957805182526020820191506020810190506020830392506102d6565b6001836020036101000a03801982511681845116808217855250505050505090500191505090815260200160405180910390208054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156103c05780601f10610395576101008083540402835291602001916103c0565b820191906000526020600020905b8154815290600101906020018083116103a357829003601f168201915b50505050509050919050565b806000836040518082805190602001908083835b6020831061040357805182526020820191506020810190506020830392506103e0565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020908051906020019061044992919061044e565b505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061048f57805160ff19168380011785556104bd565b828001600101855582156104bd579182015b828111156104bc5782518255916020019190600101906104a1565b5b5090506104ca91906104ce565b5090565b6104f091905b808211156104ec5760008160009055506001016104d4565b5090565b9056fea165627a7a723058203ffebc792829e0434ecc495da1b53d24399cd7fff506a4fd03589861843e14990029'
const contract = new caver.contract(abi)

// The from account that sends the SmartContractDeploy transaction must own enough KLAY.
const deployed = await contract.deploy({ data: byteCode }).send({ from: '0x{the address of a Klaytn account in KAS Wallet API}', gas: 10000000 })
console.log(`Deployed contract address: ${deployed.options.address}`)

When the above code is executed, the address of the deployed smart contract is displayed as shown below.

Deployed contract address: 0x5D3Cd9eB73f00BbECB949DCE08BB26019FcB599f

The following is how to execute the smart contract deployed on Klaytn using caver-js-ext-kas.

// caver-js-ext-kas
const CaverExtKAS = require('caver-js-ext-kas')

const chainId = 1001
const accessKeyId = '{access key ID of your KAS account}'
const secretAccessKey = '{secret access key of your KAS account}'

const caver = new CaverExtKAS(chainId, accessKeyId, secretAccessKey)

const abi = [
    {
        constant: true,
        inputs: [{ name: 'key', type: 'string' }],
        name: 'get',
        outputs: [{ name: '', type: 'string' }],
        payable: false,
        stateMutability: 'view',
        type: 'function',
    },
    {
        constant: false,
        inputs: [{ name: 'key', type: 'string' }, { name: 'value', type: 'string' }],
        name: 'set',
        outputs: [],
        payable: false,
        stateMutability: 'nonpayable',
        type: 'function',
    },
]
const contractAddress = '0x5D3Cd9eB73f00BbECB949DCE08BB26019FcB599f'
const contract = new caver.contract(abi, contractAddress)

// The from account that sends the SmartContractExecution transaction must own enough KLAY.
const receipt = await contract.methods.set('key', 'value').send({ from: '0x{the address of a Klaytn account in KAS Wallet API}', gas: 5000000 })
console.log(receipt)

When the above code is executed, the receipt of the SmartContractExecution transaction is output as shown below.

{
    blockHash: '0x86ba9ee3428d575438dc7dd0a83d151e400b853a948365d1aef0f73794d0e194',
    blockNumber: 45759390,
    contractAddress: null,
    from: '0x2f87b35ce367eefaa78a5d922dab39113e0bd5a9',
    gas: '0x2faf080',
    gasPrice: '0x5d21dba00',
    gasUsed: 62351,
    input: '0xe942b...',
    logsBloom: '0x00000...',
    nonce: '0x1',
    senderTxHash: '0x4eb995c841a81153f7cfec45b316b2b59c64d28e1af0be8b157d0e3f87647744',
    signatures: [
        {
            V: '0x7f6',
            R: '0x2bc966ba636c8b6358783f852ad64f372a97f8513b38e5a2dc84524850c3a6d7',
            S: '0x147e4d0a93c5052dee2d8ce5c783d10396c8f5da438b659898d0eb47c832d648',
        },
    ],
    status: true,
    to: '0x5d3cd9eb73f00bbecb949dce08bb26019fcb599f',
    transactionHash: '0x4eb995c841a81153f7cfec45b316b2b59c64d28e1af0be8b157d0e3f87647744',
    transactionIndex: 0,
    type: 'TxTypeSmartContractExecution',
    typeInt: 48,
    value: '0x0',
    events: {},
}

KAS SDK(caver-java extension)

How to deploy a smart contract using caver-java-ext-kas is as follows.

// caver-java-ext-kas
import com.klaytn.caver.contract.Contract;
import com.klaytn.caver.contract.SendOptions;
import com.klaytn.caver.utils.ChainId;
import org.web3j.protocol.exceptions.TransactionException;
import xyz.groundx.caver_ext_kas.CaverExtKAS;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
public class SampleContract {
    static final String BINARY = "608060405234801561001057600080fd5b5061051f806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c8063693ec85e1461003b578063e942b5161461016f575b600080fd5b6100f46004803603602081101561005157600080fd5b810190808035906020019064010000000081111561006e57600080fd5b82018360208201111561008057600080fd5b803590602001918460018302840111640100000000831117156100a257600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192905050506102c1565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610134578082015181840152602081019050610119565b50505050905090810190601f1680156101615780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102bf6004803603604081101561018557600080fd5b81019080803590602001906401000000008111156101a257600080fd5b8201836020820111156101b457600080fd5b803590602001918460018302840111640100000000831117156101d657600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192908035906020019064010000000081111561023957600080fd5b82018360208201111561024b57600080fd5b8035906020019184600183028401116401000000008311171561026d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192905050506103cc565b005b60606000826040518082805190602001908083835b602083106102f957805182526020820191506020810190506020830392506102d6565b6001836020036101000a03801982511681845116808217855250505050505090500191505090815260200160405180910390208054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156103c05780601f10610395576101008083540402835291602001916103c0565b820191906000526020600020905b8154815290600101906020018083116103a357829003601f168201915b50505050509050919050565b806000836040518082805190602001908083835b6020831061040357805182526020820191506020810190506020830392506103e0565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020908051906020019061044992919061044e565b505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061048f57805160ff19168380011785556104bd565b828001600101855582156104bd579182015b828111156104bc5782518255916020019190600101906104a1565b5b5090506104ca91906104ce565b5090565b6104f091905b808211156104ec5760008160009055506001016104d4565b5090565b9056fea165627a7a723058203ffebc792829e0434ecc495da1b53d24399cd7fff506a4fd03589861843e14990029";

    static final String ABI = "[{\"constant\":true,\"inputs\":[{\"name\":\"key\",\"type\":\"string\"}],\"name\":\"get\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"key\",\"type\":\"string\"},{\"name\":\"value\",\"type\":\"string\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]";

    public static void main(String[] args) throws NoSuchMethodException, TransactionException, IOException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
        String accessKey = "your access key";
        String secretAccessKey = "your secret access key";
        CaverExtKAS caver = new CaverExtKAS(ChainId.BAOBAB_TESTNET, accessKey, secretAccessKey);

        String deployer = "0x{address}";
        BigInteger gas = BigInteger.valueOf(10000000);
        SendOptions sendOptions = new SendOptions(deployer, gas);

        Contract contract = new Contract(caver, ABI);
        Contract sampleContract = contract.deploy(sendOptions, BINARY);
        System.out.println("Deployed contract address: " + sampleContract.getContractAddress());
    }
}

When the above code is executed, the address of the deployed smart contract is displayed as shown below.

Deployed contract address: 0x5D3Cd9eB73f00BbECB949DCE08BB26019FcB599f

The following is how to execute the smart contract deployed on Klaytn using caver-java-ext-kas.

// caver-java-ext-kas
import com.klaytn.caver.contract.Contract;
import com.klaytn.caver.contract.SendOptions;
import com.klaytn.caver.methods.response.TransactionReceipt;
import com.klaytn.caver.utils.ChainId;
import org.web3j.abi.datatypes.Type;
import org.web3j.protocol.exceptions.TransactionException;
import xyz.groundx.caver_ext_kas.CaverExtKAS;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;

public class SampleContract {
    static final String ABI = "[{\"constant\":true,\"inputs\":[{\"name\":\"key\",\"type\":\"string\"}],\"name\":\"get\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"key\",\"type\":\"string\"},{\"name\":\"value\",\"type\":\"string\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]";

    public static void main(String[] args) throws NoSuchMethodException, TransactionException, IOException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
        String accessKey = "your access key";
        String secretAccessKey = "your secret access key";
        CaverExtKAS caver = new CaverExtKAS(ChainId.BAOBAB_TESTNET, accessKey, secretAccessKey);

        String contractAddress = "0x5D3Cd9eB73f00BbECB949DCE08BB26019FcB599f";
        String executor = "0x{address}";

        Contract sampleContract = new Contract(caver, ABI, contractAddress);
        SendOptions sendOptions = new SendOptions(executor, BigInteger.valueOf(5000000));
        TransactionReceipt.TransactionReceiptData receiptData = sampleContract.send(sendOptions, "set", "key", "value");

        System.out.println(receiptData.getTransactionHash());
    }
}

When the above code is executed, the transaction hash of the SmartContractExecution transaction is output as shown below.

0x4eb995c841a81153f7cfec45b316b2b59c64d28e1af0be8b157d0e3f87647744

For more information about caver.contract of Caver, refer to caver-js or caver-java.

Using caver.kct.kip7 with a Klaytn account in KAS Wallet API

caver.kct.kip7 provides the functions to deploy KIP-7 token contracts to Klaytn using caver.wallet and execute pre-deployed KIP-7 token contracts. Since caver.wallet of KAS SDK is a wallet that uses KAS Wallet API, if you use caver.kct.kip7 of KAS SDK, you can easily deploy and execute KIP-7 token contract on Klaytn with a Klaytn account in KAS Wallet API.

The method to use caver.kct.kip7 using the Klaytn account in KAS Wallet API is the same as the method of using the existing caver.kct.kip7 of Caver. This section describes a simple example of deploying and executing a KIP-7 token contract. Here, the Klaytn account used to deploy and run smart contracts is the Klaytn account managed by the KAS Wallet API, and this Klaytn account must own enough KLAY to send transactions.

KAS SDK(caver-js extension)

How to deploy a KIP-7 token contract using caver-js-ext-kas is as follows.

// caver-js-ext-kas
const CaverExtKAS = require('caver-js-ext-kas')
const caver = new CaverExtKAS()

const accessKeyId = '{access key ID of your KAS account}'
const secretAccessKey = '{secret access key of your KAS account}'

caver.initKASAPI(chainId, accessKeyId, secretAccessKey)

const deployed = await caver.kct.kip7.deploy({
    name: 'Jasmine',
    symbol: 'JAS',
    decimals: 18,
    initialSupply: '100000000000000000000'
}, '0x{the address of a Klaytn account in KAS Wallet API}')
console.log(`Deployed contract address: ${deployed.options.address}`)

When the above code is executed, the address of the deployed KIP-7 token contract is displayed as shown below.

Deployed contract address: 0x42c3809EeED7c5C497067fE4092D1c354D3a01Cb

The following is how to execute the KIP-7 token contract deployed on Klaytn using caver-js-ext-kas.

// caver-js-ext-kas
const CaverExtKAS = require('caver-js-ext-kas')

const chainId = 1001
const accessKeyId = '{access key ID of your KAS account}'
const secretAccessKey = '{secret access key of your KAS account}'

const caver = new CaverExtKAS(chainId, accessKeyId, secretAccessKey)

const contractAddress = '0x42c3809EeED7c5C497067fE4092D1c354D3a01Cb'
const kip7 = new caver.kct.kip7(contractAddress)

const receipt = await kip7.transfer('0x{address in hex}', 1, { from: '0x{the address of a Klaytn account in KAS Wallet API}' })
console.log(receipt)

When the above code is executed, the receipt of the SmartContractExecution transaction is output as shown below.

{
    blockHash: '0x00335de146548227d0800087685380efcfd206f7fe1e905874ad4b6bb8e0a3f7',
    blockNumber: 45760341,
    contractAddress: null,
    from: '0x2f87b35ce367eefaa78a5d922dab39113e0bd5a9',
    gas: '0xd637',
    gasPrice: '0x5d21dba00',
    gasUsed: 41487,
    input: '0xa9059...',
    logsBloom: '0x00000...',
    nonce: '0x5',
    senderTxHash: '0x752d6ac8cf7ba0e12de8c0200fda68925f588a0b614118e19568eec4ad3fe4dd',
    signatures: [
        {
            V: '0x7f5',
            R: '0xf9d37f109b6e17099d7808ded81fe9e69086a710e027d0c64330c3b434022ea4',
            S: '0x20cb7a6afdeeaf35bb83ed9d0ca9caca17746ed475af44fe342c271ac638e1b1',
        },
    ],
    status: true,
    to: '0x42c3809eeed7c5c497067fe4092d1c354d3a01cb',
    transactionHash: '0x752d6ac8cf7ba0e12de8c0200fda68925f588a0b614118e19568eec4ad3fe4dd',
    transactionIndex: 0,
    type: 'TxTypeSmartContractExecution',
    typeInt: 48,
    value: '0x0',
    events: {
        Transfer: {
            address: '0x42c3809EeED7c5C497067fE4092D1c354D3a01Cb',
            blockNumber: 45760341,
            transactionHash: '0x752d6ac8cf7ba0e12de8c0200fda68925f588a0b614118e19568eec4ad3fe4dd',
            transactionIndex: 0,
            blockHash: '0x00335de146548227d0800087685380efcfd206f7fe1e905874ad4b6bb8e0a3f7',
            logIndex: 0,
            id: 'log_29039dd9',
            returnValues: {
                '0': '0x2F87b35Ce367EEfaA78a5d922DaB39113E0bd5a9',
                '1': '0x2F87b35Ce367EEfaA78a5d922DaB39113E0bd5a9',
                '2': '1',
                from: '0x2F87b35Ce367EEfaA78a5d922DaB39113E0bd5a9',
                to: '0x2F87b35Ce367EEfaA78a5d922DaB39113E0bd5a9',
                value: '1',
            },
            event: 'Transfer',
            signature: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',
            raw: {
                data: '0x0000000000000000000000000000000000000000000000000000000000000001',
                topics: [
                    '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',
                    '0x0000000000000000000000002f87b35ce367eefaa78a5d922dab39113e0bd5a9',
                    '0x0000000000000000000000002f87b35ce367eefaa78a5d922dab39113e0bd5a9',
                ],
            },
        },
    },
}

KAS SDK(caver-java extension)

How to deploy a KIP-7 token contract using caver-java-ext-kas is as follows.

// caver-java-ext-kas
import com.klaytn.caver.kct.kip7.KIP7;
import com.klaytn.caver.utils.ChainId;
import org.web3j.protocol.exceptions.TransactionException;
import xyz.groundx.caver_ext_kas.CaverExtKAS;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
public class SampleKIP7 {
    public static void main(String[] args) throws NoSuchMethodException, IOException, InstantiationException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, TransactionException {
        String accessKey = "your access key";
        String secretAccessKey = "your secret access key";
        CaverExtKAS caver = new CaverExtKAS(ChainId.BAOBAB_TESTNET, accessKey, secretAccessKey);

        //deployer must have KLAY to deploy and execute smart contract.
        String deployer = "0x{address}";

        BigInteger initialSupply = BigInteger.TEN.multiply(BigInteger.TEN.pow(18)); // 10 * 10^18
        KIP7 kip7 = KIP7.deploy(caver, deployer, "JASMINE", "JAS", 18, initialSupply);
        System.out.println("Deployed contract address : " + kip7.getContractAddress());
    }

When the above code is executed, the address of the deployed KIP-7 token contract is displayed as shown below.

Deployed contract address: 0x42c3809EeED7c5C497067fE4092D1c354D3a01Cb

The following is how to execute the KIP-7 token contract deployed on Klaytn using caver-java-ext-kas.

// caver-java-ext-kas
import com.klaytn.caver.contract.SendOptions;
import com.klaytn.caver.kct.kip7.KIP7;
import com.klaytn.caver.methods.response.TransactionReceipt;
import com.klaytn.caver.utils.ChainId;
import org.web3j.protocol.exceptions.TransactionException;
import xyz.groundx.caver_ext_kas.CaverExtKAS;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
public class SampleKIP7 {
    public static void main(String[] args) throws NoSuchMethodException, IOException, InstantiationException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, TransactionException {
        String accessKey = "your access key";
        String secretAccessKey = "your secret access key";
        CaverExtKAS caver = new CaverExtKAS(ChainId.BAOBAB_TESTNET, accessKey, secretAccessKey);

        //from must have KLAY to deploy and execute smart contract.
        String from = "0x{address}";
        String to = "0x{address}";

        String contractAddress = "0x42c3809EeED7c5C497067fE4092D1c354D3a01Cb";
        KIP7 kip7 = new KIP7(caver, contractAddress);

        BigInteger transferAmount = BigInteger.ONE.multiply(BigInteger.TEN.pow(18));
        SendOptions sendOptions = new SendOptions(from);
        TransactionReceipt.TransactionReceiptData receiptData = kip7.transfer(to, transferAmount, sendOptions);

        System.out.println(receiptData.getTransactionHash());
    }
}

When the above code is executed, the transaction hash of the SmartContractExecution transaction is output as shown below.

0x752d6ac8cf7ba0e12de8c0200fda68925f588a0b614118e19568eec4ad3fe4dd

For more information about caver.kct.kip7 of Caver, refer to caver-js or caver-java.

Using caver.kct.kip17 with a Klaytn Account in KAS Wallet API

caver.kct.kip17 provides the functions for deploying KIP-17 token contracts to Klaytn using caver.wallet and executing pre-deployed KIP-17 contracts. Since caver.wallet for KAS SDK is a wallet that uses KAS Wallet API, you can easily deploy and execute KIP-17 contracts on Klaytn with a Klaytn account in KAS Wallet API using caver.kct.kip17 in the KAS SDK.

Using caver.kct.kip17 with a Klaytn Account in KAS Wallet API is the same as using the existing caver.kct.kip17 in Caver. This section gives a simple example of how to deploy and execute a KIP-17 contract. Here, the Klaytn account used to deploy and run smart contracts is the Klaytn account managed by the KAS Wallet API, and this Klaytn account balance must own enough KLAY to send transactions.

KAS SDK provides KAS KIP-17 API. To use KAS KIP-17 API, please refer to Tutorial or API Reference Docs(JS, JAVA).

KAS SDK(caver-js extension)

How to deploy a KIP-17 token contract using caver-js-ext-kas is as follows.

// caver-js-ext-kas
const CaverExtKAS = require('caver-js-ext-kas')

const chainId = 1001
const accessKeyId = '{access key ID of your KAS account}'
const secretAccessKey = '{secret access key of your KAS account}'

const caver = new CaverExtKAS(chainId, accessKeyId, secretAccessKey)

const deployed = await caver.kct.kip17.deploy({
    name: 'Jasmine',
    symbol: 'JAS',
}, '0x{the address of a Klaytn account in KAS Wallet API}')
console.log(`Deployed contract address: ${deployed.options.address}`)

When the above code is executed, the address of the deployed KIP-17 token contract is displayed as below:

Deployed contract address: 0xAD719B194457D0641B410Ce75C4D22442533A781

The following is how to execute the KIP-17 token contract deployed on Klaytn using caver-js-ext-kas.

// caver-js-ext-kas
const CaverExtKAS = require('caver-js-ext-kas')

const chainId = 1001
const accessKeyId = '{access key ID of your KAS account}'
const secretAccessKey = '{secret access key of your KAS account}'

const caver = new CaverExtKAS(chainId, accessKeyId, secretAccessKey)

const contractAddress = '0xAD719B194457D0641B410Ce75C4D22442533A781'
const kip17 = new caver.kct.kip17(contractAddress)

const receipt = await kip17.mintWithTokenURI('0x{address in hex}', tokenId, tokenURI, { from: '0x{the address of a Klaytn account in KAS Wallet API}' })
console.log(receipt)

When the above code is executed, the receipt of the SmartContractExecution transaction is output as shown below.

{
        blockHash: '0xefde3a7ab101486edb9aa77b7f2f8163eb0aaaa4e8ed6d9899715a624a8daabd',
        blockNumber: 45760605,
        contractAddress: null,
        from: '0x2f87b35ce367eefaa78a5d922dab39113e0bd5a9',
        gas: '0x4246d',
        gasPrice: '0x5d21dba00',
        gasUsed: 194419,
        input: '0x50bb4...',
        logsBloom: '0x00000...',
        nonce: '0x7',
        senderTxHash: '0x6cf0c3a649a15001ede8ad522c623affe453b7da6be27276badba3a8189587be',
        signatures: [
            {
                V: '0x7f5',
                R: '0x1441ab33ade89a81ffb670791178035f8af31940b77d10cd0dc2aa86457738c9',
                S: '0x30a7cf7258f05fcf270996b14aaaba00744d6c790721de3fce21c70397c07157',
            },
        ],
        status: true,
        to: '0xad719b194457d0641b410ce75c4d22442533a781',
        transactionHash: '0x6cf0c3a649a15001ede8ad522c623affe453b7da6be27276badba3a8189587be',
        transactionIndex: 0,
        type: 'TxTypeSmartContractExecution',
        typeInt: 48,
        value: '0x0',
        events: {
            Transfer: {
                address: '0xAD719B194457D0641B410Ce75C4D22442533A781',
                blockNumber: 45760605,
                transactionHash: '0x6cf0c3a649a15001ede8ad522c623affe453b7da6be27276badba3a8189587be',
                transactionIndex: 0,
                blockHash: '0xefde3a7ab101486edb9aa77b7f2f8163eb0aaaa4e8ed6d9899715a624a8daabd',
                logIndex: 0,
                id: 'log_54be99f9',
                returnValues: {
                    '0': '0x0000000000000000000000000000000000000000',
                    '1': '0x2F87b35Ce367EEfaA78a5d922DaB39113E0bd5a9',
                    '2': '1',
                    from: '0x0000000000000000000000000000000000000000',
                    to: '0x2F87b35Ce367EEfaA78a5d922DaB39113E0bd5a9',
                    tokenId: '1',
                },
                event: 'Transfer',
                signature: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',
                raw: {
                    data: '0x',
                    topics: [
                        '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',
                        '0x0000000000000000000000000000000000000000000000000000000000000000',
                        '0x0000000000000000000000002f87b35ce367eefaa78a5d922dab39113e0bd5a9',
                        '0x0000000000000000000000000000000000000000000000000000000000000001',
                    ],
                },
            },
        },
    }

KAS SDK(caver-java extension)

You can deploy a KIP-17 contract using caver-java-ext-kas as shown below:

// caver-java-ext-kas
import com.klaytn.caver.kct.kip17.KIP17;
import com.klaytn.caver.utils.ChainId;
import org.junit.Ignore;
import org.web3j.protocol.exceptions.TransactionException;
import xyz.groundx.caver_ext_kas.CaverExtKAS;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
public class SampleKIP17 {
    public static void main(String[] args) throws NoSuchMethodException, IOException, InstantiationException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, TransactionException {
        String accessKey = "your access key";
        String secretAccessKey = "your secret access key";
        CaverExtKAS caver = new CaverExtKAS(ChainId.BAOBAB_TESTNET, accessKey, secretAccessKey);

        //deployer must have KLAY to deploy and execute smart contract.
        String deployer = "0x{deployer address}";
        KIP17 kip17 = KIP17.deploy(caver, deployer, "JASMINE", "JAS");

        System.out.println("Deployed contract address : " + kip17.getContractAddress());
    }
}

When the above code is executed, the address of the deployed KIP-17 token contract is displayed as shown below.

Deployed contract address: 0xAD719B194457D0641B410Ce75C4D22442533A781

The following is how to execute the KIP-17 token contract deployed on Klaytn using caver-java-ext-kas.

// caver-java-ext-kas
import com.klaytn.caver.contract.SendOptions;
import com.klaytn.caver.kct.kip17.KIP17;
import com.klaytn.caver.methods.response.TransactionReceipt;
import com.klaytn.caver.utils.ChainId;
import org.junit.Ignore;
import org.web3j.protocol.exceptions.TransactionException;
import xyz.groundx.caver_ext_kas.CaverExtKAS;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
public class SampleKIP17 {
    public static void main(String[] args) throws NoSuchMethodException, IOException, InstantiationException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, TransactionException {
        String accessKey = "your access key";
        String secretAccessKey = "your secret access key";
        CaverExtKAS caver = new CaverExtKAS(ChainId.BAOBAB_TESTNET, accessKey, secretAccessKey);

        String contractAddress = "0xAD719B194457D0641B410Ce75C4D22442533A781";
        KIP17 kip17 = new KIP17(caver, contractAddress);

        //from must have KLAY to deploy and execute smart contract.
        String from = "0x{from address}";
        String to = "0x{to address}";
        String tokenURI = "tokenURI";

        SendOptions sendOptions = new SendOptions(from);
        TransactionReceipt.TransactionReceiptData receiptData = kip17.mintWithTokenURI(to, BigInteger.ZERO, tokenURI, sendOptions);

        System.out.println(receiptData.getTransactionHash());
    }
}

When the above code is executed, the transaction hash of the SmartContractExecution transaction is output as shown below.

0x6cf0c3a649a15001ede8ad522c623affe453b7da6be27276badba3a8189587be

For more information about caver.kct.kip17 of Caver, refer to caver-js or caver-java.

Using KeyringContainer in KAS SDK

In KAS SDK, KASWallet which uses KAS Wallet API is provided by caver.wallet instead of KeyringContainer, an in-memory wallet provided by caver.wallet of existing caver. So, if you want to use the in-memory wallet KeyringContainer in KAS SDK, you need to instantiate it separately.

caver-js-ext-kas and caver-java-ext-kas both provide setWallet function in caver.contract and caver.kct to specify the wallet to use when deploying or executing smart contracts. Through this, you can flexibly specify and use the wallet to be used when deploying or executing smart contracts for each instance.

KAS SDK(caver-js extension)

First, how to create a KeyringContainer instance using caver-js-ext-kas is as follows.

const keyringContainer = new caver.keyringContainer()

How to use the keyringContainer created above with caver.contract is as follows.

const keyringContainer = new caver.keyringContainer()
const keyring = keyringContainer.keyring.createFromPrivateKey('0x{private key}')
keyringContainer.add(keyring)

// Using keyringContainer when deploying smart contracts
const contract = new caver.contract(abi)
contract.setWallet(keyringContainer)
const deployed = await contract.deploy({ data: byteCode }).send({ from: keyring.address, gas: 10000000 })

const receipt = await deployed.methods.set('key', 'value').send({ from: keyring.address, gas: 5000000 })

The deployed contract instance returned by executing the above code is also an object that uses same keyringContainer. If you are using a contract that has already been deployed, you can specify to use the keyringContiainer using the setWallet function as shown below.

const keyringContainer = new caver.keyringContainer()
const keyring = keyringContainer.keyring.createFromPrivateKey('0x{private key}')
keyringContainer.add(keyring)

// Using keyringContainer when executing smart contracts
const contract = new caver.contract(abi, contractAddress)
contract.setWallet(keyringContainer)
const receipt = await contract.methods.set('key', 'value').send({ from: keyring.address, gas: 5000000 })

How to use the separately created keyringContainer in caver.kct is as follows. For static functions that deploy a KIP-7 or KIP-17 token contract called deploy, you can pass the wallet to be used as the last parameter.

How to deploy KIP-7 token contract using keyringContainer with caver.kct.kip7 is as follows.

const keyringContainer = new caver.keyringContainer()
const keyring = keyringContainer.keyring.createFromPrivateKey('0x{private key}')
keyringContainer.add(keyring)

// Passing keyringContainer as the last parameter creates an instance internally and calls setWallet
const kip7 = await caver.kct.kip7.deploy({
    name: 'Jasmine',
    symbol: 'JAS',
    decimals: 18,
    initialSupply: '100000000000000000000'
}, keyring.address, keyringContainer)

const receipt = await kip7.transfer('0x{address in hex}', 1, { from: keyring.address })

Like deploy of caver.contract, the instance returned as a result of deployment is an object using same keyringContainer.

To use the keyringContainer when executing the already deployed KIP-7 token contract, you need to call the setWallet function as shown below.

const keyringContainer = new caver.keyringContainer()
const keyring = keyringContainer.keyring.createFromPrivateKey('0x{private key}')
keyringContainer.add(keyring)

const kip7 = new caver.kct.kip7(contractAddress)
kip7.setWallet(keyringContainer)
const receipt = await kip7.transfer('0x{address in hex}', 1, { from: keyring.address })

How to deploy KIP-17 token contract using keyringContainer with caver.kct.kip17 is as follows.

const keyringContainer = new caver.keyringContainer()
const keyring = keyringContainer.keyring.createFromPrivateKey('0x{private key}')
keyringContainer.add(keyring)

// Passing keyringContainer as the last parameter creates an instance internally and calls setWallet
const kip17 = await caver.kct.kip17.deploy({
    name: 'Jasmine',
    symbol: 'JAS',
}, keyring.address, keyringContainer)

const receipt = await kip17.transfer('0x{address in hex}', 1, { from: keyring.address })

Like deploy of caver.contract, the instance returned as a result of deployment is an object using same keyringContainer.

To use the keyringContainer when executing the already deployed KIP-7 token contract, you need to call the setWallet function as shown below.

const keyringContainer = new caver.keyringContainer()
const keyring = keyringContainer.keyring.createFromPrivateKey('0x{private key}')
keyringContainer.add(keyring)

const kip17 = new caver.kct.kip17(contractAddress)
kip17.setWallet(keyringContainer)
const receipt = await kip17.mintWithTokenURI('0x{address in hex}', tokenId, tokenURI, { from: keyring.address })

KAS SDK(caver-java extension)

First, how to create a KeyringContainer instance using caver-java-ext-kas is as follows.

KeyringContainer container = new KeyringContainer();

How to use the keyringContainer created above with caver.contract is as follows.

KeyringContainer container = new KeyringContainer();
SingleKeyring keyring = (SingleKeyring)container.add(KeyringFactory.createFromPrivateKey("0x{private key}"))

Contract contract = new Contract(caver, abi);
contract.setWallet(container);

SendOptions deploySendOptions = new SendOptions(keyring.getAddress(), BigInteger.valueOf(5000000));
Contract deployed = contract.deploy(deploySendOptions, bytecode);

SendOptions exeuteSendOptions = new SendOptions(keyring.getAddress(), BigInteger.valueOf(2500000));
TransactionReceipt.TransactionReceiptData receiptData = deployed.send(exeuteSendOptions, "set", "key", "value");

The deployed contract instance returned by executing the above code is also an object that uses same keyringContainer. If you are using a contract that has already been deployed, you can specify to use the keyringContiainer using the setWallet function as shown below.

KeyringContainer container = new KeyringContainer();
SingleKeyring keyring = (SingleKeyring)container.add(KeyringFactory.createFromPrivateKey("0x{private key}"));

String contractAddress = "0xAD719B194457D0641B410Ce75C4D22442533A781";
Contract deployed = new Contract(caver, abi, contractAddress);
deployed.setWallet(container);

SendOptions exeuteSendOptions = new SendOptions(keyring.getAddress(), BigInteger.valueOf(2500000));
TransactionReceipt.TransactionReceiptData receiptData = deployed.send(exeuteSendOptions, "set", "key", "value");

How to use the separately created keyringContainer in caver.kct is as follows. For static functions that deploy a KIP-7 or KIP-17 token contract called deploy, you can pass the wallet to be used as the last parameter.

How to deploy KIP-7 token contract using keyringContainer with caver.kct.kip7 is as follows.

KeyringContainer container = new KeyringContainer();
SingleKeyring deployer_keyring = (SingleKeyring)container.add(KeyringFactory.createFromPrivateKey("0x{private key}"));

BigInteger initialSupply = BigInteger.TEN.multiply(BigInteger.TEN.pow(18)); // 10 * 10^18
KIP7 kip7 = KIP7.deploy(caver, deployer_keyring.getAddress(), "JASMINE", "JAS", 18, initialSupply, container);

Like deploy of caver.contract, the instance returned as a result of deployment is an object using same keyringContainer.

To use the keyringContainer when executing the already deployed KIP-7 token contract, you need to call the setWallet function as shown below.

KeyringContainer container = new KeyringContainer();
SingleKeyring executor_keyring = (SingleKeyring)container.add(KeyringFactory.createFromPrivateKey("0x{private key}"));

String contractAddress = "0xAD719B194457D0641B410Ce75C4D22442533A781";
KIP7 kip7 = new KIP7(caver, contractAddress);
kip7.setWallet(container);

SendOptions sendOptions = new SendOptions(executor_keyring.getAddress());
BigInteger transferAmount = BigInteger.ONE.multiply(BigInteger.TEN.pow(18));
TransactionReceipt.TransactionReceiptData receiptData_transfer = kip7.transfer("0x{to address}", transferAmount, sendOptions);

How to deploy KIP-17 token contract using keyringContainer with caver.kct.kip17 is as follows.

KeyringContainer container = new KeyringContainer();
SingleKeyring deployer_keyring = (SingleKeyring)container.add(KeyringFactory.createFromPrivateKey("0x{private key}"));

KIP17 kip17 = KIP17.deploy(caver, deployer_keyring.getAddress(), "JASMINE", "JAS", container);

Like deploy of caver.contract, the instance returned as a result of deployment is an object using same keyringContainer.

To use the keyringContainer when executing the already deployed KIP-17 token contract, you need to call the setWallet function as shown below.

KeyringContainer container = new KeyringContainer();
SingleKeyring executor_keyring = (SingleKeyring)container.add(KeyringFactory.createFromPrivateKey("0x{private key}"));

String contractAddress = "0xAD719B194457D0641B410Ce75C4D22442533A781";
KIP17 kip17 = new KIP17(caver, contractAddress);
kip17.setWallet(container);

String from = "0x{from address}";
String to = "0x{to address}";
String tokenURI = "tokenURI";
SendOptions sendOptions = new SendOptions(from);
TransactionReceipt.TransactionReceiptData receiptData = kip17.mintWithTokenURI(to, BigInteger.ZERO, tokenURI, sendOptions);

caver-java KASWalletException

An HTTP error of KAS Wallet API that occurs while executing KASWallet's method is stored in a KASAPIException instance, and thus a KASAPIException instance is thrown on error. KASAPIException is an exception class that extends RuntimeException, an unchecked exception, so you don't always need to catch it. However, if you need to check the details of the HTTP error that occurred while executing the KAS Wallet API, it is recommended to check the details of the KASAPIException using the try-catch statement.

The example below catches the KASAPIException instance storing the HTTP error response occured while exeuting KASWallet's getAccount() method.

try {
    String unKnownAddress = "0x785ba1146cc1bed97b9c8d73e9293cc3b6bc3691";
    Account account = caver.wallet.getAccount(unKnownAddress);
} catch (KASAPIException e) {
    System.out.println(e.getcode()); // 400
    System.out.println(e.getMessage()); // "Bad Request"
    System.out.println(e.getResponseBody().getCode()); // 1061010
    System.out.println(e.getResponseBody().getMessage()); // "data don't exist"
}

Calling Klaytn Node API of KAS using WebSocket Provider

You can call the KAS Klaytn Node API using WebSocket Provider. To use WebSocket Provider, you have to specify the provider that you will be using for calling Node API during the initialization.

KAS SDK(caver-js extension)

First, here is how you can initialize WebSocket Provider when calling the CaverExtKAS contructor.

const CaverExtKAS = require('caver-js-ext-kas')
const caver = new CaverExtKAS(chainId, accessKeyId, secretAccessKey, { useNodeAPIWithHttp: false })
const blockNumber = await caver.rpc.klay.getBlockNumber()
console.log(blockNumber)

As the past parameter of the contructor, you can pass the object that can define the options required for initialization. The useNodeAPIWithHttp field of the options object can define the provider that is used for calling the Node API. The default value is true, using Http Provider. To use WebSocket Provider, pass useNodeAPIWithHttp defined as false. When you are using caver.initKASAPI instead of constructor, you can also pass the object for which the useNodeAPIWithHttp field is defined as the last parameter as shown below:

const CaverExtKAS = require('caver-js-ext-kas')
const caver = new CaverExtKAS()
caver.initKASAPI(chainId, accessKeyId, secretAccessKey, { useNodeAPIWithHttp: false })
const blockNumber = await caver.rpc.klay.getBlockNumber()
console.log(blockNumber)

If you are calling a different initializing function for each API, you can use caver.initNodeAPI or caver.initNodeAPIWithWebSocket to initialize the Node API.

const CaverExtKAS = require('caver-js-ext-kas')
const caver = new CaverExtKAS()
caver.initNodeAPI(chainId, accessKeyId, secretAccessKey, false)
const blockNumber = await caver.rpc.klay.getBlockNumber()
console.log(blockNumber)

You pass the Boolean value of whether Http Provider will be used as a parameter when calling caver.initNodeAPI.

const CaverExtKAS = require('caver-js-ext-kas')
const caver = new CaverExtKAS()
caver.initNodeAPIWithWebSocket(chainId, accessKeyId, secretAccessKey)
const blockNumber = await caver.rpc.klay.getBlockNumber()
console.log(blockNumber)

Using the caver.initNodeAPIWithWebSocket function will allow you to initialize, so that you can use WebSocket Provider without defining additional parameters.

For more information about caver-js, refer to here. For more information about caver-java, refer to here. For inquires about this document or KAS, please visit Developer Forum.

Last updated