/
device_definition_on_chain_service.go
350 lines (291 loc) · 10.4 KB
/
device_definition_on_chain_service.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
//nolint:tagliatelle
package gateways
import (
"context"
"encoding/json"
"fmt"
"math/big"
"net/http"
"net/url"
"path"
"strings"
"github.com/DIMO-Network/device-definitions-api/internal/config"
"github.com/DIMO-Network/device-definitions-api/internal/contracts"
"github.com/DIMO-Network/device-definitions-api/internal/infrastructure/db/models"
"github.com/DIMO-Network/device-definitions-api/internal/infrastructure/sender"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
eth_types "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/rs/zerolog"
"github.com/volatiletech/null/v8"
"github.com/volatiletech/sqlboiler/v4/types"
)
//go:generate mockgen -source device_definition_on_chain_service.go -destination mocks/device_definition_on_chain_service_mock.go -package mocks
type DeviceDefinitionOnChainService interface {
GetDeviceDefinitionByID(ctx context.Context, manufacturerID types.NullDecimal, ID string) (*models.DeviceDefinition, error)
GetDeviceDefinitions(ctx context.Context, manufacturerID types.NullDecimal, ID string, model string, year int, pageIndex, pageSize int32) ([]*models.DeviceDefinition, error)
CreateOrUpdate(ctx context.Context, make models.DeviceMake, dd models.DeviceDefinition) (*string, error)
}
type deviceDefinitionOnChainService struct {
Settings *config.Settings
Logger *zerolog.Logger
client *ethclient.Client
sender sender.Sender
chainID *big.Int
}
func NewDeviceDefinitionOnChainService(settings *config.Settings, logger *zerolog.Logger, client *ethclient.Client, chainID *big.Int, sender sender.Sender) DeviceDefinitionOnChainService {
return &deviceDefinitionOnChainService{
Settings: settings,
Logger: logger,
client: client,
chainID: chainID,
sender: sender,
}
}
func (e *deviceDefinitionOnChainService) GetDeviceDefinitionByID(ctx context.Context, manufacturerID types.NullDecimal, ID string) (*models.DeviceDefinition, error) {
if manufacturerID.IsZero() {
return nil, fmt.Errorf("manufacturerID has not value")
}
contractAddress := common.HexToAddress(e.Settings.EthereumRegistryAddress)
queryInstance, err := contracts.NewRegistry(contractAddress, e.client)
if err != nil {
return nil, fmt.Errorf("failed create NewRegistry: %w", err)
}
bigManufID := manufacturerID.Big.Int(new(big.Int))
tableName, err := queryInstance.GetDeviceDefinitionTableName(&bind.CallOpts{Context: ctx, Pending: true}, bigManufID)
if err != nil {
e.Logger.Info().Msgf("%s", err)
return nil, fmt.Errorf("failed get GetDeviceDefinitionTableName: %w", err)
}
statement := fmt.Sprintf("SELECT * FROM %s WHERE id = '%s'", tableName, ID)
queryParams := map[string]string{
"statement": statement,
}
var modelTableland []DeviceDefinitionTablelandModel
if err := e.QueryTableland(queryParams, &modelTableland); err != nil {
return nil, err
}
if len(modelTableland) > 0 {
return transformToDefinition(modelTableland[0]), nil
}
return nil, nil
}
func transformToDefinition(item DeviceDefinitionTablelandModel) *models.DeviceDefinition {
data := &models.DeviceDefinition{
ID: item.ID,
Year: item.Year,
Model: item.Model,
}
if item.Metadata.DeviceAttributes != nil && len(item.Metadata.DeviceAttributes) > 0 {
deviceTypeInfo := make(map[string]interface{})
metaData := make(map[string]interface{})
for _, attr := range item.Metadata.DeviceAttributes {
metaData[attr.Name] = attr.Value
}
deviceTypeInfo["vehicle_info"] = metaData
j, err := json.Marshal(deviceTypeInfo)
if err == nil {
data.Metadata = null.JSONFrom(j)
}
}
return data
}
func (e *deviceDefinitionOnChainService) GetDeviceDefinitions(ctx context.Context, manufacturerID types.NullDecimal, ID string, model string, year int, pageIndex, pageSize int32) ([]*models.DeviceDefinition, error) {
if manufacturerID.IsZero() {
return nil, fmt.Errorf("manufacturerID has not value")
}
contractAddress := common.HexToAddress(e.Settings.EthereumRegistryAddress)
fromAddress := e.sender.Address()
queryInstance, err := contracts.NewRegistry(contractAddress, e.client)
if err != nil {
return nil, fmt.Errorf("failed create NewRegistry: %w", err)
}
bigManufID := manufacturerID.Big.Int(new(big.Int))
tableName, err := queryInstance.GetDeviceDefinitionTableName(&bind.CallOpts{Context: ctx, Pending: true, From: fromAddress}, bigManufID)
if err != nil {
e.Logger.Info().Msgf("%s", err)
return nil, fmt.Errorf("failed get GetDeviceDefinitionTableName: %w", err)
}
var conditions []string
if year > 1980 && year < 2999 {
conditions = append(conditions, fmt.Sprintf("year = %d", year))
}
if len(model) > 0 {
conditions = append(conditions, fmt.Sprintf("model = '%s'", model))
}
if len(ID) > 0 {
conditions = append(conditions, fmt.Sprintf("id = '%s'", ID))
}
whereClause := strings.Join(conditions, " AND ")
if whereClause != "" {
whereClause = " WHERE " + whereClause
}
statement := fmt.Sprintf("SELECT * FROM %s%s LIMIT %d OFFSET %d", tableName, whereClause, pageSize, pageIndex)
queryParams := map[string]string{
"statement": statement,
}
var modelTableland []DeviceDefinitionTablelandModel
if err := e.QueryTableland(queryParams, &modelTableland); err != nil {
return nil, err
}
result := make([]*models.DeviceDefinition, len(modelTableland))
for i, item := range modelTableland {
result[i] = transformToDefinition(item)
}
return result, nil
}
func (e *deviceDefinitionOnChainService) QueryTableland(queryParams map[string]string, result interface{}) error {
fullURL, err := url.Parse(e.Settings.TablelandAPIGateway)
if err != nil {
return err
}
fullURL.Path = path.Join(fullURL.Path, "api/v1/query")
if queryParams != nil {
values := fullURL.Query()
for key, value := range queryParams {
values.Set(key, value)
}
fullURL.RawQuery = values.Encode()
}
resp, err := http.Get(fullURL.String())
if err != nil {
return err
}
defer resp.Body.Close()
fmt.Print(resp.Body)
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
return err
}
return nil
}
func (e *deviceDefinitionOnChainService) CreateOrUpdate(ctx context.Context, make models.DeviceMake, dd models.DeviceDefinition) (*string, error) {
if !e.Settings.EthereumSendTransaction {
return nil, nil
}
contractAddress := common.HexToAddress(e.Settings.EthereumRegistryAddress)
fromAddress := e.sender.Address()
nonce, err := e.client.PendingNonceAt(ctx, fromAddress)
if err != nil {
return nil, fmt.Errorf("failed get PendingNonceAt: %w", err)
}
gasPrice, err := e.client.SuggestGasPrice(ctx)
if err != nil {
return nil, fmt.Errorf("failed get SuggestGasPrice: %w", err)
}
bump := big.NewInt(20)
bumpedPrice := getGasPrice(gasPrice, bump)
fmt.Printf("GasPrice => %s Bumped Price=> %s", gasPrice, bumpedPrice)
auth, err := NewKeyedTransactorWithChainID(ctx, e.sender, e.chainID)
if err != nil {
return nil, fmt.Errorf("failed get NewKeyedTransactorWithChainID: %w", err)
}
//auth.Value = big.NewInt(0)
auth.Nonce = big.NewInt(int64(nonce))
auth.GasLimit = uint64(300000)
auth.GasPrice = bumpedPrice
auth.From = fromAddress
queryInstance, err := contracts.NewRegistry(contractAddress, e.client)
if err != nil {
return nil, fmt.Errorf("failed create NewRegistry: %w", err)
}
// Validate if manufacturer exists
bigManufID, err := queryInstance.GetManufacturerIdByName(&bind.CallOpts{Context: ctx, Pending: true}, make.Name)
if err != nil {
e.Logger.Info().Msgf("%s", err)
return nil, fmt.Errorf("failed get GetManufacturerNameById => %s: %w", make.Name, err)
}
instance, err := contracts.NewRegistryTransactor(contractAddress, e.client)
if err != nil {
return nil, fmt.Errorf("failed create NewRegistryTransactor: %w", err)
}
deviceInputs := contracts.DeviceDefinitionInput{
Id: dd.NameSlug,
Model: dd.ModelSlug,
Year: big.NewInt(int64(dd.Year)),
Metadata: "",
Ksuid: dd.ID,
DeviceType: "vehicle",
}
if make.LogoURL.Valid && len(make.LogoURL.String) > 0 {
deviceInputs.ImageURI = make.LogoURL.String
}
if dd.Metadata.Valid {
attributes := GetDeviceAttributesTyped(dd.Metadata, "vehicle_info")
type deviceAttributes struct {
DeviceAttributes []DeviceTypeAttribute `json:"device_attributes"`
}
deviceAttributesStruct := deviceAttributes{
DeviceAttributes: attributes,
}
jsonData, _ := json.Marshal(deviceAttributesStruct)
deviceInputs.Metadata = string(jsonData)
}
jsonBytes, err := json.MarshalIndent(deviceInputs, "", " ")
if err != nil {
fmt.Println("Error converting to JSON => ", err)
}
fmt.Println("InsertDeviceDefinition => ", string(jsonBytes))
tx, err := instance.InsertDeviceDefinition(auth, bigManufID, deviceInputs)
if err != nil {
e.Logger.Info().Msgf("%s", err)
return nil, fmt.Errorf("failed insert InsertDeviceDefinitionBatch: %w", err)
}
trx := tx.Hash().Hex()
return &trx, nil
}
func getGasPrice(price *big.Int, bump *big.Int) *big.Int {
// Calculating the bumped gas price
bumpAmount := new(big.Int).Mul(price, bump)
bumpAmount.Div(bumpAmount, big.NewInt(100))
bumpedPrice := new(big.Int).Add(bumpAmount, price)
return bumpedPrice
}
func NewKeyedTransactorWithChainID(context context.Context, send sender.Sender, chainID *big.Int) (*bind.TransactOpts, error) {
signer := eth_types.LatestSignerForChainID(chainID)
return &bind.TransactOpts{
From: send.Address(),
Signer: func(_ common.Address, tx *eth_types.Transaction) (*eth_types.Transaction, error) {
signature, err := send.Sign(context, signer.Hash(tx))
if err != nil {
return nil, err
}
return tx.WithSignature(signer, signature)
},
Context: context,
}, nil
}
func GetDeviceAttributesTyped(metadata null.JSON, key string) []DeviceTypeAttribute {
var respAttrs []DeviceTypeAttribute
var ai map[string]any
if err := metadata.Unmarshal(&ai); err == nil {
if ai != nil {
if a, ok := ai[key]; ok && a != nil {
attributes := ai[key].(map[string]any)
for key, value := range attributes {
respAttrs = append(respAttrs, DeviceTypeAttribute{
Name: key,
Value: fmt.Sprint(value),
})
}
}
}
}
return respAttrs
}
type DeviceTypeAttribute struct {
Name string `json:"name"`
Value string `json:"value"`
}
type DeviceDefinitionTablelandModel struct {
ID string `json:"id"`
KSUID string `json:"ksuid"`
Model string `json:"model"`
Year int16 `json:"year"`
Metadata struct {
DeviceAttributes []struct {
Name string `json:"name"`
Value string `json:"value,omitempty"`
} `json:"device_attributes"`
} `json:"metadata"`
}