Skip to content

Commit

Permalink
refactor(wallet): set server address on loading wallet (#1348)
Browse files Browse the repository at this point in the history
Co-authored-by: Javad Rajabzadeh <[email protected]>
  • Loading branch information
b00f and Ja7ad authored Jun 18, 2024
1 parent 1c01de1 commit 3e735e6
Show file tree
Hide file tree
Showing 17 changed files with 243 additions and 460 deletions.
26 changes: 13 additions & 13 deletions cmd/gtk/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,34 +170,34 @@ func setTextViewContent(tv *gtk.TextView, content string) {
buf.SetText(content)
}

func updateValidatorHint(lbl *gtk.Label, addr string, w *wallet.Wallet) {
stake, _ := w.Stake(addr)
func updateValidatorHint(lbl *gtk.Label, addr string, wlt *wallet.Wallet) {
stake, _ := wlt.Stake(addr)
hint := fmt.Sprintf("stake: %s", stake)

info := w.AddressInfo(addr)
info := wlt.AddressInfo(addr)
if info != nil && info.Label != "" {
hint += ", label: " + info.Label
}
updateHintLabel(lbl, hint)
}

func updateAccountHint(lbl *gtk.Label, addr string, w *wallet.Wallet) {
balance, _ := w.Balance(addr)
func updateAccountHint(lbl *gtk.Label, addr string, wlt *wallet.Wallet) {
balance, _ := wlt.Balance(addr)
hint := fmt.Sprintf("balance: %s", balance)

info := w.AddressInfo(addr)
info := wlt.AddressInfo(addr)
if info != nil && info.Label != "" {
hint += ", label: " + info.Label
}
updateHintLabel(lbl, hint)
}

func updateFeeHint(lbl *gtk.Label, amtStr string, w *wallet.Wallet, payloadType payload.Type) {
func updateFeeHint(lbl *gtk.Label, amtStr string, wlt *wallet.Wallet, payloadType payload.Type) {
amt, err := amount.FromString(amtStr)
if err != nil {
updateHintLabel(lbl, "")
} else {
fee, _ := w.CalculateFee(amt, payloadType)
fee, _ := wlt.CalculateFee(amt, payloadType)
hint := fmt.Sprintf("payable: %s, fee: %s",
fee+amt, fee)
updateHintLabel(lbl, hint)
Expand All @@ -209,26 +209,26 @@ func updateHintLabel(lbl *gtk.Label, hint string) {
fmt.Sprintf("<span foreground='gray' size='small'>%s</span>", hint))
}

func signAndBroadcastTransaction(parent *gtk.Dialog, msg string, w *wallet.Wallet, trx *tx.Tx) {
func signAndBroadcastTransaction(parent *gtk.Dialog, msg string, wlt *wallet.Wallet, trx *tx.Tx) {
if showQuestionDialog(parent, msg) {
password, ok := getWalletPassword(w)
password, ok := getWalletPassword(wlt)
if !ok {
return
}
err := w.SignTransaction(password, trx)
err := wlt.SignTransaction(password, trx)
if err != nil {
errorCheck(err)

return
}
txID, err := w.BroadcastTransaction(trx)
txID, err := wlt.BroadcastTransaction(trx)
if err != nil {
errorCheck(err)

return
}

err = w.Save()
err = wlt.Save()
if err != nil {
errorCheck(err)

Expand Down
7 changes: 5 additions & 2 deletions cmd/gtk/widget_wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ func buildWidgetWallet(model *walletModel) (*widgetWallet, error) {
} else {
labelEncrypted.SetText("No")
}
labelTotalBalance.SetText(model.wallet.TotalBalance().String())

totalBalance, _ := model.wallet.TotalBalance()
labelTotalBalance.SetText(totalBalance.String())

colNo := createColumn("No", IDAddressesColumnNo)
colAddress := createColumn("Address", IDAddressesColumnAddress)
Expand Down Expand Up @@ -178,8 +180,9 @@ func (ww *widgetWallet) onShowSeed() {
}

func (ww *widgetWallet) timeout() bool {
totalBalance, _ := ww.model.wallet.TotalBalance()
ww.model.rebuildModel()
ww.labelTotalBalance.SetText(ww.model.wallet.TotalBalance().String())
ww.labelTotalBalance.SetText(totalBalance.String())

return true
}
Expand Down
6 changes: 3 additions & 3 deletions cmd/wallet/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ func buildCreateCmd(parentCmd *cobra.Command) {
if *testnetOpt {
network = genesis.Testnet
}
wallet, err := wallet.Create(*pathOpt, mnemonic, password, network)
wlt, err := wallet.Create(*pathOpt, mnemonic, password, network)
cmd.FatalErrorCheck(err)

err = wallet.Save()
err = wlt.Save()
cmd.FatalErrorCheck(err)

cmd.PrintLine()
cmd.PrintSuccessMsgf("Your wallet was successfully created at: %s", wallet.Path())
cmd.PrintSuccessMsgf("Your wallet was successfully created at: %s", wlt.Path())
cmd.PrintInfoMsgf("Seed phrase: \"%v\"", mnemonic)
cmd.PrintWarnMsgf("Please keep your seed in a safe place; " +
"if you lose it, you will not be able to restore your wallet.")
Expand Down
6 changes: 3 additions & 3 deletions cmd/wallet/recover.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ func buildRecoverCmd(parentCmd *cobra.Command) {
if *testnetOpt {
chainType = genesis.Testnet
}
wallet, err := wallet.Create(*pathOpt, mnemonic, *passOpt, chainType)
wlt, err := wallet.Create(*pathOpt, mnemonic, *passOpt, chainType)
cmd.FatalErrorCheck(err)

err = wallet.Save()
err = wlt.Save()
cmd.FatalErrorCheck(err)

cmd.PrintLine()
cmd.PrintInfoMsgf("Wallet successfully recovered and saved at: %s", wallet.Path())
cmd.PrintInfoMsgf("Wallet successfully recovered and saved at: %s", wlt.Path())
}
}

Expand Down
36 changes: 18 additions & 18 deletions cmd/wallet/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func buildTransferTxCmd(parentCmd *cobra.Command) {
fee, err := amount.NewAmount(*feeOpt)
cmd.FatalErrorCheck(err)

w, err := openWallet()
wlt, err := openWallet()
cmd.FatalErrorCheck(err)

opts := []wallet.TxOption{
Expand All @@ -52,7 +52,7 @@ func buildTransferTxCmd(parentCmd *cobra.Command) {
wallet.OptionMemo(*memoOpt),
}

trx, err := w.MakeTransferTx(from, to, amt, opts...)
trx, err := wlt.MakeTransferTx(from, to, amt, opts...)
cmd.FatalErrorCheck(err)

cmd.PrintLine()
Expand All @@ -62,7 +62,7 @@ func buildTransferTxCmd(parentCmd *cobra.Command) {
cmd.PrintInfoMsgf("Amount: %s", amt)
cmd.PrintInfoMsgf("Fee : %s", trx.Fee())

signAndPublishTx(w, trx, *noConfirmOpt, *passOpt)
signAndPublishTx(wlt, trx, *noConfirmOpt, *passOpt)
}
}

Expand All @@ -88,7 +88,7 @@ func buildBondTxCmd(parentCmd *cobra.Command) {
fee, err := amount.NewAmount(*feeOpt)
cmd.FatalErrorCheck(err)

w, err := openWallet()
wlt, err := openWallet()
cmd.FatalErrorCheck(err)

opts := []wallet.TxOption{
Expand All @@ -97,7 +97,7 @@ func buildBondTxCmd(parentCmd *cobra.Command) {
wallet.OptionMemo(*memoOpt),
}

trx, err := w.MakeBondTx(from, to, *pubKeyOpt, amt, opts...)
trx, err := wlt.MakeBondTx(from, to, *pubKeyOpt, amt, opts...)
cmd.FatalErrorCheck(err)

cmd.PrintLine()
Expand All @@ -107,7 +107,7 @@ func buildBondTxCmd(parentCmd *cobra.Command) {
cmd.PrintInfoMsgf("Stake : %s", amt)
cmd.PrintInfoMsgf("Fee : %s", trx.Fee())

signAndPublishTx(w, trx, *noConfirmOpt, *passOpt)
signAndPublishTx(wlt, trx, *noConfirmOpt, *passOpt)
}
}

Expand All @@ -129,7 +129,7 @@ func buildUnbondTxCmd(parentCmd *cobra.Command) {
fee, err := amount.NewAmount(*feeOpt)
cmd.FatalErrorCheck(err)

w, err := openWallet()
wlt, err := openWallet()
cmd.FatalErrorCheck(err)

opts := []wallet.TxOption{
Expand All @@ -138,15 +138,15 @@ func buildUnbondTxCmd(parentCmd *cobra.Command) {
wallet.OptionMemo(*memoOpt),
}

trx, err := w.MakeUnbondTx(from, opts...)
trx, err := wlt.MakeUnbondTx(from, opts...)
cmd.FatalErrorCheck(err)

cmd.PrintLine()
cmd.PrintInfoMsgf("You are going to sign this \033[1mUnbond\033[0m transition:")
cmd.PrintInfoMsgf("Validator: %s", from)
cmd.PrintInfoMsgf("Fee : %s", trx.Fee())

signAndPublishTx(w, trx, *noConfirmOpt, *passOpt)
signAndPublishTx(wlt, trx, *noConfirmOpt, *passOpt)
}
}

Expand All @@ -171,7 +171,7 @@ func buildWithdrawTxCmd(parentCmd *cobra.Command) {
fee, err := amount.NewAmount(*feeOpt)
cmd.FatalErrorCheck(err)

w, err := openWallet()
wlt, err := openWallet()
cmd.FatalErrorCheck(err)

opts := []wallet.TxOption{
Expand All @@ -180,7 +180,7 @@ func buildWithdrawTxCmd(parentCmd *cobra.Command) {
wallet.OptionMemo(*memoOpt),
}

trx, err := w.MakeWithdrawTx(from, to, amt, opts...)
trx, err := wlt.MakeWithdrawTx(from, to, amt, opts...)
cmd.FatalErrorCheck(err)

cmd.PrintLine()
Expand All @@ -190,7 +190,7 @@ func buildWithdrawTxCmd(parentCmd *cobra.Command) {
cmd.PrintInfoMsgf("Amount : %s", amt)
cmd.PrintInfoMsgf("Fee : %s", trx.Fee())

signAndPublishTx(w, trx, *noConfirmOpt, *passOpt)
signAndPublishTx(wlt, trx, *noConfirmOpt, *passOpt)
}
}

Expand All @@ -210,17 +210,17 @@ func addCommonTxOptions(c *cobra.Command) (*int, *float64, *string, *bool) {
return lockTimeOpt, feeOpt, memoOpt, noConfirmOpt
}

func signAndPublishTx(w *wallet.Wallet, trx *tx.Tx, noConfirm bool, pass string) {
func signAndPublishTx(wlt *wallet.Wallet, trx *tx.Tx, noConfirm bool, pass string) {
cmd.PrintLine()
password := getPassword(w, pass)
err := w.SignTransaction(password, trx)
password := getPassword(wlt, pass)
err := wlt.SignTransaction(password, trx)
cmd.FatalErrorCheck(err)

bs, _ := trx.Bytes()
cmd.PrintInfoMsgf("Signed transaction data: %x", bs)
cmd.PrintLine()

if !w.IsOffline() {
if !wlt.IsOffline() {
if !noConfirm {
cmd.PrintInfoMsgf("You are going to broadcast the signed transition:")
cmd.PrintWarnMsgf("THIS ACTION IS NOT REVERSIBLE")
Expand All @@ -229,10 +229,10 @@ func signAndPublishTx(w *wallet.Wallet, trx *tx.Tx, noConfirm bool, pass string)
return
}
}
res, err := w.BroadcastTransaction(trx)
res, err := wlt.BroadcastTransaction(trx)
cmd.FatalErrorCheck(err)

err = w.Save()
err = wlt.Save()
cmd.FatalErrorCheck(err)

cmd.PrintInfoMsgf("Transaction hash: %s", res)
Expand Down
8 changes: 8 additions & 0 deletions util/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"crypto/subtle"
"encoding/binary"
"io"
"math/rand"
)

func Uint16ToSlice(n uint16) []byte {
Expand Down Expand Up @@ -243,3 +244,10 @@ func Trim[T any](s []T, newLength int) []T {

return s
}

// Shuffle shuffles a slice of any type.
func Shuffle[T any](slice []T) {
rand.Shuffle(len(slice), func(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
})
}
15 changes: 15 additions & 0 deletions util/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -347,3 +347,18 @@ func TestTrimSlice(t *testing.T) {
assert.Equal(t, got, tt.want, "Trim() = %v, want %v", got, tt.want)
}
}

func TestShuffle(t *testing.T) {
// Create a slice with 100 integers
ints := make([]int, 100)
for i := range ints {
ints[i] = i + 1
}
originalInts := make([]int, len(ints))
copy(originalInts, ints)

Shuffle(ints)

assert.NotEqual(t, originalInts, ints, "ints slice was not shuffled")
assert.ElementsMatch(t, originalInts, ints, "ints slice does not contain the same elements")
}
25 changes: 9 additions & 16 deletions wallet/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,49 +8,42 @@ import (
"github.com/pactus-project/pactus/types/amount"
"github.com/pactus-project/pactus/types/tx"
"github.com/pactus-project/pactus/types/tx/payload"
"github.com/pactus-project/pactus/util"
pactus "github.com/pactus-project/pactus/www/grpc/gen/go"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)

const (
AddressTypeBLSAccount string = "bls_account"
AddressTypeValidator string = "validator"
)

// gRPCClient is a gRPC client that randomly establishes a connection to a gRPC server.
// It is used to get information such as account balance or transaction data from the server.
type grpcClient struct {
ctx context.Context
cancel func() // TODO: call me!
servers []string
conn *grpc.ClientConn
blockchainClient pactus.BlockchainClient
transactionClient pactus.TransactionClient
}

func newGRPCClient(servers []string) *grpcClient {
// TODO: context should be passed here
ctx, cancel := context.WithCancel(context.Background())
func newGrpcClient() *grpcClient {
ctx := context.WithoutCancel(context.Background())

return &grpcClient{
ctx: ctx,
cancel: cancel,
servers: servers,
conn: nil,
blockchainClient: nil,
transactionClient: nil,
}
}

func (c *grpcClient) SetServerAddrs(servers []string) {
c.servers = servers
}

func (c *grpcClient) connect() error {
if c.conn != nil {
return nil
}

maxTry := util.Min(3, len(c.servers))
for i := 0; i < maxTry; i++ {
n := util.RandInt32(int32(len(c.servers)))
server := c.servers[n]
for _, server := range c.servers {
conn, err := grpc.NewClient(server,
grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
Expand Down
Loading

0 comments on commit 3e735e6

Please sign in to comment.