From 74ca58b69d4eba2641e7f7a5448790f022c30789 Mon Sep 17 00:00:00 2001 From: Aaron Date: Mon, 5 Feb 2024 16:19:09 +0200 Subject: [PATCH] fetch exchange rates from mento for the exchange:show command --- .../cli/src/utils/mento-broker-adaptor.ts | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/packages/cli/src/utils/mento-broker-adaptor.ts b/packages/cli/src/utils/mento-broker-adaptor.ts index 6eff46264..eb7655139 100644 --- a/packages/cli/src/utils/mento-broker-adaptor.ts +++ b/packages/cli/src/utils/mento-broker-adaptor.ts @@ -1,5 +1,6 @@ import { CeloTx, Connection } from '@celo/connect' import { Mento } from '@mento-protocol/mento-sdk' +import { ux } from '@oclif/core' import { ethers } from 'ethers' export async function getMentoBroker(connection: Connection) { @@ -36,3 +37,38 @@ export function convertEthersToCeloTx( } return { ...defaults, ...celoTx } } + +const VALID_SYMBOLS = new Set(['cUSD', 'cEUR', 'cREAL', 'CELO']) + +// amount is string representation of a number in wei +export async function getExchangeRates( + connection: Connection, + amount: string, + validSymbols: Set = VALID_SYMBOLS +) { + const { mento } = await getMentoBroker(connection) + + const pairs = await mento.getTradeablePairs() + // the cli only supports CELO to stable token pairs + const celoPairs = pairs.filter((pair) => { + return validSymbols.has(pair[0].symbol) && validSymbols.has(pair[1].symbol) + }) + + return Promise.all( + celoPairs.map(async (pair) => { + try { + const [buy, sell] = await Promise.all([ + mento.getAmountIn(pair[0].address, pair[1].address, amount), + mento.getAmountOut(pair[0].address, pair[1].address, amount), + ]) + return { + buy, + sell, + symbol: pair[0].symbol === 'CELO' ? pair[1].symbol : pair[0].symbol, + } + } catch (e) { + ux.error(`Error Fetching for ${pair[0].symbol} => ${pair[1].symbol}`, e as Error) + } + }) + ) +}