fix(@desktop/wallet): Replace existing model used in Community / Permissions and do the needed cleanups

fixes #12513
This commit is contained in:
Khushboo Mehta 2024-02-05 17:44:49 +01:00 committed by Khushboo-dev-cpp
parent 7caa23a042
commit 8c939ad3a3
66 changed files with 428 additions and 598 deletions

View File

@ -678,18 +678,8 @@ proc deleteCommunityTokenPermission*(self: Controller, communityId: string, perm
proc allAccountsTokenBalance*(self: Controller, symbol: string): float64 =
return self.walletAccountService.allAccountsTokenBalance(symbol)
proc getTokenList*(self: Controller): seq[TokenDto] =
return self.tokenService.getTokenList()
proc getTokenDecimals*(self: Controller, symbol: string): int =
return self.tokenService.getTokenDecimals(symbol)
proc getContractAddressesForToken*(self: Controller, symbol: string): Table[int, string] =
var contractAddresses = self.tokenService.getContractAddressesForToken(symbol)
let communityToken = self.communityService.getCommunityTokenBySymbol(self.getMySectionId(), symbol)
if communityToken.address != "":
contractAddresses[communityToken.chainId] = communityToken.address
return contractAddresses
proc findTokenBySymbol*(self: Controller, symbol: string): TokenBySymbolItem =
return self.tokenService.findTokenBySymbol(symbol)
proc getCommunityTokenList*(self: Controller): seq[CommunityTokenDto] =
return self.communityTokensService.getCommunityTokens(self.getMySectionId())

View File

@ -1309,18 +1309,22 @@ method createOrEditCommunityTokenPermission*(self: Module, communityId: string,
let viewAmount = tokenCriteria{"amount"}.getFloat
var tokenCriteriaDto = tokenCriteria.toTokenCriteriaDto
if tokenCriteriaDto.`type` == TokenType.ERC20:
tokenCriteriaDto.decimals = self.controller.getTokenDecimals(tokenCriteriaDto.symbol)
let token = self.controller.findTokenBySymbol(tokenCriteriaDto.symbol)
if token != nil:
if tokenCriteriaDto.`type` == TokenType.ERC20:
tokenCriteriaDto.decimals = token.decimals
let contractAddresses = self.controller.getContractAddressesForToken(tokenCriteriaDto.symbol)
if contractAddresses.len == 0 and tokenCriteriaDto.`type` != TokenType.ENS:
if permissionId == "":
self.onCommunityTokenPermissionCreationFailed(communityId)
if token.addressPerChainId.len == 0 and tokenCriteriaDto.`type` != TokenType.ENS:
if permissionId == "":
self.onCommunityTokenPermissionCreationFailed(communityId)
return
self.onCommunityTokenPermissionUpdateFailed(communityId)
return
self.onCommunityTokenPermissionUpdateFailed(communityId)
return
tokenCriteriaDto.amount = viewAmount.formatBiggestFloat(ffDecimal)
var contractAddresses = initTable[int, string]()
for addrPerChain in token.addressPerChainId:
contractAddresses[addrPerChain.chainId] = addrPerChain.address
tokenCriteriaDto.contractAddresses = contractAddresses
tokenPermission.tokenCriteria.add(tokenCriteriaDto)

View File

@ -186,7 +186,10 @@ proc init*(self: Controller) =
args.memberRevealedAccounts,
)
self.events.on(SIGNAL_WALLET_ACCOUNT_TOKENS_REBUILT) do(e: Args):
self.events.on(SIGNAL_TOKENS_LIST_UPDATED) do(e: Args):
self.delegate.onWalletAccountTokensRebuilt()
self.events.on(SIGNAL_WALLET_ACCOUNT_NETWORK_ENABLED_UPDATED) do(e: Args):
self.delegate.onWalletAccountTokensRebuilt()
self.events.on(SIGNAL_SHARED_KEYCARD_MODULE_USER_AUTHENTICATED) do(e: Args):
@ -369,8 +372,8 @@ proc getAllCommunityTokens*(self: Controller): seq[CommunityTokenDto] =
proc getNetwork*(self:Controller, chainId: int): NetworkDto =
self.networksService.getNetwork(chainId)
proc getTokenList*(self: Controller): seq[TokenDto] =
return self.tokenService.getTokenList()
proc getTokenBySymbolList*(self: Controller): seq[TokenBySymbolItem] =
return self.tokenService.getTokenBySymbolList()
proc shareCommunityUrlWithChatKey*(self: Controller, communityId: string): string =
return self.communityService.shareCommunityUrlWithChatKey(communityId)
@ -473,3 +476,6 @@ proc runSigningOnKeycard*(self: Controller, keyUid: string, path: string, dataTo
proc removeCommunityChat*(self: Controller, communityId: string, channelId: string) =
self.communityService.deleteCommunityChat(communityId, channelId)
proc getNetworks*(self: Controller): seq[NetworkDto] =
return self.networksService.getNetworks()

View File

@ -597,7 +597,11 @@ proc buildTokensAndCollectiblesFromWallet(self: Module) =
var tokenListItems: seq[TokenListItem]
# Common ERC20 tokens
let erc20Tokens = self.controller.getTokenList()
let allNetworks = self.controller.getNetworks().map(n => n.chainId)
let erc20Tokens = self.controller.getTokenBySymbolList().filter(t => (block:
let filteredChains = t.addressPerChainId.filter(apC => allNetworks.contains(apc.chainId))
return filteredChains.len != 0
))
for token in erc20Tokens:
let tokenListItem = initTokenListItem(
key = token.symbol,

View File

@ -132,10 +132,6 @@ proc getEnsRegisteredAddress*(self: Controller): string =
proc registerEnsGasEstimate*(self: Controller, chainId: int, ensUsername: string, address: string): int =
return self.ensService.registerEnsGasEstimate(chainId, ensUsername, address)
proc getSNTBalance*(self: Controller): string =
return self.ensService.getSNTBalance()
proc getWalletDefaultAddress*(self: Controller): string =
return self.walletAccountService.getWalletAccount(0).address
@ -145,21 +141,11 @@ proc getKeypairByAccountAddress*(self: Controller, address: string): KeypairDto
proc getCurrentCurrency*(self: Controller): string =
return self.settingsService.getCurrency()
proc getPrice*(self: Controller, crypto: string, fiat: string): float64 =
return self.tokenService.getTokenPrice(crypto, fiat)
proc getPriceBySymbol*(self: Controller, crypto: string): float64 =
return self.tokenService.getPriceBySymbol(crypto)
proc getStatusToken*(self: Controller): string =
let token = self.ensService.getStatusToken()
if token == nil:
return $ %*{}
let jsonObj = %* {
"name": token.name,
"symbol": token.symbol,
"address": token.address
}
return $jsonObj
proc getStatusTokenKey*(self: Controller): string =
return self.tokenService.getStatusTokenKey()
proc authenticate*(self: Controller, keyUid = "") =
let data = SharedKeycarModuleAuthenticationArgs(uniqueIdentifier: UNIQUE_ENS_SECTION_TRANSACTION_MODULE_IDENTIFIER,
@ -197,4 +183,4 @@ proc cancelCurrentFlow*(self: Controller) =
proc runSignFlow*(self: Controller, pin, bip44Path, txHash: string) =
self.cancelCurrentFlow()
self.connectKeycardReponseSignal()
self.keycardService.startSignFlow(bip44Path, txHash, pin)
self.keycardService.startSignFlow(bip44Path, txHash, pin)

View File

@ -72,27 +72,24 @@ method authenticateAndRegisterEns*(self: AccessInterface, chainId: int, ensUsern
maxPriorityFeePerGas: string, maxFeePerGas: string, eip1559Enabled: bool) {.base.} =
raise newException(ValueError, "No implementation available")
method getSNTBalance*(self: AccessInterface): string {.base.} =
raise newException(ValueError, "No implementation available")
method getWalletDefaultAddress*(self: AccessInterface): string {.base.} =
raise newException(ValueError, "No implementation available")
method getCurrentCurrency*(self: AccessInterface): string {.base.} =
raise newException(ValueError, "No implementation available")
method getFiatValue*(self: AccessInterface, cryptoBalance: string, cryptoSymbol: string, fiatSymbol: string): string
method getFiatValue*(self: AccessInterface, cryptoBalance: string, cryptoSymbol: string): string
{.base.} =
raise newException(ValueError, "No implementation available")
method getCryptoValue*(self: AccessInterface, fiatAmount: string, cryptoSymbol: string, fiatSymbol: string): string
method getCryptoValue*(self: AccessInterface, fiatAmount: string, cryptoSymbol: string): string
{.base.} =
raise newException(ValueError, "No implementation available")
method getGasEthValue*(self: AccessInterface, gweiValue: string, gasLimit: string): string {.base.} =
raise newException(ValueError, "No implementation available")
method getStatusToken*(self: AccessInterface): string {.base.} =
method getStatusTokenKey*(self: AccessInterface): string {.base.} =
raise newException(ValueError, "No implementation available")
method setPrefferedEnsUsername*(self: AccessInterface, ensUsername: string) {.base.} =
@ -102,4 +99,4 @@ method onKeypairAuthenticated*(self: AccessInterface, password: string, pin: str
raise newException(ValueError, "No implementation available")
method onTransactionSigned*(self: AccessInterface, keycardFlowType: string, keycardEvent: KeycardEvent) {.base.} =
raise newException(ValueError, "No implementation available")
raise newException(ValueError, "No implementation available")

View File

@ -247,40 +247,37 @@ method authenticateAndRegisterEns*(self: Module, chainId: int, ensUsername: stri
self.authenticateKeypairThatContainsObservedAddress()
method getSNTBalance*(self: Module): string =
return self.controller.getSNTBalance()
method getWalletDefaultAddress*(self: Module): string =
return self.controller.getWalletDefaultAddress()
method getCurrentCurrency*(self: Module): string =
return self.controller.getCurrentCurrency()
method getFiatValue*(self: Module, cryptoBalance: string, cryptoSymbol: string, fiatSymbol: string): string =
method getFiatValue*(self: Module, cryptoBalance: string, cryptoSymbol: string): string =
var floatCryptoBalance: float = 0
try:
floatCryptoBalance = parseFloat(cryptoBalance)
except ValueError:
return "0.00"
if (cryptoBalance == "" or cryptoSymbol == "" or fiatSymbol == ""):
if (cryptoBalance == "" or cryptoSymbol == ""):
return "0.00"
let price = self.controller.getPrice(cryptoSymbol, fiatSymbol)
let price = self.controller.getPriceBySymbol(cryptoSymbol)
let value = floatCryptoBalance * price
return fmt"{value}"
method getCryptoValue*(self: Module, fiatAmount: string, cryptoSymbol: string, fiatSymbol: string): string =
method getCryptoValue*(self: Module, fiatAmount: string, cryptoSymbol: string): string =
var fiatAmountBalance: float = 0
try:
fiatAmountBalance = parseFloat(fiatAmount)
except ValueError:
return "0.00"
if (fiatAmount == "" or cryptoSymbol == "" or fiatSymbol == ""):
if (fiatAmount == "" or cryptoSymbol == ""):
return "0.00"
let price = self.controller.getPrice(cryptoSymbol, fiatSymbol)
let price = self.controller.getPriceBySymbol(cryptoSymbol)
let value = fiatAmountBalance / price
return fmt"{value}"
@ -305,8 +302,8 @@ method getGasEthValue*(self: Module, gweiValue: string, gasLimit: string): strin
let ethValue = service_conversion.wei2Eth(weiValue)
return fmt"{ethValue}"
method getStatusToken*(self: Module): string =
return self.controller.getStatusToken()
method getStatusTokenKey*(self: Module): string =
return self.controller.getStatusTokenKey()
method setPrefferedEnsUsername*(self: Module, ensUsername: string) =
self.controller.setPreferredName(ensUsername)
@ -411,4 +408,4 @@ method onTransactionSigned*(self: Module, keycardFlowType: string, keycardEvent:
self.finish(chainId = 0, txHash = "", error = errMsg)
return
let signature = "0x" & keycardEvent.txSignature.r & keycardEvent.txSignature.s & keycardEvent.txSignature.v
self.sendEnsTxWithSignatureAndWatch(signature)
self.sendEnsTxWithSignatureAndWatch(signature)

View File

@ -112,26 +112,23 @@ QtObject:
maxPriorityFeePerGas: string, maxFeePerGas: string, eip1559Enabled: bool) {.slot.} =
self.delegate.authenticateAndRegisterEns(chainId, ensUsername, address, gas, gasPrice, maxPriorityFeePerGas, maxFeePerGas, eip1559Enabled)
proc getSNTBalance*(self: View): string {.slot.} =
return self.delegate.getSNTBalance()
proc getWalletDefaultAddress*(self: View): string {.slot.} =
return self.delegate.getWalletDefaultAddress()
proc getCurrentCurrency*(self: View): string {.slot.} =
return self.delegate.getCurrentCurrency()
proc getFiatValue*(self: View, cryptoBalance: string, cryptoSymbol: string, fiatSymbol: string): string {.slot.} =
return self.delegate.getFiatValue(cryptoBalance, cryptoSymbol, fiatSymbol)
proc getFiatValue*(self: View, cryptoBalance: string, cryptoSymbol: string): string {.slot.} =
return self.delegate.getFiatValue(cryptoBalance, cryptoSymbol)
proc getCryptoValue*(self: View, fiatAmount: string, cryptoSymbol: string, fiatSymbol: string): string {.slot.} =
return self.delegate.getCryptoValue(fiatAmount, cryptoSymbol, fiatSymbol)
proc getCryptoValue*(self: View, fiatAmount: string, cryptoSymbol: string): string {.slot.} =
return self.delegate.getCryptoValue(fiatAmount, cryptoSymbol)
proc getGasEthValue*(self: View, gweiValue: string, gasLimit: string): string {.slot.} =
return self.delegate.getGasEthValue(gweiValue, gasLimit)
proc getStatusToken*(self: View): string {.slot.} =
return self.delegate.getStatusToken()
proc getStatusTokenKey*(self: View): string {.slot.} =
return self.delegate.getStatusTokenKey()
proc setPrefferedEnsUsername*(self: View, ensUsername: string) {.slot.} =
self.delegate.setPrefferedEnsUsername(ensUsername)

View File

@ -171,24 +171,11 @@ proc getKeypairByAccountAddress*(self: Controller, address: string): KeypairDto
proc getCurrentCurrency*(self: Controller): string =
return self.settingsService.getCurrency()
proc getPrice*(self: Controller, crypto: string, fiat: string): float64 =
return self.tokenService.getTokenPrice(crypto, fiat)
proc getAppNetwork*(self: Controller): NetworkDto =
return self.networkService.getAppNetwork()
proc getStatusToken*(self: Controller): string =
let token = self.stickerService.getStatusToken()
if token == nil:
return $ %*{}
let jsonObj = %* {
"name": token.name,
"symbol": token.symbol,
"address": token.address
}
return $jsonObj
proc getStatusTokenKey*(self: Controller): string =
return self.tokenService.getStatusTokenKey()
proc authenticate*(self: Controller, keyUid = "") =
let data = SharedKeycarModuleAuthenticationArgs(uniqueIdentifier: UNIQUE_BUY_STICKER_TRANSACTION_MODULE_IDENTIFIER,

View File

@ -87,23 +87,16 @@ method gasEstimateReturned*(self: AccessInterface, estimate: int, uuid: string)
method addStickerPackToList*(self: AccessInterface, stickerPack: StickerPackDto, isInstalled: bool, isBought: bool, isPending: bool) {.base.} =
raise newException(ValueError, "No implementation available")
method getSNTBalance*(self: AccessInterface): string {.base.} =
raise newException(ValueError, "No implementation available")
method getWalletDefaultAddress*(self: AccessInterface): string {.base.} =
raise newException(ValueError, "No implementation available")
method getCurrentCurrency*(self: AccessInterface): string {.base.} =
raise newException(ValueError, "No implementation available")
method getFiatValue*(self: AccessInterface, cryptoBalance: string, cryptoSymbol: string, fiatSymbol: string): string
{.base.} =
raise newException(ValueError, "No implementation available")
method getGasEthValue*(self: AccessInterface, gweiValue: string, gasLimit: string): string {.base.} =
raise newException(ValueError, "No implementation available")
method getStatusToken*(self: AccessInterface): string {.base.} =
method getStatusTokenKey*(self: AccessInterface): string {.base.} =
raise newException(ValueError, "No implementation available")
method stickerTransactionConfirmed*(self: AccessInterface, trxType: string, packID: string, transactionHash: string) {.base.} =
@ -116,4 +109,4 @@ method onKeypairAuthenticated*(self: AccessInterface, password: string, pin: str
raise newException(ValueError, "No implementation available")
method onTransactionSigned*(self: AccessInterface, keycardFlowType: string, keycardEvent: KeycardEvent) {.base.} =
raise newException(ValueError, "No implementation available")
raise newException(ValueError, "No implementation available")

View File

@ -275,14 +275,6 @@ method getWalletDefaultAddress*(self: Module): string =
method getCurrentCurrency*(self: Module): string =
return self.controller.getCurrentCurrency()
method getFiatValue*(self: Module, cryptoBalance: string, cryptoSymbol: string, fiatSymbol: string): string =
if (cryptoBalance == "" or cryptoSymbol == "" or fiatSymbol == ""):
return "0.00"
let price = self.controller.getPrice(cryptoSymbol, fiatSymbol)
let value = parseFloat(cryptoBalance) * price
return fmt"{value:.2f}"
method getGasEthValue*(self: Module, gweiValue: string, gasLimit: string): string {.slot.} =
var gasLimitInt:int
@ -304,8 +296,8 @@ method getGasEthValue*(self: Module, gweiValue: string, gasLimit: string): strin
let ethValue = service_conversion.wei2Eth(weiValue)
return fmt"{ethValue}"
method getStatusToken*(self: Module): string =
return self.controller.getStatusToken()
method getStatusTokenKey*(self: Module): string =
return self.controller.getStatusTokenKey()
method stickerTransactionConfirmed*(self: Module, trxType: string, packID: string, transactionHash: string) =
self.view.stickerPacks.updateStickerPackInList(packID, installed = true, pending = false)

View File

@ -179,14 +179,11 @@ QtObject:
proc getCurrentCurrency*(self: View): string {.slot.} =
return self.delegate.getCurrentCurrency()
proc getFiatValue*(self: View, cryptoBalance: string, cryptoSymbol: string, fiatSymbol: string): string {.slot.} =
return self.delegate.getFiatValue(cryptoBalance, cryptoSymbol, fiatSymbol)
proc getGasEthValue*(self: View, gweiValue: string, gasLimit: string): string {.slot.} =
return self.delegate.getGasEthValue(gweiValue, gasLimit)
proc getStatusToken*(self: View): string {.slot.} =
return self.delegate.getStatusToken()
proc getStatusTokenKey*(self: View): string {.slot.} =
return self.delegate.getStatusTokenKey()
proc transactionCompleted(self: View, success: bool, txHash: string, packID: string, trxType: string) {.signal.}
proc emitTransactionCompletedSignal*(self: View, success: bool, txHash: string, packID: string, trxType: string) =

View File

@ -356,14 +356,17 @@ QtObject:
var assets = newSeq[backend_activity.Token]()
for tokenCode in self.filterTokenCodes:
for chainId in self.chainIds:
let token = self.tokenService.findTokenBySymbol(chainId, tokenCode)
# TODO: remove this call once the activity filter mechanism uses tokenKeys instead of the token
# symbol as we may have two tokens with the same symbol in the future. Only tokensKey will be unqiue
let token = self.tokenService.findTokenBySymbolAndChainId(tokenCode, chainId)
if token != nil:
let tokenType = if token.symbol == "ETH": TokenType.Native else: TokenType.ERC20
assets.add(backend_activity.Token(
tokenType: tokenType,
chainId: backend_activity.ChainId(token.chainId),
address: some(parseAddress(token.address))
))
for addrPerChain in token.addressPerChainId:
assets.add(backend_activity.Token(
tokenType: tokenType,
chainId: backend_activity.ChainId(addrPerChain.chainId),
address: some(parseAddress(addrPerChain.address))
))
self.currentActivityFilter.assets = assets

View File

@ -49,7 +49,7 @@ proc getHistoricalDataForToken*(self: Controller, symbol: string, currency: stri
self.tokenService.getHistoricalDataForToken(symbol, currency, range)
method fetchHistoricalBalanceForTokenAsJson*(self: Controller, addresses: seq[string], allAddresses: bool, tokenSymbol: string, currencySymbol: string, timeIntervalEnum: int) =
self.tokenService.fetchHistoricalBalanceForTokenAsJson(addresses, allAddresses, tokenSymbol, currencySymbol, BalanceHistoryTimeInterval(timeIntervalEnum))
self.walletAccountService.fetchHistoricalBalanceForTokenAsJson(addresses, allAddresses, tokenSymbol, currencySymbol, BalanceHistoryTimeInterval(timeIntervalEnum))
proc getSourcesOfTokensList*(self: Controller): var seq[SupportedSourcesItem] =
return self.tokenService.getSourcesOfTokensList()

View File

@ -100,8 +100,8 @@ proc getAccountByAddress*(self: Controller, address: string): WalletAccountDto =
proc getWalletAccountByIndex*(self: Controller, accountIndex: int): WalletAccountDto =
return self.walletAccountService.getWalletAccount(accountIndex)
proc getTokenBalance*(self: Controller, address: string, chainId: int, symbol: string): CurrencyAmount =
return currencyAmountToItem(self.walletAccountService.getTokenBalance(address, chainId, symbol), self.currencyService.getCurrencyFormat(symbol))
proc getTokenBalance*(self: Controller, address: string, chainId: int, tokensKey: string): CurrencyAmount =
return currencyAmountToItem(self.walletAccountService.getTokenBalance(address, chainId, tokensKey), self.walletAccountService.getCurrencyFormat(tokensKey))
proc authenticate*(self: Controller, keyUid = "") =
let data = SharedKeycarModuleAuthenticationArgs(uniqueIdentifier: UNIQUE_WALLET_SECTION_SEND_MODULE_IDENTIFIER,
@ -114,10 +114,10 @@ proc suggestedRoutes*(self: Controller, accountFrom: string, accountTo: string,
disabledToChainIDs, preferredChainIDs, sendType, lockedInAmounts)
return suggestedRoutes.toJson()
proc transfer*(self: Controller, from_addr: string, to_addr: string, tokenSymbol: string,
proc transfer*(self: Controller, from_addr: string, to_addr: string, assetKey: string,
value: string, uuid: string, selectedRoutes: seq[TransactionPathDto], password: string, sendType: SendType,
usePassword: bool, doHashing: bool, tokenName: string, isOwnerToken: bool) =
self.transactionService.transfer(from_addr, to_addr, tokenSymbol, value, uuid, selectedRoutes, password, sendType,
self.transactionService.transfer(from_addr, to_addr, assetKey, value, uuid, selectedRoutes, password, sendType,
usePassword, doHashing, tokenName, isOwnerToken)
proc proceedWithTransactionsSignatures*(self: Controller, fromAddr: string, toAddr: string, uuid: string,

View File

@ -21,7 +21,7 @@ method isLoaded*(self: AccessInterface): bool {.base.} =
method refreshWalletAccounts*(self: AccessInterface) {.base.} =
raise newException(ValueError, "No implementation available")
method getTokenBalance*(self: AccessInterface, address: string, chainId: int, symbol: string): CurrencyAmount {.base.} =
method getTokenBalance*(self: AccessInterface, address: string, chainId: int, tokensKey: string): CurrencyAmount {.base.} =
raise newException(ValueError, "No implementation available")
method suggestedRoutes*(self: AccessInterface, accountFrom: string, accountTo: string, amount: UInt256, token: string, disabledFromChainIDs,
@ -32,7 +32,7 @@ method suggestedRoutesReady*(self: AccessInterface, suggestedRoutes: SuggestedRo
raise newException(ValueError, "No implementation available")
method authenticateAndTransfer*(self: AccessInterface, from_addr: string, to_addr: string,
tokenSymbol: string, value: string, uuid: string, sendType: SendType, selectedTokenName: string, selectedTokenIsOwnerToken: bool) {.base.} =
assetKey: string, value: string, uuid: string, sendType: SendType, selectedTokenName: string, selectedTokenIsOwnerToken: bool) {.base.} =
raise newException(ValueError, "No implementation available")
method onUserAuthenticated*(self: AccessInterface, password: string, pin: string) {.base.} =

View File

@ -32,7 +32,7 @@ type TmpSendTransactionDetails = object
fromAddr: string
fromAddrPath: string
toAddr: string
tokenSymbol: string
assetKey: string
value: string
paths: seq[TransactionPathDto]
uuid: string
@ -59,7 +59,7 @@ type
receiveCurrentAccountIndex: int
# Forward declaration
method getTokenBalance*(self: Module, address: string, chainId: int, symbol: string): CurrencyAmount
method getTokenBalance*(self: Module, address: string, chainId: int, tokensKey: string): CurrencyAmount
proc newModule*(
delegate: delegate_interface.AccessInterface,
@ -128,7 +128,7 @@ proc convertNetworkDtoToNetworkItem(self: Module, network: NetworkDto): NetworkI
true,
false,
true,
self.getTokenBalance(self.view.getSelectedSenderAccountAddress(), network.chainId, self.view.getSelectedAssetSymbol())
self.getTokenBalance(self.view.getSelectedSenderAccountAddress(), network.chainId, self.view.getSelectedAssetKey())
)
proc convertSuggestedFeesDtoToGasFeesItem(self: Module, gasFees: SuggestedFeesDto): GasFeesItem =
@ -252,13 +252,13 @@ method viewDidLoad*(self: Module) =
self.moduleLoaded = true
self.delegate.sendModuleDidLoad()
method getTokenBalance*(self: Module, address: string, chainId: int, symbol: string): CurrencyAmount =
return self.controller.getTokenBalance(address, chainId, symbol)
method getTokenBalance*(self: Module, address: string, chainId: int, tokensKey: string): CurrencyAmount =
return self.controller.getTokenBalance(address, chainId, tokensKey)
method authenticateAndTransfer*(self: Module, fromAddr: string, toAddr: string, tokenSymbol: string, value: string, uuid: string, sendType: SendType, selectedTokenName: string, selectedTokenIsOwnerToken: bool) =
method authenticateAndTransfer*(self: Module, fromAddr: string, toAddr: string, assetKey: string, value: string, uuid: string, sendType: SendType, selectedTokenName: string, selectedTokenIsOwnerToken: bool) =
self.tmpSendTransactionDetails.fromAddr = fromAddr
self.tmpSendTransactionDetails.toAddr = toAddr
self.tmpSendTransactionDetails.tokenSymbol = tokenSymbol
self.tmpSendTransactionDetails.assetKey = assetKey
self.tmpSendTransactionDetails.value = value
self.tmpSendTransactionDetails.uuid = uuid
self.tmpSendTransactionDetails.sendType = sendType
@ -287,7 +287,7 @@ method onUserAuthenticated*(self: Module, password: string, pin: string) =
let usePassword = self.tmpSendTransactionDetails.fromAddrPath.len == 0
self.controller.transfer(
self.tmpSendTransactionDetails.fromAddr, self.tmpSendTransactionDetails.toAddr,
self.tmpSendTransactionDetails.tokenSymbol, self.tmpSendTransactionDetails.value, self.tmpSendTransactionDetails.uuid,
self.tmpSendTransactionDetails.assetKey, self.tmpSendTransactionDetails.value, self.tmpSendTransactionDetails.uuid,
self.tmpSendTransactionDetails.paths, password, self.tmpSendTransactionDetails.sendType, usePassword, doHashing,
self.tmpSendTransactionDetails.tokenName, self.tmpSendTransactionDetails.isOwnerToken
)

View File

@ -20,7 +20,7 @@ QtObject:
fromNetworksModel: NetworkModel
toNetworksModel: NetworkModel
transactionRoutes: TransactionRoutes
selectedAssetSymbol: string
selectedAssetKey: string
showUnPreferredChains: bool
sendType: transaction_dto.SendType
selectedTokenIsOwnerToken: bool
@ -126,17 +126,17 @@ QtObject:
read = getToNetworksModel
notify = toNetworksModelChanged
proc selectedAssetSymbolChanged*(self: View) {.signal.}
proc getSelectedAssetSymbol*(self: View): string {.slot.} =
return self.selectedAssetSymbol
proc setSelectedAssetSymbol(self: View, symbol: string) {.slot.} =
self.selectedAssetSymbol = symbol
proc selectedAssetKeyChanged*(self: View) {.signal.}
proc getSelectedAssetKey*(self: View): string {.slot.} =
return self.selectedAssetKey
proc setSelectedAssetKey(self: View, assetKey: string) {.slot.} =
self.selectedAssetKey = assetKey
self.updateNetworksTokenBalance()
self.selectedAssetSymbolChanged()
QtProperty[string] selectedAssetSymbol:
write = setSelectedAssetSymbol
read = getSelectedAssetSymbol
notify = selectedAssetSymbolChanged
self.selectedAssetKeyChanged()
QtProperty[string] selectedAssetKey:
write = setSelectedAssetKey
read = getSelectedAssetKey
notify = selectedAssetKeyChanged
proc showUnPreferredChainsChanged*(self: View) {.signal.}
proc getShowUnPreferredChains(self: View): bool {.slot.} =
@ -186,8 +186,8 @@ QtObject:
proc updateNetworksTokenBalance(self: View) =
for chainId in self.toNetworksModel.getAllNetworksChainIds():
self.fromNetworksModel.updateTokenBalanceForSymbol(chainId, self.delegate.getTokenBalance(self.selectedSenderAccount.address(), chainId, self.selectedAssetSymbol))
self.toNetworksModel.updateTokenBalanceForSymbol(chainId, self.delegate.getTokenBalance(self.selectedSenderAccount.address(), chainId, self.selectedAssetSymbol))
self.fromNetworksModel.updateTokenBalanceForSymbol(chainId, self.delegate.getTokenBalance(self.selectedSenderAccount.address(), chainId, self.selectedAssetKey))
self.toNetworksModel.updateTokenBalanceForSymbol(chainId, self.delegate.getTokenBalance(self.selectedSenderAccount.address(), chainId, self.selectedAssetKey))
proc setItems*(self: View, items: seq[AccountItem]) =
self.accounts.setItems(items)
@ -206,7 +206,7 @@ QtObject:
self.transactionSent(chainId, txHash, uuid, error)
proc authenticateAndTransfer*(self: View, value: string, uuid: string) {.slot.} =
self.delegate.authenticateAndTransfer(self.selectedSenderAccount.address(), self.selectedRecipient, self.selectedAssetSymbol, value, uuid, self.sendType, self.selectedTokenName, self.selectedTokenIsOwnerToken)
self.delegate.authenticateAndTransfer(self.selectedSenderAccount.address(), self.selectedRecipient, self.selectedAssetKey, value, uuid, self.sendType, self.selectedTokenName, self.selectedTokenIsOwnerToken)
proc suggestedRoutesReady*(self: View, suggestedRoutes: QVariant) {.signal.}
proc setTransactionRoute*(self: View, routes: TransactionRoutes) =
@ -221,7 +221,7 @@ QtObject:
discard
return self.delegate.suggestedRoutes(self.selectedSenderAccount.address(), self.selectedRecipient,
parsedAmount, self.selectedAssetSymbol, self.fromNetworksModel.getRouteDisabledNetworkChainIds(),
parsedAmount, self.selectedAssetKey, self.fromNetworksModel.getRouteDisabledNetworkChainIds(),
self.toNetworksModel.getRouteDisabledNetworkChainIds(), self.toNetworksModel.getRoutePreferredNetworkChainIds(),
self.sendType, self.fromNetworksModel.getRouteLockedChainIds())
@ -276,7 +276,7 @@ QtObject:
self.fromNetworksModel.reset()
self.toNetworksModel.reset()
self.transactionRoutes = newTransactionRoutes()
self.selectedAssetSymbol = ""
self.selectedAssetKey = ""
self.showUnPreferredChains = false
proc getLayer1NetworkChainId*(self: View): string =

View File

@ -853,5 +853,5 @@ proc getCurrencyFormat*(self: Controller, symbol: string): CurrencyFormatDto =
proc getTotalCurrencyBalance*(self: Controller, address: string, chainIds: seq[int]): float64 =
return self.walletAccountService.getTotalCurrencyBalance(@[address], chainIds)
proc parseCurrencyValue*(self: Controller, symbol: string, amountInt: UInt256): float64 =
return self.walletAccountService.parseCurrencyValue(symbol, amountInt)
proc parseCurrencyValueByTokensKey*(self: Controller, tokensKey: string, amountInt: UInt256): float64 =
return self.walletAccountService.parseCurrencyValueByTokensKey(tokensKey, amountInt)

View File

@ -678,7 +678,7 @@ method onTokensRebuilt*[T](self: Module[T], accountAddresses: seq[string], accou
for token in accountTokens:
let filteredBalances = token.balancesPerAccount.filter(b => b.account == accAdd)
for balance in filteredBalances:
totalTokenBalance += self.controller.parseCurrencyValue(token.symbol, balance.balance)
totalTokenBalance += self.controller.parseCurrencyValueByTokensKey(token.tokensKey, balance.balance)
let balance = currencyAmountToItem(totalTokenBalance, currencyFormat)
if not self.getKeyPairForProcessing().isNil:
self.getKeyPairForProcessing().setBalanceForAddress(address, balance)

View File

@ -3,5 +3,8 @@ const
ERC20_TRANSACTION_TYPE* = "erc20"
ERC721_TRANSACTION_TYPE* = "erc721"
SNT_CONTRACT_ADDRESS* = "0x744d70fdbe2ba4cf95131626614a1763df805b9e"
STT_CONTRACT_ADDRESS* = "0x3d6afaa395c31fcd391fe3d562e75fe9e8ec7e6a"
TX_HASH_LEN* = 32 * 2
TX_HASH_LEN_WITH_PREFIX* = TX_HASH_LEN + 2
TX_HASH_LEN_WITH_PREFIX* = TX_HASH_LEN + 2

View File

@ -851,11 +851,10 @@ QtObject:
dataToEmit.errorCode = ComputeFeeErrorCode.Other
self.events.emit(SIGNAL_COMPUTE_AIRDROP_FEE, dataToEmit)
proc getFiatValue*(self: Service, cryptoBalance: float, cryptoSymbol: string): float =
proc getFiatValue(self: Service, cryptoBalance: float, cryptoSymbol: string): float =
if (cryptoSymbol == ""):
return 0.0
let currentCurrency = self.settingsService.getCurrency()
let price = self.tokenService.getTokenPrice(cryptoSymbol, currentCurrency)
let price = self.tokenService.getPriceBySymbol(cryptoSymbol)
return cryptoBalance * price
proc findContractByUniqueId*(self: Service, contractUniqueKey: string): CommunityTokenDto =
@ -1111,7 +1110,7 @@ QtObject:
balanceItem => balanceItem.account == walletAddress.toLower() and
balanceItem.chainId == chainId).map(b => b.balance)
for b in balances:
balance += self.currencyService.parseCurrencyValue(token.symbol, b)
balance += self.currencyService.parseCurrencyValueByTokensKey(token.tokensKey, b)
return balance
proc createComputeFeeArgsFromEthAndBalance(self: Service, ethValue: float, balance: float): ComputeFeeArgs =

View File

@ -116,6 +116,20 @@ QtObject:
return i.toFloat() + r.toFloat() / p.toFloat()
# TODO: left this for activity controller as it uses token symbol
# which may not be unique needs to be refactored. Also needed for
# hasGas api which also needs to be rethought
# https://github.com/status-im/status-desktop/issues/13505
proc parseCurrencyValue*(self: Service, symbol: string, amountInt: UInt256): float64 =
let decimals = self.tokenService.getTokenDecimals(symbol)
let token = self.tokenService.findTokenBySymbol(symbol)
var decimals: int = 0
if token != nil:
decimals = token.decimals
return u256ToFloat(decimals, amountInt)
proc parseCurrencyValueByTokensKey*(self: Service, tokensKey: string, amountInt: UInt256): float64 =
let token = self.tokenService.getTokenBySymbolByTokensKey(tokensKey)
var decimals: int = 0
if token != nil:
decimals = token.decimals
return u256ToFloat(decimals, amountInt)

View File

@ -20,6 +20,7 @@ import app_service/service/token/service as token_service
import app_service/service/eth/utils as status_utils
import app_service/service/eth/dto/coder
import app_service/service/eth/dto/transaction
import app_service/common/wallet_constants
import dto/ens_username_dto
export ens_username_dto
@ -305,17 +306,6 @@ QtObject:
result = 380000
error "error occurred", procName="registerENSGasEstimate", msg = e.msg
proc getStatusToken*(self: Service): TokenDto =
let networkDto = self.networkService.getAppNetwork()
return self.tokenService.findTokenBySymbol(networkDto.chainId, networkDto.sntSymbol())
proc getSNTBalance*(self: Service): string =
let token = self.getStatusToken()
let account = self.walletAccountService.getWalletAccount(0).address
let balance = self.walletAccountService.getTokenBalance(account, self.getChainId(), token.symbol)
return $balance
proc resourceUrl*(self: Service, username: string): (string, string, string) =
try:
let response = status_ens.resourceURL(self.getChainId(), username)
@ -430,13 +420,17 @@ QtObject:
let dto = EnsUsernameDto(chainId: chainId, username: ensUsername)
self.pendingEnsUsernames.incl(dto)
elif txType == PendingTransactionTypeDto.RegisterENS:
let sntContract = self.getStatusToken()
var sntContract: string = ""
if self.settingsService.areTestNetworksEnabled():
sntContract = STT_CONTRACT_ADDRESS
else:
sntContract = SNT_CONTRACT_ADDRESS
let ensUsernameFinal = self.formatUsername(ensUsername, true)
if not self.add(chainId, ensUsernameFinal):
result.error = "failed to add ens username"
error "error occurred", procName="sendEnsTxWithSignatureAndWatch", msg = result.error
return
self.transactionService.watchTransaction(transactionHash, fromAddress, $sntContract.address, $txType,
self.transactionService.watchTransaction(transactionHash, fromAddress, sntContract, $txType,
ensUsernameFinal, chainId)
let dto = EnsUsernameDto(chainId: chainId, username: ensUsernameFinal)
self.pendingEnsUsernames.incl(dto)

View File

@ -103,18 +103,6 @@ proc getExpirationTime*(chainId: int, username: string): int =
let res = status_ens.expireAt(chainId, username)
return fromHex[int](res.result.getStr)
proc getPrice*(chainId: int): Stuint[256] =
try:
let response = status_ens.price(chainId)
if not response.error.isNil:
error "Error getting ens username price, ", errDescription=response.error.message
if response.result.getStr == "0x":
error "Error getting ens username price: 0x"
result = fromHex(Stuint[256], response.result.getStr)
except RpcException as e:
error "Error obtaining expiration time", err=e.msg
proc hex2Token*(input: string, decimals: int): string =
var value = fromHex(Stuint[256], input)

View File

@ -46,12 +46,6 @@ proc `$`*(self: NetworkDto): string =
proc hash*(self: NetworkDto): Hash =
return self.chainId.hash
proc sntSymbol*(self: NetworkDto): string =
if self.chainId == Mainnet:
return "SNT"
else:
return "STT"
type CombinedNetworkDto* = ref object
prod* {.serializedFieldName("Prod").}: NetworkDto
test* {.serializedFieldName("Test").}: NetworkDto

View File

@ -183,10 +183,6 @@ QtObject:
else:
self.revertTransaction($PendingTransactionTypeDto.BuyStickerPack, receivedData.data, receivedData.transactionHash)
proc getStatusToken*(self: Service): TokenDto =
let networkDto = self.networkService.getAppNetwork()
return self.tokenService.findTokenBySymbol(networkDto.chainId, networkDto.sntSymbol())
proc setMarketStickerPacks*(self: Service, strickersJSON: string) {.slot.} =
let stickersResult = Json.decode(strickersJSON, tuple[packs: seq[StickerPackDto], error: string])
@ -469,7 +465,6 @@ QtObject:
error "error occurred", procName="sendBuyingStickersTxWithSignatureAndWatch", msg = result.error
return
let sntContract = self.getStatusToken()
self.transactionService.watchTransaction(
transactionHash,
fromAddress,

View File

@ -119,51 +119,3 @@ const getTokenHistoricalDataTask*: Task = proc(argEncoded: string) {.gcsafe, nim
"error": "Historical market value not found",
}
arg.finish(output)
type
BalanceHistoryTimeInterval* {.pure.} = enum
BalanceHistory7Hours = 0,
BalanceHistory1Month,
BalanceHistory6Months,
BalanceHistory1Year,
BalanceHistoryAllTime
type
GetTokenBalanceHistoryDataTaskArg = ref object of QObjectTaskArg
chainIds: seq[int]
addresses: seq[string]
allAddresses: bool
tokenSymbol: string
currencySymbol: string
timeInterval: BalanceHistoryTimeInterval
const getTokenBalanceHistoryDataTask*: Task = proc(argEncoded: string) {.gcsafe, nimcall.} =
let arg = decode[GetTokenBalanceHistoryDataTaskArg](argEncoded)
var response = %*{}
try:
# status-go time intervals are starting from 1
response = backend.getBalanceHistory(arg.chainIds, arg.addresses, arg.tokenSymbol, arg.currencySymbol, int(arg.timeInterval) + 1).result
let output = %* {
"chainIds": arg.chainIds,
"addresses": arg.addresses,
"allAddresses": arg.allAddresses,
"tokenSymbol": arg.tokenSymbol,
"currencySymbol": arg.currencySymbol,
"timeInterval": int(arg.timeInterval),
"historicalData": response
}
arg.finish(output)
return
except Exception as e:
let output = %* {
"chainIds": arg.chainIds,
"addresses": arg.addresses,
"allAddresses": arg.allAddresses,
"tokenSymbol": arg.tokenSymbol,
"currencySymbol": arg.currencySymbol,
"timeInterval": int(arg.timeInterval),
"error": e.msg,
}
arg.finish(output)

View File

@ -4,7 +4,6 @@ include app_service/common/json_utils
import json_serialization
# TODO: remove once this is moved to wallet_accounts service
const WEEKLY_TIME_RANGE* = 0
const MONTHLY_TIME_RANGE* = 1
const HALF_YEARLY_TIME_RANGE* = 2
@ -47,26 +46,6 @@ proc `$`*(self: TokenDto): string =
image: {self.image}
]"""
# TODO: Remove after https://github.com/status-im/status-desktop/issues/12513
proc newTokenDto*(
address: string,
name: string,
symbol: string,
decimals: int,
chainId: int,
communityId: string = "",
image: string = ""
): TokenDto =
return TokenDto(
address: address,
name: name,
symbol: symbol,
decimals: decimals,
chainId: chainId,
communityId: communityId,
image: image
)
type TokenSourceDto* = ref object of RootObj
name* {.serializedFieldName("name").}: string
tokens* {.serializedFieldName("tokens").}: seq[TokenDto]

View File

@ -11,6 +11,7 @@ import app/core/eventemitter
import app/core/tasks/[qt, threadpool]
import app/core/signals/types
import app_service/common/cache
import app_service/common/wallet_constants
import constants as main_constants
import ./dto, ./service_items
@ -31,7 +32,6 @@ const CRYPTO_SUB_UNITS_TO_FACTOR = {
# Signals which may be emitted by this service:
const SIGNAL_TOKEN_HISTORICAL_DATA_LOADED* = "tokenHistoricalDataLoaded"
const SIGNAL_BALANCE_HISTORY_DATA_READY* = "tokenBalanceHistoryDataReady"
const SIGNAL_TOKENS_LIST_UPDATED* = "tokensListUpdated"
const SIGNAL_TOKENS_DETAILS_ABOUT_TO_BE_UPDATED* = "tokensDetailsAboutToBeUpdated"
const SIGNAL_TOKENS_DETAILS_UPDATED* = "tokensDetailsUpdated"
@ -49,15 +49,6 @@ type
TokenHistoricalDataArgs* = ref object of Args
result*: string
type
TokenBalanceHistoryDataArgs* = ref object of Args
result*: string
type
TokenData* = ref object of RootObj
addresses*: Table[int, string]
decimals*: int
QtObject:
type Service* = ref object of QObject
events: EventEmitter
@ -65,13 +56,6 @@ QtObject:
networkService: network_service.Service
settingsService: settings_service.Service
# TODO: remove these once community usage of this service is removed etc...
tokens: Table[int, seq[TokenDto]]
tokenList: seq[TokenDto]
tokensToAddressesMap: Table[string, TokenData]
priceCache: TimedCache[float64]
sourcesOfTokensList: seq[SupportedSourcesItem]
flatTokenList: seq[TokenItem]
tokenBySymbolList: seq[TokenBySymbolItem]
@ -86,8 +70,6 @@ QtObject:
tokenListUpdatedAt: int64
proc getCurrency*(self: Service): string
proc updateCachedTokenPrice(self: Service, crypto: string, fiat: string, price: float64)
proc jsonToPricesMap(node: JsonNode): Table[string, Table[string, float64]]
proc rebuildMarketData*(self: Service)
proc delete*(self: Service) =
@ -105,10 +87,6 @@ QtObject:
result.threadpool = threadpool
result.networkService = networkService
result.settingsService = settingsService
result.tokens = initTable[int, seq[TokenDto]]()
result.priceCache = newTimedCache[float64]()
result.tokenList = @[]
result.tokensToAddressesMap = initTable[string, TokenData]()
result.sourcesOfTokensList = @[]
result.flatTokenList = @[]
@ -348,65 +326,7 @@ QtObject:
)
self.threadpool.start(arg)
# TODO: Remove after https://github.com/status-im/status-desktop/issues/12513
proc loadData*(self: Service) =
try:
let networks = self.networkService.getNetworks()
for network in networks:
let network = network # TODO https://github.com/nim-lang/Nim/issues/16740
var found = false
for chainId in self.tokens.keys:
if chainId == network.chainId:
found = true
break
if found:
continue
let responseTokens = backend.getTokens(network.chainId)
let default_tokens = Json.decode($responseTokens.result, seq[TokenDto], allowUnknownFields = true)
self.tokens[network.chainId] = default_tokens.filter(
proc(x: TokenDto): bool = x.chainId == network.chainId
)
let nativeToken = newTokenDto(
address = "0x0000000000000000000000000000000000000000",
name = network.nativeCurrencyName,
symbol = network.nativeCurrencySymbol,
decimals = network.nativeCurrencyDecimals,
chainId = network.chainId,
communityID = ""
)
if not self.tokensToAddressesMap.hasKey(network.nativeCurrencySymbol):
self.tokenList.add(nativeToken)
self.tokensToAddressesMap[nativeToken.symbol] = TokenData(
addresses: initTable[int, string](),
)
if not self.tokensToAddressesMap[nativeToken.symbol].addresses.hasKey(nativeToken.chainId):
self.tokensToAddressesMap[nativeToken.symbol].addresses[nativeToken.chainId] = $nativeToken.address
self.tokensToAddressesMap[nativeToken.symbol].decimals = nativeToken.decimals
for token in default_tokens:
if not self.tokensToAddressesMap.hasKey(token.symbol):
self.tokenList.add(token)
self.tokensToAddressesMap[token.symbol] = TokenData(
addresses: initTable[int, string](),
)
if not self.tokensToAddressesMap[token.symbol].addresses.hasKey(token.chainId):
self.tokensToAddressesMap[token.symbol].addresses[token.chainId] = $token.address
self.tokensToAddressesMap[token.symbol].decimals = token.decimals
except Exception as e:
error "Tokens init error", errDesription = e.msg
proc init*(self: Service) =
if(not main_constants.WALLET_ENABLED):
return
self.loadData()
self.events.on(SignalType.Wallet.event) do(e:Args):
var data = WalletSignal(e)
case data.eventType:
@ -472,90 +392,59 @@ QtObject:
else:
return self.tokenPriceTable[symbol]
# TODO: Remove after https://github.com/status-im/status-desktop/issues/12513
proc getTokenList*(self: Service): seq[TokenDto] =
return self.tokenList
proc getTokenBySymbolByTokensKey*(self: Service, key: string): TokenBySymbolItem =
for token in self.tokenBySymbolList:
if token.key == key:
return token
return nil
proc hasContractAddressesForToken*(self: Service, symbol: string): bool =
return self.tokensToAddressesMap.hasKey(symbol)
proc getTokenBySymbolByContractAddr(self: Service, contractAddr: string): TokenBySymbolItem =
for token in self.tokenBySymbolList:
for addrPerChainId in token.addressPerChainId:
if addrPerChainId.address == contractAddr:
return token
return nil
proc getTokenDecimals*(self: Service, symbol: string): int =
if self.hasContractAddressesForToken(symbol):
return self.tokensToAddressesMap[symbol].decimals
proc getStatusTokenKey*(self: Service): string =
var token: TokenBySymbolItem
if self.settingsService.areTestNetworksEnabled():
token = self.getTokenBySymbolByContractAddr(STT_CONTRACT_ADDRESS)
else:
token = self.getTokenBySymbolByContractAddr(SNT_CONTRACT_ADDRESS)
if token != nil:
return token.key
else:
return ""
proc getContractAddressesForToken*(self: Service, symbol: string): Table[int, string] =
if self.hasContractAddressesForToken(symbol):
return self.tokensToAddressesMap[symbol].addresses
proc findTokenBySymbol*(self: Service, chainId: int, symbol: string): TokenDto =
if not self.tokens.hasKey(chainId):
return
for token in self.tokens[chainId]:
# TODO: needed in token permission right now, and activity controller which needs
# to consider that token symbol may not be unique
# https://github.com/status-im/status-desktop/issues/13505
proc findTokenBySymbol*(self: Service, symbol: string): TokenBySymbolItem =
for token in self.tokenBySymbolList:
if token.symbol == symbol:
return token
return nil
# TODO: Shouldnt be needed after accounts assets are restructured
proc findTokenByAddress*(self: Service, networkChainId: int, address: string): TokenDto =
if not self.tokens.hasKey(networkChainId):
return
for token in self.tokens[networkChainId]:
if token.address == address:
return token
# TODO: remove this call once the activty filter mechanism uses tokenKeys instead of the token
# symbol as we may have two tokens with the same symbol in the future. Only tokensKey will be unqiue
# https://github.com/status-im/status-desktop/issues/13505
proc findTokenBySymbolAndChainId*(self: Service, symbol: string, chainId: int): TokenBySymbolItem =
for token in self.tokenBySymbolList:
if token.symbol == symbol:
for addrPerChainId in token.addressPerChainId:
if addrPerChainId.chainId == chainId:
return token
return nil
proc getTokenPriceCacheKey(crypto: string, fiat: string) : string =
return crypto & fiat
# TODO: Perhaps will be removed after transactions in chat is refactored
proc findTokenByAddress*(self: Service, networkChainId: int, address: string): TokenBySymbolItem =
for token in self.tokenBySymbolList:
for addrPerChainId in token.addressPerChainId:
if addrPerChainId.chainId == networkChainId and addrPerChainId.address == address:
return token
return nil
proc getCryptoKeyAndFactor(crypto: string) : (string, float64) =
return CRYPTO_SUB_UNITS_TO_FACTOR.getOrDefault(crypto, (crypto, 1.0))
proc jsonToPricesMap(node: JsonNode) : Table[string, Table[string, float64]] =
result = initTable[string, Table[string, float64]]()
for (symbol, pricePerCurrency) in node.pairs:
result[symbol] = initTable[string, float64]()
for (currency, price) in pricePerCurrency.pairs:
result[symbol][currency] = price.getFloat
proc isCachedTokenPriceRecent*(self: Service, crypto: string, fiat: string): bool =
let (cryptoKey, _) = getCryptoKeyAndFactor(crypto)
let cacheKey = getTokenPriceCacheKey(cryptoKey, fiat)
return self.priceCache.isCached(cacheKey)
proc getTokenPrice*(self: Service, crypto: string, fiat: string): float64 =
let (cryptoKey, factor) = getCryptoKeyAndFactor(crypto)
let cacheKey = getTokenPriceCacheKey(cryptoKey, fiat)
if self.priceCache.isCached(cacheKey):
return self.priceCache.get(cacheKey) * factor
try:
let response = backend.fetchPrices(@[cryptoKey], @[fiat])
let prices = jsonToPricesMap(response.result)
if not prices.hasKey(cryptoKey) or not prices[cryptoKey].hasKey(fiat):
return 0.0
self.updateCachedTokenPrice(cryptoKey, fiat, prices[cryptoKey][fiat])
return prices[cryptoKey][fiat] * factor
except Exception as e:
let errDesription = e.msg
error "error: ", errDesription
return 0.0
proc getCachedTokenPrice*(self: Service, crypto: string, fiat: string, fetchIfNotPresent: bool = false): float64 =
let (cryptoKey, factor) = getCryptoKeyAndFactor(crypto)
let cacheKey = getTokenPriceCacheKey(cryptoKey, fiat)
if self.priceCache.hasKey(cacheKey):
return self.priceCache.get(cacheKey) * factor
elif fetchIfNotPresent:
return self.getTokenPrice(crypto, fiat)
else:
return 0.0
proc updateCachedTokenPrice(self: Service, crypto: string, fiat: string, price: float64) =
let cacheKey = getTokenPriceCacheKey(crypto, fiat)
self.priceCache.set(cacheKey, price)
# History Data
# History Data
proc tokenHistoricalDataResolved*(self: Service, response: string) {.slot.} =
let responseObj = response.parseJson
if (responseObj.kind != JObject):
@ -577,52 +466,7 @@ QtObject:
)
self.threadpool.start(arg)
# TODO: The below two APIS are not linked with generic tokens list but with assets per account and should perhaps be moved to
# wallet_account->token_service.nim and clean up rest of the code too. Callback to process the response of
# fetchHistoricalBalanceForTokenAsJson call
proc tokenBalanceHistoryDataResolved*(self: Service, response: string) {.slot.} =
let responseObj = response.parseJson
if (responseObj.kind != JObject):
warn "blance history response is not a json object"
return
self.events.emit(SIGNAL_BALANCE_HISTORY_DATA_READY, TokenBalanceHistoryDataArgs(
result: response
))
proc fetchHistoricalBalanceForTokenAsJson*(self: Service, addresses: seq[string], allAddresses: bool, tokenSymbol: string, currencySymbol: string, timeInterval: BalanceHistoryTimeInterval) =
# create an empty list of chain ids
var chainIds: seq[int] = @[]
let networks = self.networkService.getNetworks()
for network in networks:
if network.enabled:
if network.nativeCurrencySymbol == tokenSymbol:
chainIds.add(network.chainId)
else:
if not self.tokens.hasKey(network.chainId):
continue
for token in self.tokens[network.chainId]:
if token.symbol == tokenSymbol:
chainIds.add(network.chainId)
if chainIds.len == 0:
error "failed to find a network with the symbol", tokenSymbol
return
let arg = GetTokenBalanceHistoryDataTaskArg(
tptr: cast[ByteAddress](getTokenBalanceHistoryDataTask),
vptr: cast[ByteAddress](self.vptr),
slot: "tokenBalanceHistoryDataResolved",
chainIds: chainIds,
addresses: addresses,
allAddresses: allAddresses,
tokenSymbol: tokenSymbol,
currencySymbol: currencySymbol,
timeInterval: timeInterval
)
self.threadpool.start(arg)
return
# Token Management
proc getTokenPreferences*(self: Service): JsonNode =
try:
let response = backend.getTokenPreferences()

View File

@ -389,8 +389,11 @@ QtObject:
tokenSym = contract_tokenId[1]
else:
let network = self.networkService.getNetwork(chainID)
let token = self.tokenService.findTokenBySymbol(network.chainId, tokenSym)
toAddress = parseAddress(token.address)
let token = self.tokenService.getTokenBySymbolByTokensKey(tokenSym)
if token != nil:
for addressPerChain in token.addressPerChainId:
if addressPerChain.chainId == network.chainId:
toAddress = parseAddress(addressPerChain.address)
let transfer = Transfer(
to: parseAddress(to_addr),
@ -438,7 +441,7 @@ QtObject:
self: Service,
fromAddr: string,
toAddr: string,
tokenSymbol: string,
assetKey: string,
value: string,
uuid: string,
selectedRoutes: seq[TransactionPathDto],
@ -461,6 +464,11 @@ QtObject:
if(selectedRoutes.len > 0):
chainID = selectedRoutes[0].fromNetwork.chainID
var tokenSymbol = ""
let token = self.tokenService.getTokenBySymbolByTokensKey(assetKey)
if token != nil:
tokenSymbol = token.symbol
let network = self.networkService.getNetwork(chainID)
if network.nativeCurrencySymbol == tokenSymbol:
isEthTx = true
@ -499,6 +507,13 @@ QtObject:
proc suggestedRoutes*(self: Service, accountFrom: string, accountTo: string, amount: Uint256, token: string, disabledFromChainIDs,
disabledToChainIDs, preferredChainIDs: seq[int], sendType: SendType, lockedInAmounts: string): SuggestedRoutesDto =
var tokenId: string = ""
if sendType == ERC721Transfer:
tokenId = token
else:
let token = self.tokenService.getTokenBySymbolByTokensKey(token)
if token != nil:
tokenId = token.symbol
let arg = GetSuggestedRoutesTaskArg(
tptr: cast[ByteAddress](getSuggestedRoutesTask),
vptr: cast[ByteAddress](self.vptr),
@ -506,7 +521,7 @@ QtObject:
accountFrom: accountFrom,
accountTo: accountTo,
amount: amount,
token: token,
token: tokenId,
disabledFromChainIDs: disabledFromChainIDs,
disabledToChainIDs: disabledToChainIDs,
preferredChainIDs: preferredChainIDs,

View File

@ -208,3 +208,55 @@ const migrateNonProfileKeycardKeypairToAppTask*: Task = proc(argEncoded: string)
except Exception as e:
error "error migrating a non profile keycard keypair: ", message = e.msg
arg.finish(responseJson)
#################################################
# Async fetching of token balances for a given account(s)
#################################################
type
BalanceHistoryTimeInterval* {.pure.} = enum
BalanceHistory7Hours = 0,
BalanceHistory1Month,
BalanceHistory6Months,
BalanceHistory1Year,
BalanceHistoryAllTime
type
GetTokenBalanceHistoryDataTaskArg = ref object of QObjectTaskArg
chainIds: seq[int]
addresses: seq[string]
allAddresses: bool
tokenSymbol: string
currencySymbol: string
timeInterval: BalanceHistoryTimeInterval
const getTokenBalanceHistoryDataTask*: Task = proc(argEncoded: string) {.gcsafe, nimcall.} =
let arg = decode[GetTokenBalanceHistoryDataTaskArg](argEncoded)
var response = %*{}
try:
# status-go time intervals are starting from 1
response = backend.getBalanceHistory(arg.chainIds, arg.addresses, arg.tokenSymbol, arg.currencySymbol, int(arg.timeInterval) + 1).result
let output = %* {
"chainIds": arg.chainIds,
"addresses": arg.addresses,
"allAddresses": arg.allAddresses,
"tokenSymbol": arg.tokenSymbol,
"currencySymbol": arg.currencySymbol,
"timeInterval": int(arg.timeInterval),
"historicalData": response
}
arg.finish(output)
return
except Exception as e:
let output = %* {
"chainIds": arg.chainIds,
"addresses": arg.addresses,
"allAddresses": arg.allAddresses,
"tokenSymbol": arg.tokenSymbol,
"currencySymbol": arg.currencySymbol,
"timeInterval": int(arg.timeInterval),
"error": e.msg,
}
arg.finish(output)

View File

@ -0,0 +1,34 @@
proc tokenBalanceHistoryDataResolved*(self: Service, response: string) {.slot.} =
let responseObj = response.parseJson
if (responseObj.kind != JObject):
warn "blance history response is not a json object"
return
self.events.emit(SIGNAL_BALANCE_HISTORY_DATA_READY, TokenBalanceHistoryDataArgs(
result: response
))
proc fetchHistoricalBalanceForTokenAsJson*(self: Service, addresses: seq[string], allAddresses: bool, tokenSymbol: string, currencySymbol: string, timeInterval: BalanceHistoryTimeInterval) =
# create an empty list of chain ids
var chainIds: seq[int] = self.networkService.getNetworks().filter(n => n.enabled and n.nativeCurrencySymbol == tokenSymbol).map(n => n.chainId)
if chainIds.len == 0:
let tokenChainIds = self.tokenService.getFlatTokensList().filter(t => t.symbol == tokenSymbol and t.communityId.isEmptyOrWhitespace).map(t => t.chainID)
chainIds = concat(chainIds, tokenChainIds)
if chainIds.len == 0:
error "failed to find a network with the symbol", tokenSymbol
return
let arg = GetTokenBalanceHistoryDataTaskArg(
tptr: cast[ByteAddress](getTokenBalanceHistoryDataTask),
vptr: cast[ByteAddress](self.vptr),
slot: "tokenBalanceHistoryDataResolved",
chainIds: chainIds,
addresses: addresses,
allAddresses: allAddresses,
tokenSymbol: tokenSymbol,
currencySymbol: currencySymbol,
timeInterval: timeInterval
)
self.threadpool.start(arg)
return

View File

@ -65,6 +65,8 @@ QtObject:
proc onMigratedAccountsForKeycardRemoved*(self: Service, response: string) {.slot.}
proc onFetchChainIdForUrl*(self: Service, jsonString: string) {.slot.}
proc onNonProfileKeycardKeypairMigratedToApp*(self: Service, response: string) {.slot.}
proc tokenBalanceHistoryDataResolved*(self: Service, response: string) {.slot.}
proc parseCurrencyValueByTokensKey*(self: Service, tokensKey: string, amountInt: UInt256): float64
proc delete*(self: Service) =
self.closingApp = true
@ -93,3 +95,4 @@ QtObject:
include service_account
include service_token
include service_keycard
include balance_history

View File

@ -526,7 +526,6 @@ proc toggleTestNetworksEnabled*(self: Service) =
discard self.settingsService.toggleTestNetworksEnabled()
let addresses = self.getWalletAddresses()
self.buildAllTokens(addresses, store = true)
self.tokenService.loadData()
self.checkRecentHistory(addresses)
self.events.emit(SIGNAL_WALLET_ACCOUNT_NETWORK_ENABLED_UPDATED, Args())
@ -535,7 +534,6 @@ proc toggleIsSepoliaEnabled*(self: Service) =
self.networkService.resetNetworks()
let addresses = self.getWalletAddresses()
self.buildAllTokens(addresses, store = true)
self.tokenService.loadData()
self.checkRecentHistory(addresses)
self.events.emit(SIGNAL_WALLET_ACCOUNT_NETWORK_ENABLED_UPDATED, Args())

View File

@ -95,7 +95,7 @@ proc getTotalCurrencyBalance*(self: Service, addresses: seq[string], chainIds: s
let price = self.tokenService.getPriceBySymbol(token.symbol)
let balances = token.balancesPerAccount.filter(a => addresses.contains(a.account) and chainIds.contains(a.chainId))
for balance in balances:
totalBalance = totalBalance + (self.currencyService.parseCurrencyValue(token.symbol, balance.balance)*price)
totalBalance = totalBalance + (self.parseCurrencyValueByTokensKey(token.tokensKey, balance.balance)*price)
return totalBalance
proc getGroupedAccountsAssetsList*(self: Service): var seq[GroupedTokenItem] =
@ -137,16 +137,16 @@ proc allAccountsTokenBalance*(self: Service, symbol: string): float64 =
if token.symbol == symbol:
for balance in token.balancesPerAccount:
if accountsAddresses.contains(balance.account):
totalTokenBalance += self.currencyService.parseCurrencyValue(symbol, balance.balance)
totalTokenBalance += self.parseCurrencyValueByTokensKey(token.tokensKey, balance.balance)
return totalTokenBalance
proc getTokenBalance*(self: Service, address: string, chainId: int, symbol: string): float64 =
proc getTokenBalance*(self: Service, address: string, chainId: int, tokensKey: string): float64 =
var totalTokenBalance = 0.0
for token in self.groupedAccountsTokensList:
if token.symbol == symbol:
if token.tokensKey == tokensKey:
let balances = token.balancesPerAccount.filter(b => address == b.account and chainId == b.chainId)
for balance in balances:
totalTokenBalance = totalTokenBalance + self.currencyService.parseCurrencyValue(token.symbol, balance.balance)
totalTokenBalance = totalTokenBalance + self.parseCurrencyValueByTokensKey(token.tokensKey, balance.balance)
return totalTokenBalance
proc checkRecentHistory*(self: Service, addresses: seq[string]) =
@ -164,5 +164,12 @@ proc reloadAccountTokens*(self: Service) =
self.buildAllTokens(addresses, store = true)
self.checkRecentHistory(addresses)
proc parseCurrencyValue*(self: Service, symbol: string, amountInt: UInt256): float64 =
return self.currencyService.parseCurrencyValue(symbol, amountInt)
proc parseCurrencyValueByTokensKey*(self: Service, tokensKey: string, amountInt: UInt256): float64 =
return self.currencyService.parseCurrencyValueByTokensKey(tokensKey, amountInt)
proc getCurrencyFormat(self: Service, tokensKey: string): CurrencyFormatDto =
var symbol: string = ""
for token in self.tokenService.getTokenBySymbolList():
if token.key == tokensKey:
symbol = token.symbol
return self.currencyService.getCurrencyFormat(symbol)

View File

@ -37,6 +37,8 @@ const SIGNAL_KEYCARD_UNLOCKED* = "keycardUnlocked"
const SIGNAL_KEYCARD_UID_UPDATED* = "keycardUidUpdated"
const SIGNAL_KEYCARD_NAME_CHANGED* = "keycardNameChanged"
const SIGNAL_BALANCE_HISTORY_DATA_READY* = "tokenBalanceHistoryDataReady"
#################################################
# Payload sent via above defined signals
#################################################
@ -81,3 +83,7 @@ type ChainIdForUrlArgs* = ref object of Args
success*: bool
url*: string
isMainUrl*: bool
type
TokenBalanceHistoryDataArgs* = ref object of Args
result*: string

View File

@ -99,9 +99,6 @@ rpc(getSavedAddresses, "wakuext"):
rpc(checkConnected, "wallet"):
discard
rpc(getTokens, "wallet"):
chainId: int
rpc(getTokenList, "wallet"):
discard

View File

@ -6,10 +6,13 @@ import StatusQ.Core 0.1
import shared.popups.send.views 1.0
import Storybook 1.0
import Models 1.0
SplitView {
id: root
readonly property var tokensBySymbolModel: TokensBySymbolModel {}
readonly property double maxCryptoBalance: parseFloat(maxCryptoBalanceText.text)
readonly property double rate: parseFloat(rateText.text)
readonly property int decimals: parseInt(decimalsText.text)
@ -28,19 +31,13 @@ SplitView {
id: amountToSendInput
isBridgeTx: false
interactive: true
selectedSymbol: "Crypto"
selectedHolding: tokensBySymbolModel.data[0]
inputIsFiat: fiatInput.checked
maxInputBalance: inputIsFiat ? getFiatValue(root.maxCryptoBalance)
maxInputBalance: inputIsFiat ? root.maxCryptoBalance*amountToSendInput.selectedHolding.marketDetails.currencyPrice.amount
: root.maxCryptoBalance
currentCurrency: "Fiat"
getFiatValue: function(cryptoValue) {
return cryptoValue * root.rate
}
getCryptoValue: function(fiatValue) {
return fiatValue / root.rate
}
formatCurrencyAmount: function(amount, symbol, options = null, locale = null) {
const currencyAmount = {
amount: amount,

View File

@ -67,7 +67,7 @@ SplitView {
rootStore: QtObject {
readonly property string currentCurrency: "EUR"
function getFiatValue(cryptoValue, symbol, currentCurrency) {
function getFiatValue(cryptoValue, symbol) {
return cryptoValue * 0.1;
}

View File

@ -23,7 +23,7 @@ SplitView {
property bool isIncoming: false
Component.onCompleted: {
RootStore.getFiatValue = (cryptoValue, symbol, currentCurrency) => { return (cryptoValue * 1800).toPrecision(2) }
RootStore.getFiatValue = (cryptoValue, symbol) => { return (cryptoValue * 1800).toPrecision(2) }
RootStore.getNetworkIcon = (chainId) => { return "tiny/network/Network=Ethereum" }
RootStore.getLatestBlockNumber = () => { return 4 }
RootStore.hex2Dec = (number) => { return 10 }

View File

@ -16,7 +16,7 @@ QtObject {
return LocaleUtils.currencyAmountToLocaleString(currencyAmount, options, locale)
}
function getFiatValue(balance, cryptoSymbol, fiatSymbol) {
function getFiatValue(balance, cryptoSymbol) {
return balance
}

View File

@ -39,7 +39,7 @@ QtObject {
signal resolvedENS(var resolvedPubKey, var resolvedAddress, var uuid)
}
property string selectedAssetSymbol
property string selectedAssetKey
property bool showUnPreferredChains: false
property int sendType: Constants.SendType.Transfer
property string selectedRecipient
@ -195,8 +195,8 @@ QtObject {
root.selectedRecipient = recipientAddress
}
function setSelectedAssetSymbol(symbol) {
root.selectedAssetSymbol = symbol
function setSelectedAssetKey(assetsKey) {
root.selectedAssetKey = assetsKey
}
function getWei2Eth(wei, decimals) {
@ -245,7 +245,7 @@ QtObject {
root.amountToSend = ""
root.sendType = Constants.SendType.Transfer
root.selectedRecipient = ""
root.selectedAssetSymbol = ""
root.selectedAssetKey = ""
root.showUnPreferredChains = false
root.fromNetworksModel.reset()
root.toNetworksModel.reset()

View File

@ -30,22 +30,16 @@ QtObject {
return stickersModule.getCurrentCurrency()
}
function getFiatValue(balance, cryptoSymbol, fiatSymbol) {
if(!root.stickersModule)
return ""
return stickersModule.getFiatValue(balance, cryptoSymbol, fiatSymbol)
}
function getGasEthValue(gweiValue, gasLimit) {
if(!root.stickersModule)
return ""
return stickersModule.getGasEthValue(gweiValue, gasLimit)
}
function getStatusToken() {
function getStatusTokenKey() {
if(!root.stickersModule)
return ""
return stickersModule.getStatusToken()
return stickersModule.getStatusTokenKey()
}
function estimate(packId, selectedAccount, price, uuid) {

View File

@ -278,6 +278,7 @@ StatusSectionLayout {
id: statusStickerPackClickPopup
StatusStickerPackClickPopup{
transactionStore: root.transactionStore
walletAssetsStore: root.walletAssetsStore
onClosed: {
destroy();
}

View File

@ -13,7 +13,7 @@ SortFilterProxyModel {
property var selectedChannels
property var allChannels
sourceModel: LeftJoinModel {
property var jointModel: LeftJoinModel {
readonly property var channelsModelAlignedKey: SortFilterProxyModel {
sourceModel: root.allChannels
proxyRoles: [
@ -29,6 +29,8 @@ SortFilterProxyModel {
joinRole: "key"
}
sourceModel: jointModel
proxyRoles: [
FastExpressionRole {
name: "text"

View File

@ -184,8 +184,8 @@ StatusSectionLayout {
implicitWidth: parent.width
implicitHeight: parent.height
ensUsernamesStore: root.store.ensUsernamesStore
walletAssetsStore: root.walletAssetsStore
contactsStore: root.store.contactsStore
stickersStore: root.store.stickersStore
networkConnectionStore: root.networkConnectionStore
transactionStore: root.transactionStore
profileContentWidth: d.contentWidth

View File

@ -106,12 +106,6 @@ QtObject {
return ensUsernamesModule.getEnsRegistry()
}
function getSntBalance() {
if(!root.ensUsernamesModule)
return ""
return ensUsernamesModule.getSNTBalance()
}
function getWalletDefaultAddress() {
if(!root.ensUsernamesModule)
return ""
@ -124,28 +118,16 @@ QtObject {
return ensUsernamesModule.getCurrentCurrency()
}
function getFiatValue(balance, cryptoSymbol, fiatSymbol) {
if(!root.ensUsernamesModule)
return ""
return ensUsernamesModule.getFiatValue(balance, cryptoSymbol, fiatSymbol)
}
function getCryptoValue(balance, cryptoSymbol, fiatSymbol) {
if(!root.ensUsernamesModule)
return ""
return ensUsernamesModule.getCryptoValue(balance, cryptoSymbol, fiatSymbol)
}
function getGasEthValue(gweiValue, gasLimit) {
if(!root.ensUsernamesModule)
return ""
return ensUsernamesModule.getGasEthValue(gweiValue, gasLimit)
}
function getStatusToken() {
function getStatusTokenKey() {
if(!root.ensUsernamesModule)
return ""
return ensUsernamesModule.getStatusToken()
return ensUsernamesModule.getStatusTokenKey()
}
function removeEnsUsername(chainId, ensUsername) {

View File

@ -9,23 +9,37 @@ import shared.status 1.0
import shared.popups.send 1.0
import shared.stores.send 1.0
import StatusQ 0.1
import StatusQ.Core 0.1
import StatusQ.Core.Theme 0.1
import StatusQ.Core.Utils 0.1
import StatusQ.Controls 0.1
import StatusQ.Components 0.1
import AppLayouts.Wallet.stores 1.0
Item {
id: root
property var ensUsernamesStore
property var contactsStore
property var stickersStore
required property TransactionStore transactionStore
property WalletAssetsStore walletAssetsStore
property string username: ""
signal backBtnClicked();
signal usernameRegistered(userName: string);
QtObject {
id: d
readonly property var sntToken: ModelUtils.getByKey(root.walletAssetsStore.groupedAccountAssetsModel, "tokensKey", root.ensUsernamesStore.getStatusTokenKey())
readonly property SumAggregator aggregator: SumAggregator {
model: !!d.sntToken && !!d.sntToken.balances ? d.sntToken.balances: nil
roleName: "balance"
}
property real sntBalance: !!sntToken && !!sntToken.decimals ? aggregator.value/(10 ** sntToken.decimals): 0
}
StatusBaseText {
id: sectionTitle
text: qsTr("ENS usernames")
@ -54,7 +68,7 @@ Item {
preSelectedSendType: Constants.SendType.ENSRegister
preSelectedRecipient: root.ensUsernamesStore.getEnsRegisteredAddress()
preDefinedAmountToSend: LocaleUtils.numberToLocaleString(10)
preSelectedHoldingID: JSON.parse(root.stickersStore.getStatusToken()).symbol
preSelectedHoldingID: !!d.sntToken && !!d.sntToken.symbol ? d.sntToken.symbol: ""
preSelectedHoldingType: Constants.TokenType.ERC20
sendTransaction: function() {
if(bestRoutes.count === 1) {
@ -391,10 +405,10 @@ Item {
anchors.bottomMargin: Style.current.padding
anchors.right: parent.right
anchors.rightMargin: Style.current.padding
text: parseFloat(root.ensUsernamesStore.getSntBalance()) < 10 ?
text: d.sntBalance < 10 ?
qsTr("Not enough SNT") :
qsTr("Register")
enabled: parseFloat(root.ensUsernamesStore.getSntBalance()) >= 10 && termsAndConditionsCheckbox.checked
enabled: d.sntBalance >= 10 && termsAndConditionsCheckbox.checked
onClicked: transactionDialog.open()
}
}

View File

@ -7,15 +7,17 @@ import utils 1.0
import shared 1.0
import shared.stores.send 1.0
import AppLayouts.Wallet.stores 1.0
import "../stores"
Item {
id: ensView
property EnsUsernamesStore ensUsernamesStore
property WalletAssetsStore walletAssetsStore
property var contactsStore
property var stickersStore
property var networkConnectionStore
required property TransactionStore transactionStore
@ -246,8 +248,8 @@ Item {
EnsTermsAndConditionsView {
ensUsernamesStore: ensView.ensUsernamesStore
contactsStore: ensView.contactsStore
stickersStore: ensView.stickersStore
transactionStore: ensView.transactionStore
walletAssetsStore: ensView.walletAssetsStore
username: selectedUsername
onBackBtnClicked: back();
onUsernameRegistered: done(userName);

View File

@ -77,7 +77,7 @@ Item {
return outSymbol || !transaction.tokenOutAddress ? formatted : "%1 (%2)".arg(formatted).arg(Utils.compactAddress(transaction.tokenOutAddress, 4))
}
readonly property real feeEthValue: d.details ? RootStore.getFeeEthValue(d.details.totalFees) : 0
readonly property real feeFiatValue: root.isTransactionValid ? RootStore.getFiatValue(d.feeEthValue, Constants.ethToken, RootStore.currentCurrency) : 0
readonly property real feeFiatValue: root.isTransactionValid ? RootStore.getFiatValue(d.feeEthValue, Constants.ethToken) : 0
readonly property int transactionType: root.isTransactionValid ? transaction.txType : Constants.TransactionType.Send
readonly property bool isBridge: d.transactionType === Constants.TransactionType.Bridge
@ -627,7 +627,7 @@ Item {
return RootStore.formatCurrencyAmount(transactionHeader.inCryptoValue, d.inSymbol)
} else if (type === Constants.TransactionType.Bridge) {
// Reduce crypto value by fee value
const valueInCrypto = RootStore.getCryptoValue(transactionHeader.outFiatValue - d.feeFiatValue, d.inSymbol, RootStore.currentCurrency)
const valueInCrypto = RootStore.getCryptoValue(transactionHeader.outFiatValue - d.feeFiatValue, d.inSymbol)
return RootStore.formatCurrencyAmount(valueInCrypto, d.inSymbol)
}
return ""
@ -670,7 +670,7 @@ Item {
let fiatValue
if (!d.symbol) {
const maxFeeEth = RootStore.getFeeEthValue(d.details.maxTotalFees)
fiatValue = RootStore.getFiatValue(maxFeeEth, Constants.ethToken, RootStore.currentCurrency)
fiatValue = RootStore.getFiatValue(maxFeeEth, Constants.ethToken)
} else {
fiatValue = d.feeFiatValue
}
@ -713,7 +713,7 @@ Item {
return ""
if (showMaxFee) {
const maxFeeEth = RootStore.getFeeEthValue(d.details.maxTotalFees)
const maxFeeFiat = RootStore.getFiatValue(d.feeEthValue, "ETH", RootStore.currentCurrency)
const maxFeeFiat = RootStore.getFiatValue(d.feeEthValue, Constants.ethToken)
return RootStore.formatCurrencyAmount(maxFeeFiat, RootStore.currentCurrency)
} else if (showFee) {
return RootStore.formatCurrencyAmount(d.feeFiatValue, RootStore.currentCurrency)

View File

@ -494,6 +494,7 @@ Item {
id: statusStickersPopup
store: appMain.rootChatStore
transactionStore: appMain.transactionStore
walletAssetsStore: appMain.walletAssetsStore
}
}

View File

@ -53,11 +53,11 @@ StatusListItem {
readonly property bool isMultiTransaction: isModelDataValid && modelData.isMultiTransaction
readonly property string currentCurrency: rootStore.currentCurrency
readonly property double cryptoValue: isModelDataValid ? modelData.amount : 0.0
readonly property double fiatValue: isModelDataValid && !isMultiTransaction ? rootStore.getFiatValue(cryptoValue, modelData.symbol, currentCurrency) : 0.0
readonly property double fiatValue: isModelDataValid && !isMultiTransaction ? rootStore.getFiatValue(cryptoValue, modelData.symbol) : 0.0
readonly property double inCryptoValue: isModelDataValid ? modelData.inAmount : 0.0
readonly property double inFiatValue: isModelDataValid && isMultiTransaction ? rootStore.getFiatValue(inCryptoValue, modelData.inSymbol, currentCurrency): 0.0
readonly property double inFiatValue: isModelDataValid && isMultiTransaction ? rootStore.getFiatValue(inCryptoValue, modelData.inSymbol): 0.0
readonly property double outCryptoValue: isModelDataValid ? modelData.outAmount : 0.0
readonly property double outFiatValue: isModelDataValid && isMultiTransaction ? rootStore.getFiatValue(outCryptoValue, modelData.outSymbol, currentCurrency): 0.0
readonly property double outFiatValue: isModelDataValid && isMultiTransaction ? rootStore.getFiatValue(outCryptoValue, modelData.outSymbol): 0.0
readonly property double feeCryptoValue: 0.0 // TODO fill when bridge data is implemented
readonly property double feeFiatValue: 0.0 // TODO fill when bridge data is implemented
readonly property string communityName: isModelDataValid && modelData.communityName ? modelData.communityName : ""
@ -411,7 +411,7 @@ StatusListItem {
// VALUES
const fiatTransactionValue = rootStore.formatCurrencyAmount(isMultiTransaction ? root.outFiatValue : root.fiatValue, root.currentCurrency)
const feeFiatValue = rootStore.getFiatValue(feeEthValue, "ETH", root.currentCurrency)
const feeFiatValue = rootStore.getFiatValue(feeEthValue, Constants.ethToken)
let valuesString = ""
if (!root.isNFT) {
switch(type) {
@ -431,7 +431,7 @@ StatusListItem {
valuesString += qsTr("Amount received %1 (%2)").arg(crypto).arg(fiat) + endl2
} else if (type === Constants.TransactionType.Bridge) {
// Reduce crypto value by fee value
const valueInCrypto = rootStore.getCryptoValue(root.fiatValue - feeFiatValue, modelData.inSymbol, root.currentCurrency)
const valueInCrypto = rootStore.getCryptoValue(root.fiatValue - feeFiatValue, modelData.inSymbol)
const crypto = rootStore.formatCurrencyAmount(valueInCrypto, modelData.inSymbol)
const fiat = rootStore.formatCurrencyAmount(root.fiatValue - feeFiatValue, root.currentCurrency)
valuesString += qsTr("Amount received %1 (%2)").arg(crypto).arg(fiat) + endl2

View File

@ -80,7 +80,7 @@ StatusDialog {
readonly property double maxFiatBalance: isSelectedHoldingValidAsset ? selectedHolding.currentCurrencyBalance : 0
readonly property double maxCryptoBalance: isSelectedHoldingValidAsset ? selectedHolding.currentBalance : 0
readonly property double maxInputBalance: amountToSendInput.inputIsFiat ? maxFiatBalance : maxCryptoBalance
readonly property string inputSymbol: amountToSendInput.inputIsFiat ? currencyStore.currentCurrency : store.selectedAssetSymbol
readonly property string inputSymbol: amountToSendInput.inputIsFiat ? currencyStore.currentCurrency : !!d.selectedHolding && !!d.selectedHolding.symbol ? d.selectedHolding.symbol: ""
readonly property bool errorMode: popup.isLoading || !recipientLoader.ready ? false : errorType !== Constants.NoError || networkSelector.errorMode || !amountToSendInput.inputNumberValid
readonly property string uuid: Utils.uuid()
property bool isPendingTx: false
@ -124,12 +124,12 @@ StatusDialog {
if (d.selectedHoldingType === Constants.TokenType.ERC20) {
if(!d.ensOrStickersPurpose && store.sendType !== Constants.SendType.Bridge)
store.setSendType(Constants.SendType.Transfer)
store.setSelectedAssetSymbol(selectedHolding.symbol)
store.setSelectedAssetKey(selectedHolding.tokensKey)
store.setSelectedTokenIsOwnerToken(false)
} else if (d.selectedHoldingType === Constants.TokenType.ERC721) {
store.setSendType(Constants.SendType.ERC721Transfer)
amountToSendInput.input.text = 1
store.setSelectedAssetSymbol(selectedHolding.contractAddress+":"+selectedHolding.tokenId)
store.setSelectedAssetKey(selectedHolding.contractAddress+":"+selectedHolding.tokenId)
store.setRouteEnabledFromChains(selectedHolding.chainId)
store.updateRoutePreferredChains(selectedHolding.chainId)
store.setSelectedTokenIsOwnerToken(selectedHolding.communityPrivilegesLevel === Constants.TokenPrivilegesLevel.Owner)
@ -324,7 +324,7 @@ StatusDialog {
Layout.fillWidth: true
isBridgeTx: d.isBridgeTx
interactive: popup.interactive
selectedSymbol: store.selectedAssetSymbol
selectedHolding: d.selectedHolding
maxInputBalance: d.maxInputBalance
currentCurrency: d.currencyStore.currentCurrency
@ -332,14 +332,6 @@ StatusDialog {
? holdingSelector.selectedItem.decimals
: 0
getFiatValue: function(cryptoValue) {
return selectedSymbol ? d.currencyStore.getFiatValue(cryptoValue, selectedSymbol, currentCurrency) : 0.0
}
getCryptoValue: function(fiatValue) {
return selectedSymbol ? d.currencyStore.getCryptoValue(fiatValue, selectedSymbol, currentCurrency) : 0.0
}
formatCurrencyAmount: d.currencyStore.formatCurrencyAmount
onReCalculateSuggestedRoute: popup.recalculateRoutesAndFees()
input.input.tabNavItem: recipientLoader.item
@ -356,16 +348,13 @@ StatusDialog {
visible: !!popup.bestRoutes && popup.bestRoutes !== undefined &&
popup.bestRoutes.count > 0 && amountToSendInput.inputNumberValid
isLoading: popup.isLoading
selectedSymbol: store.selectedAssetSymbol
selectedHolding: d.selectedHolding
isBridgeTx: d.isBridgeTx
cryptoValueToReceive: d.totalAmountToReceive
inputIsFiat: amountToSendInput.inputIsFiat
minCryptoDecimals: amountToSendInput.minReceiveCryptoDecimals
minFiatDecimals: amountToSendInput.minReceiveFiatDecimals
currentCurrency: d.currencyStore.currentCurrency
getFiatValue: function(cryptoValue) {
return d.currencyStore.getFiatValue(cryptoValue, selectedSymbol, currentCurrency)
}
formatCurrencyAmount: d.currencyStore.formatCurrencyAmount
}
}
@ -505,7 +494,7 @@ StatusDialog {
anchors.leftMargin: Style.current.bigPadding
anchors.rightMargin: Style.current.bigPadding
visible: recipientLoader.ready && !!d.selectedHolding && networkSelector.advancedOrCustomMode && amountToSendInput.inputNumberValid
selectedTokenSymbol: store.selectedAssetSymbol
selectedTokenSymbol: d.selectedHolding.symbol
isLoading: popup.isLoading
bestRoutes: popup.bestRoutes
store: popup.store
@ -533,8 +522,10 @@ StatusDialog {
popup.bestRoutes = txRoutes.suggestedRoutes
let gasTimeEstimate = txRoutes.gasTimeEstimate
d.totalTimeEstimate = popup.store.getLabelForEstimatedTxTime(gasTimeEstimate.totalTime)
d.totalFeesInFiat = d.currencyStore.getFiatValue( gasTimeEstimate.totalFeesInEth, "ETH", d.currencyStore.currentCurrency) +
d.currencyStore.getFiatValue(gasTimeEstimate.totalTokenFees, fees.selectedTokenSymbol, d.currencyStore.currentCurrency)
let totalTokenFeesInFiat = 0
if (!!d.selectedHolding && !!d.selectedHolding.marketDetails && !!d.selectedHolding.marketDetails.currencyPrice)
totalTokenFeesInFiat = gasTimeEstimate.totalTokenFees * d.selectedHolding.marketDetails.currencyPrice.amount
d.totalFeesInFiat = d.currencyStore.getFiatValue(gasTimeEstimate.totalFeesInEth, Constants.ethToken) + totalTokenFeesInFiat
d.totalAmountToReceive = popup.store.getWei2Eth(txRoutes.amountToReceive, d.selectedHolding.decimals)
networkSelector.toNetworksList = txRoutes.toNetworksModel
popup.isLoading = false

View File

@ -49,13 +49,13 @@ Item {
statusListItemIcon.active: true
statusListItemIcon.opacity: modelData.isFirstSimpleTx
title: qsTr("%1 transaction fee").arg(root.getNetworkName(modelData.fromNetwork))
subTitle: root.formatCurrencyAmount(totalGasAmountEth, "ETH")
subTitle: root.formatCurrencyAmount(totalGasAmountEth, Constants.ethToken)
property double totalGasAmountEth: {
let maxFees = modelData.gasFees.maxFeePerGasM
let gasPrice = modelData.gasFees.eip1559Enabled ? maxFees : modelData.gasFees.gasPrice
return root.getGasEthValue(gasPrice , modelData.gasAmount)
}
property double totalGasAmountFiat: root.getFiatValue(totalGasAmountEth, "ETH", root.currentCurrency)
property double totalGasAmountFiat: root.getFiatValue(totalGasAmountEth, Constants.ethToken)
statusListItemSubTitle.width: listItem.width/2 - Style.current.smallPadding
statusListItemSubTitle.elide: Text.ElideMiddle
statusListItemSubTitle.wrapMode: Text.NoWrap
@ -83,8 +83,8 @@ Item {
statusListItemIcon.opacity: modelData.isFirstSimpleTx
title: qsTr("Approve %1 %2 Bridge").arg(root.getNetworkName(modelData.fromNetwork)).arg(root.selectedTokenSymbol)
property double approvalGasFees: modelData.approvalGasFees
property string approvalGasFeesSymbol: "ETH"
property double approvalGasFeesFiat: root.getFiatValue(approvalGasFees, approvalGasFeesSymbol, root.currentCurrency)
property string approvalGasFeesSymbol: Constants.ethToken
property double approvalGasFeesFiat: root.getFiatValue(approvalGasFees, approvalGasFeesSymbol)
subTitle: root.formatCurrencyAmount(approvalGasFees, approvalGasFeesSymbol)
statusListItemSubTitle.width: listItem1.width/2 - Style.current.smallPadding
statusListItemSubTitle.elide: Text.ElideMiddle
@ -115,7 +115,7 @@ Item {
statusListItemIcon.opacity: modelData.isFirstBridgeTx
title: qsTr("%1 -> %2 bridge").arg(root.getNetworkName(modelData.fromNetwork)).arg(root.getNetworkName(modelData.toNetwork))
property double tokenFees: modelData.tokenFees
property double tokenFeesFiat: root.getFiatValue(tokenFees, root.selectedTokenSymbol, root.currentCurrency)
property double tokenFeesFiat: root.getFiatValue(tokenFees, root.selectedTokenSymbol)
subTitle: root.formatCurrencyAmount(tokenFees, root.selectedTokenSymbol)
visible: modelData.bridgeName !== "Transfer"
statusListItemSubTitle.width: 100

View File

@ -10,7 +10,7 @@ import shared.stores 1.0
ColumnLayout {
id: root
property string selectedSymbol
property var selectedHolding
property bool isLoading: false
property double cryptoValueToReceive
property bool isBridgeTx: false
@ -18,21 +18,21 @@ ColumnLayout {
property string currentCurrency
property int minCryptoDecimals: 0
property int minFiatDecimals: 0
property var getFiatValue: function(cryptoValue) {}
property var formatCurrencyAmount: function() {}
QtObject {
id: d
readonly property string fiatValue: {
if(!root.selectedSymbol || !cryptoValueToReceive)
if(!root.selectedHolding || !root.selectedHolding.symbol || !root.selectedHolding.marketDetails ||
!root.selectedHolding.marketDetails.currencyPrice || !cryptoValueToReceive)
return LocaleUtils.numberToLocaleString(0, 2)
let fiatValue = root.getFiatValue(cryptoValueToReceive, root.selectedSymbol, root.currentCurrency)
let fiatValue = cryptoValueToReceive * root.selectedHolding.marketDetails.currencyPrice.amount
return root.formatCurrencyAmount(fiatValue, root.currentCurrency, inputIsFiat ? {"minDecimals": root.minFiatDecimals, "stripTrailingZeroes": true} : {})
}
readonly property string cryptoValue: {
if(!root.selectedSymbol || !cryptoValueToReceive)
if(!root.selectedHolding || !root.selectedHolding.symbol || !cryptoValueToReceive)
return LocaleUtils.numberToLocaleString(0, 2)
return root.formatCurrencyAmount(cryptoValueToReceive, root.selectedSymbol, !inputIsFiat ? {"minDecimals": root.minCryptoDecimals, "stripTrailingZeroes": true} : {})
return root.formatCurrencyAmount(cryptoValueToReceive, root.selectedHolding.symbol, !inputIsFiat ? {"minDecimals": root.minCryptoDecimals, "stripTrailingZeroes": true} : {})
}
}

View File

@ -25,7 +25,7 @@ ColumnLayout {
readonly property int minReceiveFiatDecimals:
inputIsFiat ? minSendFiatDecimals + 1 : 0
property string selectedSymbol // Crypto asset symbol like ETH
property var selectedHolding // Crypto asset symbol like ETH
property string currentCurrency // Fiat currency symbol like USD
property int multiplierIndex // How divisible the token is, 18 for ETH
@ -42,10 +42,6 @@ ColumnLayout {
readonly property alias cryptoValueToSendFloat: d.cryptoValueToSend
property var getFiatValue: cryptoValue => {}
property var getCryptoValue: fiatValue => {}
property var formatCurrencyAmount:
(amount, symbol, options = null, locale = null) => {}
@ -59,8 +55,11 @@ ColumnLayout {
Binding on cryptoValueToSend {
value: {
root.selectedSymbol
return root.inputIsFiat ? root.getCryptoValue(d.fiatValueToSend)
root.selectedHolding
if(!root.selectedHolding || !root.selectedHolding.marketDetails || !root.selectedHolding.marketDetails.currencyPrice) {
return 0
}
return root.inputIsFiat ? d.fiatValueToSend/root.selectedHolding.marketDetails.currencyPrice.amount
: d.inputNumber
}
delayed: true
@ -68,13 +67,18 @@ ColumnLayout {
Binding on fiatValueToSend {
value: {
root.selectedSymbol
root.selectedHolding
if(!root.selectedHolding || !root.selectedHolding.marketDetails || !root.selectedHolding.marketDetails.currencyPrice) {
return 0
}
return root.inputIsFiat ? d.inputNumber
: root.getFiatValue(d.cryptoValueToSend)
: d.cryptoValueToSend * root.selectedHolding.marketDetails.currencyPrice.amount
}
delayed: true
}
readonly property string selectedSymbol: !!root.selectedHolding && !!root.selectedHolding.symbol ? root.selectedHolding.symbol: ""
readonly property string cryptoValueRawToSend: {
if (!root.inputNumberValid)
return "0"
@ -119,7 +123,7 @@ ColumnLayout {
property double topAmountToSend: !inputIsFiat ? d.cryptoValueToSend
: d.fiatValueToSend
property string topAmountSymbol: !inputIsFiat ? root.selectedSymbol
property string topAmountSymbol: !inputIsFiat ? d.selectedSymbol
: root.currentCurrency
Layout.alignment: Qt.AlignLeft
@ -175,7 +179,7 @@ ColumnLayout {
property double bottomAmountToSend: inputIsFiat ? d.cryptoValueToSend
: d.fiatValueToSend
property string bottomAmountSymbol: inputIsFiat ? selectedSymbol
property string bottomAmountSymbol: inputIsFiat ? d.selectedSymbol
: currentCurrency
Layout.alignment: Qt.AlignLeft | Qt.AlignBottom

View File

@ -86,6 +86,7 @@ Item {
errorMode: root.errorMode
errorType: root.errorType
toNetworksList: root.toNetworksList
selectedSymbol: root.selectedAsset.symbol
weiToEth: function(wei) {
if(!!selectedAsset && root.selectedAsset !== undefined)
return parseFloat(store.getWei2Eth(wei, root.selectedAsset.decimals))

View File

@ -27,6 +27,7 @@ RowLayout {
property var reCalculateSuggestedRoute: function() {}
property bool errorMode: false
property int errorType: Constants.NoError
property string selectedSymbol
spacing: 10
StatusRoundIcon {
@ -102,7 +103,7 @@ RowLayout {
if(root.isERC721Transfer)
return ""
let amountOut = root.weiToEth(model.amountOut)
return root.formatCurrencyAmount(amountOut, store.selectedAssetSymbol, {"minDecimals": root.minReceiveCryptoDecimals})
return root.formatCurrencyAmount(amountOut, root.selectedSymbol, {"minDecimals": root.minReceiveCryptoDecimals})
}
statusListItemSubTitle.color: root.errorMode ? Theme.palette.dangerColor1 : Theme.palette.primaryColor1
asset.width: 32
@ -125,7 +126,7 @@ RowLayout {
rightPadding: 5
implicitWidth: 410
title: chainName
subTitle: root.formatCurrencyAmount(tokenBalance.amount, store.selectedAssetSymbol)
subTitle: root.formatCurrencyAmount(tokenBalance.amount, root.selectedSymbol)
statusListItemSubTitle.color: Theme.palette.primaryColor1
asset.width: 32
asset.height: 32

View File

@ -5,6 +5,7 @@ import QtGraphicalEffects 1.0
import QtQml.Models 2.13
import StatusQ.Core 0.1
import StatusQ.Core.Utils 0.1
import StatusQ.Controls 0.1
import utils 1.0
@ -18,6 +19,7 @@ import shared.stores.send 1.0
//TODO remove this dependency!
import AppLayouts.Chat.stores 1.0
import AppLayouts.Wallet.stores 1.0
Item {
id: root
@ -25,6 +27,7 @@ Item {
property var store
property var stickerPacks: StickerPackData {}
required property TransactionStore transactionStore
required property WalletAssetsStore walletAssetsStore
property string packId
property bool marketVisible
@ -206,7 +209,10 @@ Item {
preSelectedSendType: Constants.SendType.StickersBuy
preSelectedRecipient: root.store.stickersStore.getStickersMarketAddress()
preDefinedAmountToSend: LocaleUtils.numberToLocaleString(parseFloat(price))
preSelectedHoldingID: JSON.parse(root.store.stickersStore.getStatusToken()).symbol
preSelectedHoldingID: {
let token = ModelUtils.getByKey(root.walletAssetsStore.groupedAccountAssetsModel, "tokensKey", root.store.stickersStore.getStatusTokenKey())
return !!token && !!token.symbol ? token.symbol : ""
}
preSelectedHoldingType: Constants.TokenType.ERC20
sendTransaction: function() {
if(bestRoutes.count === 1) {

View File

@ -15,6 +15,7 @@ import shared.stores.send 1.0
//TODO remove this dependency!
import "../../../app/AppLayouts/Chat/stores"
import AppLayouts.Wallet.stores 1.0
// TODO: replace with StatusModal
ModalPopup {
@ -24,6 +25,7 @@ ModalPopup {
property var store
required property TransactionStore transactionStore
required property WalletAssetsStore walletAssetsStore
property string thumbnail: ""
property string name: ""
property string author: ""
@ -75,7 +77,10 @@ ModalPopup {
preSelectedSendType: Constants.SendType.StickersBuy
preSelectedRecipient: stickerPackDetailsPopup.store.stickersStore.getStickersMarketAddress()
preDefinedAmountToSend: LocaleUtils.numberToLocaleString(parseFloat(price))
preSelectedHoldingID: JSON.parse(stickerPackDetailsPopup.store.stickersStore.getStatusToken()).symbol
preSelectedHoldingID: {
let token = ModelUtils.getByKey(root.walletAssetsStore.groupedAccountAssetsModel, "tokensKey", stickerPackDetailsPopup.store.stickersStore.getStatusTokenKey())
return !!token && !!token.symbol ? token.symbol : ""
}
preSelectedHoldingType: Constants.TokenType.ERC20
sendTransaction: function() {
if(bestRoutes.count === 1) {

View File

@ -13,12 +13,14 @@ import StatusQ.Controls 0.1
import StatusQ.Components 0.1
//TODO improve this!
import AppLayouts.Chat.stores 1.0
import AppLayouts.Wallet.stores 1.0
Popup {
id: root
property var store
required property TransactionStore transactionStore
required property WalletAssetsStore walletAssetsStore
signal stickerSelected(string hashId, string packId, string url)
@ -98,6 +100,7 @@ Popup {
Layout.fillHeight: true
store: root.store
transactionStore: root.transactionStore
walletAssetsStore: root.walletAssetsStore
stickerPacks: d.stickerPackList
packId: stickerPackListView.selectedPackId
marketVisible: d.stickerPacksLoaded && d.online

View File

@ -988,13 +988,13 @@ QtObject {
return LocaleUtils.currencyAmountToLocaleString(currencyAmount, options, locale)
}
function getFiatValue(cryptoAmount, cryptoSymbol, fiatSymbol) {
var amount = profileSectionStore.profileSectionModuleInst.ensUsernamesModule.getFiatValue(cryptoAmount, cryptoSymbol, fiatSymbol)
function getFiatValue(cryptoAmount, cryptoSymbol) {
var amount = profileSectionStore.profileSectionModuleInst.ensUsernamesModule.getFiatValue(cryptoAmount, cryptoSymbol)
return parseFloat(amount)
}
function getCryptoValue(fiatAmount, cryptoSymbol, fiatSymbol) {
var amount = profileSectionStore.profileSectionModuleInst.ensUsernamesModule.getCryptoValue(fiatAmount, cryptoSymbol, fiatSymbol)
function getCryptoValue(fiatAmount, cryptoSymbol) {
var amount = profileSectionStore.profileSectionModuleInst.ensUsernamesModule.getCryptoValue(fiatAmount, cryptoSymbol)
return parseFloat(amount)
}

View File

@ -177,12 +177,12 @@ QtObject {
return currencyStore.getCurrencyAmount(amount, symbol)
}
function getFiatValue(balance, cryptoSymbol, fiatSymbol) {
return currencyStore.getFiatValue(balance, cryptoSymbol, fiatSymbol)
function getFiatValue(balance, cryptoSymbol) {
return currencyStore.getFiatValue(balance, cryptoSymbol)
}
function getCryptoValue(balance, cryptoSymbol, fiatSymbol) {
return currencyStore.getCryptoValue(balance, cryptoSymbol, fiatSymbol)
function getCryptoValue(balance, cryptoSymbol) {
return currencyStore.getCryptoValue(balance, cryptoSymbol)
}
function getGasEthValue(gweiValue, gasLimit) {

View File

@ -40,7 +40,7 @@ QtObject {
}
]
}
property string selectedAssetSymbol: walletSectionSendInst.selectedAssetSymbol
property string selectedAssetKey: walletSectionSendInst.selectedAssetKey
property bool showUnPreferredChains: walletSectionSendInst.showUnPreferredChains
property int sendType: walletSectionSendInst.sendType
property string selectedRecipient: walletSectionSendInst.selectedRecipient
@ -209,8 +209,8 @@ QtObject {
fromNetworksModel.setRouteEnabledFromChains(chainId)
}
function setSelectedAssetSymbol(symbol) {
walletSectionSendInst.setSelectedAssetSymbol(symbol)
function setSelectedAssetKey(assetsKey) {
walletSectionSendInst.setSelectedAssetKey(assetsKey)
}
function getNetworkName(chainId) {

View File

@ -67,8 +67,7 @@ Item {
if (!tokenAmount || !token.symbol) {
return "0"
}
var defaultFiatSymbol = root.store.currentCurrency
return root.store.getFiatValue(tokenAmount, token.symbol, defaultFiatSymbol) + " " + defaultFiatSymbol
return root.store.getFiatValue(tokenAmount, token.symbol) + " " + defaultFiatSymbol
}
property int state: transactionParamsObject.commandState