Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion __tests__/helpers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ test('Update list', () => {

test('Transaction type', () => {
const transaction1 = {
'version': 1,
'tx_id': '00034a15973117852c45520af9e4296c68adb9d39dc99a0342e23cd6686b295e',
'inputs': [],
'outputs': [
Expand All @@ -53,6 +54,7 @@ test('Transaction type', () => {
};

const transaction2 = {
'version': 1,
'tx_id': '00034a15973117852c45520af9e4296c68adb9d39dc99a0342e23cd6686b295d',
'inputs': [
{
Expand Down Expand Up @@ -83,6 +85,7 @@ test('Transaction type', () => {
};

const genesisBlock = {
'version': 0,
'tx_id': '000164e1e7ec7700a18750f9f50a1a9b63f6c7268637c072ae9ee181e58eb01b',
'inputs': [],
'outputs': [
Expand All @@ -98,7 +101,7 @@ test('Transaction type', () => {
]
};

expect(helpers.getTxType(transaction1).toLowerCase()).toBe('block');
expect(helpers.getTxType(transaction1).toLowerCase()).toBe('transaction');
expect(helpers.getTxType(transaction2).toLowerCase()).toBe('transaction');
expect(helpers.getTxType(genesisBlock).toLowerCase()).toBe('block');
});
Expand Down
28 changes: 20 additions & 8 deletions __tests__/tokens_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,14 @@ import wallet from '../src/wallet';
import version from '../src/version';
import { util } from 'bitcore-lib';
import WebSocketHandler from '../src/WebSocketHandler';
import { InsufficientFundsError } from '../src/errors';
import { InsufficientFundsError, TokenValidationError } from '../src/errors';

const storage = require('../src/storage').default;

const createdTxHash = '00034a15973117852c45520af9e4296c68adb9d39dc99a0342e23cd6686b295e';
const createdToken = util.buffer.bufferToHex(tokens.getTokenUID(createdTxHash, 0));
const pin = '123456';
const token1 = {'name': '1234', 'uid': '1234', 'symbol': '1234'};

beforeEach(() => {
WebSocketHandler.started = true;
Expand All @@ -38,6 +39,18 @@ mock.onPost('thin_wallet/send_tokens').reply((config) => {
return [200, ret];
});

mock.onGet('thin_wallet/token').reply((config) => {
const ret = {
'mint': [],
'melt': [],
'name': token1.name,
'symbol': token1.symbol,
'total': 100
}
return [200, ret];
});


test('Token UID', () => {
const txID = '00034a15973117852c45520af9e4296c68adb9d39dc99a0342e23cd6686b295e';
const txID2 = '00034a15973117852c45520af9e4296c68adb9d39dc99a0342e23cd6686b295c';
Expand Down Expand Up @@ -121,8 +134,7 @@ test('Insufficient funds', async (done) => {
}
});

test('Tokens handling', () => {
const token1 = {'name': '1234', 'uid': '1234', 'symbol': '1234'};
test('Tokens handling', async () => {
const token2 = {'name': 'abcd', 'uid': 'abcd', 'symbol': 'abcd'};
const token3 = {'name': HATHOR_TOKEN_CONFIG.name, 'uid': HATHOR_TOKEN_CONFIG.uid};
const myTokens = [token1, token2, token3];
Expand Down Expand Up @@ -167,12 +179,12 @@ test('Tokens handling', () => {

// Validates configuration string before add
const config = tokens.getConfigurationString(token1.uid, token1.name, token1.symbol);
expect(tokens.validateTokenToAddByConfigurationString(config).success).toBe(true);
expect(tokens.validateTokenToAddByConfigurationString(config, token2.uid).success).toBe(false);
expect(tokens.validateTokenToAddByConfigurationString(config+'a').success).toBe(false);
expect(tokens.validateTokenToAddByConfigurationString('').success).toBe(false);
await expect(tokens.validateTokenToAddByConfigurationString(config)).resolves.toBeInstanceOf(Object);
await expect(tokens.validateTokenToAddByConfigurationString(config, token2.uid)).rejects.toThrow(TokenValidationError);
await expect(tokens.validateTokenToAddByConfigurationString(config+'a')).rejects.toThrow(TokenValidationError);
await expect(tokens.validateTokenToAddByConfigurationString('')).rejects.toThrow(TokenValidationError);

// Cant add the same token twice
tokens.addToken(token1.uid, token1.name, token1.symbol)
expect(tokens.validateTokenToAddByConfigurationString(config).success).toBe(false);
await expect(tokens.validateTokenToAddByConfigurationString(config)).rejects.toThrow(TokenValidationError);
});
2 changes: 1 addition & 1 deletion __tests__/transaction_utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ test('Prepare data to send tokens', async (done) => {
expect(txData['inputs'][0].data.length > 0).toBeTruthy();

transaction.completeTx(txData);
transaction.setWeight(txData);
transaction.setWeightIfNeeded(txData);
expect(txData['nonce']).toBe(0);
expect(txData['version']).toBe(DEFAULT_TX_VERSION);
expect(txData['timestamp'] > 0).toBeTruthy();
Expand Down
14 changes: 9 additions & 5 deletions __tests__/wallet.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ test('Wallet operations for transaction', () => {

let historyTransactions = {
'00034a15973117852c45520af9e4296c68adb9d39dc99a0342e23cd6686b295e': {
'version': 1,
'tx_id': '00034a15973117852c45520af9e4296c68adb9d39dc99a0342e23cd6686b295e',
'inputs': [],
'outputs': [
Expand All @@ -39,9 +40,10 @@ test('Wallet operations for transaction', () => {
'token': '01',
}
],
'tokens': ['01']
'tokens': [{uid: '01', name: '01', symbol: '01'}]
},
'00034a15973117852c45520af9e4296c68adb9d39dc99a0342e23cd6686b295f': {
'version': 1,
'tx_id': '00034a15973117852c45520af9e4296c68adb9d39dc99a0342e23cd6686b295f',
'inputs': [],
'outputs': [
Expand All @@ -66,9 +68,10 @@ test('Wallet operations for transaction', () => {
'token': '01',
},
],
'tokens': ['01']
'tokens': [{uid: '01', name: '01', symbol: '01'}]
},
'00034a15973117852c45520af9e4296c68adb9d39dc99a0342e23cd6686b295d': {
'version': 1,
'tx_id': '00034a15973117852c45520af9e4296c68adb9d39dc99a0342e23cd6686b295d',
'inputs': [
{
Expand Down Expand Up @@ -104,9 +107,10 @@ test('Wallet operations for transaction', () => {
'spent_by': null,
},
],
'tokens': ['01']
'tokens': [{uid: '01', name: '01', symbol: '01'}]
},
'00034a15973117852c45520af9e4296c68adb9d39dc99a0342e23cd6686b295c': {
'version': 0,
'tx_id': '00034a15973117852c45520af9e4296c68adb9d39dc99a0342e23cd6686b295c',
'inputs': [],
'outputs': [
Expand All @@ -121,7 +125,7 @@ test('Wallet operations for transaction', () => {
'spent_by': null,
},
],
'tokens': ['01']
'tokens': [{uid: '01', name: '01', symbol: '01'}]
}
}

Expand Down Expand Up @@ -184,7 +188,7 @@ test('Wallet operations for transaction', () => {
'spent_by': null,
},
],
'tokens': ['01']
'tokens': [{uid: '01', name: '01', symbol: '01'}]
};


Expand Down
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ var txApi = require('./lib/api/txApi');
var versionApi = require('./lib/api/version');
var axios = require('./lib/api/axiosInstance');
var storage = require('./lib/storage');
var MemoryStore = require('./lib/memory_store');

module.exports = {
helpers: helpers.default,
Expand All @@ -28,4 +29,5 @@ module.exports = {
constants: constants,
axios: axios,
storage: storage.default,
MemoryStore: MemoryStore.default,
}
48 changes: 48 additions & 0 deletions src/api/wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,54 @@ const walletApi = {
});
},

/**
* Call get general token info API
*
* @param {string} uid Token uid to get the general info
* @param {function} resolve Method to be called after response arrives
*
* @return {Promise}
* @memberof ApiWallet
* @inner
*/
getGeneralTokenInfo(uid, resolve) {
const data = {id: uid};
return createRequestInstance(resolve).get('thin_wallet/token', {'params': data}).then((res) => {
resolve(res.data)
}, (res) => {
return Promise.reject(res);
});
},

/**
* Call get token transaction history API
*
* @param {string} uid Token uid to get the info
* @param {number} count Quantity of elements to be returned
* @param {string} hash Hash of transaction as reference in pagination
* @param {number} timestamp Timestamp of transaction as reference in pagination
* @param {string} page The button clicked in the pagination ('previous' or 'next')
* @param {function} resolve Method to be called after response arrives
*
* @return {Promise}
* @memberof ApiWallet
* @inner
*/
getTokenHistory(uid, count, hash, timestamp, page, resolve) {
const data = {id: uid, count};

if (hash) {
data['hash'] = hash
data['timestamp'] = timestamp
data['page'] = page
}

return createRequestInstance(resolve).get('thin_wallet/token_history', {'params': data}).then((res) => {
resolve(res.data)
}, (res) => {
return Promise.reject(res);
});
},
};

export default walletApi;
5 changes: 5 additions & 0 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ export const DEFAULT_SERVERS = [
*/
export const DEFAULT_SERVER = DEFAULT_SERVERS[0];

/**
* Block version field
*/
export const BLOCK_VERSION = 0;

/**
* Transaction version field
*/
Expand Down
8 changes: 8 additions & 0 deletions src/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,11 @@ export class ConstantNotSet extends Error {}
* @inner
*/
export class CreateTokenTxInvalid extends Error {}

/**
* Error thrown when validating a registration of new token
*
* @memberof Errors
* @inner
*/
export class TokenValidationError extends Error {}
33 changes: 24 additions & 9 deletions src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import path from 'path';

import storage from './storage';
import tokens from './tokens';
import { GENESIS_BLOCK, DECIMAL_PLACES, DEFAULT_SERVER } from './constants';
import { BLOCK_VERSION, CREATE_TOKEN_TX_VERSION, DEFAULT_TX_VERSION, GENESIS_BLOCK, DECIMAL_PLACES, DEFAULT_SERVER } from './constants';

/**
* Helper methods
Expand Down Expand Up @@ -56,8 +56,15 @@ const helpers = {
if (this.isBlock(tx)) {
return 'Block';
} else {
return 'Transaction';
if (tx.version === DEFAULT_TX_VERSION) {
return 'Transaction';
} else if (tx.version === CREATE_TOKEN_TX_VERSION) {
return 'Create token transaction';
}
}
Comment thread
pedroferreira1 marked this conversation as resolved.

// If there is no match
return 'Unknown';
},

/**
Expand All @@ -71,13 +78,7 @@ const helpers = {
* @inner
*/
isBlock(tx) {
if (GENESIS_BLOCK.indexOf(tx.tx_id) > -1) {
return true;
}
if (tx.inputs.length === 0) {
return true;
}
return false;
return tx.version === BLOCK_VERSION;
},


Expand Down Expand Up @@ -328,6 +329,20 @@ const helpers = {
getWithdrawAmount(meltAmount) {
return Math.floor(tokens.getDepositPercentage() * meltAmount);
},

/**
* Cleans a string for comparison. Remove multiple spaces, and spaces at the beginning and end, and transform to lowercase.
*
* @param {string} string String to be cleaned
*
* @return {string} String after clean
* @memberof Helpers
* @inner
*
*/
cleanupString(string) {
return string.replace(/\s\s+/g, ' ').trim().toLowerCase();
}
}

export default helpers;
32 changes: 32 additions & 0 deletions src/memory_store.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Copyright (c) Hathor Labs and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

export default class MemoryStore {
constructor() {
this.hathorMemoryStorage = {};
}

getItem(key) {
const ret = this.hathorMemoryStorage[key];
if (ret === undefined) {
return null
}
return ret;
}

setItem(key, value) {
this.hathorMemoryStorage[key] = value;
}

removeItem(key) {
delete this.hathorMemoryStorage[key];
}

clear() {
this.hathorMemoryStorage = {};
}
}
Loading