github.com/aergoio/aergo@v1.3.1/cmd/brick/exec/getstateAccount.go (about)

     1  package exec
     2  
     3  import (
     4  	"fmt"
     5  	"math/big"
     6  
     7  	"github.com/aergoio/aergo/cmd/brick/context"
     8  	"github.com/aergoio/aergo/contract"
     9  )
    10  
    11  func init() {
    12  	registerExec(&getStateAccount{})
    13  }
    14  
    15  type getStateAccount struct{}
    16  
    17  func (c *getStateAccount) Command() string {
    18  	return "getstate"
    19  }
    20  
    21  func (c *getStateAccount) Syntax() string {
    22  	return fmt.Sprintf("%s", context.AccountSymbol)
    23  }
    24  
    25  func (c *getStateAccount) Usage() string {
    26  	return fmt.Sprintf("getstate <account_name> `[expected_balance]`")
    27  }
    28  
    29  func (c *getStateAccount) Describe() string {
    30  	return "create an account with a given amount of balance"
    31  }
    32  
    33  func (c *getStateAccount) Validate(args string) error {
    34  	if context.Get() == nil {
    35  		return fmt.Errorf("load chain first")
    36  	}
    37  
    38  	_, _, err := c.parse(args)
    39  
    40  	return err
    41  }
    42  
    43  func (c *getStateAccount) parse(args string) (string, string, error) {
    44  	splitArgs := context.SplitSpaceAndAccent(args, false)
    45  	if len(splitArgs) < 1 {
    46  		return "", "", fmt.Errorf("need an arguments. usage: %s", c.Usage())
    47  	}
    48  
    49  	expectedResult := ""
    50  	if len(splitArgs) == 2 {
    51  		expectedResult = splitArgs[1].Text
    52  	} else if len(splitArgs) > 2 {
    53  		return "", "", fmt.Errorf("too many arguments. usage: %s", c.Usage())
    54  	}
    55  
    56  	return splitArgs[0].Text, expectedResult, nil
    57  }
    58  
    59  func (c *getStateAccount) Run(args string) (string, error) {
    60  	accountName, expectedResult, _ := c.parse(args)
    61  
    62  	state, err := context.Get().GetAccountState(accountName)
    63  
    64  	if err != nil {
    65  		return "", err
    66  	}
    67  	if expectedResult == "" {
    68  		return fmt.Sprintf("%s = %d", contract.StrToAddress(accountName), new(big.Int).SetBytes(state.GetBalance())), nil
    69  	} else {
    70  		strRet := fmt.Sprintf("%d", new(big.Int).SetBytes(state.GetBalance()))
    71  		if expectedResult == strRet {
    72  			return "state compare successfully", nil
    73  		} else {
    74  			return "", fmt.Errorf("state compre fail. Expected: %s, Actual: %s", expectedResult, strRet)
    75  		}
    76  	}
    77  }