Developing Klaytn Wallet with KAS #1

Tech at Klaytn
Klaytn
Published in
6 min readMay 20, 2021

See the list of articles here.
🇰🇷: KAS를 이용하여 Klaytn 지갑 기능 개발하기 #1

KAS Introduction

KAS (Klaytn API Service) is a cloud platform that provides the APIs that support Klaytn’s features to help developers using Klaytn to build applications more easily and quickly.

The APIs currently provided by KAS are Wallet API, Token History API, Anchor API, Node API, KIP-7 API, KIP-17 API and so on. In this article, we will introduce how to develop blockchain applications on Klaytn using the various APIs.

Lately, there has been a growing interest in user acquisition and service integration using blockchain wallets. We will show you how to develop a Klaytn-based wallet feature using KAS.

Designing a Klaytn Wallet

Analyzing Usage Scenario

Before we start developing a Klaytn wallet, let’s analyze the requirements from the users’ perspective. As it is the case with most crypto products, the most important feature would be token management. In the first article of this series, we will introduce how to create a Klaytn account using KAS and to use KLAY, the native token for the Klaytn Blockchain. When thinking about a Klaytn-based blockchain application, there are two main functionalities: account management and KLAY management. The diagram below gives you the details. Account management includes account creation, history and deletion, whereas KLAY management includes KLAY transfer and transaction history query.

Deployment Architecture

We mentioned the two main functionalities required to develop a Klaytn-based wallet. For these, you need a wallet App that provides the UI and a backend Wallet Server which communicates with KAS. The latter would have a database in order to manage its users or to provide additional features.

To fulfill the user scenario as defined above, we would have to use the Wallet API, Node API, and Token History API. The diagram below is an abstract deployment architecture that shows the connectivity between the wallet service and the Klaytn API Service.

Setting up KAS Developing Environment

Before we can get started, we first have to register on KAS Console after consulting KAS Docs. And then we have to obtain the credentials to use the service APIs. You can obtain them in KAS Console > Security > Credential. Make sure not to lose the Access Key and Secret Key.

Implementing Functionalities for Klaytn Wallet

In this section, we will look at how to develop the following three functionalities: Klaytn account management, KLAY transfer, and KLAY transaction history query.

The environment in this tutorial is based on KAS SDK. If you use another programming language that is not supported by KAS SDK, please refer to KAS Docs. Below, we have an overview of everything that is required to develop Klaytn wallet functionalities. It uses Wallet, Node, and Token History APIs.

Klaytn Account Management

In order to develop a wallet service, you first have to create a Klaytn account that consists of a private key and a public key. But what happens if the keys of multiple users get exposed due to some internal or external factors? The assets of the users would be compromised. That is why KAS provides a wallet service for the developers and users to store their keys safely.

KAS Wallet manages the keys based on the Hardware Security Module (HSM). With HSM, the insiders have no way of finding out the keys, and it is cryptographically guaranteed that the keys remain concealed even in the event of an exposure. You can rest assured with KASWallet.

Now, we have to think about how the wallet user and the Klaytn account provided by KAS are connected. From the user’s point of view, Klaytn account address is too complicated to memorize and use. So we need to link the addresses with a human-readable user ID, as shown below.

In the Entity Relationship Diagram (ERD), Account is data which is retrievable through the KAS Wallet Service. The wallet service manages user information. You can create an account for KAS Wallet, which was linked when registering for KAS, and connect it as the code below:

// controllers/user.jsUser = require(‘../models/user’);const CaverExtKAS = require(‘caver-js-ext-kas’);
const caver = new CaverExtKAS();
caver.initKASAPI(
1001,
accessKey,
secretKey,
);
exports.signup = async (req, res) => {
var user = new user();
user.name = req.body.name;
user.phoneNumber = req.body.phone;
user.password = req.body.password;
// KAS: Create a Klaytn account.
const result = await caver.kas.wallet.createAccount();
user.address = result.address;
user.save(function (err) {
if (err) res.json(err);
res.json(user);
});
};

KLAY Transfer

In the previous section, we connected a wallet service account, which we need for our wallet service. Now, let’s take a look at how user A can send KLAY to user B.

Let’s say that user A only knows user B’s ID, and not the complicated information such as the Klaytn account. The wallet service receives the user ID, converts it to the Klaytn account, and sends KLAY using wallet service. Take a good look at the code below.

// controllers/token.js
User = require(‘../models/user’);
const CaverExtKAS = require(‘caver-js-ext-kas’);
const caver = new CaverExtKAS();
const accessKey = ‘’;
const secretKey = ‘’;
caver.initKASAPI(1001, accessKey, secretKey);exports.transfer = async (req, res) => {
// NOTE: authenticate requester.
const value = req.body.value;
const fromUser = await User.findOne({ name: req.body.fromUser });
const toUser = await User.findOne({ name: req.body.toUser });
// NOTE: you need to handle errors // KAS: invoke a value transfer transaction
const tx = {
from: fromUser.address,
to: toUser.address,
value: value,
submit: true,
};
const result = await caver.kas.wallet.requestValueTransfer(tx);
res.json(result);
};

Query Account

To verify that the transaction between two users was successful, you can check the balance of the Klaytn account. You can do this by using the Klaytn Node API. The Node API gives you the features of a Klaytn node, while providing a more enhanced security than operating a KEN. We therefore suggest using Node API for a smooth operation of service in terms of availability and performance. The below sample code shows you how to retrieve the account balance as explained so far:

// controller/user.js
// ... omitted ...
exports.get = async (req, res) => {
const user = await User.findOne({ name: req.params.name });
const balance = await caver.rpc.klay.getBalance(user.address); res.json({
...user._doc,
balance,
});
};

KLAY Transaction History Inquiry

To query KLAY transaction history, you can use the Token History API on KAS. Token History provides the API for retrieving the transaction history for various token types like KLAY, FT, NFT, or MT that exist on Klaytn. The transaction history provided by Token History API is based on Klaytn account addresses. From the perspective of user-friendliness, however, using user names would be better than Klaytn account addresses. So the transaction history, sent and received via the Token History API, must be converted to be mapped to usernames managed by the wallet service, as the example below shows:

// controllers/token.js
// ... omitted ...
exports.history = async (req, res) => {
const user = await User.fineOne({ name: req.params.name });
const result = await caver.kas.tokenHistory.getransferHistoryByAccount(
user.address,
);
Promise.all(
result.items.map(async (el) => {
console.log(el);
const peb = cv.utils.hexToNumberString(el.value);
const fee = cv.utils.hexToNumberString(el.fee);
const ef = cv.utils.toChecksumAddress(el.from);
let from =
user.address == ef ? user : await User.findOne({ address: ef});
from = from ? from.name : ef;
const et = cv.utils.toChecksumAddress(el.to);
let to =
user.address == et ? user : await User.findOne({ address: et});
to = to ? to.name : et;
console.log(from, to);
return {
from,
to,
fee: cv.utils.fromPeb(fee, ‘KLAY’),
value: cv.utils.fromPeb(peb, ‘KLAY’),
};
});
).then((data) => res.json(data));
};

Conclusion

In this article, we looked at how to develop a Klaytn wallet using KAS API. In the next article, we will learn how to manage tokens that follow the KIP-17 standard.

References

KAS Wallet API Reference: https://refs.klaytnapi.com/en/wallet/latest
KAS Token History API Reference: https://refs.klaytnapi.com/en/th/latest
KAS Node API Reference: https://refs.klaytnapi.com/en/node/latest
KAS Docs: https://docs.klaytnapi.com/

--

--