}
// MergeSpendAction merge common assetID and accountID spend action
-func MergeSpendAction(spendActions []txbuilder.Action) []txbuilder.Action {
- actions := []txbuilder.Action{}
- actionMap := make(map[string]*spendAction)
+func MergeSpendAction(actions []txbuilder.Action) []txbuilder.Action {
+ resultActions := []txbuilder.Action{}
+ spendActionMap := make(map[string]*spendAction)
- for _, act := range spendActions {
+ for _, act := range actions {
switch act := act.(type) {
case *spendAction:
actionKey := act.AssetId.String() + act.AccountID
- if tmpAct, ok := actionMap[actionKey]; ok {
+ if tmpAct, ok := spendActionMap[actionKey]; ok {
tmpAct.Amount += act.Amount
} else {
- actionMap[actionKey] = act
+ spendActionMap[actionKey] = act
+ resultActions = append(resultActions, act)
}
default:
- actions = append(actions, act)
+ resultActions = append(resultActions, act)
}
}
-
- for actKey := range actionMap {
- spend := actionMap[actKey]
- actions = append(actions, txbuilder.Action(spend))
- }
-
- return actions
+ return resultActions
}
func (a *spendAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
},
{
testActions: []txbuilder.Action{
+ txbuilder.Action(&spendUTXOAction{
+ OutputID: &bc.Hash{V0: 128},
+ }),
txbuilder.Action(&spendAction{
AssetAmount: bc.AssetAmount{
AssetId: testBTM,
},
AccountID: "test_account1",
}),
+ txbuilder.Action(&spendUTXOAction{
+ OutputID: &bc.Hash{V0: 256},
+ }),
txbuilder.Action(&spendAction{
AssetAmount: bc.AssetAmount{
AssetId: testAssetID2,
}),
},
wantActions: []txbuilder.Action{
+ txbuilder.Action(&spendUTXOAction{
+ OutputID: &bc.Hash{V0: 128},
+ }),
txbuilder.Action(&spendAction{
AssetAmount: bc.AssetAmount{
AssetId: testBTM,
},
AccountID: "test_account1",
}),
+ txbuilder.Action(&spendUTXOAction{
+ OutputID: &bc.Hash{V0: 256},
+ }),
txbuilder.Action(&spendAction{
AssetAmount: bc.AssetAmount{
AssetId: testAssetID2,
AccountID: "test_account2",
}),
},
- testActionCount: 3,
- wantActionCount: 3,
+ testActionCount: 5,
+ wantActionCount: 5,
},
}
return nil, errors.New("transaction only contain spend actions, didn't have output actions")
}
- spendActions := []txbuilder.Action{}
actions := make([]txbuilder.Action, 0, len(req.Actions))
for i, act := range req.Actions {
typ, ok := act["type"].(string)
if err != nil {
return nil, errors.WithDetailf(errBadAction, "%s on action %d", err.Error(), i)
}
-
- if typ == "spend_account" {
- spendActions = append(spendActions, action)
- } else {
- actions = append(actions, action)
- }
+ actions = append(actions, action)
}
- actions = append(account.MergeSpendAction(spendActions), actions...)
+ actions = account.MergeSpendAction(actions)
ttl := req.TTL.Duration
if ttl == 0 {