Skip to content

Commit 2c360f0

Browse files
committed
Additional tests for TradeAPI utils and public method comments
1 parent e4a87aa commit 2c360f0

File tree

8 files changed

+362
-33
lines changed

8 files changed

+362
-33
lines changed

src/api/TradeAPI.ts

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,25 @@ export default class TradeAPI {
135135
);
136136
}
137137

138+
/**
139+
* Call 0x API to generate a trade quote for two SetToken components.
140+
*
141+
* @param fromToken Address of token being sold
142+
* @param toToken Address of token being bought
143+
* @param fromTokenDecimals Token decimals of token being sold (ex: 18)
144+
* @param toTokenDecimals Token decimals of token being bought (ex: 18)
145+
* @param rawAmount String quantity of token to sell (ex: "0.5")
146+
* @param fromAddress SetToken address which holds the buy / sell components
147+
* @param setToken SetTokenAPI instance
148+
* @param gasPrice (Optional) gasPrice to calculate gas costs with (Default: fetched from GasNow)
149+
* @param slippagePercentage (Optional) maximum slippage, determines min receive quantity. (Default: 2%)
150+
* @param isFirmQuote (Optional) Whether quote request is indicative or firm
151+
* @param feePercentage (Optional) Default: 0
152+
* @param feeRecipient (Optional) Default: 0xD3D555Bb655AcBA9452bfC6D7cEa8cC7b3628C55
153+
* @param excludedSources (Optional) Exchanges to exclude (Default: ['Kyber', 'Eth2Dai', 'Uniswap', 'Mesh'])
154+
*
155+
* @return {Promise<TradeQuote>}
156+
*/
138157
public async fetchTradeQuoteAsync(
139158
fromToken: Address,
140159
toToken: Address,
@@ -159,7 +178,6 @@ export default class TradeAPI {
159178

160179
const chainId = (await this.provider.getNetwork()).chainId;
161180

162-
// @ts-ignore
163181
return this.tradeQuoter.generate({
164182
fromToken,
165183
toToken,
@@ -180,30 +198,61 @@ export default class TradeAPI {
180198
});
181199
}
182200

183-
public async fetchTokenList(): Promise<CoinGeckoTokenData[]> {
201+
/**
202+
* Fetches a list of tokens and their metadata from CoinGecko. Each entry includes
203+
* the token's address, proper name, decimals, exchange symbol and a logo URI if available.
204+
* For Ethereum, this is a list of tokens tradeable on Uniswap, for Polygon it's a list of
205+
* tokens tradeable on Sushiswap's Polygon exchange. Method is useful for acquiring token decimals
206+
* necessary to generate a trade quote and images for representing available tokens in a UI.
207+
*
208+
* @return List of tradeable tokens for chain platform
209+
*/
210+
public async fetchTokenListAsync(): Promise<CoinGeckoTokenData[]> {
184211
await this.initializeForChain();
185212
return this.coinGecko.fetchTokenList();
186213
}
187214

188-
public async fetchTokenMap(): Promise<CoinGeckoTokenMap> {
215+
/**
216+
* Fetches the same info as `fetchTokenList` in the form of a map indexed by address. Method is
217+
* useful if you're cacheing the token list and want quick lookups for a variety of trades.
218+
*
219+
* @return Map of token addresses to token metadata
220+
*/
221+
public async fetchTokenMapAsync(): Promise<CoinGeckoTokenMap> {
189222
await this.initializeForChain();
190223
return this.coinGecko.fetchTokenMap();
191224
}
192225

193-
public async fetchCoinPrices(
226+
/**
227+
* Fetches a list of prices vs currencies for the specified inputs from CoinGecko
228+
*
229+
* @param contractAddresses String array of contract addresses
230+
* @param vsCurrencies String array of currency codes (see CoinGecko api for a complete list)
231+
*
232+
* @return List of prices vs currencies
233+
*/
234+
public async fetchCoinPricesAsync(
194235
contractAddresses: string[],
195236
vsCurrencies: string[]
196237
): Promise<CoinGeckoCoinPrices> {
197238
await this.initializeForChain();
198239
return this.coinGecko.fetchCoinPrices({contractAddresses, vsCurrencies});
199240
}
200241

201-
public async fetchGasPrice(speed: GasOracleSpeed): Promise<number> {
242+
/**
243+
* Fetches the recommended gas price for a specified execution speed.
244+
*
245+
* @param speed (Optional) string value: "average" | "fast" | "fastest" (Default: fast)
246+
*
247+
* @return Number: gas price
248+
*/
249+
public async fetchGasPriceAsync(speed?: GasOracleSpeed): Promise<number> {
202250
await this.initializeForChain();
203251
const oracle = new GasOracleService(this.chainId);
204252
return oracle.fetchGasPrice(speed);
205253
}
206254

255+
207256
private async initializeForChain() {
208257
if (this.coinGecko === undefined) {
209258
const network = await this.provider.getNetwork();

src/api/utils/coingecko.ts

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,24 @@ export class CoinGeckoDataService {
122122
return this.tokenMap;
123123
}
124124

125+
public convertTokenListToAddressMap(list: CoinGeckoTokenData[] = []): CoinGeckoTokenMap {
126+
const tokenMap: CoinGeckoTokenMap = {};
127+
128+
for (const entry of list) {
129+
tokenMap[entry.address] = Object.assign({}, entry);
130+
}
131+
132+
return tokenMap;
133+
}
134+
135+
private getPlatform(): string {
136+
switch (this.chainId) {
137+
case 1: return 'ethereum';
138+
case 137: return 'polygon-pos';
139+
default: return '';
140+
}
141+
}
142+
125143
private async fetchEthereumTokenList(): Promise<CoinGeckoTokenData[]> {
126144
const url = 'https://tokens.coingecko.com/uniswap/all.json';
127145
const response = await axios.get(url);
@@ -226,22 +244,4 @@ export class CoinGeckoDataService {
226244
const data = (await axios.get(url)).data;
227245
return data;
228246
}
229-
230-
private convertTokenListToAddressMap(list: CoinGeckoTokenData[] = []): CoinGeckoTokenMap {
231-
const tokenMap: CoinGeckoTokenMap = {};
232-
233-
for (const entry of list) {
234-
tokenMap[entry.address] = Object.assign({}, entry);
235-
}
236-
237-
return tokenMap;
238-
}
239-
240-
private getPlatform(): string {
241-
switch (this.chainId) {
242-
case 1: return 'ethereum';
243-
case 137: return 'polygon-pos';
244-
default: return '';
245-
}
246-
}
247247
}

src/api/utils/gasOracle.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,6 @@ export class GasOracleService {
6767
const url = 'https://www.gasnow.org/api/v3/gas/price';
6868
const data: GasNowData = (await axios.get(url)).data.data;
6969

70-
// EthGasStation returns gas price in x10 Gwei (divite by 10 to convert it to gwei)
7170
switch (speed) {
7271
case GasOracleService.AVERAGE: return data.standard / 1e9;
7372
case GasOracleService.FAST: return data.fast / 1e9;

src/api/utils/tradeQuoter.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ export class TradeQuoter {
235235

236236
const fromTokenAmount = quote.sellAmount;
237237

238-
// Convert to BigDecimal to get cieling in fromUnits calculation
238+
// Convert to BigDecimal to get ceiling in fromUnits calculation
239239
// This is necessary to derive the trade amount ZeroEx expects when scaling is
240240
// done in the TradeModule contract. (ethers.FixedNumber does not work for this case)
241241
const fromTokenAmountBD = new BigDecimal(fromTokenAmount.toString());
@@ -422,8 +422,7 @@ export class TradeQuoter {
422422
const gasCostBuffer = (100 + this.tradeQuoteGasBuffer) / 100;
423423
return Math.floor(gas.toNumber() * gasCostBuffer);
424424
} catch (error) {
425-
console.log('error --> ' + error);
426-
throw new Error('Unable to fetch gas cost estimate for trade');
425+
throw new Error('Unable to fetch gas cost estimate for trade' + error);
427426
}
428427
}
429428

src/assertions/CommonAssertions.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ export class CommonAssertions {
120120
const validChainIds = [1, 137];
121121

122122
if ( !validChainIds.includes(chainId)) {
123-
throw new Error('Unsupported chainId: ${chainId}. Must be one of ${validChainIds}');
123+
throw new Error(`Unsupported chainId: ${chainId}. Must be one of ${validChainIds}`);
124124
}
125125
}
126126
}

0 commit comments

Comments
 (0)