xek-sdk
Version:
SDK for katana blockchain
99 lines (80 loc) • 2.86 kB
JavaScript
;
const API = require ('./api');
const Wallet = require ('./wallet');
const BigNumber = require ('bignumber.js');
const utils = require ('./utils/utils');
const {CURVE_TYPE, TX_FEE} = require ('./constant');
class XEKSdk {
constructor (chain, api) {
if (!api) {
this.webAPI = new API ();
} else {
this.webAPI = new API (api);
}
this.wallet = Wallet;
this.utils = utils;
this.CHAINID = chain;
}
async createSendTx (from, to, amount, privateKey) {
try {
//verify inputs
if (!this.utils.isAddress (from)) {
return new Error ('Sender must be a address');
}
if (!this.utils.isAddress (to)) {
return new Error ('Receiver must be a address');
}
if (!this.utils.isUint (amount)) {
return new Error ('Amount must be unsigned integer');
}
// thuannd start
let fee = TX_FEE
// thuannd end
fee = new BigNumber (fee);
//get balance of sender
let balance = await this.webAPI.getBalance (from);
let sufficientBalance = new BigNumber (amount).plus (new BigNumber (fee));
//check balance sender
if (!( new BigNumber (balance).isGreaterThanOrEqualTo (sufficientBalance) )) {
return new Error ('Balance is Insufficient');
}
//get sequence of sender
let sequence = await this.webAPI.getSequence (from);
if (!sequence && this.utils.isUint (sequence)) {
return new Error ('Sequence must be unsigned integer');
}
let senderSequence = new BigNumber (sequence).plus (1).toNumber ();
let tx;
if (from === to) {
return new Error ('Can not send for yourself');
} else {
// thuannd start: don't send fee to admin anymore
tx = this.wallet.createTx(from, to, amount, senderSequence, this.CHAINID);
// thuannd end
}
//create tx
if (!tx) {
return new Error ('Invalid inputs when create transaction');
}
// signature
const signature = await this.wallet.signatureOffline (tx, privateKey);
if (!signature) {
return new Error ('Sign transaction failed');
}
// get public key
const publicKey = await this.wallet.getPublicKeyOffline (privateKey, CURVE_TYPE);
if (!publicKey) {
return new Error ('Get public key failed');
}
//create envelop for transaction
const txEnvelope = this.wallet.createEnvelopTx (from, publicKey, signature, tx);
//broadcast transaction
const result = await this.webAPI.sendTransaction (txEnvelope);
return result;
} catch (e) {
console.log ('Send transaction failed ', e);
throw new Error ('Send transaction failed');
}
}
}
module.exports = XEKSdk;