Skip to content

Commit

Permalink
Merge branches 'feat/allow-to-allot-mana' and 'develop-iota2.0' of gi…
Browse files Browse the repository at this point in the history
…thub.com:iotaledger/firefly into feat/allow-to-allot-mana
  • Loading branch information
cpl121 committed Mar 21, 2024
2 parents 3c208f3 + 764039e commit 0e476af
Show file tree
Hide file tree
Showing 45 changed files with 600 additions and 238 deletions.
36 changes: 26 additions & 10 deletions packages/desktop/components/AccountManagementDetails.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -167,16 +167,19 @@
{/if}
</right-pane-title>
<div class="flex flex-row space-x-2 w-1/2">
<Tile>
<div class="flex flex-col space-y-2 items-center justify-center w-full">
<Text type={TextType.h3}>
{formattedBalance}
</Text>
<Text color="gray-600" fontWeight={FontWeight.medium} fontSize="12" type={TextType.p}
>{localize('views.accountManagement.details.balance')}</Text
>
</div>
</Tile>
<!-- TODO: Remove this if when calculate the balance of an account output https://github.com/iotaledger/firefly/issues/8080 -->
{#if !accountId}
<Tile>
<div class="flex flex-col space-y-2 items-center justify-center w-full">
<Text type={TextType.h3}>
{formattedBalance}
</Text>
<Text color="gray-600" fontWeight={FontWeight.medium} fontSize="12" type={TextType.p}
>{localize('views.accountManagement.details.balance')}</Text
>
</div>
</Tile>
{/if}

{#if hasStakingFeature}
<Tile>
Expand All @@ -188,6 +191,19 @@
</div>
</Tile>
{/if}

{#if accountId}
<Tile>
<div class="flex flex-col space-y-2 items-center justify-center w-full">
<Text type={TextType.h3}>
{$selectedWallet?.balances?.blockIssuanceCredits?.[accountId] || 0}
</Text>
<Text color="gray-600" fontWeight={FontWeight.medium} fontSize="12" type={TextType.p}
>{localize('views.accountManagement.details.blockIssuanceCredits')}</Text
>
</div>
</Tile>
{/if}
</div>
{#if accountId}
<div class="flex flex-col space-y-2">
Expand Down
88 changes: 88 additions & 0 deletions packages/desktop/components/ManaBox.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<script lang="ts">
import { localize } from '@core/i18n'
import {
DEFAULT_SECONDS_PER_SLOT,
ITransactionInfoToCalculateManaCost,
getExtraMana,
getManaBalance,
} from '@core/network'
import { activeProfile } from '@core/profile'
import { MILLISECONDS_PER_SECOND } from '@core/utils'
import { selectedWallet, formatTokenAmountBestMatch, selectedWalletAssets } from '@core/wallet'
import { KeyValueBox, Text, TextType } from '@ui'
import { onMount, onDestroy } from 'svelte'
export let transactionInfo: ITransactionInfoToCalculateManaCost
export let hasEnoughMana: boolean
export let showCountdown: boolean = true
const NUMBER_OF_EXTRA_SLOTS_MANA = 3
const extraMana: number = getExtraMana(NUMBER_OF_EXTRA_SLOTS_MANA)
let requiredTxManaCost: number = 0
let countdownInterval: NodeJS.Timeout
let secondsToRefreshManaCost = NUMBER_OF_EXTRA_SLOTS_MANA * DEFAULT_SECONDS_PER_SLOT
$: (transactionInfo?.preparedTransaction || transactionInfo?.preparedTransactionError) && calculateManaCost()
$: mana = ($selectedWalletAssets?.[$activeProfile?.network?.id] ?? {}).mana
$: availableMana = getManaBalance($selectedWallet?.balances?.mana?.available)
$: requiredMana = requiredTxManaCost + extraMana
$: hasEnoughMana = availableMana >= requiredMana
function calculateManaCost() {

Check warning on line 32 in packages/desktop/components/ManaBox.svelte

View workflow job for this annotation

GitHub Actions / lint

Missing return type on function
if (
transactionInfo?.preparedTransactionError &&
transactionInfo.preparedTransactionError.message?.includes('slots remaining until enough mana')
) {
const splittedError = transactionInfo.preparedTransactionError.message?.split(' ')
const requiredManaForTransaction = splittedError[splittedError.indexOf('required') + 1]?.replace(',', '')
requiredTxManaCost = Number(requiredManaForTransaction ?? 0)
} else if (transactionInfo?.preparedTransaction) {
requiredTxManaCost =
transactionInfo.preparedTransaction._preparedData?.transaction?.allotments?.reduce(
(acc, { mana }) => acc + Number(mana),
0
) || 0
}
}
onMount(() => {
calculateManaCost()
countdownInterval = setInterval(() => {
secondsToRefreshManaCost -= 1
if (secondsToRefreshManaCost <= 0) {
calculateManaCost()
secondsToRefreshManaCost = NUMBER_OF_EXTRA_SLOTS_MANA * DEFAULT_SECONDS_PER_SLOT
}
}, MILLISECONDS_PER_SECOND)
})
onDestroy(() => {
clearInterval(countdownInterval)
})
</script>

<div class="flex flex-col space-y-2">
<KeyValueBox
keyText={localize('general.manaCost')}
valueText={formatTokenAmountBestMatch(requiredMana, mana.metadata)}
/>

{#if !hasEnoughMana}
<Text type={TextType.p} error classes="text-center">
{localize('general.insufficientMana', {
values: {
availableMana: formatTokenAmountBestMatch(availableMana, mana.metadata),
},
})}
</Text>
{:else if showCountdown}
<Text type={TextType.p} classes="text-center">
{localize('general.secondsToRefreshManaCost', {
values: {
seconds: secondsToRefreshManaCost,
},
})}
</Text>
{/if}
</div>
1 change: 1 addition & 0 deletions packages/desktop/components/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@ export { default as VotingPower } from './VotingPower.svelte'
export { default as VestingSchedule } from './VestingSchedule.svelte'
export { default as AccountManagementDetails } from './AccountManagementDetails.svelte'
export { default as AccountManagementList } from './AccountManagementList.svelte'
export { default as ManaBox } from './ManaBox.svelte'
57 changes: 38 additions & 19 deletions packages/desktop/components/popups/ActivityDetailsPopup.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { PopupId, closePopup, openPopup } from '@auxiliary/popup'
import { openUrlInBrowser } from '@core/app'
import { localize } from '@core/i18n'
import { ExplorerEndpoint } from '@core/network'
import { ExplorerEndpoint, ITransactionInfoToCalculateManaCost } from '@core/network'
import { getOfficialExplorerUrl } from '@core/network/utils'
import { activeProfile, checkActiveProfileAuth } from '@core/profile'
import { setClipboard, truncateString } from '@core/utils'
Expand All @@ -12,6 +12,7 @@
ActivityType,
claimActivity,
rejectActivity,
selectedWallet,
selectedWalletActivities,
} from '@core/wallet'
import {
Expand All @@ -29,12 +30,16 @@
} from '@ui'
import { TextHintVariant } from '@ui/enums'
import { onMount } from 'svelte'
import { ManaBox } from '@components'
export let activityId: string
export let _onMount: (..._: any[]) => Promise<void> = async () => {}
const explorerUrl = getOfficialExplorerUrl($activeProfile?.network?.id)
const transactionInfo: ITransactionInfoToCalculateManaCost = {}
let hasEnoughMana = false
$: activity = $selectedWalletActivities?.find((_activity) => _activity.id === activityId)
$: isTimelocked = activity?.asyncData?.asyncStatus === ActivityAsyncStatus.Timelocked
$: isActivityIncomingAndUnclaimed =
Expand Down Expand Up @@ -69,6 +74,14 @@
await checkActiveProfileAuth(claim, { stronghold: true, ledger: false })
}
async function prepareClaimOutput(): Promise<void> {
try {
transactionInfo.preparedTransaction = await $selectedWallet?.prepareClaimOutputs([activity.outputId])
} catch (error) {
transactionInfo.preparedTransactionError = error
}
}
function onRejectClick(): void {
openPopup({
id: PopupId.Confirmation,
Expand All @@ -94,6 +107,9 @@
onMount(async () => {
try {
await _onMount()
if (!isTimelocked && isActivityIncomingAndUnclaimed) {
await prepareClaimOutput()
}
} catch (err) {
console.error(err)
}
Expand Down Expand Up @@ -139,24 +155,27 @@
<ActivityInformation {activity} />
</activity-details>
{#if !isTimelocked && isActivityIncomingAndUnclaimed}
<popup-buttons class="flex flex-row flex-nowrap w-full space-x-4">
<Button
outline
classes="w-full"
disabled={activity.asyncData?.isClaiming || activity.asyncData?.isRejected}
onClick={onRejectClick}
>
{localize('actions.reject')}
</Button>
<Button
classes="w-full"
disabled={activity.asyncData?.isClaiming}
onClick={onClaimClick}
isBusy={activity.asyncData?.isClaiming}
>
{localize('actions.claim')}
</Button>
</popup-buttons>
<div class="flex flex-col space-y-4">
<ManaBox {transactionInfo} bind:hasEnoughMana />
<popup-buttons class="flex flex-row flex-nowrap w-full space-x-4">
<Button
outline
classes="w-full"
disabled={activity.asyncData?.isClaiming || activity.asyncData?.isRejected}
onClick={onRejectClick}
>
{localize('actions.reject')}
</Button>
<Button
classes="w-full"
disabled={activity.asyncData?.isClaiming || !hasEnoughMana}
onClick={onClaimClick}
isBusy={activity.asyncData?.isClaiming}
>
{localize('actions.claim')}
</Button>
</popup-buttons>
</div>
{/if}
</activity-details-popup>
{/if}
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,12 @@
function getManaBreakdown(): BalanceBreakdown {
const totalBalanceWithoutBic = getManaBalance(walletBalance?.mana?.total)
const availableBalance = getManaBalance(walletBalance?.mana?.available)
const totalBalance = totalBalanceWithoutBic + walletBalance.blockIssuanceCredits
const totalBalance = totalBalanceWithoutBic + walletBalance.totalWalletBic
const subBreakdown = {
availableMana: { amount: availableBalance },
lockedMana: { amount: totalBalanceWithoutBic - availableBalance },
bicMana: { amount: walletBalance.blockIssuanceCredits },
bicMana: { amount: walletBalance.totalWalletBic },
}
return { amount: totalBalance, subBreakdown, isBaseToken: false }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,22 @@
import { Button, Text, TextHint, FontWeight, TextType, ButtonVariant, KeyValueBox } from '@ui'
import { localize } from '@core/i18n'
import { closePopup, openPopup, PopupId } from '@auxiliary/popup'
import { burnAsset, formatTokenAmountBestMatch, IAsset } from '@core/wallet'
import { burnAsset, formatTokenAmountBestMatch, getDefaultTransactionOptions, IAsset } from '@core/wallet'
import { checkActiveProfileAuth } from '@core/profile'
import { handleError } from '@core/error/handlers'
import { onMount } from 'svelte'
import { selectedWallet } from '@core/wallet'
import { TextHintVariant } from '@ui/enums'
import { ManaBox } from '@components'
import { ITransactionInfoToCalculateManaCost } from '@core/network'
export let asset: IAsset
export let rawAmount: string
export let _onMount: (..._: any[]) => Promise<void> = async () => {}
const transactionInfo: ITransactionInfoToCalculateManaCost = {}
let hasEnoughMana = false
$: formattedAmount = formatTokenAmountBestMatch(Number(rawAmount), asset?.metadata)
function onBackClick(): void {
Expand All @@ -36,9 +41,24 @@
}
}
async function prepareBurnFoundryTransaction(): Promise<void> {
if (asset && $selectedWallet && rawAmount) {
try {
transactionInfo.preparedTransaction = await $selectedWallet.prepareBurnNativeToken(
asset.id,
BigInt(rawAmount),
getDefaultTransactionOptions()
)
} catch (error) {
transactionInfo.preparedTransactionError = error
}
}
}
onMount(async () => {
try {
await _onMount()
await prepareBurnFoundryTransaction()
} catch (err) {
handleError(err)
}
Expand All @@ -57,14 +77,15 @@
<KeyValueBox keyText={localize('popups.nativeToken.property.assetId')} valueText={asset.id} isCopyable />
<KeyValueBox keyText={localize('general.amount')} valueText={formattedAmount} />
<TextHint variant={TextHintVariant.Warning} text={localize('actions.confirmTokenBurn.hint')} />
<ManaBox {transactionInfo} bind:hasEnoughMana />
</div>
<popup-buttons class="flex flex-row flex-nowrap w-full space-x-4">
<Button classes="w-full" outline onClick={onBackClick}>{localize('actions.back')}</Button>
<Button
classes="w-full"
variant={ButtonVariant.Warning}
isBusy={$selectedWallet?.isTransferring}
disabled={$selectedWallet?.isTransferring}
disabled={$selectedWallet?.isTransferring || !hasEnoughMana}
onClick={onBurnTokenClick}
>
{localize('actions.burnToken')}
Expand Down
25 changes: 24 additions & 1 deletion packages/desktop/components/popups/CreateDelegationPopup.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
} from '@core/wallet'
import { AccountAddress, CreateDelegationParams } from '@iota/sdk/out/types'
import { Text, TextType, AssetAmountInput, TextInput, Button, HTMLButtonType } from '@ui'
import { ManaBox } from '@components'
import { onMount } from 'svelte'
import { ITransactionInfoToCalculateManaCost } from '@core/network'
export let _onMount: (..._: any[]) => Promise<void> = async () => {}
export let rawAmount: string = $selectedWallet?.balances?.baseCoin?.available?.toString()
Expand All @@ -23,6 +25,9 @@
let amount: string
let confirmDisabled = false
const transactionInfo: ITransactionInfoToCalculateManaCost = {}
let hasEnoughMana = false
$: asset = $visibleSelectedWalletAssets[$activeProfile?.network?.id].baseCoin
$: hasTransactionInProgress =
$selectedWallet?.hasConsolidatingOutputsTransactionInProgress ||
Expand All @@ -36,7 +41,7 @@
return
}
const convertedSliderAmount = convertToRawAmount(amount, asset?.metadata)?.toString()
confirmDisabled = convertedSliderAmount === rawAmount || hasTransactionInProgress
confirmDisabled = convertedSliderAmount === rawAmount || hasTransactionInProgress || !hasEnoughMana
}
async function onSubmit(): Promise<void> {
Expand Down Expand Up @@ -67,13 +72,30 @@
}
}
async function prepareDelegationOutput(): Promise<void> {
const params: CreateDelegationParams = {
address: AddressConverter.addressToBech32(new AccountAddress($selectedWallet?.mainAccountId)),
delegatedAmount: rawAmount,
validatorAddress: new AccountAddress(AddressConverter.parseBech32Address(accountAddress)),
}
try {
transactionInfo.preparedTransaction = await $selectedWallet?.prepareCreateDelegation(
params,
getDefaultTransactionOptions()
)
} catch (error) {
transactionInfo.preparedTransactionError = error
}
}
function onCancelClick(): void {
closePopup()
}
onMount(async () => {
try {
await _onMount()
await prepareDelegationOutput()
} catch (err) {
handleError(err.error)
}
Expand All @@ -99,6 +121,7 @@
placeholder={localize('popups.createDelegation.account.title')}
label={localize('popups.createDelegation.account.description')}
/>
<ManaBox {transactionInfo} bind:hasEnoughMana />
</div>
<div class="flex flex-row flex-nowrap w-full space-x-4">
<Button outline disabled={hasTransactionInProgress} classes="w-full" onClick={onCancelClick}>
Expand Down
Loading

0 comments on commit 0e476af

Please sign in to comment.