Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add parameters api module #46

Merged
merged 9 commits into from
Mar 30, 2018
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
18 changes: 13 additions & 5 deletions src/modules/openledger.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ import * as types from '../mutations';
const initialState = {
depositAddress: '',
pending: false,
coins: {},
coins: false,
error: false
};

const actions = {
async checkIfAddressIsValid(state, { asset, address }) {
const valid = await API.Openledger.validateAddress({ asset, address });
return valid;
},
async fetchDepositAddress(store, { asset }) {
const { commit, rootGetters } = store;
const user = rootGetters['account/getCurrentUserName'];
Expand All @@ -19,12 +23,11 @@ const actions = {
const cachedAddresses = PersistentStorage.getOpenledgerAddresses();

if (cachedAddresses[asset]) {
console.log('FROM CACHE');
const address = cachedAddresses[asset];
commit(types.FETCH_OPENLEDGER_DEPOSIT_ADDRESS_COMPLETE, { address });
} else {
console.log('LOAD', asset, user);
const lastAddress = await API.Openledger.getLastDepositAdress({
const lastAddress = await API.Openledger.getLastDepositAddress({
asset,
user
});
Expand All @@ -35,7 +38,7 @@ const actions = {
PersistentStorage.setOpenledgerAddresses(cachedAddresses);
commit(types.FETCH_OPENLEDGER_DEPOSIT_ADDRESS_COMPLETE, { address });
} else {
const newAddress = await API.Openledger.requestDepositAdress({
const newAddress = await API.Openledger.requestDepositAddress({
asset,
user
});
Expand All @@ -52,9 +55,14 @@ const actions = {
}
}
},
async fetchCoins({ commit }) {
async fetchCoins({ state, commit }) {
commit(types.FETCH_OPENLEDGER_COINS_REQUEST);

if (state.coins) {
commit(types.FETCH_OPENLEDGER_COINS_COMPLETE, { coins: state.coins });
return;
}

const fetchResult = await API.Openledger.fetchCoins();


Expand Down
9 changes: 8 additions & 1 deletion src/modules/transactions.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Vue from 'vue';
import API from '../services/api';
import * as types from '../mutations';
import * as actions from '../actions/transactions';

Expand All @@ -17,7 +18,13 @@ const getters = {
getPendingDistribution: state => state.pendingDistributionUpdate,
hasPendingTransfer: state => state.pendingTransfer !== false,
areTransactionsProcessing: state => state.transactionsProcessing,
getPendingTransfer: state => state.pendingTransfer
getPendingTransfer: state => state.pendingTransfer,
getMemoPrice: () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Зачем нужен этот геттер? 2) Так геттеры лучше не юзать, все таки они чисто для получения данных из стейта

return (memo) => {
const price = API.Transactions.getMemoPrice(memo);
return price;
};
}
};

const mutations = {
Expand Down
4 changes: 3 additions & 1 deletion src/services/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import Transactions from './api/transactions';
import Market from './api/market';
import Operations from './api/operations';
import Openledger from './api/openledger';
import Parameters from './api/parameters';

const API = {
Connection,
Expand All @@ -15,7 +16,8 @@ const API = {
Transactions,
Market,
Operations,
Openledger
Openledger,
Parameters
};

export default API;
24 changes: 20 additions & 4 deletions src/services/api/openledger.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const baseUrl = 'https://ol-api1.openledger.info/api/v0/ol/support';
const newAdressUri = '/simple-api/initiate-trade';
const lastAdressUri = '/simple-api/get-last-address';
const coinsUri = '/coins';
const validateStart = '/wallets/';
const validateEnd = '/address-validator?address=';

const processRequest = async ({ url, request }) => {
try {
Expand Down Expand Up @@ -31,7 +33,7 @@ const fetchCoins = async () => {
return result;
};

const requestDepositAdress = async ({ asset, user }) => {
const requestDepositAddress = async ({ asset, user }) => {
const url = baseUrl + newAdressUri;
const inputCoinType = asset.toLowerCase();
const outputCoinType = 'open.' + inputCoinType;
Expand All @@ -53,7 +55,7 @@ const requestDepositAdress = async ({ asset, user }) => {
return { success: true, data: result.data.inputAddress };
};

const getLastDepositAdress = async ({ asset, user }) => {
const getLastDepositAddress = async ({ asset, user }) => {
const url = baseUrl + lastAdressUri;
const coin = 'open.' + asset.toLowerCase();
const account = user;
Expand All @@ -74,8 +76,22 @@ const getLastDepositAdress = async ({ asset, user }) => {
return { success: true, data: result.data.address };
};

const validateAddress = async ({ asset, address }) => {
const headers = new Headers({ Accept: 'application/json' });
const url = baseUrl + validateStart + asset + validateEnd + encodeURIComponent(address);

try {
const reply = await fetch(url, { method: 'GET', headers });
const json = await reply.json();
return json.isValid;
} catch (error) {
return false;
}
};

export default {
requestDepositAdress,
getLastDepositAdress,
requestDepositAddress,
getLastDepositAddress,
validateAddress,
fetchCoins
};
12 changes: 6 additions & 6 deletions src/services/api/operations.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ const Operations = {
},

// Gets operation's data based on it's block number
_getOperationDate: (operation, ApiObject, ApiObjectDyn, operationType) => {
const blockInterval = ApiObject[0].parameters.block_interval;
_getOperationDate: (operation, Parameters, ApiObjectDyn, operationType) => {
const blockInterval = Parameters.block_interval;
const headBlock = ApiObjectDyn[0].head_block_number;
const headBlockTime = new Date(ApiObjectDyn[0].time + 'Z');
const secondsBelow = (headBlock - operation.block_num) * blockInterval;
Expand Down Expand Up @@ -48,10 +48,10 @@ const Operations = {
},

// Parses operation for improved format
_parseOperation: async (operation, userId, ApiObject, ApiObjectDyn) => {
_parseOperation: async (operation, userId, Parameters, ApiObjectDyn) => {
const [type, payload] = operation.op;
const operationType = Operations._operationTypes[type];
const date = Operations._getOperationDate(operation, ApiObject, ApiObjectDyn, operationType);
const date = Operations._getOperationDate(operation, Parameters, ApiObjectDyn, operationType);

let isBid = false;
let otherUserName = null;
Expand All @@ -78,14 +78,14 @@ const Operations = {
// that were user in it
parseOperations: async ({ operations, userId }) => {
const ApiInstance = Apis.instance();
const ApiObject = await ApiInstance.db_api().exec('get_objects', [['2.0.0']]);
const Parameters = await API.Parameters.getParameters();
const ApiObjectDyn = await ApiInstance.db_api().exec('get_objects', [['2.1.0']]);

const operationTypes = [0, 1, 2, 4];
const filteredOperations = operations.filter(op => operationTypes.includes(op.op[0]));

const parsedOperations = await Promise.all(filteredOperations.map(async operation => {
return Operations._parseOperation(operation, userId, ApiObject, ApiObjectDyn);
return Operations._parseOperation(operation, userId, Parameters, ApiObjectDyn);
}));

const assetsIds = Operations._getOperationsAssetsIds(parsedOperations);
Expand Down
42 changes: 42 additions & 0 deletions src/services/api/parameters.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { Apis } from 'bitsharesjs-ws';
import { ChainTypes } from 'bitsharesjs';

const { operations } = ChainTypes;
let cacheParameters = false;

const getParameters = async () => {
if (cacheParameters) {
return cacheParameters;
}

const [{ parameters }] = await Apis.instance().db_api().exec('get_objects', [['2.0.0']]);
cacheParameters = parameters;
return cacheParameters;
};

export const getCachedComissions = () => {
const { current_fees: { parameters: fees, scale } } = cacheParameters;
return { fees, scale };
};

export const getComissions = async () => {
if (cacheParameters) {
return getCachedComissions();
}

const { current_fees: { parameters: fees, scale } } = await getParameters();
console.log('Service:', fees);
return { fees, scale };
};

export const getComission = async (type) => {
const ops = Object.keys(operations);
const opIndex = ops.indexOf(type);
const { fees } = await getComissions();
if (opIndex > -1) {
return fees[opIndex][1].fee;
}
return false;
};

export default { getParameters, getComissions, getComission, getCachedComissions };
32 changes: 23 additions & 9 deletions src/services/api/transactions.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { TransactionBuilder } from 'bitsharesjs';
import { TransactionBuilder, ChainTypes, ops, PrivateKey } from 'bitsharesjs';
import { ChainConfig } from 'bitsharesjs-ws';
import { getUser } from './account';
import { encryptMemo } from '../../utils';
import { getCachedComissions } from './parameters';


const signTransaction = async (transaction, { active, owner }) => {
Expand Down Expand Up @@ -74,13 +75,25 @@ const transferAsset = async (fromId, to, assetId, amount, keys, memo = false) =>
});
};

// const processOrders = async (orders) => {
// const transaction = new TransactionBuilder();
// orders.forEach(o => transaction.add_type_operation('limit_order_create', o));
// API.Transactions.signTransaction(transaction, {active: k, owner: k});
// await transaction.set_required_fees()
// console.log(await transaction.broadcast());
// }
const getMemoPrice = (memo) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что это такое?

const privKey = '5KikQ23YhcM7jdfHbFBQg1G7Do5y6SgD9sdBZq7BqQWXmNH7gqo';
const memoToKey = 'BTS8eLeqSZZtB1YHdw7KjQxRSRmaKAseCxhUSqaLxUdqvdGpp6nck';
const pKey = PrivateKey.fromWif(privKey);

const { fees } = getCachedComissions();
const operations = Object.keys(ChainTypes.operations);
const opIndex = operations.indexOf('transfer');
const { fee, price_per_kbyte: kbytePrice } = fees[opIndex][1];

const encrypted = encryptMemo(memo, pKey, memoToKey);

const serialized = ops.memo_data.fromObject(encrypted);
const stringified = JSON.stringify(ops.memo_data.toHex(serialized));
const byteLength = Buffer.byteLength(stringified, 'hex');
const memoFee = Math.floor((kbytePrice * byteLength) / 1024);

return fee + memoFee;
};

const placeOrders = async ({ orders, keys }) => {
const transaction = new TransactionBuilder();
Expand Down Expand Up @@ -111,5 +124,6 @@ const placeOrders = async ({ orders, keys }) => {
export default {
transferAsset,
signTransaction,
placeOrders
placeOrders,
getMemoPrice
};