Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ref(transfer token switch): Refactor for token switching at transfer #6895

Merged
merged 44 commits into from
Aug 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
dafc0b5
ref: refactored useToken and crosschains tokens
hassnian Aug 23, 2023
cfee756
fix: balance issue
hassnian Aug 23, 2023
b2fdb6b
ref: isTokenValidForChain and removed unused vars
hassnian Aug 23, 2023
ff9c13e
Merge branch 'main' into issue-6857
hassnian Aug 23, 2023
c7d8366
fix: duplicate import
hassnian Aug 23, 2023
dbd5b6c
fix: unsued prefix param
hassnian Aug 23, 2023
784f547
ref: removed extra enum and used existing type
hassnian Aug 23, 2023
7d8a50b
Merge branch 'main' into issue-6857
hassnian Aug 23, 2023
dbada4f
add: default token and mutilchain tokenDecimals
hassnian Aug 23, 2023
1aa97df
ref: reduce functino size , exceeds 25 allowed
hassnian Aug 23, 2023
4c110e9
Merge branch 'main' into issue-6857
hassnian Aug 23, 2023
09d3a73
Revert "ref: reduce functino size , exceeds 25 allowed"
hassnian Aug 23, 2023
e32933d
ref: TokenDecimals type
hassnian Aug 23, 2023
856e26d
add: token trasnfer
hassnian Aug 24, 2023
8dd4ccf
fix: add null
hassnian Aug 24, 2023
fd1bea5
fix: add null check
hassnian Aug 24, 2023
eadfd34
Merge branch 'main' into issue-6857
hassnian Aug 24, 2023
569468c
Merge branch 'main' into issue-6857
hassnian Aug 24, 2023
e80fd55
Merge branch 'main' into issue-6857
hassnian Aug 24, 2023
6ca1a66
Merge branch 'main' into issue-6857
hassnian Aug 24, 2023
9ce141b
fix: sonarcloud issues
hassnian Aug 24, 2023
9b6ac48
ref: rename
hassnian Aug 24, 2023
fa6544e
Merge branch 'main' into issue-6857
hassnian Aug 25, 2023
6124b55
add: filter by current network
hassnian Aug 25, 2023
887292c
Merge branch 'issue-6857' of https://github.com/hassnian/nft-gallery …
hassnian Aug 25, 2023
89e04e8
fix: token query not synced
hassnian Aug 25, 2023
7390bb4
remove: not current chain case
hassnian Aug 25, 2023
ef2f650
fix: on token switch update field on usd value
hassnian Aug 25, 2023
727eabc
ref: useTokens tokens current chain
hassnian Aug 25, 2023
9cd6e52
ref: simplifying code
hassnian Aug 25, 2023
c37900c
fix: clear token from query
hassnian Aug 25, 2023
a1349c2
Merge branch 'main' into issue-6857
hassnian Aug 26, 2023
eadc65c
add: back all tokens visible
hassnian Aug 26, 2023
3818269
ref: getChainTokenIds
hassnian Aug 26, 2023
01368a2
Merge branch 'main' into issue-6857
hassnian Aug 27, 2023
131c239
ref: link token switch to native tokens
hassnian Aug 27, 2023
fd040c6
ref: 🧽 multichain assets support
hassnian Aug 27, 2023
478019f
ref: 🧼 removed multichain assets changes
hassnian Aug 27, 2023
77f76e3
ref: 🧼 moved networkToPrefix to original file
hassnian Aug 27, 2023
4a7823c
Merge branch 'main' into issue-6857
hassnian Aug 27, 2023
988a670
del: remove unused import
hassnian Aug 27, 2023
eaa051d
Merge branch 'issue-6857' of https://github.com/hassnian/nft-gallery …
hassnian Aug 27, 2023
7d29b01
fix: bsx balance showing KSM instate of BSX
hassnian Aug 28, 2023
cdc383a
fix: add defaul value
hassnian Aug 28, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 82 additions & 79 deletions components/transfer/Transfer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,6 @@ import {
} from '@/utils/format/balance'
import { getNumberSumOfObjectField } from '@/utils/math'
import { useFiatStore } from '@/stores/fiat'
import { useIdentityStore } from '@/stores/identity'
import Avatar from '@/components/shared/Avatar.vue'
import Identity from '@/components/identity/IdentityIndex.vue'
import { getMovedItemToFront } from '@/utils/objects'
Expand All @@ -260,6 +259,7 @@ import {
} from '@kodadot1/brick'
import TransferTokenTabs, { TransferTokenTab } from './TransferTokenTabs.vue'
import { TokenDetails } from '@/composables/useToken'
import { ApiPromise } from '@polkadot/api'
const Money = defineAsyncComponent(
() => import('@/components/shared/format/Money.vue')
)
Expand All @@ -269,9 +269,9 @@ const router = useRouter()
const { $consola, $i18n } = useNuxtApp()
const { unit, decimals } = useChain()
const { apiInstance } = useApi()
const { urlPrefix, setUrlPrefix } = usePrefix()
const { urlPrefix } = usePrefix()
const { isLogIn, accountId } = useAuth()
const identityStore = useIdentityStore()
const { getBalance } = useBalance()
const { fetchFiatPrice, getCurrentTokenValue } = useFiatStore()
const { initTransactionLoader, isLoading, resolveStatus, status } =
useTransactionStatus()
Expand All @@ -284,12 +284,14 @@ export type TargetAddress = {
token?: number | string
}
const isMobile = computed(() => useWindowSize().width.value <= 1024)
const balance = computed(() => getBalance(unit.value) || 0)

