This repository has been archived by the owner on Dec 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
tx.go
100 lines (85 loc) · 2.55 KB
/
tx.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
package panacea
import (
clienttx "github.com/cosmos/cosmos-sdk/client/tx"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/bech32"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
"github.com/medibloc/panacea-doracle/config"
)
type TxBuilder struct {
client QueryClient
}
func NewTxBuilder(client QueryClient) *TxBuilder {
return &TxBuilder{
client: client,
}
}
// GenerateTxBytes generates transaction byte array.
func (tb TxBuilder) GenerateTxBytes(privKey cryptotypes.PrivKey, conf *config.Config, msg ...sdk.Msg) ([]byte, error) {
defaultFeeAmount, err := sdk.ParseCoinsNormalized(conf.Panacea.DefaultFeeAmount)
if err != nil {
return nil, err
}
txBytes, err := tb.GenerateSignedTxBytes(privKey, conf.Panacea.DefaultGasLimit, defaultFeeAmount, msg...)
if err != nil {
return nil, err
}
return txBytes, nil
}
// GenerateSignedTxBytes signs msgs using the private key and returns the signed Tx message in form of byte array.
func (tb TxBuilder) GenerateSignedTxBytes(
privateKey cryptotypes.PrivKey,
gasLimit uint64,
feeAmount sdk.Coins,
msg ...sdk.Msg,
) ([]byte, error) {
txConfig := authtx.NewTxConfig(tb.client.cdc, []signing.SignMode{signing.SignMode_SIGN_MODE_DIRECT})
txBuilder := txConfig.NewTxBuilder()
txBuilder.SetGasLimit(gasLimit)
txBuilder.SetFeeAmount(feeAmount)
if err := txBuilder.SetMsgs(msg...); err != nil {
return nil, err
}
signerAddress, err := bech32.ConvertAndEncode(HRP, privateKey.PubKey().Address().Bytes())
if err != nil {
return nil, err
}
signerAccount, err := tb.client.GetAccount(signerAddress)
if err != nil {
return nil, err
}
sigV2 := signing.SignatureV2{
PubKey: privateKey.PubKey(),
Data: &signing.SingleSignatureData{
SignMode: signing.SignMode_SIGN_MODE_DIRECT,
Signature: nil,
},
Sequence: signerAccount.GetSequence(),
}
if err := txBuilder.SetSignatures(sigV2); err != nil {
return nil, err
}
signerData := authsigning.SignerData{
ChainID: tb.client.chainID,
AccountNumber: signerAccount.GetAccountNumber(),
Sequence: signerAccount.GetSequence(),
}
sigV2, err = clienttx.SignWithPrivKey(
signing.SignMode_SIGN_MODE_DIRECT,
signerData,
txBuilder,
privateKey,
txConfig,
signerAccount.GetSequence(),
)
if err != nil {
return nil, err
}
if err := txBuilder.SetSignatures(sigV2); err != nil {
return nil, err
}
return txConfig.TxEncoder()(txBuilder.GetTx())
}