removed cfd

This commit is contained in:
Kirill Litvinov
2023-07-06 14:22:26 +03:00
parent abdd849eeb
commit 0c02ff821a
21 changed files with 5 additions and 521 deletions

View File

@@ -8,7 +8,7 @@ import errorSchema from './schemas/errorSchema.js';
import placeAtomicSwapSchema from './schemas/placeAtomicSwapSchema.js';
import { AggregatorWS } from './ws/index.js';
import { atomicSwapHistorySchema } from './schemas/atomicSwapHistorySchema.js';
import type { BasicAuthCredentials, Exchange, SignedCancelOrderRequest, SignedCFDOrder, SignedOrder } from '../../types.js';
import type { BasicAuthCredentials, Exchange, SignedCancelOrderRequest, SignedOrder } from '../../types.js';
import { pairConfigSchema } from './schemas/index.js';
import {
aggregatedOrderbookSchema, exchangeOrderbookSchema, poolReservesSchema,
@@ -55,7 +55,6 @@ class Aggregator {
this.getTradeProfits = this.getTradeProfits.bind(this);
this.placeAtomicSwap = this.placeAtomicSwap.bind(this);
this.placeOrder = this.placeOrder.bind(this);
this.placeCFDOrder = this.placeCFDOrder.bind(this);
this.cancelOrder = this.cancelOrder.bind(this);
this.checkWhitelisted = this.checkWhitelisted.bind(this);
this.getLockedBalance = this.getLockedBalance.bind(this);
@@ -249,40 +248,6 @@ class Aggregator {
errorSchema,
);
placeCFDOrder = (
signedOrder: SignedCFDOrder,
isReversedOrder?: boolean,
) => {
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
...(isReversedOrder !== undefined) && {
'X-Reverse-Order': isReversedOrder ? 'true' : 'false',
},
...this.basicAuthHeaders,
};
return fetchWithValidation(
`${this.apiUrl}/api/v1/order/futures`,
z.object({
orderId: z.string(),
placementRequests: z.array(
z.object({
amount: z.number(),
brokerAddress: z.string(),
exchange: z.string(),
}),
).optional(),
}),
{
headers,
method: 'POST',
body: JSON.stringify(signedOrder),
},
errorSchema,
);
};
getSwapInfo = (
type: 'exactSpend' | 'exactReceive',
assetIn: string,

View File

@@ -7,7 +7,6 @@ const MessageType = {
ASSET_PAIRS_CONFIG_UPDATE: 'apcu',
ASSET_PAIR_CONFIG_UPDATE: 'apiu',
ADDRESS_UPDATE: 'au',
CFD_ADDRESS_UPDATE: 'auf',
FUTURES_TRADE_INFO_UPDATE: 'fti',
BROKER_TRADABLE_ATOMIC_SWAP_ASSETS_BALANCE_UPDATE: 'btasabu',
UNSUBSCRIPTION_DONE: 'ud',

View File

@@ -3,7 +3,6 @@ const SubscriptionType = {
ASSET_PAIR_CONFIG_UPDATES_SUBSCRIBE: 'apius',
AGGREGATED_ORDER_BOOK_UPDATES_SUBSCRIBE: 'aobus',
ADDRESS_UPDATES_SUBSCRIBE: 'aus',
CFD_ADDRESS_UPDATES_SUBSCRIBE: 'ausf',
BROKER_TRADABLE_ATOMIC_SWAP_ASSETS_BALANCE_UPDATES_SUBSCRIBE: 'btasabus',
SWAP_SUBSCRIBE: 'ss',
FUTURES_TRADE_INFO_SUBSCRIBE: 'fts',

View File

@@ -11,12 +11,11 @@ import {
import UnsubscriptionType from './UnsubscriptionType.js';
import type {
SwapInfoBase, AssetPairUpdate, OrderbookItem,
Balance, Exchange, CFDBalance, FuturesTradeInfo, SwapInfo, Json, BasicAuthCredentials,
Balance, Exchange, FuturesTradeInfo, SwapInfo, Json, BasicAuthCredentials,
} from '../../../types.js';
import unsubscriptionDoneSchema from './schemas/unsubscriptionDoneSchema.js';
import assetPairConfigSchema from './schemas/assetPairConfigSchema.js';
import type { fullOrderSchema, orderUpdateSchema } from './schemas/addressUpdateSchema.js';
import cfdAddressUpdateSchema from './schemas/cfdAddressUpdateSchema.js';
import futuresTradeInfoSchema from './schemas/futuresTradeInfoSchema.js';
import { objectKeys } from '../../../utils/objectKeys.js';
// import assertError from '../../../utils/assertError.js';
@@ -30,7 +29,6 @@ const messageSchema = z.union([
initMessageSchema,
pingPongMessageSchema,
addressUpdateSchema,
cfdAddressUpdateSchema,
assetPairsConfigSchema,
assetPairConfigSchema,
brokerMessageSchema,
@@ -120,32 +118,14 @@ type AddressUpdateInitial = {
orders?: Array<z.infer<typeof fullOrderSchema>> | undefined // The field is not defined if the user has no orders
}
type CfdAddressUpdateUpdate = {
kind: 'update'
balances?: CFDBalance[] | undefined
order?: z.infer<typeof orderUpdateSchema> | z.infer<typeof fullOrderSchema> | undefined
}
type CfdAddressUpdateInitial = {
kind: 'initial'
balances: CFDBalance[]
orders?: Array<z.infer<typeof fullOrderSchema>> | undefined // The field is not defined if the user has no orders
}
type AddressUpdateSubscription = {
payload: string
callback: (data: AddressUpdateUpdate | AddressUpdateInitial) => void
errorCb?: (message: string) => void
}
type CfdAddressUpdateSubscription = {
payload: string
callback: (data: CfdAddressUpdateUpdate | CfdAddressUpdateInitial) => void
}
type Subscription = {
[SubscriptionType.ADDRESS_UPDATES_SUBSCRIBE]: AddressUpdateSubscription
[SubscriptionType.CFD_ADDRESS_UPDATES_SUBSCRIBE]: CfdAddressUpdateSubscription
[SubscriptionType.AGGREGATED_ORDER_BOOK_UPDATES_SUBSCRIBE]: AggregatedOrderbookSubscription
[SubscriptionType.ASSET_PAIRS_CONFIG_UPDATES_SUBSCRIBE]: PairsConfigSubscription
[SubscriptionType.ASSET_PAIR_CONFIG_UPDATES_SUBSCRIBE]: PairConfigSubscription
@@ -401,15 +381,6 @@ class AggregatorWS {
delete this.subscriptions[SubscriptionType.ADDRESS_UPDATES_SUBSCRIBE]?.[key];
}
}
const aufSubscriptions = this.subscriptions[SubscriptionType.CFD_ADDRESS_UPDATES_SUBSCRIBE];
if (aufSubscriptions) {
const targetAufSub = Object.entries(aufSubscriptions).find(([, value]) => value?.payload === newestSubId);
if (targetAufSub) {
const [key] = targetAufSub;
delete this.subscriptions[SubscriptionType.CFD_ADDRESS_UPDATES_SUBSCRIBE]?.[key];
}
}
} else if (uuidValidate(newestSubId)) {
// is swap info subscription (contains hyphen)
delete this.subscriptions[SubscriptionType.SWAP_SUBSCRIBE]?.[newestSubId];
@@ -674,46 +645,6 @@ class AggregatorWS {
});
}
break;
case MessageType.CFD_ADDRESS_UPDATE:
switch (json.k) { // message kind
case 'i': { // initial
const fullOrders = (json.o)
? json.o.reduce<Array<z.infer<typeof fullOrderSchema>>>((prev, o) => {
prev.push(o);
return prev;
}, [])
: undefined;
this.subscriptions[
SubscriptionType.CFD_ADDRESS_UPDATES_SUBSCRIBE
]?.[json.id]?.callback({
kind: 'initial',
orders: fullOrders,
balances: json.b,
});
}
break;
case 'u': { // update
let orderUpdate: z.infer<typeof orderUpdateSchema> | z.infer<typeof fullOrderSchema> | undefined;
if (json.o) {
const firstOrder = json.o[0];
orderUpdate = firstOrder;
}
this.subscriptions[
SubscriptionType.CFD_ADDRESS_UPDATES_SUBSCRIBE
]?.[json.id]?.callback({
kind: 'update',
order: orderUpdate,
balances: json.b,
});
}
break;
default:
break;
}
break;
case MessageType.ADDRESS_UPDATE: {
const balances = (json.b)
? Object.entries(json.b)

View File

@@ -5,7 +5,6 @@ import subOrderStatuses from '../../../../constants/subOrderStatuses.js';
import MessageType from '../MessageType.js';
import balancesSchema from './balancesSchema.js';
import baseMessageSchema from './baseMessageSchema.js';
import executionTypes from '../../../../constants/cfdExecutionTypes.js';
const baseAddressUpdate = baseMessageSchema.extend({
id: z.string(),
@@ -35,7 +34,6 @@ export const orderUpdateSchema = z.object({
S: z.enum(orderStatuses), // status
l: z.boolean().optional(), // is liquidation order
t: z.number(), // update time
E: z.enum(executionTypes).optional(), // execution type
C: z.string().optional(), // trigger condition
c: subOrderSchema.array(),
})
@@ -48,7 +46,6 @@ export const orderUpdateSchema = z.object({
settledAmount: o.A,
status: o.S,
liquidated: o.l,
executionType: o.E,
triggerCondition: o.C,
subOrders: o.c.map((so) => ({
pair: so.P,
@@ -80,7 +77,6 @@ export const fullOrderSchema = z.object({
T: z.number(), // creation time / unix timestamp
t: z.number(), // update time
c: subOrderSchema.array(),
E: z.enum(executionTypes).optional(), // execution type
C: z.string().optional(), // trigger condition
ro: z.boolean().optional(), // is reversed order
}).transform((val) => ({
@@ -101,7 +97,6 @@ export const fullOrderSchema = z.object({
pair: o.P,
amount: o.a,
price: o.p,
executionType: o.E,
triggerCondition: o.C,
isReversedOrder: o.ro,
subOrders: o.c.map((so) => ({

View File

@@ -1,33 +0,0 @@
import { z } from 'zod';
import { fullOrderSchema, orderUpdateSchema } from './addressUpdateSchema.js';
import baseMessageSchema from './baseMessageSchema.js';
import MessageType from '../MessageType.js';
import cfdBalancesSchema from './cfdBalancesSchema.js';
const baseCfdAddressUpdate = baseMessageSchema.extend({
id: z.string(),
T: z.literal(MessageType.CFD_ADDRESS_UPDATE),
S: z.string(), // subscription
uc: z.array(z.enum(['b', 'o'])), // update content
});
const updateMessageSchema = baseCfdAddressUpdate.extend({
k: z.literal('u'), // kind of message: "u" - updates
uc: z.array(z.enum(['b', 'o'])), // update content: "o" - orders updates, "b" - balance updates
b: cfdBalancesSchema.optional(),
o: z.tuple([fullOrderSchema.or(orderUpdateSchema)]).optional(),
});
const initialMessageSchema = baseCfdAddressUpdate.extend({
k: z.literal('i'), // kind of message: "i" - initial
b: cfdBalancesSchema,
o: z.array(fullOrderSchema)
.optional(), // When no orders — no field
});
const cfdAddressUpdateSchema = z.union([
initialMessageSchema,
updateMessageSchema,
]);
export default cfdAddressUpdateSchema

View File

@@ -1,52 +0,0 @@
import { z } from 'zod';
import positionStatuses from '../../../../constants/positionStatuses.js';
const cfdBalanceSchema = z
.object({
i: z.string(),
b: z.string(),
pnl: z.string(),
fr: z.string(),
e: z.string(),
p: z.string(),
cp: z.string(),
pp: z.string(),
r: z.string(),
m: z.string(),
mu: z.string(),
fmu: z.string(),
awb: z.string(),
l: z.string(),
s: z.enum(positionStatuses),
lfrs: z.string(),
lfrd: z.string(),
sfrs: z.string(),
sfrd: z.string(),
sop: z.string().optional(),
})
.transform((obj) => ({
instrument: obj.i,
balance: obj.b,
profitLoss: obj.pnl,
fundingRate: obj.fr,
equity: obj.e,
position: obj.p,
currentPrice: obj.cp,
positionPrice: obj.pp,
reserves: obj.r,
margin: obj.m,
marginUSD: obj.mu,
freeMarginUSD: obj.fmu,
availableWithdrawBalance: obj.awb,
leverage: obj.l,
status: obj.s,
longFundingRatePerSecond: obj.lfrs,
longFundingRatePerDay: obj.lfrd,
shortFundingRatePerSecond: obj.sfrs,
shortFundingRatePerDay: obj.sfrd,
stopOutPrice: obj.sop,
}));
const cfdBalancesSchema = z.array(cfdBalanceSchema);
export default cfdBalancesSchema;

View File

@@ -7,6 +7,5 @@ export { default as initMessageSchema } from './initMessageSchema.js';
export { default as pingPongMessageSchema } from './pingPongMessageSchema.js';
export { default as swapInfoSchema } from './swapInfoSchema.js';
export { default as balancesSchema } from './balancesSchema.js';
export { default as cfdBalancesSchema } from './cfdBalancesSchema.js';
export * from './orderBookSchema.js';

View File

@@ -9,8 +9,6 @@ import {
userEarnedSchema,
type PairStatusEnum,
pairStatusSchema,
cfdContractsSchema,
cfdHistorySchema,
governanceContractsSchema,
governancePoolsSchema,
governancePoolSchema,
@@ -59,12 +57,6 @@ type AtomicSwapHistoryTargetQuery = AtomicSwapHistoryBaseQuery & {
expiredRedeem?: 0 | 1
state?: 'REDEEMED' | 'BEFORE-REDEEM'
}
type CfdHistoryQuery = {
instrument?: string
page?: number
limit?: number
} & Partial<Record<string, string | number>>
class BlockchainService {
private readonly apiUrl: string;
@@ -110,8 +102,6 @@ class BlockchainService {
this.getBlockNumber = this.getBlockNumber.bind(this);
this.getRedeemOrderBySecretHash = this.getRedeemOrderBySecretHash.bind(this);
this.claimOrder = this.claimOrder.bind(this);
this.getCFDContracts = this.getCFDContracts.bind(this);
this.getCFDHistory = this.getCFDHistory.bind(this);
this.getGovernanceContracts = this.getGovernanceContracts.bind(this);
this.getGovernancePools = this.getGovernancePools.bind(this);
this.getGovernancePool = this.getGovernancePool.bind(this);
@@ -222,12 +212,6 @@ class BlockchainService {
{ headers: this.basicAuthHeaders }
);
getCFDPrices = () => fetchWithValidation(
`${this.apiUrl}/api/cfd/prices`,
z.record(z.string()).transform(makePartial),
{ headers: this.basicAuthHeaders }
);
getTokensFee = () => fetchWithValidation(
`${this.apiUrl}/api/tokensFee`,
z.record(z.string()).transform(makePartial),
@@ -454,24 +438,6 @@ class BlockchainService {
},
);
getCFDContracts = () => fetchWithValidation(
`${this.apiUrl}/api/cfd/contracts`,
cfdContractsSchema,
{ headers: this.basicAuthHeaders },
);
getCFDHistory = (address: string, query: CfdHistoryQuery = {}) => {
const url = new URL(`${this.apiUrl}/api/cfd/deposit-withdraw/${address}`);
Object.entries(query)
.forEach(([key, value]) => {
if (value === undefined) throw new Error('Value must be defined');
url.searchParams.append(key, value.toString());
});
return fetchWithValidation(url.toString(), cfdHistorySchema, { headers: this.basicAuthHeaders });
};
getGovernanceContracts = () => fetchWithValidation(
`${this.apiUrl}/api/governance/info`,
governanceContractsSchema,

View File

@@ -1,20 +0,0 @@
import { z } from 'zod';
const cfdContractsSchema = z.array(z.object({
name: z.string(),
alias: z.string(),
address: z.string(),
leverage: z.number(),
soLevel: z.number(),
shortFR: z.number(),
longFR: z.number(),
shortFRStored: z.number(),
longFRStored: z.number(),
lastFRPriceUpdateTime: z.number(),
priceIndex: z.number(),
feePercent: z.number(),
withdrawMarginLevel: z.number(),
delegateContractAddress: z.string(),
}));
export default cfdContractsSchema;

View File

@@ -1,52 +0,0 @@
import { z } from 'zod';
import { HistoryTransactionStatus } from '../../../types.js';
export enum historyTransactionType {
WITHDRAW = 'withdrawal',
DEPOSIT = 'deposit',
}
const cfdHistoryItem = z.object({
_id: z.string(),
__v: z.number(),
address: z.string(),
instrument: z.string(),
instrumentAddress: z.string(),
balance: z.string(),
amount: z.string(),
amountNumber: z.string(),
position: z.string(),
reason: z.enum(['WITHDRAW', 'DEPOSIT']),
positionPrice: z.string(),
fundingRate: z.string(),
transactionHash: z.string(),
blockNumber: z.number(),
createdAt: z.number(),
});
const cfdHistorySchema = z.object({
success: z.boolean(),
count: z.number(),
total: z.number(),
pagination: z.object({}),
data: z.array(cfdHistoryItem),
}).transform((response) => {
return response.data.map((item) => {
const {
createdAt, reason, transactionHash, amountNumber,
} = item;
const type = historyTransactionType[reason];
return {
type,
date: createdAt,
token: 'USDT',
amount: amountNumber,
status: HistoryTransactionStatus.DONE,
transactionHash,
user: item.address,
};
});
});
export default cfdHistorySchema;

View File

@@ -12,8 +12,6 @@ export { default as atomicSummarySchema } from './atomicSummarySchema.js';
export { default as poolsLpAndStakedSchema } from './poolsLpAndStakedSchema.js';
export { default as userVotesSchema } from './userVotesSchema.js';
export { default as userEarnedSchema } from './userEarnedSchema.js';
export { default as cfdContractsSchema } from './cfdContractsSchema.js';
export { default as cfdHistorySchema } from './cfdHistorySchema.js';
export { default as governanceContractsSchema } from './governanceContractsSchema.js';
export { default as governancePoolsSchema } from './governancePoolsSchema.js';
export { default as governancePoolSchema } from './governancePoolSchema.js';