Skip to content

Commit

Permalink
add: basic hasEnough and hasEnoughInOtherChains
Browse files Browse the repository at this point in the history
  • Loading branch information
hassnian committed Oct 17, 2023
1 parent 765fe70 commit c55e671
Show file tree
Hide file tree
Showing 8 changed files with 247 additions and 127 deletions.
112 changes: 3 additions & 109 deletions components/balance/MultipleBalances.vue
Original file line number Diff line number Diff line change
Expand Up @@ -59,40 +59,20 @@

<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { ApiPromise, WsProvider } from '@polkadot/api'
import { decodeAddress, encodeAddress } from '@polkadot/util-crypto'
import { CHAINS, ENDPOINT_MAP } from '@kodadot1/static'
import { NeoSkeleton } from '@kodadot1/brick'
import { balanceOf } from '@kodadot1/sub-api'
import format, { formatNumber } from '@/utils/format/balance'
import { useFiatStore } from '@/stores/fiat'
import { calculateExactUsdFromToken } from '@/utils/calculation'
import { getAssetIdByAccount } from '@/utils/api/bsx/query'
import { toDefaultAddress } from '@/utils/account'
import { formatNumber } from '@/utils/format/balance'
import { ChainToken, useIdentityStore } from '@/stores/identity'
import type { PalletBalancesAccountData } from '@polkadot/types/lookup'
const { accountId } = useAuth()
const { isTestnet } = usePrefix()
const refetchMultipleBalanceTimer = ref()
const identityStore = useIdentityStore()
const { fetchMultipleBalance, currentNetwork } = useMultiBalance()
const {

Check failure on line 71 in components/balance/MultipleBalances.vue

View workflow job for this annotation

GitHub Actions / runner / eslint

[eslint] reported by reviewdog 🐶 Replace `⏎··multiBalances,⏎··multiBalanceNetwork,⏎` with `·multiBalances,·multiBalanceNetwork·` Raw Output: {"ruleId":"prettier/prettier","severity":2,"message":"Replace `⏎··multiBalances,⏎··multiBalanceNetwork,⏎` with `·multiBalances,·multiBalanceNetwork·`","line":71,"column":8,"nodeType":null,"messageId":"replace","endLine":74,"endColumn":1,"fix":{"range":[2192,2233],"text":" multiBalances, multiBalanceNetwork "}}
multiBalances,
multiBalanceAssets,
multiBalanceAssetsTestnet,
multiBalanceNetwork,
} = storeToRefs(identityStore)
const networkToPrefix = {
polkadot: 'dot',
kusama: 'ksm',
basilisk: 'bsx',
kusamaHub: 'ahk',
'basilisk-testnet': 'snek',
polkadotHub: 'ahp',
}
const isBalanceLoading = computed(
() => identityStore.getStatusMultiBalances === 'loading',
)
Expand All @@ -113,92 +93,6 @@ const isEmptyBalanceOnAllChains = computed(() => {
filterEmptyBalanceChains(multiBalances.value.chains[chain]).length !== 0,
)
})
const currentNetwork = computed(() =>
isTestnet.value ? 'test-network' : 'main-network',
)
const fiatStore = useFiatStore()
function calculateUsd(amount: string, token = 'KSM') {
if (!amount) {
return 0
}
const amountToNumber = Number(amount.replace(/\,/g, ''))
return calculateExactUsdFromToken(
amountToNumber,
Number(fiatStore.getCurrentTokenValue(token)),
)
}
async function getBalance(chainName: string, token = 'KSM', tokenId = 0) {
const currentAddress = accountId.value
const prefix = networkToPrefix[chainName]
const chain = CHAINS[prefix]
const defaultAddress = toDefaultAddress(currentAddress)
const publicKey = decodeAddress(currentAddress)
const prefixAddress = encodeAddress(publicKey, chain.ss58Format)
const wsProvider = new WsProvider(ENDPOINT_MAP[prefix])
const api = await ApiPromise.create({
provider: wsProvider,
})
let currentBalance
let nativeBalance
if (tokenId) {
nativeBalance = (
(await api.query.tokens.accounts(
prefixAddress,
tokenId,
)) as PalletBalancesAccountData
).free.toString()
currentBalance = format(nativeBalance, chain.tokenDecimals, false)
} else {
nativeBalance = await balanceOf(api, prefixAddress)
currentBalance = format(nativeBalance, chain.tokenDecimals, false)
}
let selectedTokenId = String(tokenId)
if (chainName === 'basilisk') {
selectedTokenId = await getAssetIdByAccount(api, prefixAddress)
}
const usd = calculateUsd(currentBalance, token)
identityStore.setMultiBalances({
address: defaultAddress,
chains: {
[chainName]: {
[token.toLowerCase()]: {
address: prefixAddress,
balance: currentBalance,
nativeBalance,
usd,
selected: selectedTokenId === String(tokenId),
},
},
},
chainName,
})
identityStore.multiBalanceNetwork = currentNetwork.value
await wsProvider.disconnect()
}
const fetchMultipleBalance = async () => {
await fiatStore.fetchFiatPrice()
const assets = isTestnet.value
? multiBalanceAssetsTestnet.value
: multiBalanceAssets.value
assets.forEach((item) => {
getBalance(item.chain, item.token, Number(item.tokenId))
})
}
onMounted(async () => {
if (currentNetwork.value !== multiBalanceNetwork.value) {
Expand Down
49 changes: 49 additions & 0 deletions components/common/autoTeleport/AutoTeleportActionButton.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@

Check failure on line 1 in components/common/autoTeleport/AutoTeleportActionButton.vue

View workflow job for this annotation

GitHub Actions / runner / eslint

[eslint] reported by reviewdog 🐶 Delete `⏎` Raw Output: {"ruleId":"prettier/prettier","severity":2,"message":"Delete `⏎`","line":1,"column":1,"nodeType":null,"messageId":"delete","endLine":2,"endColumn":1,"fix":{"range":[0,1],"text":""}}
<template>
<div class="is-flex is-flex-direction-column w-full">

Check failure on line 3 in components/common/autoTeleport/AutoTeleportActionButton.vue

View workflow job for this annotation

GitHub Actions / runner / eslint

[eslint] reported by reviewdog 🐶 Delete `··` Raw Output: {"ruleId":"prettier/prettier","severity":2,"message":"Delete `··`","line":3,"column":1,"nodeType":null,"messageId":"delete","endLine":3,"endColumn":3,"fix":{"range":[12,14],"text":""}}

Check failure on line 4 in components/common/autoTeleport/AutoTeleportActionButton.vue

View workflow job for this annotation

GitHub Actions / runner / eslint

[eslint] reported by reviewdog 🐶 Replace `⏎········<div·class="is-flex·is-justify-content-space-between·w-full·mb-4"` with `····<div⏎······class="is-flex·is-justify-content-space-between·w-full·mb-4"⏎·····` Raw Output: {"ruleId":"prettier/prettier","severity":2,"message":"Replace `⏎········<div·class=\"is-flex·is-justify-content-space-between·w-full·mb-4\"` with `····<div⏎······class=\"is-flex·is-justify-content-space-between·w-full·mb-4\"⏎·····`","line":4,"column":1,"nodeType":null,"messageId":"replace","endLine":5,"endColumn":74,"fix":{"range":[70,144],"text":" <div\n class=\"is-flex is-justify-content-space-between w-full mb-4\"\n "}}
<div class="is-flex is-justify-content-space-between w-full mb-4" v-if="showTeleport">
<p class="has-text-weight-bold">Auto Teleport</p>

Check failure on line 6 in components/common/autoTeleport/AutoTeleportActionButton.vue

View workflow job for this annotation

GitHub Actions / runner / eslint

[eslint] reported by reviewdog 🐶 Delete `······` Raw Output: {"ruleId":"prettier/prettier","severity":2,"message":"Delete `······`","line":6,"column":7,"nodeType":null,"messageId":"delete","endLine":6,"endColumn":13,"fix":{"range":[172,178],"text":""}}

<NeoSwitch

Check failure on line 8 in components/common/autoTeleport/AutoTeleportActionButton.vue

View workflow job for this annotation

GitHub Actions / runner / eslint

[eslint] reported by reviewdog 🐶 Replace `······<NeoSwitch⏎················v-model="autoTeleport"⏎···············` with `<NeoSwitch·v-model="autoTeleport"` Raw Output: {"ruleId":"prettier/prettier","severity":2,"message":"Replace `······<NeoSwitch⏎················v-model=\"autoTeleport\"⏎···············` with `<NeoSwitch·v-model=\"autoTeleport\"`","line":8,"column":7,"nodeType":null,"messageId":"replace","endLine":10,"endColumn":16,"fix":{"range":[235,306],"text":"<NeoSwitch v-model=\"autoTeleport\""}}
v-model="autoTeleport"
data-testid="auto-teleport-switch" />
</div>

Check failure on line 11 in components/common/autoTeleport/AutoTeleportActionButton.vue

View workflow job for this annotation

GitHub Actions / runner / eslint

[eslint] reported by reviewdog 🐶 Delete `····` Raw Output: {"ruleId":"prettier/prettier","severity":2,"message":"Delete `····`","line":11,"column":5,"nodeType":null,"messageId":"delete","endLine":11,"endColumn":9,"fix":{"range":[349,353],"text":""}}

<NeoButton

Check failure on line 13 in components/common/autoTeleport/AutoTeleportActionButton.vue

View workflow job for this annotation

GitHub Actions / runner / eslint

[eslint] reported by reviewdog 🐶 Replace `········` with `····` Raw Output: {"ruleId":"prettier/prettier","severity":2,"message":"Replace `········` with `····`","line":13,"column":1,"nodeType":null,"messageId":"replace","endLine":13,"endColumn":9,"fix":{"range":[361,369],"text":" "}}
:label="label"

Check failure on line 14 in components/common/autoTeleport/AutoTeleportActionButton.vue

View workflow job for this annotation

GitHub Actions / runner / eslint

[eslint] reported by reviewdog 🐶 Delete `····` Raw Output: {"ruleId":"prettier/prettier","severity":2,"message":"Delete `····`","line":14,"column":1,"nodeType":null,"messageId":"delete","endLine":14,"endColumn":5,"fix":{"range":[380,384],"text":""}}
variant="k-accent"
no-shadow
:disabled="false"
class="is-flex is-flex-grow-1 btn-height"
/>

<div class="is-flex is-justify-content-center mt-4" v-if="showTeleport">
<span class="has-text-grey">Or</span>

<a class="ml-2" @click="rampActive = true"
>+ {{ $t('addFunds') }} Via Onramp</a
>
</div>

</div>
</template>

<script setup lang="ts">
import { NeoButton , NeoSwitch } from '@kodadot1/brick'
const props = defineProps<{
amount: number,
label: string
}>()
const autoTeleport = ref(false)
const { hasEnough, hasEnoughInOtherChains} = useAutoTeleport(computed(() => props.amount))
const showTeleport = computed(() => !hasEnough.value)
</script>

<style scoped>
</style>
11 changes: 7 additions & 4 deletions components/common/confirmPurchaseModal/ConfirmPurchaseModal.vue
Original file line number Diff line number Diff line change
Expand Up @@ -47,20 +47,21 @@
{{ $t('confirmPurchase.youWillPay') }}
<div class="is-flex">
<CommonTokenMoney
:value="totalNFTsPrice + totalRoyalties"
:value="totalWithRoyalties"
class="has-text-grey" />
<span class="has-text-weight-bold ml-2"> {{ priceUSD }}$ </span>
</div>
</div>

<div class="is-flex is-justify-content-space-between py-5 px-6">
<NeoButton
<AutoTeleportActionButton :label="btnLabel" />
<!-- <NeoButton
:label="btnLabel"
variant="k-accent"
no-shadow
:disabled="disabled"
class="is-flex is-flex-grow-1 btn-height"
@click="confirm" />
@click="confirm" /> -->
</div>
</div>
</NeoModal>
Expand Down Expand Up @@ -109,8 +110,10 @@ const totalRoyalties = computed(() =>
),
)
const totalWithRoyalties = computed(() => totalNFTsPrice.value + totalRoyalties.value)
const balanceIsEnough = computed(
() => totalNFTsPrice.value + totalRoyalties.value < balance.value,
() => totalWithRoyalties.value < balance.value,
)
const btnLabel = computed(() => {
Expand Down
15 changes: 5 additions & 10 deletions components/teleport/Teleport.vue
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ import {
TeleprtType,
chainToPrefixMap,
whichTeleportType,
allowedTransitions
} from '@/utils/teleport'
import { notificationTypes, showNotification } from '@/utils/notification'
import useAuth from '@/composables/useAuth'
Expand Down Expand Up @@ -151,17 +152,11 @@ const tokenFiatValue = computed(() => {
return fiatStore.getCurrentKSMValue
case 'DOT':
return fiatStore.getCurrentDOTValue
default:
return 0
}
return 0
})
const allowedTransitiosn = {
[Chain.KUSAMA]: [Chain.BASILISK, Chain.STATEMINE],
[Chain.BASILISK]: [Chain.KUSAMA],
[Chain.STATEMINE]: [Chain.KUSAMA],
[Chain.POLKADOT]: [Chain.STATEMINT],
[Chain.STATEMINT]: [Chain.POLKADOT],
}
const chainBalances = {
[Chain.KUSAMA]: () =>
identityStore.multiBalances.chains.kusama?.ksm?.nativeBalance,
Expand All @@ -176,7 +171,7 @@ const chainBalances = {
}
const isDisabled = (chain: Chain) => {
return !allowedTransitiosn[fromChain.value].includes(chain)
return !allowedTransitions[fromChain.value].includes(chain)
}
const fromTabs = [
Expand Down Expand Up @@ -261,7 +256,7 @@ const explorerUrl = computed(() => {
}`
})
const getFirstAllowedDestination = (chain: Chain) => {
return allowedTransitiosn[chain][0]
return allowedTransitions[chain][0]
}
const onChainChange = (selectedChain, setFrom = true) => {
Expand Down
32 changes: 32 additions & 0 deletions composables/useAutoTeleport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@


import {allowedTransitions as teleportRoutes, prefixToChainMap, chainToPrefixMap } from "@/utils/teleport"

export default function (neededAmount: ComputedRef<number>) {
const { urlPrefix } = usePrefix()
const { balance , getBalance } = useBalance()
const {fetchMultipleBalance} = useMultiBalance()

const hasEnough = computed(() => neededAmount.value < balance.value)
const targetChains = computed(() => teleportRoutes[prefixToChainMap[urlPrefix.value]])

const targetChainsBalances = computed(() => targetChains.value.reduce((reducer, chainPrefix) => {
const prefix = chainToPrefixMap[chainPrefix]
return {
...reducer,
[prefix]: getBalance('KSM', prefix)
}
}, {}))

const hasEnoughInOtherChains = computed(() => Object.values(targetChainsBalances.value).some(Boolean))

onMounted(async () => {
await fetchMultipleBalance()
})

return {
hasEnough,
hasEnoughInOtherChains,
// teleport:
}
}
11 changes: 7 additions & 4 deletions composables/useBalance.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
import { useIdentityStore } from '@/stores/identity'
import { getKusamaAssetId } from '@/utils/api/bsx/query'
import { Prefix } from '@kodadot1/static'

export default function () {
const { urlPrefix } = usePrefix()
const identityStore = useIdentityStore()

const getBalance = (token: string) => {
const getBalance = (token: string, prefix: Prefix|null = null) => {
prefix = prefix ? prefix : urlPrefix.value
token = token.toLocaleLowerCase()
switch (urlPrefix.value) {
switch (prefix) {
case 'rmrk':
case 'ksm':
case 'ahk':
case 'ahp':
case 'dot':
return identityStore.getAuthBalance
const balance = computed(() => identityStore.auth.balance)
return balance.value ? balance.value[prefix] || '0' : '0'
case 'bsx':
return identityStore.multiBalances.chains.basilisk?.[token]
?.nativeBalance
Expand All @@ -22,7 +25,7 @@ export default function () {
?.nativeBalance
default:
return identityStore.getTokenBalanceOf(
getKusamaAssetId(urlPrefix.value),
getKusamaAssetId(prefix),
)
}
}
Expand Down
Loading

0 comments on commit c55e671

Please sign in to comment.