github.com/aergoio/aergo@v1.3.1/cmd/brick/exec/queryContract.go (about) 1 package exec 2 3 import ( 4 "fmt" 5 6 "github.com/aergoio/aergo/cmd/brick/context" 7 ) 8 9 func init() { 10 registerExec(&queryContract{}) 11 } 12 13 type queryContract struct{} 14 15 func (c *queryContract) Command() string { 16 return "query" 17 } 18 19 func (c *queryContract) Syntax() string { 20 return fmt.Sprintf("%s %s %s %s %s", context.ContractSymbol, context.FunctionSymbol, 21 context.ContractArgsSymbol, context.ExpectedSymbol, context.ExpectedErrSymbol) 22 } 23 24 func (c *queryContract) Usage() string { 25 return fmt.Sprintf("query <contract_name> <func_name> `[query_json_str]` `[expected_query_result]` `[expected_error_str]`") 26 } 27 28 func (c *queryContract) Describe() string { 29 return "query a smart contract" 30 } 31 32 func (c *queryContract) Validate(args string) error { 33 34 // is chain is loaded? 35 if context.Get() == nil { 36 return fmt.Errorf("load chain first") 37 } 38 39 _, _, _, _, _, err := c.parse(args) 40 41 return err 42 } 43 44 func (c *queryContract) parse(args string) (string, string, string, string, string, error) { 45 46 splitArgs := context.SplitSpaceAndAccent(args, false) 47 if len(splitArgs) < 2 { 48 return "", "", "", "", "", fmt.Errorf("need at least 2 arguments. usage: %s", c.Usage()) 49 } 50 51 queryCode := "[]" 52 53 if len(splitArgs) >= 3 { 54 queryCode = splitArgs[2].Text 55 } 56 57 expectedResult := "" 58 expectedError := "" 59 if len(splitArgs) == 4 { 60 expectedResult = splitArgs[3].Text 61 } else if len(splitArgs) == 5 { 62 expectedResult = splitArgs[3].Text 63 expectedError = splitArgs[4].Text 64 } else if len(splitArgs) > 5 { 65 return "", "", "", "", "", fmt.Errorf("too many arguments. usage: %s", c.Usage()) 66 } 67 68 return splitArgs[0].Text, // contractName 69 splitArgs[1].Text, //funcName 70 queryCode, //queryCode 71 expectedResult, //expectedResult 72 expectedError, 73 nil 74 } 75 76 func (c *queryContract) Run(args string) (string, error) { 77 contractName, funcName, queryCode, expectedResult, expectedError, _ := c.parse(args) 78 79 formattedQuery := fmt.Sprintf("{\"name\":\"%s\",\"args\":%s}", funcName, queryCode) 80 81 if expectedResult == "" { 82 // there is no expected result 83 isTestPassed, result, err := context.Get().QueryOnly(contractName, formattedQuery, expectedError) 84 85 if err != nil { 86 return "", err 87 } else if isTestPassed { 88 return "query to a smart contract successfully", nil 89 } 90 91 return result, nil 92 } 93 // there is expected result 94 err := context.Get().Query(contractName, formattedQuery, expectedError, expectedResult) 95 96 if err != nil { 97 return "", err 98 } 99 100 Index(context.ExpectedSymbol, expectedResult) 101 if expectedError != "" { 102 Index(context.ExpectedErrSymbol, expectedError) 103 } 104 105 return "query to a smart contract successfully", nil 106 }