rewrite rpc sampler client

This commit is contained in:
Romain Butteaud
2021-09-17 13:32:26 -07:00
parent 5d4481f0f0
commit 15b7cf3986
4 changed files with 53 additions and 134 deletions

View File

@@ -1,58 +1,32 @@
import { Client } from 'jayson';
import { Client as RPCClient } from 'jayson';
import {
Address,
LiquidityResponse,
RpcLiquidityRequest,
TokenResponse,
RPCSamplerCallback,
} from './utils/market_operation_utils/sampler_types';
export interface SamplerServiceInterface {
getSellLiquidityAsync(reqs: RpcLiquidityRequest[]): Promise<LiquidityResponse[]>;
// getBuyLiquidityAsync(reqs: RpcLiquidityRequest[]): Promise<LiquidityResponse[]>;
// getTokensAsync(tokenAddresses: Address[]): Promise<TokenResponse[]>;
// getPrices(tokenPaths: Address[][]): Promise<bigint[]>;
}
const RPC_SAMPLER_SERVICE_URL = '';
const RPC_SAMPLER_SERVICE_PORT = 7002;
export class RpcSamplerClient {
private readonly _rpcUrl: string;
private readonly _rpcClient: RPCClient;
export class RpcSamplerClient implements SamplerServiceInterface {
// tslint:disable:prefer-function-over-method
public async getSellLiquidityAsync(reqs: RpcLiquidityRequest[]): Promise<LiquidityResponse[]> {
/**
* @param rpcUrl URL to the Sampler Service to which JSON RPC requests should be sent
*/
constructor() {
this._rpcUrl = RPC_SAMPLER_SERVICE_URL;
this._rpcClient = RPCClient.http({ port: RPC_SAMPLER_SERVICE_PORT });
}
public async getSellLiquidityAsync(reqs: RpcLiquidityRequest[], rpcSamplerCallback: RPCSamplerCallback): Promise<void> {
try {
const client = Client.http({ port: 7002});
const response = client.request(`get_sell_liquidity`, [reqs], (callback: any) => {
console.log(callback);
this._rpcClient.request(`get_sell_liquidity`, [reqs], (err: any, liquidityResponses: LiquidityResponse[]) => {
return rpcSamplerCallback(err, liquidityResponses);
});
return [];
} catch (err) {
throw new Error(`error with sampler service: ${err}`);
}
}
// tslint:disable:prefer-function-over-method
// public async getBuyLiquidityAsync(reqs: RpcLiquidityRequest[]): Promise<LiquidityResponse[]> {
// try {
// return await axios.post(`${SAMPLER_SERVICE_URL}/get_buy_liquidity`, reqs, {
// headers: {
// 'Content-Type': 'application/json',
// },
// timeout: 1000,
// });
// } catch (err) {
// throw new Error(`error with sampler service: ${err}`);
// }
// }
// // tslint:disable:prefer-function-over-method
// public async getTokensAsync(tokenAddresses: Address[]): Promise<TokenResponse[]> {
// try {
// return await axios.post(`${SAMPLER_SERVICE_URL}/get_tokens`, tokenAddresses, {
// headers: {
// 'Content-Type': 'application/json',
// },
// timeout: 1000,
// });
// } catch (err) {
// throw new Error(`error with sampler service: ${err}`);
// }
// }
}
}

View File

@@ -153,7 +153,9 @@ export class MarketOperationUtils {
// this._nativeFeeTokenAmount,
// ),
// Get sell quotes for taker -> maker.
this._sampler.getSellQuotesAsync(quoteSourceFilters.sources, makerToken, takerToken, takerAmount),
this._sampler.getSellQuotesAsync(quoteSourceFilters.sources, makerToken, takerToken, takerAmount, (err, dexQuotes) => {
return dexQuotes;
}),
// this._sampler.getTwoHopSellQuotes(
// quoteSourceFilters.isAllowed(ERC20BridgeSource.MultiHop) ? quoteSourceFilters.sources : [],
// makerToken,

View File

@@ -2,8 +2,8 @@ import { ChainId } from '@0x/contract-addresses';
import { LimitOrderFields } from '@0x/protocol-utils';
import { BigNumber, logUtils } from '@0x/utils';
import * as _ from 'lodash';
import { RpcSamplerClient } from '../../rpc_sampler_client';
import { RpcSamplerClient } from '../../rpc_sampler_client';
import { SamplerCallResult, SignedNativeOrder } from '../../types';
import { ERC20BridgeSamplerContract } from '../../wrappers';
@@ -45,7 +45,7 @@ import { getLiquidityProvidersForPair } from './liquidity_provider_utils';
import { getIntermediateTokens } from './multihop_utils';
import { BalancerPoolsCache, BalancerV2PoolsCache, CreamPoolsCache, PoolsCache } from './pools_cache';
import { SamplerContractOperation } from './sampler_contract_operation';
import { Address, RpcLiquidityRequest } from './sampler_types';
import { Address, LiquidityResponse, RpcLiquidityRequest } from './sampler_types';
import { SourceFilters } from './source_filters';
import {
BalancerFillData,
@@ -98,6 +98,8 @@ export const BATCH_SOURCE_FILTERS = SourceFilters.all().exclude([ERC20BridgeSour
* Composable operations that can be batched in a single transaction,
* for use with `DexOrderSampler.executeAsync()`.
*/
export declare type JSONRPCQuoteCallback = (err: Error | null, dexQuotes: Array<Array<DexSample<FillData>>>) => void;
export class SamplerOperations {
public readonly liquidityProviderRegistry: LiquidityProviderRegistry;
public readonly poolsCaches: { [key in SourcesWithPoolsCache]: PoolsCache };
@@ -134,6 +136,7 @@ export class SamplerOperations {
bancorServiceFn()
.then(service => (this._bancorService = service))
.catch(/* do nothing */);
this.rpcSamplerClient = new RpcSamplerClient();
}
public async getTokenDecimalsAsync(tokens: Address[]): Promise<number[]> {
@@ -146,7 +149,9 @@ export class SamplerOperations {
makerToken: string,
takerToken: string,
takerAmount: BigNumber,
): Promise<Array<Array<DexSample<FillData>>>> {
callback: JSONRPCQuoteCallback,
// ): Promise<Array<Array<DexSample<FillData>>>> {
): Promise<void> {
const rpcLiquidityRequests: RpcLiquidityRequest[] = sources.map(source => {
return {
tokenPath: [makerToken, takerToken],
@@ -155,21 +160,21 @@ export class SamplerOperations {
demand: true,
};
});
const rpcLiquidityResponse = await this.rpcSamplerClient.getSellLiquidityAsync(rpcLiquidityRequests);
// const dexQuotes: Array<Array<DexSample<FillData>>> = rpcLiquidityResponse.map((response, i) => {
// const dexSample: Array<DexSample<FillData>> = response.liquidityCurve.map((point, j) => {
// const fillData: DexSample = {
// source: response.source,
// fillData: point.encodedFillData,
// input: point.sellAmount,
// output: point.buyAmount,
// };
// return fillData;
// });
// return dexSample;
// });
return [];
// return dexQuotes;
await this.rpcSamplerClient.getSellLiquidityAsync(rpcLiquidityRequests, (err, rpcSamplerCallback: any) => {
const dexQuotes: Array<Array<DexSample<FillData>>> = rpcSamplerCallback.result.map((liquidityResponse: LiquidityResponse) => {
const dexSample: Array<DexSample<FillData>> = liquidityResponse.liquidityCurves.map((point, j) => {
const fillData: DexSample = {
source: liquidityResponse.source,
fillData: point[j].encodedFillData,
input: point[j].sellAmount,
output: point[j].buyAmount,
};
return fillData;
});
return dexSample;
});
callback(err, dexQuotes);
});
}
public async getBuyQuotesAsync(

View File

@@ -5,10 +5,14 @@ import { ERC20BridgeSource } from './types';
export type Bytes = string;
export type Address = Bytes;
export type LiquiditySource = ERC20BridgeSource;
export declare type RPCSamplerCallback = (err: Error | null, results: LiquidityResponse[]) => void;
export interface RpcLiquidityRequest {
tokenPath: Address[];
inputAmount: string;
source: ERC20BridgeSource; // LiquiditySource; TODO (Romain): should probably link them somehow?
source: LiquiditySource;
demand: boolean;
}
@@ -19,79 +23,13 @@ export interface LiquidityCurvePoint {
}
export interface LiquidityResponse {
source: ERC20BridgeSource; //LiquiditySource;
liquidityCurve: LiquidityCurvePoint[][];
}
export interface Market {
getSellLiquidityAsync(sellAmount: bigint, demand: boolean): Promise<LiquidityCurvePoint[]>;
getBuyLiquidityAsync(buyAmount: bigint, demand: boolean): Promise<LiquidityCurvePoint[]>;
getPriceAsync(): Promise<bigint>;
source: LiquiditySource;
liquidityCurves: LiquidityCurvePoint[][];
}
export interface TokenResponse {
address: Address;
symbol: string;
decimals: number;
gasCost: number;
gasCost: 0;
}
// tslint:disable: enum-naming
export enum LiquiditySource {
Native = 'Native',
Uniswap = 'Uniswap',
UniswapV2 = 'Uniswap_V2',
Eth2Dai = 'Eth2Dai',
Kyber = 'Kyber',
Curve = 'Curve',
LiquidityProvider = 'LiquidityProvider',
MultiBridge = 'MultiBridge',
Balancer = 'Balancer',
BalancerV2 = 'Balancer_V2',
Cream = 'CREAM',
Bancor = 'Bancor',
MakerPsm = 'MakerPsm',
MStable = 'mStable',
Mooniswap = 'Mooniswap',
MultiHop = 'MultiHop',
Shell = 'Shell',
Swerve = 'Swerve',
SnowSwap = 'SnowSwap',
SushiSwap = 'SushiSwap',
Dodo = 'DODO',
DodoV2 = 'DODO_V2',
CryptoCom = 'CryptoCom',
Linkswap = 'Linkswap',
KyberDmm = 'KyberDMM',
Smoothy = 'Smoothy',
Component = 'Component',
Saddle = 'Saddle',
XSigma = 'xSigma',
UniswapV3 = 'Uniswap_V3',
CurveV2 = 'Curve_V2',
Lido = 'Lido',
ShibaSwap = 'ShibaSwap',
JetSwap = 'JetSwap',
Clipper = 'Clipper',
// BSC only
PancakeSwap = 'PancakeSwap',
PancakeSwapV2 = 'PancakeSwap_V2',
BakerySwap = 'BakerySwap',
Nerve = 'Nerve',
Belt = 'Belt',
Ellipsis = 'Ellipsis',
ApeSwap = 'ApeSwap',
CafeSwap = 'CafeSwap',
CheeseSwap = 'CheeseSwap',
JulSwap = 'JulSwap',
ACryptos = 'ACryptoS',
// Polygon only
QuickSwap = 'QuickSwap',
ComethSwap = 'ComethSwap',
Dfyn = 'Dfyn',
WaultSwap = 'WaultSwap',
Polydex = 'Polydex',
FirebirdOneSwap = 'FirebirdOneSwap',
IronSwap = 'IronSwap',
}
// tslint:enable: enum-naming