Skip to content

Commit

Permalink
backend/exchange: refactor region codes endpoint
Browse files Browse the repository at this point in the history
The previous endpoint was returning exchange availability data for each
region, which was not needed. Now it just returns a string array of
region codes, which simplifies a bit both BE and FE.
  • Loading branch information
Beerosagos committed Feb 13, 2025
1 parent c008d6b commit 1ce9535
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 44 deletions.
6 changes: 3 additions & 3 deletions backend/exchanges/exchanges.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ import (
"github.com/BitBoxSwiss/bitbox-wallet-app/util/logging"
)

// regionCodes is an array containing ISO 3166-1 alpha-2 code of all regions.
// RegionCodes is an array containing ISO 3166-1 alpha-2 code of all regions.
// Source: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
var regionCodes = []string{
var RegionCodes = []string{
"AD", "AE", "AF", "AG", "AI", "AL", "AM", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ",
"BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS",
"BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN",
Expand Down Expand Up @@ -151,7 +151,7 @@ func ListExchangesByRegion(account accounts.Interface, httpClient *http.Client)
isBtcDirectSupported := IsBtcDirectSupported(account.Coin().Code())

exchangeRegions := ExchangeRegionList{}
for _, code := range regionCodes {
for _, code := range RegionCodes {
// default behavior is to show the exchange if the supported regions check fails.
moonpayEnabled, pocketEnabled := true, true
if moonpayError == nil {
Expand Down
22 changes: 3 additions & 19 deletions backend/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ func NewHandlers(
getAPIRouterNoError(apiRouter)("/certs/download", handlers.postCertsDownload).Methods("POST")
getAPIRouterNoError(apiRouter)("/electrum/check", handlers.postElectrumCheck).Methods("POST")
getAPIRouterNoError(apiRouter)("/socksproxy/check", handlers.postSocksProxyCheck).Methods("POST")
getAPIRouterNoError(apiRouter)("/exchange/by-region/{code}", handlers.getExchangesByRegion).Methods("GET")
getAPIRouterNoError(apiRouter)("/exchange/region-codes", handlers.getExchangeRegionCodes).Methods("GET")
getAPIRouterNoError(apiRouter)("/exchange/deals/{action}/{code}", handlers.getExchangeDeals).Methods("GET")
getAPIRouterNoError(apiRouter)("/exchange/supported/{code}", handlers.getExchangeSupported).Methods("GET")
getAPIRouterNoError(apiRouter)("/exchange/btcdirect-otc/supported/{code}", handlers.getExchangeBtcDirectOTCSupported).Methods("GET")
Expand Down Expand Up @@ -1262,24 +1262,8 @@ func (handlers *Handlers) getSupportedCoins(*http.Request) interface{} {
return result
}

func (handlers *Handlers) getExchangesByRegion(r *http.Request) interface{} {
type errorResult struct {
Error string `json:"error"`
}

acct, err := handlers.backend.GetAccountFromCode(accountsTypes.Code(mux.Vars(r)["code"]))
if err != nil {
handlers.log.Error(err)
return errorResult{Error: err.Error()}
}

accountValid := acct != nil && acct.Offline() == nil && !acct.FatalError()
if !accountValid {
handlers.log.Error("Account not valid")
return errorResult{Error: "Account not valid"}
}

return exchanges.ListExchangesByRegion(acct, handlers.backend.HTTPClient())
func (handlers *Handlers) getExchangeRegionCodes(r *http.Request) interface{} {
return exchanges.RegionCodes
}

func (handlers *Handlers) postBitsuranceLookup(r *http.Request) interface{} {
Expand Down
20 changes: 5 additions & 15 deletions frontends/web/src/api/exchanges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,9 @@
import { AccountCode } from './account';
import { apiGet, apiPost } from '@/utils/request';

export type ExchangeRegionList = {
regions: ExchangeRegion[];
}

export type ExchangeRegion = {
code: string;
isMoonpayEnabled: boolean;
isPocketEnabled: boolean;
}

export const getExchangesByRegion = (code: string) => {
return (): Promise<ExchangeRegionList> => {
return apiGet(`exchange/by-region/${code}`);
export const getExchangeRegionCodes = () => {
return (): Promise<string[]> => {
return apiGet('exchange/region-codes');
};
};

Expand Down Expand Up @@ -65,7 +55,7 @@ export type TExchangeDealsResponse = ExchangeDealsList | ExchangeError

export type TExchangeAction = 'buy' | 'sell';

export const getExchangeDeals = (action: TExchangeAction, accountCode: AccountCode, region: ExchangeRegion['code']): Promise<TExchangeDealsResponse> => {
export const getExchangeDeals = (action: TExchangeAction, accountCode: AccountCode, region: string): Promise<TExchangeDealsResponse> => {
return apiGet(`exchange/deals/${action}/${accountCode}?region=${region}`);
};

Expand Down Expand Up @@ -136,7 +126,7 @@ export type TBtcDirectResponse = {
success: false;
};

export const getBtcDirectOTCSupported = (code: AccountCode, region: ExchangeRegion['code']) => {
export const getBtcDirectOTCSupported = (code: AccountCode, region: string) => {
return (): Promise<TBtcDirectResponse> => {
return apiGet(`exchange/btcdirect-otc/supported/${code}?region=${region}`);
};
Expand Down
14 changes: 7 additions & 7 deletions frontends/web/src/routes/exchange/exchange.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export const Exchange = ({ code, accounts, deviceIDs }: TProps) => {
const [supportedAccounts, setSupportedAccounts] = useState<IAccount[]>([]);
const [activeTab, setActiveTab] = useState<exchangesAPI.TExchangeAction>('buy');

const regionList = useLoad(exchangesAPI.getExchangesByRegion(code));
const regionCodes = useLoad(exchangesAPI.getExchangeRegionCodes());
const nativeLocale = useLoad(getNativeLocale);
const config = useLoad(getConfig);

Expand All @@ -69,13 +69,13 @@ export const Exchange = ({ code, accounts, deviceIDs }: TProps) => {

// update region Select component when `regionList` or `config` gets populated.
useEffect(() => {
if (!regionList || !config) {
if (!regionCodes || !config) {
return;
}
const regionNames = new Intl.DisplayNames([i18n.language], { type: 'region' }) || '';
const regions: TOption[] = regionList.regions.map(region => ({
value: region.code,
label: regionNames.of(region.code) || region.code
const regions: TOption[] = regionCodes.map(code => ({
value: code,
label: regionNames.of(code) || code
}));

regions.sort((a, b) => a.label.localeCompare(b.label, i18n.language));
Expand All @@ -95,10 +95,10 @@ export const Exchange = ({ code, accounts, deviceIDs }: TProps) => {
// user never selected a region preference, will derive it from native locale.
const userRegion = getRegionNameFromLocale(nativeLocale || '');
//Region is available in the list
const regionAvailable = !!(regionList.regions.find(region => region.code === userRegion));
const regionAvailable = !!(regionCodes.find(code => code === userRegion));
//Pre-selecting the region
setSelectedRegion(regionAvailable ? userRegion : '');
}, [regionList, config, nativeLocale]);
}, [regionCodes, config, nativeLocale]);


const goToExchange = (exchange: string) => {
Expand Down

0 comments on commit 1ce9535

Please sign in to comment.