Skip to content

Commit

Permalink
refactor: api wallet
Browse files Browse the repository at this point in the history
  • Loading branch information
stackchain committed Oct 20, 2023
1 parent 7347eed commit 094c2f4
Show file tree
Hide file tree
Showing 23 changed files with 400 additions and 47 deletions.
23 changes: 19 additions & 4 deletions apps/wallet-mobile/src/TxHistory/TxHistoryNavigator.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import {createStackNavigator} from '@react-navigation/stack'
import {supportedProviders, swapApiMaker, swapManagerMaker, SwapProvider, swapStorageMaker} from '@yoroi/swap'
import {
milkTokenId,
supportedProviders,
swapApiMaker,
swapManagerMaker,
SwapProvider,
swapStorageMaker,
} from '@yoroi/swap'
import {Swap} from '@yoroi/types'
import React from 'react'
import {defineMessages, useIntl} from 'react-intl'
import {StyleSheet, Text, TouchableOpacity, TouchableOpacityProps} from 'react-native'
Expand Down Expand Up @@ -29,15 +37,18 @@ import {BackButton, defaultStackNavigationOptions, TxHistoryRoutes, useWalletNav
import {ReceiveScreen} from '../Receive/ReceiveScreen'
import {useSelectedWallet} from '../SelectedWallet'
import {COLORS} from '../theme'
import {useStakingKey, useWalletName} from '../yoroi-wallets/hooks'
import {useFrontendFees, useStakingKey, useWalletName} from '../yoroi-wallets/hooks'
import {ModalInfo} from './ModalInfo'
import {TxDetails} from './TxDetails'
import {TxHistory} from './TxHistory'

const aggregator: Swap.Aggregator = 'muesliswap'

const Stack = createStackNavigator<TxHistoryRoutes>()
export const TxHistoryNavigator = () => {
const strings = useStrings()
const wallet = useSelectedWallet()
const {frontendFees} = useFrontendFees(wallet)

const walletName = useWalletName(wallet)
const stakingKey = useStakingKey(wallet)
Expand All @@ -47,7 +58,7 @@ export const TxHistoryNavigator = () => {
const hideModalInfo = React.useCallback(() => setModalInfoState(false), [])

const swapStorage = React.useMemo(() => swapStorageMaker(), [])
const swapAPI = React.useMemo(
const swapApi = React.useMemo(
() =>
swapApiMaker({
isMainnet: wallet.networkId !== 300,
Expand All @@ -58,7 +69,11 @@ export const TxHistoryNavigator = () => {
[wallet.networkId, stakingKey, wallet.primaryTokenInfo.id],
)

const swapManager = React.useMemo(() => swapManagerMaker(swapStorage, swapAPI), [swapStorage, swapAPI])
const swapManager = React.useMemo(() => {
const frontendFee = frontendFees?.[aggregator] ?? []
const aggregatorToken = wallet.networkId !== 300 ? milkTokenId.mainnet : milkTokenId.preprod
return swapManagerMaker({swapStorage, swapApi, frontendFee, aggregator, aggregatorToken})
}, [frontendFees, wallet.networkId, swapStorage, swapApi])

return (
<SendProvider key={wallet.id}>
Expand Down
31 changes: 18 additions & 13 deletions apps/wallet-mobile/src/yoroi-wallets/cardano/byron/ByronWallet.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {PrivateKey} from '@emurgo/cross-csl-core'
import * as yoroiLib from '@emurgo/yoroi-lib'
import {AppApi} from '@yoroi/api'
import {parseSafe} from '@yoroi/common'
import {App, Balance} from '@yoroi/types'
import assert from 'assert'
Expand Down Expand Up @@ -43,7 +44,7 @@ import {genTimeToSlot} from '../../utils/timeUtils'
import {validatePassword} from '../../utils/validators'
import {WalletMeta} from '../../walletManager'
import {Cardano, CardanoMobile} from '../../wallets'
import * as api from '../api'
import * as legacyApi from '../api'
import {encryptWithPassword} from '../catalyst/catalystCipher'
import {generatePrivateKeyForCatalyst} from '../catalyst/catalystUtils'
import {AddressChain, AddressChainJSON, Addresses, AddressGenerator} from '../chain'
Expand Down Expand Up @@ -124,7 +125,11 @@ export type WalletJSON = ShelleyWalletJSON | ByronWalletJSON
const networkId = NETWORK_REGISTRY.HASKELL_SHELLEY
const implementationId = WALLET_IMPLEMENTATION_REGISTRY.HASKELL_BYRON

const appApi = AppApi.mockAppApi
// const api = AppApi.appApiMaker({baseUrl: API_ROOT})

export class ByronWallet implements YoroiWallet {
readonly api: App.Api = appApi
readonly primaryToken: DefaultAsset
readonly primaryTokenInfo: Balance.TokenInfo
readonly id: string
Expand Down Expand Up @@ -917,7 +922,7 @@ export class ByronWallet implements YoroiWallet {
const absSlotNumber = new BigNumber(timeToSlotFn({time}).slot)
const changeAddr = await this.getAddressedChangeAddress()
const addressedUtxos = await this.getAddressedUtxos()
const accountState = await api.getAccountState(
const accountState = await legacyApi.getAccountState(
{addresses: [this.rewardAddressHex]},
this.getNetworkConfig().BACKEND,
)
Expand Down Expand Up @@ -1008,11 +1013,11 @@ export class ByronWallet implements YoroiWallet {
// =================== backend API =================== //

async checkServerStatus() {
return api.checkServerStatus(this.getBackendConfig())
return legacyApi.checkServerStatus(this.getBackendConfig())
}

async submitTransaction(signedTx: string) {
const response: any = await api.submitTransaction(signedTx, this.getBackendConfig())
const response: any = await legacyApi.submitTransaction(signedTx, this.getBackendConfig())
Logger.info(response)
return response as any
}
Expand Down Expand Up @@ -1078,11 +1083,11 @@ export class ByronWallet implements YoroiWallet {
}

async fetchAccountState(): Promise<AccountStateResponse> {
return api.bulkGetAccountState([this.rewardAddressHex], this.getBackendConfig())
return legacyApi.bulkGetAccountState([this.rewardAddressHex], this.getBackendConfig())
}

async fetchPoolInfo(request: PoolInfoRequest) {
return api.getPoolInfo(request, this.getBackendConfig())
return legacyApi.getPoolInfo(request, this.getBackendConfig())
}

public async signRawTx(txHex: string, pKeys: PrivateKey[]) {
Expand All @@ -1104,31 +1109,31 @@ export class ByronWallet implements YoroiWallet {
return primaryTokenInfo.testnet
}

return api.getTokenInfo(tokenId, `${apiUrl}/metadata`, this.getBackendConfig())
return legacyApi.getTokenInfo(tokenId, `${apiUrl}/metadata`, this.getBackendConfig())
}

async fetchFundInfo(): Promise<FundInfoResponse> {
return api.getFundInfo(this.getBackendConfig(), this.getNetworkConfig().IS_MAINNET)
return legacyApi.getFundInfo(this.getBackendConfig(), this.getNetworkConfig().IS_MAINNET)
}

async fetchTxStatus(request: TxStatusRequest): Promise<TxStatusResponse> {
return api.fetchTxStatus(request, this.getBackendConfig())
return legacyApi.fetchTxStatus(request, this.getBackendConfig())
}

async fetchTipStatus(): Promise<TipStatusResponse> {
return api.getTipStatus(this.getBackendConfig())
return legacyApi.getTipStatus(this.getBackendConfig())
}

async fetchCurrentPrice(symbol: CurrencySymbol): Promise<number> {
return api.fetchCurrentPrice(symbol, this.getBackendConfig())
return legacyApi.fetchCurrentPrice(symbol, this.getBackendConfig())
}

// TODO: caching
fetchNftModerationStatus(fingerprint: string): Promise<YoroiNftModerationStatus> {
const backendConfig = this.getBackendConfig()
const networkConfig = this.getNetworkConfig()
const isMainnet = networkConfig.IS_MAINNET
return api.getNFTModerationStatus(fingerprint, {...backendConfig, mainnet: isMainnet})
return legacyApi.getNFTModerationStatus(fingerprint, {...backendConfig, mainnet: isMainnet})
}

private state: WalletState = {
Expand Down Expand Up @@ -1296,7 +1301,7 @@ export class ByronWallet implements YoroiWallet {

private async discoverAddresses() {
// last chunk gap limit check
const filterFn = (addrs) => api.filterUsedAddresses(addrs, this.getBackendConfig())
const filterFn = (addrs) => legacyApi.filterUsedAddresses(addrs, this.getBackendConfig())
await Promise.all([this.internalChain.sync(filterFn), this.externalChain.sync(filterFn)])
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {PrivateKey} from '@emurgo/cross-csl-core'
import {Datum} from '@emurgo/yoroi-lib'
import {AppApi} from '@yoroi/api'
import {parseSafe} from '@yoroi/common'
import {App, Balance} from '@yoroi/types'
import assert from 'assert'
Expand Down Expand Up @@ -35,7 +36,7 @@ import {asQuantity, Quantities} from '../../utils'
import {validatePassword} from '../../utils/validators'
import {WalletMeta} from '../../walletManager'
import {Cardano, CardanoMobile} from '../../wallets'
import * as api from '../api'
import * as legacyApi from '../api'
import {encryptWithPassword} from '../catalyst/catalystCipher'
import {generatePrivateKeyForCatalyst} from '../catalyst/catalystUtils'
import {AddressChain, AddressChainJSON, Addresses, AddressGenerator} from '../chain'
Expand Down Expand Up @@ -156,7 +157,11 @@ export const makeShelleyWallet = (constants: typeof MAINNET | typeof TESTNET) =>
},
}

const appApi = AppApi.mockAppApi
// const api = AppApi.appApiMaker({baseUrl: API_ROOT})

return class ShelleyWallet implements YoroiWallet {
readonly api: App.Api = appApi
readonly primaryToken: DefaultAsset = PRIMARY_TOKEN
readonly primaryTokenInfo: Balance.TokenInfo = PRIMARY_TOKEN_INFO
readonly walletImplementationId = WALLET_IMPLEMENTATION_ID
Expand Down Expand Up @@ -827,7 +832,7 @@ export const makeShelleyWallet = (constants: typeof MAINNET | typeof TESTNET) =>
const absSlotNumber = new BigNumber(getTime(time).absoluteSlot)
const changeAddr = await this.getAddressedChangeAddress()
const addressedUtxos = await this.getAddressedUtxos()
const accountState = await api.getAccountState({addresses: [this.rewardAddressHex]}, BACKEND)
const accountState = await legacyApi.getAccountState({addresses: [this.rewardAddressHex]}, BACKEND)

const withdrawalTx = await Cardano.createUnsignedWithdrawalTx(
accountState,
Expand Down Expand Up @@ -947,11 +952,11 @@ export const makeShelleyWallet = (constants: typeof MAINNET | typeof TESTNET) =>
// =================== backend API =================== //

async checkServerStatus() {
return api.checkServerStatus(BACKEND)
return legacyApi.checkServerStatus(BACKEND)
}

async submitTransaction(signedTx: string) {
const response: any = await api.submitTransaction(signedTx, BACKEND)
const response: any = await legacyApi.submitTransaction(signedTx, BACKEND)
Logger.info(response)
return response as any
}
Expand Down Expand Up @@ -1017,38 +1022,38 @@ export const makeShelleyWallet = (constants: typeof MAINNET | typeof TESTNET) =>
}

async fetchAccountState(): Promise<AccountStateResponse> {
return api.bulkGetAccountState([this.rewardAddressHex], BACKEND)
return legacyApi.bulkGetAccountState([this.rewardAddressHex], BACKEND)
}

async fetchPoolInfo(request: PoolInfoRequest) {
return api.getPoolInfo(request, BACKEND)
return legacyApi.getPoolInfo(request, BACKEND)
}

fetchTokenInfo(tokenId: string) {
return tokenId === '' || tokenId === 'ADA'
? Promise.resolve(PRIMARY_TOKEN_INFO)
: api.getTokenInfo(tokenId, `${TOKEN_INFO_SERVICE}/metadata`, BACKEND)
: legacyApi.getTokenInfo(tokenId, `${TOKEN_INFO_SERVICE}/metadata`, BACKEND)
}

async fetchFundInfo(): Promise<FundInfoResponse> {
return api.getFundInfo(BACKEND, IS_MAINNET)
return legacyApi.getFundInfo(BACKEND, IS_MAINNET)
}

async fetchTxStatus(request: TxStatusRequest): Promise<TxStatusResponse> {
return api.fetchTxStatus(request, BACKEND)
return legacyApi.fetchTxStatus(request, BACKEND)
}

async fetchTipStatus(): Promise<TipStatusResponse> {
return api.getTipStatus(BACKEND)
return legacyApi.getTipStatus(BACKEND)
}

async fetchCurrentPrice(symbol: CurrencySymbol): Promise<number> {
return api.fetchCurrentPrice(symbol, BACKEND)
return legacyApi.fetchCurrentPrice(symbol, BACKEND)
}

// TODO: caching
fetchNftModerationStatus(fingerprint: string): Promise<YoroiNftModerationStatus> {
return api.getNFTModerationStatus(fingerprint, {...BACKEND, mainnet: true})
return legacyApi.getNFTModerationStatus(fingerprint, {...BACKEND, mainnet: true})
}

private state: WalletState = {
Expand Down Expand Up @@ -1214,7 +1219,7 @@ export const makeShelleyWallet = (constants: typeof MAINNET | typeof TESTNET) =>

private async discoverAddresses() {
// last chunk gap limit check
const filterFn = (addrs) => api.filterUsedAddresses(addrs, BACKEND)
const filterFn = (addrs) => legacyApi.filterUsedAddresses(addrs, BACKEND)
await Promise.all([this.internalChain.sync(filterFn), this.externalChain.sync(filterFn)])
}

Expand Down
5 changes: 4 additions & 1 deletion apps/wallet-mobile/src/yoroi-wallets/cardano/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
TxMetadata as TxMetadataType,
UnsignedTx as UnsignedTxType,
} from '@emurgo/yoroi-lib'
import {Balance} from '@yoroi/types'
import {App, Balance} from '@yoroi/types'
import {BigNumber} from 'bignumber.js'

import {HWDeviceInfo} from '../hw'
Expand Down Expand Up @@ -97,6 +97,9 @@ export type YoroiWallet = {
primaryToken: Readonly<DefaultAsset>
primaryTokenInfo: Readonly<Balance.TokenInfo>

// API
api: App.Api

signRawTx(txHex: string, pKeys: PrivateKey[]): Promise<Uint8Array | undefined>

// Sending
Expand Down
19 changes: 18 additions & 1 deletion apps/wallet-mobile/src/yoroi-wallets/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import AsyncStorage, {AsyncStorageStatic} from '@react-native-async-storage/async-storage'
import {useNavigation} from '@react-navigation/native'
import {parseBoolean, useStorage} from '@yoroi/common'
import {Balance} from '@yoroi/types'
import {App, Balance} from '@yoroi/types'
import {Buffer} from 'buffer'
import * as React from 'react'
import {useCallback, useMemo} from 'react'
Expand Down Expand Up @@ -613,6 +613,23 @@ export const useWalletNames = (
}
}

export const useFrontendFees = (
wallet: YoroiWallet,
options?: UseQueryOptions<App.FrontendFeesResponse, Error, App.FrontendFeesResponse, [string, 'frontend-fees']>,
) => {
const query = useQuery({
suspense: true,
queryKey: [wallet.id, 'frontend-fees'],
...options,
queryFn: () => wallet.api.getFrontendFees(),
})

return {
...query,
frontendFees: query.data,
}
}

export const useWalletMetas = (walletManager: WalletManager, options?: UseQueryOptions<Array<WalletMeta>, Error>) => {
const query = useQuery({
queryKey: ['walletMetas'],
Expand Down
2 changes: 2 additions & 0 deletions apps/wallet-mobile/src/yoroi-wallets/mocks/wallet.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/no-explicit-any */
import {action} from '@storybook/addon-actions'
import {AppApi} from '@yoroi/api'
import {Balance} from '@yoroi/types'
import BigNumber from 'bignumber.js'

Expand Down Expand Up @@ -41,6 +42,7 @@ const walletMeta: WalletMeta = {

const wallet: YoroiWallet = {
id: 'wallet-id',
api: AppApi.mockAppApi,
primaryToken: PRIMARY_TOKEN,
primaryTokenInfo: PRIMARY_TOKEN_INFO,
walletImplementationId: 'haskell-shelley',
Expand Down
2 changes: 1 addition & 1 deletion metro.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module.exports = {
path.resolve(__dirname, "packages/types"),
path.resolve(__dirname, "packages/banxa"),
path.resolve(__dirname, "packages/common"),
path.resolve(__dirname, "packages/cardano"),
path.resolve(__dirname, "packages/api"),
path.resolve(__dirname, "packages/openswap"),
path.resolve(__dirname, "packages/swap"),
path.resolve(__dirname, "apps/wallet-mobile"),
Expand Down
6 changes: 3 additions & 3 deletions packages/api/package.json
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
{
"name": "@yoroi/api",
"version": "1.0.0",
"description": "The Cardano package of Yoroi SDK",
"description": "The API package of Yoroi SDK",
"keywords": [
"yoroi",
"cardano",
"swap",
"browser",
"react"
],
"homepage": "https://github.com/Emurgo/yoroi/packages/cardano#readme",
"homepage": "https://github.com/Emurgo/yoroi/packages/api#readme",
"bugs": {
"url": "https://github.com/Emurgo/yoroi/issues"
},
"repository": {
"type": "github",
"url": "https://github.com/Emurgo/yoroi.git",
"directory": "packages/cardano"
"directory": "packages/api"
},
"license": "Apache-2.0",
"author": "EMURGO Fintech <[email protected]> (https://github.com/Emurgo/yoroi)",
Expand Down
Loading

0 comments on commit 094c2f4

Please sign in to comment.