Skip to content

Commit

Permalink
chappjc review and other stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
buck54321 committed Jul 21, 2022
1 parent 78a8aa2 commit c5b40ba
Show file tree
Hide file tree
Showing 9 changed files with 87 additions and 82 deletions.
3 changes: 2 additions & 1 deletion client/asset/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,8 @@ func Asset(assetID uint32) *RegisteredAsset {
return ra
}

// Token returns *Token for a registered token, or nil if the token is unknown.
// TokenInfo returns *Token for a registered token, or nil if the token is
// unknown.
func TokenInfo(assetID uint32) *Token {
driversMtx.RLock()
defer driversMtx.RUnlock()
Expand Down
63 changes: 32 additions & 31 deletions client/core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -1503,7 +1503,7 @@ func (c *Core) storeDepositAddress(wdbID []byte, addr string) error {
func (c *Core) connectAndUpdateWallet(w *xcWallet) error {
assetID := w.AssetID

token := asset.TokenInfo(w.AssetID)
token := asset.TokenInfo(assetID)
if token != nil {
parentWallet, found := c.wallet(token.ParentID)
if !found {
Expand Down Expand Up @@ -1816,13 +1816,15 @@ func (c *Core) CreateWallet(appPW, walletPW []byte, form *WalletForm) error {
// If this isn't a token, easy route.
token := asset.TokenInfo(assetID)
if token == nil {
return c.createWalletOrToken(crypter, walletPW, form)
_, err = c.createWalletOrToken(crypter, walletPW, form)
return err
}

// If the parent already exists, easy route.
_, found := c.wallet(token.ParentID)
if found {
return c.createWalletOrToken(crypter, walletPW, form)
_, err = c.createWalletOrToken(crypter, walletPW, form)
return err
}

// Double-registration mode. The parent wallet will be created
Expand All @@ -1840,13 +1842,14 @@ func (c *Core) CreateWallet(appPW, walletPW []byte, form *WalletForm) error {
form.ParentForm.AssetID, token.ParentID)
}

if c.setWalletCreationPending(assetID); err != nil {
if err = c.setWalletCreationPending(assetID); err != nil {
// Creation already pending?
return err
}

// Create the parent synchronously.
if err := c.createWalletOrToken(crypter, walletPW, form.ParentForm); err != nil {
parentWallet, err := c.createWalletOrToken(crypter, walletPW, form.ParentForm)
if err != nil {
c.setWalletCreationComplete(assetID)
return fmt.Errorf("error creating parent wallet: %v", err)
}
Expand All @@ -1862,19 +1865,6 @@ func (c *Core) CreateWallet(appPW, walletPW []byte, form *WalletForm) error {
defer c.setWalletCreationComplete(assetID)
defer crypter.Close()

reportErr := func(userMsg, s string, a ...interface{}) {
c.log.Errorf(s, a...)
subject, details := c.formatDetails(TopicQueuedCreationFailed, unbip(token.ParentID), symbol, userMsg)
// Send this with details, but at level Data, so that the error
// message can displayed on the creation form.
c.notify(newWalletCreationNote(TopicQueuedCreationFailed, subject, details, db.Data, assetID))
}

parentWallet, found := c.wallet(token.ParentID)
if !found {
reportErr("parent wallet missing", "parent %s wallet missing after creation", unbip(token.ParentID))
return
}
for {
parentWallet.mtx.RLock()
synced := parentWallet.synced
Expand All @@ -1890,8 +1880,10 @@ func (c *Core) CreateWallet(appPW, walletPW []byte, form *WalletForm) error {
}
// If there was a walletPW provided, it was for the parent wallet, so
// use nil here.
if err := c.createWalletOrToken(crypter, nil, form); err != nil {
reportErr("create error", "failed to create token wallet: %v", err)
if _, err := c.createWalletOrToken(crypter, nil, form); err != nil {
c.log.Errorf("failed to create token wallet: %v", err)
subject, details := c.formatDetails(TopicQueuedCreationFailed, unbip(token.ParentID), symbol)
c.notify(newWalletCreationNote(TopicQueuedCreationFailed, subject, details, db.ErrorLevel, assetID))
} else {
c.notify(newWalletCreationNote(TopicQueuedCreationSuccess, "", "", db.Data, assetID))
}
Expand All @@ -1900,7 +1892,7 @@ func (c *Core) CreateWallet(appPW, walletPW []byte, form *WalletForm) error {
return nil
}

func (c *Core) createWalletOrToken(crypter encrypt.Crypter, walletPW []byte, form *WalletForm) (err error) {
func (c *Core) createWalletOrToken(crypter encrypt.Crypter, walletPW []byte, form *WalletForm) (wallet *xcWallet, err error) {
assetID := form.AssetID
symbol := unbip(assetID)
token := asset.TokenInfo(assetID)
Expand All @@ -1911,29 +1903,29 @@ func (c *Core) createWalletOrToken(crypter encrypt.Crypter, walletPW []byte, for
dbWallet, err = c.createWallet(crypter, walletPW, assetID, form)
}
if err != nil {
return err
return nil, err
}

wallet, err := c.loadWallet(dbWallet)
wallet, err = c.loadWallet(dbWallet)
if err != nil {
return fmt.Errorf("error loading wallet for %d -> %s: %w", assetID, symbol, err)
return nil, fmt.Errorf("error loading wallet for %d -> %s: %w", assetID, symbol, err)
}

dbWallet.Address, err = c.connectWallet(wallet)
if err != nil {
return err
return nil, err
}

initErr := func(s string, a ...interface{}) error {
initErr := func(s string, a ...interface{}) (*xcWallet, error) {
_ = wallet.Lock(2 * time.Second) // just try, but don't confuse the user with an error
wallet.Disconnect()
return fmt.Errorf(s, a...)
return nil, fmt.Errorf(s, a...)
}

err = wallet.Unlock(crypter)
if err != nil {
wallet.Disconnect()
return fmt.Errorf("%s wallet authentication error: %w", symbol, err)
return nil, fmt.Errorf("%s wallet authentication error: %w", symbol, err)
}

balances, err := c.walletBalance(wallet)
Expand Down Expand Up @@ -1961,7 +1953,7 @@ func (c *Core) createWalletOrToken(crypter encrypt.Crypter, walletPW []byte, for

c.notify(newWalletStateNote(wallet.state()))

return nil
return wallet, nil
}

func (c *Core) createWallet(crypter encrypt.Crypter, walletPW []byte, assetID uint32, form *WalletForm) (*db.Wallet, error) {
Expand Down Expand Up @@ -2029,13 +2021,22 @@ func (c *Core) createTokenWallet(tokenID uint32, token *asset.Token, form *Walle
return nil, fmt.Errorf("parent wallet %s is not a TokenMaster", unbip(token.ParentID))
}

// Sometimes core will insert data into the Settings map to communicate
// information back to the wallet, so it cannot be nil.
if form.Config == nil {
form.Config = make(map[string]string)
}

if err := tokenMaster.CreateTokenWallet(tokenID, form.Config); err != nil {
return nil, fmt.Errorf("CreateTokenWallet error: %w", err)
}

return &db.Wallet{
Type: "token",
AssetID: tokenID,
Type: "token",
AssetID: tokenID,
Settings: form.Config,
// EncryptedPW ignored because we assume throughout that token wallet
// authorization is handled by the parent.
// Balance and Address are set after connect.
}, nil
}
Expand Down
2 changes: 1 addition & 1 deletion client/core/locale_ntfn.go
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ var enUS = map[Topic]*translation{
// [parentSymbol, tokenSymbol, errorMsg]
TopicQueuedCreationFailed: {
subject: "Failed to create token wallet",
template: "After creating %s wallet, failed to create the %s wallet: %s",
template: "After creating %s wallet, failed to create the %s wallet",
},
}

Expand Down
6 changes: 3 additions & 3 deletions client/webserver/site/src/js/markets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2511,9 +2511,9 @@ class BalanceWidget {
*/
setWallets (host: string, baseID: number, quoteID: number) {
const parentID = (assetID: number) => {
const token = app().assets[assetID].token
if (!token) return parentIDNone
return token.parentID
const asset = app().assets[assetID]
if (asset?.token) return asset.token.parentID
return parentIDNone
}
this.dex = app().user.exchanges[host]
this.base.id = baseID
Expand Down
2 changes: 1 addition & 1 deletion dex/networks/eth/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ func VersionedNetworkToken(assetID uint32, contractVer uint32, net dex.Network)
return token, addrs.Address, contract.Address, nil
}

// MaybeReadSimnetAddrs attemps to read the info files generated by the eth
// MaybeReadSimnetAddrs attempts to read the info files generated by the eth
// simnet harness to populate swap contract and token addresses in
// ContractAddresses and Tokens.
func MaybeReadSimnetAddrs() {
Expand Down
12 changes: 6 additions & 6 deletions dex/testing/loadbot/compound.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ func runCompound() {
wg.Add(4)
go func() {
defer wg.Done()
runTrader(newSideStacker(true, 5, 3, alpha, false), "CMPD:STACKER:0")
runTrader(newSideStacker(true, 5, 3, alpha, false, log.SubLogger("STACKER:0")), "CMPD:STACKER:0")
}()
go func() {
defer wg.Done()
runTrader(newSideStacker(false, 5, 3, alpha, false), "CMPD:STACKER:1")
runTrader(newSideStacker(false, 5, 3, alpha, false, log.SubLogger("STACKER:1")), "CMPD:STACKER:1")
}()
go func() {
defer wg.Done()
Expand Down Expand Up @@ -65,19 +65,19 @@ func runHeavy() {
wg.Add(5)
go func() {
defer wg.Done()
runTrader(newSideStacker(true, 12, 6, alpha, true), "HEAVY:STACKER:0")
runTrader(newSideStacker(true, 12, 6, alpha, true, log.SubLogger("STACKER:0")), "HEAVY:STACKER:0")
}()
go func() {
defer wg.Done()
runTrader(newSideStacker(false, 12, 6, alpha, true), "HEAVY:STACKER:1")
runTrader(newSideStacker(false, 12, 6, alpha, true, log.SubLogger("STACKER:1")), "HEAVY:STACKER:1")
}()
go func() {
defer wg.Done()
runTrader(newSideStacker(true, 8, 4, beta, false), "HEAVY:STACKER:2")
runTrader(newSideStacker(true, 8, 4, beta, false, log.SubLogger("STACKER:2")), "HEAVY:STACKER:2")
}()
go func() {
defer wg.Done()
runTrader(newSideStacker(false, 8, 4, beta, false), "HEAVY:STACKER:3")
runTrader(newSideStacker(false, 8, 4, beta, false, log.SubLogger("STACKER:3")), "HEAVY:STACKER:3")
}()
go func() {
defer wg.Done()
Expand Down
17 changes: 10 additions & 7 deletions dex/testing/loadbot/sidestacker.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"time"

"decred.org/dcrdex/client/core"
"decred.org/dcrdex/dex"
"decred.org/dcrdex/dex/calc"
"decred.org/dcrdex/dex/msgjson"
"decred.org/dcrdex/dex/order"
Expand All @@ -22,6 +23,7 @@ const stackerSpread = 0.05
// side before submitting taker orders for the other. There is some built-in
// randomness to the rates and quantities of the sideStacker's orders.
type sideStacker struct {
log dex.Logger
node string
seller bool
metered bool
Expand All @@ -36,8 +38,9 @@ type sideStacker struct {

var _ Trader = (*sideStacker)(nil)

func newSideStacker(seller bool, numStanding, ordsPerEpoch int, node string, metered bool) *sideStacker {
func newSideStacker(seller bool, numStanding, ordsPerEpoch int, node string, metered bool, log dex.Logger) *sideStacker {
return &sideStacker{
log: log,
node: node,
seller: seller,
metered: metered,
Expand All @@ -56,11 +59,11 @@ func runSideStacker(numStanding, ordsPerEpoch int) {
wg.Add(2)
go func() {
defer wg.Done()
runTrader(newSideStacker(true, numStanding, ordsPerEpoch, alpha, false), "STACKER:0")
runTrader(newSideStacker(true, numStanding, ordsPerEpoch, alpha, false, log.SubLogger("STACKER:0")), "STACKER:0")
}()
go func() {
defer wg.Done()
runTrader(newSideStacker(false, numStanding, ordsPerEpoch, alpha, false), "STACKER:1")
runTrader(newSideStacker(false, numStanding, ordsPerEpoch, alpha, false, log.SubLogger("STACKER:1")), "STACKER:1")
}()
wg.Wait()

Expand All @@ -78,7 +81,7 @@ func (s *sideStacker) SetupWallets(m *Mantle) {
baseCoins, quoteCoins, minBaseQty, maxBaseQty, minQuoteQty, maxQuoteQty := walletConfig(maxOrderLots, maxActiveOrders, s.seller)
m.createWallet(baseSymbol, s.node, minBaseQty, maxBaseQty, baseCoins)
m.createWallet(quoteSymbol, s.node, minQuoteQty, maxQuoteQty, quoteCoins)
m.log.Infof("Side Stacker has been initialized with %d target standing orders, %d orders "+
s.log.Infof("Side Stacker has been initialized with %d target standing orders, %d orders "+
"per epoch, %s to %s %s balance, and %s to %s %s balance, %d initial %s coins, %d initial %s coins",
s.numStanding, s.ordsPerEpoch, valString(minBaseQty, baseSymbol), valString(maxBaseQty, baseSymbol), baseSymbol,
valString(minQuoteQty, quoteSymbol), valString(maxQuoteQty, quoteSymbol), quoteSymbol, baseCoins, baseSymbol, quoteCoins, quoteSymbol)
Expand All @@ -90,7 +93,7 @@ func (s *sideStacker) SetupWallets(m *Mantle) {
func (s *sideStacker) HandleNotification(m *Mantle, note core.Notification) {
switch n := note.(type) {
case *core.EpochNotification:
m.log.Debugf("Epoch note received: %s", mustJSON(note))
s.log.Debugf("Epoch note received: %s", mustJSON(note))
if n.MarketID == market {
// delay the orders, since the epoch note comes before the order
// book updates associated with the last epoch. Ideally, we want a
Expand All @@ -107,7 +110,7 @@ func (s *sideStacker) HandleNotification(m *Mantle, note core.Notification) {
m.replenishBalances()
}
case *core.BalanceNote:
log.Infof("sidestacker balance: %s = %d available, %d locked", unbip(n.AssetID), n.Balance.Available, n.Balance.Locked)
s.log.Infof("Balance: %s = %d available, %d locked", unbip(n.AssetID), n.Balance.Available, n.Balance.Locked)
}
}

Expand Down Expand Up @@ -157,7 +160,7 @@ func (s *sideStacker) stack(m *Mantle) {
}
numNewStanding = clamp(numNewStanding, 0, s.ordsPerEpoch)
numMatchers := s.ordsPerEpoch - numNewStanding
m.log.Infof("Side Stacker (seller = %t) placing %d standers and %d matchers. Currently %d active orders",
s.log.Infof("Seller = %t placing %d standers and %d matchers. Currently %d active orders",
s.seller, numNewStanding, numMatchers, activeOrders)

qty := func() uint64 {
Expand Down
18 changes: 9 additions & 9 deletions server/asset/eth/coiner.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ type redeemCoin struct {
// it in the mempool. It also tells us all the data we need to confirm a tx
// will do what we expect if mined and satisfies contract constraints. These
// fields are verified when the Confirmations method is called.
func (eth *AssetBackend) newSwapCoin(coinID []byte, contractData []byte) (*swapCoin, error) {
bc, err := eth.baseCoin(coinID, contractData)
func (be *AssetBackend) newSwapCoin(coinID []byte, contractData []byte) (*swapCoin, error) {
bc, err := be.baseCoin(coinID, contractData)
if err != nil {
return nil, err
}
Expand All @@ -66,7 +66,7 @@ func (eth *AssetBackend) newSwapCoin(coinID []byte, contractData []byte) (*swapC
return nil, fmt.Errorf("tx %v does not contain initiation with secret hash %x", bc.txHash, bc.secretHash)
}

if eth.assetID == BipID {
if be.assetID == BipID {
var sum uint64
for _, in := range inits {
sum += in.Value
Expand All @@ -87,8 +87,8 @@ func (eth *AssetBackend) newSwapCoin(coinID []byte, contractData []byte) (*swapC
// TODO: The redeemCoin's Confirmation method is never used by the current
// swapper implementation. Might consider an API change for
// asset.Backend.Redemption.
func (eth *AssetBackend) newRedeemCoin(coinID []byte, contractData []byte) (*redeemCoin, error) {
bc, err := eth.baseCoin(coinID, contractData)
func (be *AssetBackend) newRedeemCoin(coinID []byte, contractData []byte) (*redeemCoin, error) {
bc, err := be.baseCoin(coinID, contractData)
if err != nil {
return nil, err
}
Expand All @@ -113,12 +113,12 @@ func (eth *AssetBackend) newRedeemCoin(coinID []byte, contractData []byte) (*red
}

// The baseCoin is basic tx and swap contract data.
func (eth *AssetBackend) baseCoin(coinID []byte, contractData []byte) (*baseCoin, error) {
func (be *AssetBackend) baseCoin(coinID []byte, contractData []byte) (*baseCoin, error) {
txHash, err := dexeth.DecodeCoinID(coinID)
if err != nil {
return nil, err
}
tx, _, err := eth.node.transaction(eth.ctx, txHash)
tx, _, err := be.node.transaction(be.ctx, txHash)
if err != nil {
if errors.Is(err, ethereum.NotFound) {
return nil, asset.CoinNotFoundError
Expand All @@ -139,7 +139,7 @@ func (eth *AssetBackend) baseCoin(coinID []byte, contractData []byte) (*baseCoin
return nil, fmt.Errorf("contract version %d not supported, only %d", contractVer, version)
}
contractAddr := tx.To()
if *contractAddr != eth.contractAddr {
if *contractAddr != be.contractAddr {
return nil, fmt.Errorf("contract address is not supported: %v", contractAddr)
}

Expand Down Expand Up @@ -179,7 +179,7 @@ func (eth *AssetBackend) baseCoin(coinID []byte, contractData []byte) (*baseCoin
}

return &baseCoin{
backend: eth,
backend: be,
secretHash: secretHash,
gasFeeCap: gasFeeCapGwei,
gasTipCap: gasTipCapGwei,
Expand Down
Loading

0 comments on commit c5b40ba

Please sign in to comment.