Skip to content

Commit

Permalink
review changes and refactor
Browse files Browse the repository at this point in the history
Signed-off-by: Philemon Ukane <ukanephilemon@gmail.com>
  • Loading branch information
ukane-philemon committed Dec 13, 2023
1 parent eea085d commit 17b362e
Show file tree
Hide file tree
Showing 3 changed files with 104 additions and 161 deletions.
10 changes: 5 additions & 5 deletions dexc/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,9 @@ func Start(ctx context.Context, root, lang, logDir, logLvl string, net libutils.
// Use a goroutine to start dex core as it'll block until dex core exits.
go func() {
dc.Run(ctx)
close(shutdownChan)
dc.Core = nil
logCloser()
close(shutdownChan)
dc.Core = nil // do this after all shutdownChan listeners must've stopped waiting
}()

return dc, nil
Expand All @@ -136,9 +136,9 @@ func (dc *DEXClient) HasWallet(assetID int32) bool {

// AddWallet attempts to connect or create the wallet with the provided details
// to the DEX client.
// NOTE: Before connecting a dcr wallet, first call mw.UseDcrWalletForDex to
// configure the dcr ExchangeWallet to use a custom wallet instead of the
// default rpc wallet.
// NOTE: Before connecting a dcr wallet, dcr ExchangeWallet must have been
// configured to use a custom wallet instead of the default rpc wallet. See
// libwallet.AssetManager.PrepareDexSupportForDcrWallet().
func (dc *DEXClient) AddWallet(assetID uint32, settings map[string]string, appPW, walletPW []byte) error {
assetInfo, err := asset.Info(assetID)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion libwallet/assets/dcr/dex_asset.go
Original file line number Diff line number Diff line change
Expand Up @@ -507,5 +507,5 @@ func (da *DEXAsset) AddressPrivKey(ctx context.Context, addr stdaddr.Address) (*

// Part of the Wallet interface.
func (da *DEXAsset) Reconfigure(_ context.Context, cfg *dexasset.WalletConfig, _ dex.Network, _, _ string) (restart bool, err error) {

Check warning on line 509 in libwallet/assets/dcr/dex_asset.go

View workflow job for this annotation

GitHub Actions / Build

unused-parameter: parameter 'cfg' seems to be unused, consider removing or renaming it as _ (revive)
return cfg.Type != walletTypeSPV, nil
return false, nil
}
253 changes: 98 additions & 155 deletions ui/page/dcrdex/dex_onboarding_page.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,11 @@ func (pg *DEXOnboarding) OnNavigatedTo() {}
// components unless they'll be recreated in the OnNavigatedTo() method.
// Part of the load.Page interface.
func (pg *DEXOnboarding) OnNavigatedFrom() {
// Empty dex pass
for i := range pg.dexPass {
pg.dexPass[i] = 0
}

// Remove bond confirmation listener if any.
if pg.bondSourceWalletSelector != nil {
pg.bondSourceWalletSelector.SelectedWallet().RemoveTxAndBlockNotificationListener(DEXOnboardingPageID)
Expand Down Expand Up @@ -478,7 +483,7 @@ func (pg *DEXOnboarding) formFooterButtons(gtx C) D {
case onboardingChooseServer, onBoardingStepAddServer:
backBtnEnabled = !pg.dexc.IsDEXPasswordSet()
case onboardingPostBond:
nextBtnEnabled = pg.validateBondStrength() && pg.bondAccountHasEnough()
nextBtnEnabled = pg.validateBondStrength() && pg.bondAccountHasEnough() && !pg.isLoading
}

pg.nextBtn.Text = values.String(values.StrNext)
Expand Down Expand Up @@ -889,53 +894,10 @@ func (pg *DEXOnboarding) HandleUserInteractions() {
return
}
}
pg.bondServer = serverInfo

// Proceed to next step if we already have the dex pass cached.
if len(pg.dexPass) > 0 {
go pg.connectServerAndPrepareForBonding()
break
}

if !pg.dexc.IsDEXPasswordSet() {
// Fresh onboarding process.
pg.isLoading = true
go func() {
defer func() {
pg.isLoading = false
}()

pg.dexPass = []byte(pg.passwordEditor.Editor.Text())
if err := pg.dexc.InitWithPassword(pg.dexPass, nil); err != nil {
pg.notifyError(err.Error())
return
}

pg.connectServerAndPrepareForBonding()
}()
break
}

// User already has dex password set but did not finish the
// onboarding.
dexPasswordModal := modal.NewCreatePasswordModal(pg.Load).
EnableName(false).
EnableConfirmPassword(false).
Title(values.String(values.StrDexPassword)).
SetPositiveButtonCallback(func(_, password string, pm *modal.CreatePasswordModal) bool {
pg.dexPass = []byte(password)
err := pg.dexc.Login(pg.dexPass)
if err != nil {
pm.SetError(err.Error())
pm.SetLoading(false)
return false
}
pg.bondServer = serverInfo
pg.connectServerAndPrepareForBonding()

pg.connectServerAndPrepareForBonding()
return true
})
dexPasswordModal.SetPasswordTitleVisibility(false)
pg.ParentWindow().ShowModal(dexPasswordModal)
case onboardingPostBond:
// Validate all input fields.
hasEnough := pg.bondAccountHasEnough()
Expand All @@ -944,137 +906,47 @@ func (pg *DEXOnboarding) HandleUserInteractions() {
break
}

asset := pg.bondSourceWalletSelector.SelectedWallet()
if !asset.IsSynced() { // Only fully synced wallets should post bonds.
if !pg.bondSourceWalletSelector.SelectedWallet().IsSynced() { // Only fully synced wallets should post bonds.
pg.notifyError(values.String(values.StrWalletNotSynced))
return
}

bondAsset := pg.bondServer.bondAssets[asset.GetAssetType()]
postBond := &core.PostBondForm{
Addr: pg.bondServer.url,
AppPass: pg.dexPass,
Asset: &bondAsset.ID,
Bond: uint64(pg.newTier) * bondAsset.Amt,
Cert: pg.bondServer.cert,
FeeBuffer: pg.dexc.BondsFeeBuffer(bondAsset.ID),
}
dexClient := pg.AssetsManager.DexClient()
// Initialize with password now, if dex password has not been
// initialized.
if !dexClient.IsDEXPasswordSet() {
pg.isLoading = true
go func() {
pg.dexPass = []byte(pg.passwordEditor.Editor.Text())
if err := dexClient.InitWithPassword(pg.dexPass, nil); err != nil {
pg.isLoading = false
pg.notifyError(err.Error())
return
}

pg.isLoading = true
go func() {
defer func() {
pg.isLoading = false
pg.postBond()
}()

res, err := pg.dexc.PostBond(postBond)
if err != nil {
pg.notifyError(fmt.Sprintf("Failed to post bond: %v", err))
return
}

pg.bondConfirmationInfo = &bondConfirmationInfo{
requiredBondConf: res.ReqConfirms,
bondCoinID: res.BondID,
}

pg.currentStep = onBoardingStepWaitForConfirmation
pg.scrollContainer.Position.Offset = 0 // Scroll to the top of the confirmation page after leaving the long post bond form.
pg.ParentWindow().Reload()
}()

dexClient := pg.AssetsManager.DexClient()
hasDEXPass := dexClient.IsDEXPasswordSet()
nextStep := func(dexPass []byte) {
pg.bondConfirmationInfo = new(bondConfirmationInfo)
bondAsset := pg.bondServer.bondAssets[asset.GetAssetType()]
postBond := &core.PostBondForm{
Addr: pg.bondServer.url,
AppPass: dexPass,
Asset: &bondAsset.ID,
Bond: uint64(pg.newTier) * bondAsset.Amt,
Cert: pg.bondServer.cert,
FeeBuffer: dexClient.BondsFeeBuffer(bondAsset.ID),
}

walletPasswordModal := modal.NewCreatePasswordModal(pg.Load).
EnableName(false).
EnableConfirmPassword(false).
Title(values.String(values.StrEnterSpendingPassword)).
SetPositiveButtonCallback(func(_, walletPass string, pm *modal.CreatePasswordModal) bool {
pg.isLoading = true
go func() {
defer func() {
pg.isLoading = false
}()

if !hasDEXPass {
if err := dexClient.InitWithPassword(dexPass, nil); err != nil {
pg.notifyError(err.Error())
return
}
}

if !dexClient.HasWallet(int32(bondAsset.ID)) {
cfg := map[string]string{
dexc.DexDcrWalletIDConfigKey: fmt.Sprintf("%d", asset.GetWalletID()),
dexc.DexDcrWalletAccountNameConfigKey: pg.bondSourceAccountSelector.SelectedAccount().AccountName,
}

// Add bond wallet to core if it does not exist.
err := dexClient.AddWallet(*postBond.Asset, cfg, dexPass, []byte(walletPass))
if err != nil {
pg.notifyError(fmt.Sprintf("Failed to prepare bond wallet: %v", err))
return
}
}

res, err := dexClient.PostBond(postBond)
if err != nil {
pg.notifyError(fmt.Sprintf("Failed to post bond: %v", err))
return
}

// Listen for new block updates. This listener is removed in OnNavigateFrom().
asset.AddTxAndBlockNotificationListener(&sharedW.TxAndBlockNotificationListener{
OnBlockAttached: func(_ int, _ int32) {
pg.bondConfirmationInfo.currentBondConf++
pg.ParentWindow().Reload()
},
}, DEXOnboardingPageID)

pg.bondConfirmationInfo.requiredBondConf = res.ReqConfirms
pg.bondConfirmationInfo.bondCoinID = res.BondID
pg.currentStep = onBoardingStepWaitForConfirmation
pg.scrollContainer.Position.Offset = 0 // Scroll to the top of the confirmation page after leaving the long post bond form.
pg.ParentWindow().Reload()
}()

return true
})
pg.ParentWindow().ShowModal(walletPasswordModal)
}

if !hasDEXPass {
nextStep([]byte(pg.passwordEditor.Editor.Text()))
return
}

// dexc password has been sent already.
dexPasswordModal := modal.NewCreatePasswordModal(pg.Load).
EnableName(false).
EnableConfirmPassword(false).
Title(values.String(values.StrDexPassword)).
SetPositiveButtonCallback(func(_, password string, pm *modal.CreatePasswordModal) bool {
err := dexClient.Login([]byte(password))
pg.dexPass = []byte(password)
err := dexClient.Login(pg.dexPass)
if err != nil {
pm.SetError(err.Error())
pm.SetLoading(false)
return false
}

pm.Dismiss()
nextStep([]byte(password))
go pg.postBond()
return true
})
dexPasswordModal.SetPasswordTitleVisibility(false)
pg.ParentWindow().ShowModal(dexPasswordModal)

case onBoardingStepWaitForConfirmation:
Expand Down Expand Up @@ -1153,6 +1025,77 @@ func (pg *DEXOnboarding) connectServerAndPrepareForBonding() {
pg.ParentWindow().Reload()
}

func (pg *DEXOnboarding) postBond() {
dexClient := pg.AssetsManager.DexClient()
asset := pg.bondSourceWalletSelector.SelectedWallet()
bondAsset := pg.bondServer.bondAssets[asset.GetAssetType()]
postBond := &core.PostBondForm{
Addr: pg.bondServer.url,
AppPass: pg.dexPass,
Asset: &bondAsset.ID,
Bond: uint64(pg.newTier) * bondAsset.Amt,
Cert: pg.bondServer.cert,
FeeBuffer: dexClient.BondsFeeBuffer(bondAsset.ID),
}

// postBondFn sends the actual request to post bond.
postBondFn := func(walletPass string) {
defer func() {
pg.isLoading = false
}()

// Add bond wallet to core if it does not exist.
if !dexClient.HasWallet(int32(bondAsset.ID)) {
cfg := map[string]string{
dexc.DexDcrWalletIDConfigKey: fmt.Sprintf("%d", asset.GetWalletID()),
dexc.DexDcrWalletAccountNameConfigKey: pg.bondSourceAccountSelector.SelectedAccount().AccountName,
}

err := dexClient.AddWallet(*postBond.Asset, cfg, pg.dexPass, []byte(walletPass))
if err != nil {
pg.notifyError(fmt.Sprintf("Failed to prepare bond wallet: %v", err))
return
}
}

res, err := dexClient.PostBond(postBond)
if err != nil {
pg.notifyError(fmt.Sprintf("Failed to post bond: %v", err))
return
}

pg.bondConfirmationInfo = &bondConfirmationInfo{
requiredBondConf: res.ReqConfirms,
bondCoinID: res.BondID,
}

// Listen for new block updates. This listener is removed in OnNavigateFrom().
asset.AddTxAndBlockNotificationListener(&sharedW.TxAndBlockNotificationListener{
OnBlockAttached: func(_ int, _ int32) {
pg.bondConfirmationInfo.currentBondConf++
pg.ParentWindow().Reload()
},
}, DEXOnboardingPageID)

pg.currentStep = onBoardingStepWaitForConfirmation
pg.scrollContainer.Position.Offset = 0 // Scroll to the top of the confirmation page after leaving the long post bond form.
pg.ParentWindow().Reload()
}

// Request for wallet password before attempting to post bond.
walletPasswordModal := modal.NewCreatePasswordModal(pg.Load).
EnableName(false).
EnableConfirmPassword(false).
Title(values.String(values.StrEnterSpendingPassword)).
SetPositiveButtonCallback(func(_, walletPass string, pm *modal.CreatePasswordModal) bool {
pg.isLoading = true
go postBondFn(walletPass)
return true
})
pg.ParentWindow().ShowModal(walletPasswordModal)

}

func (pg *DEXOnboarding) notifyError(errMsg string) {
errModal := modal.NewErrorModal(pg.Load, errMsg, modal.DefaultClickFunc())
pg.ParentWindow().ShowModal(errModal)
Expand Down

0 comments on commit 17b362e

Please sign in to comment.