-
Notifications
You must be signed in to change notification settings - Fork 2
/
fake.go
74 lines (61 loc) · 2.04 KB
/
fake.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package simulation
import (
"errors"
"fmt"
"math/big"
"math/rand"
"github.com/hdac-io/friday/baseapp"
sdk "github.com/hdac-io/friday/types"
"github.com/hdac-io/friday/x/auth"
"github.com/hdac-io/friday/x/auth/types"
"github.com/hdac-io/friday/x/simulation"
)
// SimulateDeductFee
func SimulateDeductFee(ak auth.AccountKeeper, supplyKeeper types.SupplyKeeper) simulation.Operation {
return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context,
accs []simulation.Account) (
opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) {
account := simulation.RandomAcc(r, accs)
stored := ak.GetAccount(ctx, account.Address)
initCoins := stored.GetCoins()
opMsg = simulation.NewOperationMsgBasic(types.ModuleName, "deduct_fee", "", false, nil)
feeCollector := ak.GetAccount(ctx, supplyKeeper.GetModuleAddress(types.FeeCollectorName))
if feeCollector == nil {
panic(fmt.Errorf("fee collector account hasn't been set"))
}
if len(initCoins) == 0 {
return opMsg, nil, nil
}
denomIndex := r.Intn(len(initCoins))
randCoin := initCoins[denomIndex]
amt, err := randPositiveInt(r, randCoin.Amount)
if err != nil {
return opMsg, nil, nil
}
// Create a random fee and verify the fees are within the account's spendable
// balance.
fees := sdk.NewCoins(sdk.NewCoin(randCoin.Denom, amt))
spendableCoins := stored.SpendableCoins(ctx.BlockHeader().Time)
if _, hasNeg := spendableCoins.SafeSub(fees); hasNeg {
return opMsg, nil, nil
}
// get the new account balance
_, hasNeg := initCoins.SafeSub(fees)
if hasNeg {
return opMsg, nil, nil
}
err = supplyKeeper.SendCoinsFromAccountToModule(ctx, stored.GetAddress(), types.FeeCollectorName, fees)
if err != nil {
panic(err)
}
opMsg.OK = true
return opMsg, nil, nil
}
}
func randPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) {
if !max.GT(sdk.OneInt()) {
return sdk.Int{}, errors.New("max too small")
}
max = max.Sub(sdk.OneInt())
return sdk.NewIntFromBigInt(new(big.Int).Rand(r, max.BigInt())).Add(sdk.OneInt()), nil
}