/
utils.go
238 lines (210 loc) · 7.22 KB
/
utils.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// Copyright 2021 Evmos Foundation
// This file is part of Evmos' Ethermint library.
//
// The Ethermint library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The Ethermint library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the Ethermint library. If not, see https://github.com/decimalteam/ethermint/blob/main/LICENSE
package keeper
import (
"encoding/json"
"github.com/decimalteam/ethermint/server/config"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common/hexutil"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
ethtypes "github.com/ethereum/go-ethereum/core/types"
errorsmod "cosmossdk.io/errors"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
errortypes "github.com/cosmos/cosmos-sdk/types/errors"
authante "github.com/cosmos/cosmos-sdk/x/auth/ante"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/decimalteam/ethermint/x/evm/types"
)
// GetCoinbaseAddress returns the block proposer's validator operator address.
func (k Keeper) GetCoinbaseAddress(ctx sdk.Context, proposerAddress sdk.ConsAddress) (common.Address, error) {
validator, found := k.stakingKeeper.GetValidatorByConsAddr(ctx, GetProposerAddress(ctx, proposerAddress))
if !found {
return common.Address{}, errorsmod.Wrapf(
stakingtypes.ErrNoValidatorFound,
"failed to retrieve validator from block proposer address %s",
proposerAddress.String(),
)
}
coinbase := common.BytesToAddress(validator.GetOperator())
return coinbase, nil
}
// GetProposerAddress returns current block proposer's address when provided proposer address is empty.
func GetProposerAddress(ctx sdk.Context, proposerAddress sdk.ConsAddress) sdk.ConsAddress {
if len(proposerAddress) == 0 {
proposerAddress = ctx.BlockHeader().ProposerAddress
}
return proposerAddress
}
// DeductTxCostsFromUserBalance deducts the fees from the user balance. Returns an
// error if the specified sender address does not exist or the account balance is not sufficient.
func (k *Keeper) DeductTxCostsFromUserBalance(
ctx sdk.Context,
fees sdk.Coins,
from common.Address,
) error {
// fetch sender account
signerAcc, err := authante.GetSignerAcc(ctx, k.accountKeeper, from.Bytes())
if err != nil {
return errorsmod.Wrapf(err, "account not found for sender %s", from)
}
// deduct the full gas cost from the user balance
if err := authante.DeductFees(k.bankKeeper, ctx, signerAcc, fees); err != nil {
return errorsmod.Wrapf(err, "failed to deduct full gas cost %s from the user %s balance", fees, from)
}
return nil
}
// VerifyFee is used to return the fee for the given transaction data in sdk.Coins. It checks that the
// gas limit is not reached, the gas limit is higher than the intrinsic gas and that the
// base fee is higher than the gas fee cap.
func VerifyFee(
txData types.TxData,
denom string,
baseFee *big.Int,
homestead, istanbul, isShanghai, isCheckTx bool,
) (sdk.Coins, error) {
isContractCreation := txData.GetTo() == nil
gasLimit := txData.GetGas()
var accessList ethtypes.AccessList
if txData.GetAccessList() != nil {
accessList = txData.GetAccessList()
}
intrinsicGas, err := core.IntrinsicGas(txData.GetData(), accessList, isContractCreation, homestead, istanbul, isShanghai)
if err != nil {
return nil, errorsmod.Wrapf(
err,
"failed to retrieve intrinsic gas, contract creation = %t; homestead = %t, istanbul = %t",
isContractCreation, homestead, istanbul,
)
}
// intrinsic gas verification during CheckTx
if isCheckTx && gasLimit < intrinsicGas {
return nil, errorsmod.Wrapf(
errortypes.ErrOutOfGas,
"gas limit too low: %d (gas limit) < %d (intrinsic gas)", gasLimit, intrinsicGas,
)
}
if baseFee != nil && txData.GetGasFeeCap().Cmp(baseFee) < 0 {
return nil, errorsmod.Wrapf(errortypes.ErrInsufficientFee,
"the tx gasfeecap is lower than the tx baseFee: %s (gasfeecap), %s (basefee) ",
txData.GetGasFeeCap(),
baseFee)
}
feeAmt := txData.EffectiveFee(baseFee)
if feeAmt.Sign() == 0 {
// zero fee, no need to deduct
return sdk.Coins{}, nil
}
return sdk.Coins{{Denom: denom, Amount: sdkmath.NewIntFromBigInt(feeAmt)}}, nil
}
// CheckSenderBalance validates that the tx cost value is positive and that the
// sender has enough funds to pay for the fees and value of the transaction.
func CheckSenderBalance(
balance sdkmath.Int,
txData types.TxData,
) error {
cost := txData.Cost()
if cost.Sign() < 0 {
return errorsmod.Wrapf(
errortypes.ErrInvalidCoins,
"tx cost (%s) is negative and invalid", cost,
)
}
if balance.IsNegative() || balance.BigInt().Cmp(cost) < 0 {
return errorsmod.Wrapf(
errortypes.ErrInsufficientFunds,
"sender balance < tx cost (%s < %s)", balance, txData.Cost(),
)
}
return nil
}
// CallEVM performs a smart contract method call using given args
func (k *Keeper) CallEVM(
ctx sdk.Context,
abi abi.ABI,
from, contract common.Address,
commit bool,
method string,
args ...interface{},
) (*types.MsgEthereumTxResponse, error) {
data, err := abi.Pack(method, args...)
if err != nil {
return nil, errorsmod.Wrap(
err,
errorsmod.Wrap(err, "failed to create transaction data").Error(),
)
}
resp, err := k.CallEVMWithData(ctx, from, &contract, data, commit)
if err != nil {
return nil, errorsmod.Wrapf(err, "contract call failed: method '%s', contract '%s'", method, contract)
}
return resp, nil
}
// CallEVMWithData performs a smart contract method call using contract data
func (k *Keeper) CallEVMWithData(
ctx sdk.Context,
from common.Address,
contract *common.Address,
data []byte,
commit bool,
) (*types.MsgEthereumTxResponse, error) {
nonce, err := k.accountKeeper.GetSequence(ctx, from.Bytes())
if err != nil {
return nil, err
}
gasCap := config.DefaultGasCap
if commit {
args, err := json.Marshal(types.TransactionArgs{
From: &from,
To: contract,
Data: (*hexutil.Bytes)(&data),
})
if err != nil {
return nil, errorsmod.Wrapf(errortypes.ErrJSONMarshal, "failed to marshal tx args: %s", err.Error())
}
gasRes, err := k.EstimateGas(sdk.WrapSDKContext(ctx), &types.EthCallRequest{
Args: args,
GasCap: config.DefaultGasCap,
})
if err != nil {
return nil, err
}
gasCap = gasRes.Gas
}
msg := core.Message{
From: from,
Nonce: nonce,
GasLimit: gasCap,
GasPrice: big.NewInt(0),
GasFeeCap: big.NewInt(0),
GasTipCap: big.NewInt(0),
To: contract,
Value: big.NewInt(0),
Data: data,
AccessList: ethtypes.AccessList{},
SkipAccountChecks: true,
}
res, err := k.ApplyMessage(ctx, msg, types.NewNoOpTracer(), commit)
if err != nil {
return nil, err
}
if res.Failed() {
return nil, errorsmod.Wrap(types.ErrVMExecution, res.VmError)
}
return res, nil
}