-
Notifications
You must be signed in to change notification settings - Fork 1
/
meta_tx.go
273 lines (253 loc) · 8.15 KB
/
meta_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
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package metax
import (
"bytes"
"context"
"encoding/json"
"fmt"
"math/big"
"net/http"
"time"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/signer/core/apitypes"
)
type MetaTxMessage struct {
From common.Address `json:"from"`
To common.Address `json:"to"`
Token common.Address `json:"token"`
TxGas uint64 `json:"txGas"`
TokenGasPrice string `json:"tokenGasPrice"`
BatchId *big.Int `json:"batchId"`
BatchNonce *big.Int `json:"batchNonce"`
Deadline *big.Int `json:"deadline"`
Data string `json:"data"`
}
type MetaTxRequest struct {
From string `json:"from"`
To string `json:"to"`
ApiID string `json:"apiId"`
Params []interface{} `json:"params"`
SignatureType string `json:"signatureType"`
}
type MetaTxResponse struct {
TxHash common.Hash `json:"txHash"`
Log string `json:"log"`
Flag int `json:"flag"`
Message string `json:"message"`
Error string `json:"error"`
Code int `json:"code"`
Limit struct {
Type int `json:"type"`
LimitLeft int `json:"limitLeft"`
ResetTime int `json:"resetTime"`
} `json:"limit"`
Allowed bool `json:"allowed"`
}
func (m *MetaTxMessage) TypedData() apitypes.TypedDataMessage {
return apitypes.TypedDataMessage{
"from": m.From.Hex(),
"to": m.To.Hex(),
"token": m.Token.Hex(),
"txGas": hexutil.EncodeUint64(m.TxGas),
"tokenGasPrice": m.TokenGasPrice,
"batchId": m.BatchId.String(),
"batchNonce": m.BatchNonce.String(),
"deadline": m.Deadline.String(),
"data": m.Data,
}
}
func (b *Bcnmy) SendMetaNativeTx(data *MetaTxRequest) (*MetaTxResponse, error) {
responseCh := make(chan interface{}, 1)
errorCh := make(chan error)
defer close(errorCh)
defer close(responseCh)
body, err := json.Marshal(data)
if err != nil {
b.logger.WithError(err).Error("json marshal `MetaTxRequest` data failed")
return nil, err
}
req, err := http.NewRequest(http.MethodPost, MetaTxNativeURL, bytes.NewBuffer(body))
if err != nil {
b.logger.Error("SendMetaNativeTx NewRequest failed")
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("x-api-key", b.apiKey)
var resp MetaTxResponse
b.asyncHttpx(req, &resp, errorCh, responseCh)
select {
case ret := <-responseCh:
resp, ok := ret.(*MetaTxResponse)
if !ok {
return nil, fmt.Errorf("MetaAPI failed")
}
if resp.TxHash == common.HexToHash("0x0") {
err := fmt.Errorf("Message: %s, Code: %s, Limit: %v", resp.Message, resp.Code, resp.Limit)
return resp, err
}
return resp, nil
case err := <-errorCh:
b.logger.WithError(err).Error(err.Error())
return nil, err
}
}
func (b *Bcnmy) RawTransact(signer *Signer, method string, params ...interface{}) (*MetaTxResponse, *types.Transaction, *types.Receipt, error) {
apiId, ok := b.apiID[method]
if !ok {
err := fmt.Errorf("ApiId %s not found for %s", apiId.ID, method)
b.logger.Error(err.Error())
return nil, nil, err
}
funcSig, err := b.abi.Pack(method, params...)
if err != nil {
b.logger.WithError(err).Error("Abi Pack failed")
return nil, nil, err
}
callMsg := ethereum.CallMsg{
From: signer.Address,
To: &b.address,
Data: funcSig,
}
callOpts := bind.CallOpts{
Context: b.ctx,
From: signer.Address,
}
estimateGas, err := b.ethClient.EstimateGas(b.ctx, callMsg)
if err != nil {
b.logger.WithError(err).Error("EstimateGas failed")
return nil, nil, err
}
batchNonce, err := b.trustedForwarder.Contract.GetNonce(&callOpts, signer.Address, b.batchId)
if err != nil {
b.logger.WithError(err).Errorf("GetNonce from %s failed", b.batchId)
return nil, nil, err
}
metaTxMessage := &MetaTxMessage{
From: signer.Address,
To: b.address,
Token: common.HexToAddress("0x0"),
TxGas: estimateGas,
TokenGasPrice: "0",
BatchId: b.batchId,
BatchNonce: batchNonce,
Deadline: big.NewInt(time.Now().Add(time.Hour).Unix()),
Data: hexutil.Encode(funcSig),
}
typedData := apitypes.TypedData{
Types: SignedTypes,
PrimaryType: ForwardRequestType,
Domain: apitypes.TypedDataDomain{
Name: ForwardRequestName,
Version: Version,
VerifyingContract: b.trustedForwarder.Address.Hex(),
Salt: hexutil.Encode(common.LeftPadBytes(b.chainId.Bytes(), 32)),
},
Message: metaTxMessage.TypedData(),
}
signature, err := signer.SignTypedData(typedData)
if err != nil {
b.logger.WithError(err).Error("Signer signTypeData failed")
return nil, nil, err
}
domainSeparator, err := typedData.HashStruct(EIP712DomainType, typedData.Domain.Map())
if err != nil {
b.logger.WithError(err).Error("EIP712Domain Separator hash failed")
return nil, nil, err
}
req := &MetaTxRequest{
From: signer.Address.Hex(),
To: b.address.Hex(),
ApiID: apiId.ID,
Params: []interface{}{
metaTxMessage,
hexutil.Encode(domainSeparator),
hexutil.Encode(signature),
},
SignatureType: SignatureEIP712Type,
}
resp, err := b.SendMetaNativeTx(req)
if err != nil {
b.logger.Errorf("Transaction failed: %v", err)
return resp, nil, nil, err
}
tx, _, err := b.ethClient.TransactionByHash(b.ctx, resp.TxHash)
if err != nil {
b.logger.Errorf("Checking TransactionByHash failed: %v", err)
return resp, nil, nil, err
}
receipt, err := bind.WaitMined(context.Background(), b.ethClient, tx)
return resp, tx, receipt, err
}
func (b *Bcnmy) BuildTransactParams(metaTxMessage *MetaTxMessage, typedDataHash string) ([]byte, error) {
typedData := apitypes.TypedData{
Types: SignedTypes,
PrimaryType: ForwardRequestType,
Domain: apitypes.TypedDataDomain{
Name: ForwardRequestName,
Version: Version,
VerifyingContract: b.trustedForwarder.Address.Hex(),
Salt: hexutil.Encode(common.LeftPadBytes(b.chainId.Bytes(), 32)),
},
Message: metaTxMessage.TypedData(),
}
hash, err := typedData.HashStruct(typedData.PrimaryType, typedData.Message)
if err != nil {
b.logger.Errorf("HashStruct failed to hash typedData, %v", err)
return nil, err
}
if hash.String() != typedDataHash {
err := fmt.Errorf("Hash string not match parameter hash: %s typedDataHash %s", hash.String(), typedDataHash)
b.logger.Errorf("%v", err)
return nil, err
}
return typedData.HashStruct(EIP712DomainType, typedData.Domain.Map())
}
// / Backend using this method, handle frontend passing signature, MetaTxMessage and
// / ForwardRequestType data Hash value
func (b *Bcnmy) EnhanceTransact(from string, method string, signature []byte, metaTxMessage *MetaTxMessage, typedDataHash string) (*MetaTxResponse, *types.Transaction, *types.Receipt, error) {
apiId, ok := b.apiID[method]
if !ok {
err := fmt.Errorf("ApiId %s not found for %s", apiId.ID, method)
b.logger.Error(err.Error())
return nil, nil, err
}
domainSeparator, err := b.BuildTransactParams(metaTxMessage, typedDataHash)
if err != nil {
b.logger.WithError(err).Error("EIP712Domain Separator hash failed")
return nil, nil, err
}
req := &MetaTxRequest{
From: from,
To: b.address.Hex(),
ApiID: apiId.ID,
Params: []interface{}{
metaTxMessage,
hexutil.Encode(domainSeparator),
hexutil.Encode(signature),
},
SignatureType: SignatureEIP712Type,
}
resp, err := b.SendMetaNativeTx(req)
if err != nil {
b.logger.Errorf("Transaction failed: %v", err)
return resp, nil, nil, err
}
tx, _, err := b.ethClient.TransactionByHash(b.ctx, resp.TxHash)
if err != nil {
b.logger.Errorf("Checking TransactionByHash failed: %v", err)
return resp, nil, nil, err
}
receipt, err := bind.WaitMined(context.Background(), b.ethClient, tx)
return resp, tx, receipt, err
}
func (b *Bcnmy) Pack(method string, params ...interface{}) ([]byte, error) {
data, err := b.abi.Pack(method, params...)
if err != nil {
b.logger.WithError(err).Error("Abi Pack failed")
return nil, err
}
return data, err
}