const transactionValue = ref('')
const sendSameAmount = ref(false)
const displayUnit = ref<'token' | 'usd'>('token')
const { getTokenIconBySymbol } = useIcon()
const { tokens, getPrefixByToken, availableTokens } = useToken()

const { tokens } = useToken()

const selectedTabFirst = ref(true)
const tokenIcon = computed(() => getTokenIconBySymbol(unit.value))
Expand All @@ -308,8 +310,6 @@ const displayTotalValue = computed(() =>
: [`${totalTokenAmount.value} ${unit.value}`, `$${totalUsdValue.value}`]
)

const balance = computed(() => identityStore.getAuthBalance)

const disabled = computed(
() =>
!isLogIn.value ||
Expand All @@ -319,20 +319,16 @@ const disabled = computed(

const handleTokenSelect = (newToken: string) => {
selectedTabFirst.value = false
const token = tokens.value.find((t) => t.symbol === newToken)

if (token) {
const chain = getPrefixByToken(token.symbol)

if (!chain) {
$consola.error(
`[ERR: INVALID TOKEN] Chain for token ${token.symbol} is not valid`
)
return
}
const token = tokens.value.find((t) => t.symbol === newToken)

setUrlPrefix(chain)
if (!token) {
return
}

routerReplace({
params: { prefix: token.defaultChain },
Jarsen136 marked this conversation as resolved.
Show resolved Hide resolved
})
}

const generateTokenTabs = (
Expand Down Expand Up @@ -478,11 +474,7 @@ const unifyAddressAmount = (target: TargetAddress) => {

const updateTargetAdressesOnTokenSwitch = () => {
targetAddresses.value.forEach((targetAddress) => {
if (displayUnit.value === 'usd') {
onUsdFieldChange(targetAddress)
} else {
onAmountFieldChange(targetAddress)
}
onUsdFieldChange(targetAddress)
})
}

Expand All @@ -503,6 +495,46 @@ const handleOpenConfirmModal = () => {
}
}

const getAmountToTransfer = (amount: number, decimals: number) =>
String(calculateBalance(Number(amount), decimals))

interface TransferParams {
api: ApiPromise
decimals: number
}

const getMultipleAddressesTransferParams = ({
api,
decimals,
}: TransferParams) => {
const arg = [
targetAddresses.value.map((target) => {
const amountToTransfer = getAmountToTransfer(
target.token as number,
decimals
)

return api.tx.balances.transfer(
target.address as string,
amountToTransfer
)
}),
]

return [api.tx.utility.batch, arg]
}

const getSingleAddressTransferParams = ({ api, decimals }: TransferParams) => {
const target = targetAddresses.value[0]

const amountToTransfer = getAmountToTransfer(target.token as number, decimals)

return [
api.tx.balances.transfer,
[target.address as string, amountToTransfer],
]
}

const submit = async (
event: any,
usedNodeUrls: string[] = []
Expand All @@ -514,28 +546,21 @@ const submit = async (
const api = await apiInstance.value

const numOfTargetAddresses = targetAddresses.value.length
const cb =
numOfTargetAddresses > 1 ? api.tx.utility.batch : api.tx.balances.transfer
const arg =
numOfTargetAddresses > 1
? [
targetAddresses.value.map((target) => {
const amountToTransfer = String(
calculateBalance(Number(target.token), decimals.value)
)
return api.tx.balances.transfer(
target.address as string,
amountToTransfer
)
}),
]
: [
targetAddresses.value[0].address as string,
calculateBalance(
Number(targetAddresses.value[0].token),
decimals.value
),
]
const multipleAddresses = numOfTargetAddresses > 1

let cb, arg

if (multipleAddresses) {
;[cb, arg] = getMultipleAddressesTransferParams({
api,
decimals: decimals.value as number,
})
} else {
;[cb, arg] = getSingleAddressTransferParams({
api,
decimals: decimals.value as number,
})
}

const tx = await exec(
accountId.value,
Expand Down Expand Up @@ -625,48 +650,26 @@ const addAddress = () => {
})
}

const syncQueryToken = () => {
const { query } = route

const token = query.token?.toString()

if (!token || !availableTokens.includes(token)) {
return
}

const chain = getPrefixByToken(token)

if (!chain) {
return
}

setUrlPrefix(chain)
}

watch(
route,
() => {
syncQueryToken()
},
{ immediate: true, deep: true }
)

onMounted(() => {
fetchFiatPrice().then(checkQueryParams)
})

const routerReplace = ({ params = {}, query = {} }) => {
router
.replace({
params: params,
query: {
...route.query,
...query,
},
})
.catch(() => null) // null to further not throw navigation errors
}

watchDebounced(
() => targetAddresses.value[0].usd,
(usdamount) => {
router
.replace({
query: {
...route.query,
usdamount: (usdamount || 0).toString(),
token: unit.value,
},
})
.catch(() => null) // null to further not throw navigation errors
routerReplace({ query: { usdamount: (usdamount || 0).toString() } })
},
{ debounce: 300 }
)
Expand Down
15 changes: 11 additions & 4 deletions composables/useBalance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,33 @@ import { getKusamaAssetId } from '@/utils/api/bsx/query'
export default function () {
const { urlPrefix } = usePrefix()
const identityStore = useIdentityStore()
const balance = computed(() => {

const getBalance = (token: string) => {
token = token.toLocaleLowerCase()
switch (urlPrefix.value) {
case 'rmrk':
case 'ksm':
case 'ahk':
case 'ahp':
case 'dot':
return identityStore.getAuthBalance
case 'bsx':
return identityStore.multiBalances.chains.basilisk?.ksm?.nativeBalance
return identityStore.multiBalances.chains.basilisk?.[token]
?.nativeBalance
case 'snek':
return identityStore.multiBalances.chains['basilisk-testnet']?.ksm
return identityStore.multiBalances.chains['basilisk-testnet']?.[token]
?.nativeBalance
default:
return identityStore.getTokenBalanceOf(
getKusamaAssetId(urlPrefix.value)
)
}
})
}

const balance = computed(() => getBalance('KSM'))

return {
balance,
getBalance,
}
}
60 changes: 13 additions & 47 deletions composables/useToken.ts
Original file line number Diff line number Diff line change
@@ -1,74 +1,40 @@
import { useFiatStore } from '@/stores/fiat'
import { type ChainProperties, type Prefix } from '@kodadot1/static'
import { chainPropListOf } from '@/utils/config/chain.config'
import { groupByNestedProperty } from '@/utils/objects'
import { availablePrefixes } from '@/utils/chain'
import { type Prefix } from '@kodadot1/static'
import { useIdentityStore } from '@/stores/identity'
import { defultTokenChain } from '@/utils/config/chain.config'

export interface TokenDetails {
symbol: string
value: number | string | null
icon: string
chains: Prefix[]
defaultChain: Prefix
}

const getAssetToken = (asset) => asset?.token || 'KSM'
const getUniqueArrayItems = (items: string[]) => [...new Set(items)]

export default function useToken() {
const { getCurrentTokenValue } = useFiatStore()
const { getTokenIconBySymbol } = useIcon()
const { multiBalanceAssets } = useIdentityStore()

const availableChains = availablePrefixes().map(
(item) => item.value as Prefix
)

const availableTokens = ['BSX', 'DOT', 'KSM']

const chainsProperties = computed(() => {
return availableChains.reduce(
(reducer, chain: Prefix) => ({
...reducer,
[chain]: chainPropListOf(chain),
}),
{}
) as { [k in Prefix]: ChainProperties }[]
})

const groupedTokensByChains = computed(() =>
groupByNestedProperty(chainsProperties.value, 'tokenSymbol')
const availableAssets = computed(() => multiBalanceAssets)
const availableTokensAcrossAllChains = computed(() =>
getUniqueArrayItems(Object.values(availableAssets.value).map(getAssetToken))
)

const getTokenChain = (token: string): Prefix[] =>
groupedTokensByChains.value[token] || []

const tokens = computed<TokenDetails[]>(() => {
const filteredTokens = Object.keys(groupedTokensByChains.value).filter(
(token) => availableTokens.includes(token)
)

return filteredTokens.map((tokenSymbol) => {
return availableTokensAcrossAllChains.value.map((tokenSymbol) => {
return {
symbol: tokenSymbol as string,
value: getCurrentTokenValue(tokenSymbol),
icon: getTokenIconBySymbol(tokenSymbol),
chains: getTokenChain(tokenSymbol),
defaultChain: defultTokenChain[tokenSymbol],
}
})
})

const getPrefixByToken = (token: string): Prefix | null => {
switch (token.toLowerCase()) {
case 'bsx':
return 'bsx'
case 'dot':
return 'dot'
case 'ksm':
return 'ksm'
default:
return null
}
}

return {
tokens,
availableTokens,
getPrefixByToken,
}
}
1 change: 1 addition & 0 deletions stores/identity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ type ChainType =
| 'basilisk-testnet'
| 'statemine'
| 'statemint'

type ChainDetail = {
balance: string
nativeBalance: string
Expand Down
8 changes: 8 additions & 0 deletions utils/config/chain.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,11 @@ export const chainAssetOf = (prefix: Prefix): AssetItem => {
decimals,
}
}

export const defultTokenChain: Record<string, Prefix> = {
KSM: 'ksm',
DOT: 'dot',
BSX: 'bsx',
GLMR: 'glmr',
MOVR: 'movr',
}
Loading