github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/api/request.go (about)

     1  package api
     2  
     3  import (
     4  	"context"
     5  	"strings"
     6  
     7  	"github.com/bytom/bytom/consensus"
     8  	"github.com/bytom/bytom/encoding/json"
     9  	"github.com/bytom/bytom/errors"
    10  	"github.com/bytom/bytom/protocol/bc/types"
    11  )
    12  
    13  // action error
    14  var (
    15  	ErrBadActionType         = errors.New("bad action type")
    16  	ErrBadAction             = errors.New("bad action object")
    17  	ErrBadActionConstruction = errors.New("bad action construction")
    18  )
    19  
    20  // BuildRequest is main struct when building transactions
    21  type BuildRequest struct {
    22  	Tx        *types.TxData            `json:"base_transaction"`
    23  	Actions   []map[string]interface{} `json:"actions"`
    24  	TTL       json.Duration            `json:"ttl"`
    25  	TimeRange uint64                   `json:"time_range"`
    26  }
    27  
    28  func (a *API) completeMissingIDs(ctx context.Context, br *BuildRequest) error {
    29  	for i, m := range br.Actions {
    30  		if err := a.completeMissingAssetID(m, i); err != nil {
    31  			return err
    32  		}
    33  		if err := a.completeMissingAccountID(m, i, ctx); err != nil {
    34  			return err
    35  		}
    36  	}
    37  	return nil
    38  }
    39  
    40  func (a *API) completeMissingAssetID(m map[string]interface{}, index int) error {
    41  	id, _ := m["asset_id"].(string)
    42  	alias, _ := m["asset_alias"].(string)
    43  	if id == "" && alias != "" {
    44  		alias = strings.ToUpper(alias)
    45  		switch alias {
    46  		case consensus.BTMAlias:
    47  			m["asset_id"] = consensus.BTMAssetID.String()
    48  		default:
    49  			asset, err := a.wallet.AssetReg.FindByAlias(alias)
    50  			if err != nil {
    51  				return errors.WithDetailf(err, "invalid asset alias %s on action %d", alias, index)
    52  			}
    53  			m["asset_id"] = asset.AssetID.String()
    54  		}
    55  	}
    56  	return nil
    57  }
    58  
    59  func (a *API) completeMissingAccountID(m map[string]interface{}, index int, ctx context.Context) error {
    60  	id, _ := m["account_id"].(string)
    61  	alias, _ := m["account_alias"].(string)
    62  	if id == "" && alias != "" {
    63  		acc, err := a.wallet.AccountMgr.FindByAlias(alias)
    64  		if err != nil {
    65  			return errors.WithDetailf(err, "invalid account alias %s on action %d", alias, index)
    66  		}
    67  		m["account_id"] = acc.ID
    68  	}
    69  	return nil
    70  }