Skip to content

Commit

Permalink
feat: improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
evavirseda committed Mar 26, 2024
1 parent 39a3d84 commit 286f93b
Showing 1 changed file with 63 additions and 67 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,9 @@
ITransactionInfoToCalculateManaCost,
getManaBalance,
getPassiveManaForOutput,
nodeInfoProtocolParameters,
DEFAULT_SECONDS_PER_SLOT,
} from '@core/network'
import { activeProfile } from '@core/profile'
import { implicitAccountCreationRouter } from '@core/router'
import { MILLISECONDS_PER_SECOND, SECONDS_PER_MINUTE, getBestTimeDuration } from '@core/utils'
import { IWalletState, formatTokenAmountBestMatch, selectedWallet, selectedWalletAssets } from '@core/wallet'
import { OutputData } from '@iota/sdk/out/types'
Expand All @@ -30,27 +28,23 @@
export let outputId: string | undefined
const LOW_MANA_GENERATION_SECONDS = 10 * SECONDS_PER_MINUTE
const minCommittableAge = $nodeInfoProtocolParameters?.minCommittableAge
const transactionInfo: ITransactionInfoToCalculateManaCost = {}
let walletAddress: string = ''
const transactionInfo: ITransactionInfoToCalculateManaCost = {}
let hasEnoughMana = false
let isCongestionNotFound: boolean | null = null
let isLowManaGeneration = false
let seconds: number = 10
let countdownInterval: NodeJS.Timeout
$: timeRemaining = `${getBestTimeDuration(seconds * MILLISECONDS_PER_SECOND)} remaining`
let isCongestionNotFound: boolean | null = null
$: baseCoin = $selectedWalletAssets?.[$activeProfile?.network?.id]?.baseCoin
$: selectedOutput = getSelectedOutput($selectedWallet, outputId)
let totalAvailableMana: number
$: $selectedWallet, (totalAvailableMana = getTotalAvailableMana())
$: $selectedWallet, (totalAvailableMana = getTotalAvailableMana()), prepareTransaction(selectedOutput?.outputId)
let formattedSelectedOutputBlance: string
let formattedSelectedOutputBalance: string
$: selectedOutput,
(formattedSelectedOutputBlance = baseCoin
(formattedSelectedOutputBalance = baseCoin
? formatTokenAmountBestMatch(Number(selectedOutput?.output.amount), baseCoin.metadata)
: '-')
$: formattedWalletBalance =
Expand Down Expand Up @@ -88,64 +82,66 @@
}, 0)
}
async function prepareImplicitAccountWithRetry(outputId: string): Promise<void> {
async function prepareTransaction(outputId: string): Promise<void> {
if (!outputId) return
try {
await $selectedWallet.prepareImplicitAccountTransition(outputId).then((prepareTx) => {
transactionInfo.preparedTransaction = prepareTx
isCongestionNotFound = false
seconds = 0
$implicitAccountCreationRouter.next()
})
transactionInfo.preparedTransaction = await $selectedWallet?.prepareImplicitAccountTransition(outputId)
isCongestionNotFound = false
seconds = 0 // If we don't get an error, it's because we can follow on to the next step
} catch (error) {
// Handle "congestion not found" error and retry
if (error.message.includes('congestion was not found')) {
if (error.message?.includes('congestion was not found')) {
isCongestionNotFound = true
await retryWithTimeout(minCommittableAge)
// Retry implicit account creation after timeout
await attemptImplicitAccountCreation()
} else if (error.message?.includes('slots remaining until enough mana')) {
await $selectedWallet
?.prepareImplicitAccountTransition(outputId)
.then(() => {
isCongestionNotFound = false
})
.catch((error) => {
console.error(error)
})
}
if (error.message?.includes('slots remaining until enough mana')) {
transactionInfo.preparedTransactionError = error.message
const slotsRemaining = Number(error.message?.split(' ').reverse()[0].replace('`', ''))
seconds = slotsRemaining * DEFAULT_SECONDS_PER_SLOT
isLowManaGeneration = seconds >= LOW_MANA_GENERATION_SECONDS
isCongestionNotFound = false
// Start countdown after successful preparation
countdownInterval = setInterval(() => {
seconds -= 1
if (seconds <= 0) {
$implicitAccountCreationRouter.next()
}
}, MILLISECONDS_PER_SECOND)
}
}
}
// ----------------------------------------------------------------
let seconds: number = 10
let countdownInterval: NodeJS.Timeout
let timeRemaining: string
async function retryWithTimeout(timeout: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, timeout)
})
}
async function attemptImplicitAccountCreation(): Promise<void> {
try {
/* eslint-disable @typescript-eslint/no-misused-promises */
await prepareImplicitAccountWithRetry(selectedOutput.outputId)
} catch (error) {
setTimeout(attemptImplicitAccountCreation, minCommittableAge)
$: timeRemaining = `${getBestTimeDuration(seconds * MILLISECONDS_PER_SECOND)} remaining`
$: {
async () => {
await prepareTransaction(selectedOutput.outputId)
}
}
onMount(async () => {
onMount(() => {
$selectedWallet?.address().then((address) => (walletAddress = address))
await attemptImplicitAccountCreation()
if (seconds === 0) onTimeout()
countdownInterval = setInterval(() => {
seconds -= 1
if (seconds <= 0) {
clearInterval(countdownInterval)
onTimeout()
}
}, MILLISECONDS_PER_SECOND)
})
onDestroy(() => {
clearInterval(countdownInterval)
})
const onTimeout = (): void => {
// $implicitAccountCreationRouter.next()
}
// ----------------------------------------------------------------
</script>

<step-content class={`flex flex-col items-center justify-between h-full ${isLowManaGeneration ? 'pt-8' : 'pt-14'}`}>
<step-content class={`flex flex-col items-center justify-between h-full ${isLowManaGeneration ? 'pt-8' : 'pt-20'}`}>
<div class="flex flex-col h-full justify-between space-y-4 items-center">
<div class="flex flex-col text-center space-y-4 max-w-md">
<div class={`flex items-center justify-center ${isLowManaGeneration ? 'mb-2' : 'mb-7'}`}>
Expand All @@ -154,6 +150,14 @@
alt={localize('views.implicit-account-creation.steps.step2.title')}
/>
</div>
<Text
type={TextType.h5}
fontSize="15"
color="blue-700"
darkColor="blue-700"
fontWeight={FontWeight.semibold}
>{localize('views.implicit-account-creation.steps.step2.view.subtitle')}</Text
>
{#if isCongestionNotFound}
<div class="flex items-center justify-center space-x-2">
<Text type={TextType.h5} fontWeight={FontWeight.normal} color="gray-600" darkColor="gray-400">
Expand All @@ -162,35 +166,27 @@
<Spinner size={16} />
</div>
{:else}
<Text
type={TextType.h5}
fontSize="15"
color="blue-700"
darkColor="blue-700"
fontWeight={FontWeight.semibold}
>{localize('views.implicit-account-creation.steps.step2.view.subtitle')}</Text
>
<Text type={TextType.h5} fontWeight={FontWeight.normal} color="gray-600" darkColor="gray-400">
{timeRemaining}
</Text>
{/if}
<Text type={TextType.h3} fontWeight={FontWeight.semibold}>
{localize('views.implicit-account-creation.steps.step2.view.title')}
{formattedSelectedOutputBlance}
{formattedSelectedOutputBalance}
</Text>
<div class="flex flex-col space-y-2">
<KeyValueBox
keyText={localize('views.implicit-account-creation.steps.step2.view.eyebrow')}
valueText={formattedWalletBalance}
/>
{#if !isCongestionNotFound}
{#if isLowManaGeneration}
<div class="flex flex-col space-y-2">
<KeyValueBox
keyText={localize('views.implicit-account-creation.steps.step2.view.eyebrow')}
valueText={formattedWalletBalance}
/>
<KeyValueBox
keyText={localize('views.implicit-account-creation.steps.step2.view.generatedMana')}
valueText={formattedManaBalance}
/>
<ManaBox {transactionInfo} bind:hasEnoughMana showCountdown={false} />
{/if}
</div>
</div>
{/if}
</div>
{#if isLowManaGeneration}
<div class="flex flex-col space-y-2 w-2/3">
Expand Down

0 comments on commit 286f93b

Please sign in to comment.