This repository was archived by the owner on May 26, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustody.go
More file actions
392 lines (331 loc) · 12.1 KB
/
custody.go
File metadata and controls
392 lines (331 loc) · 12.1 KB
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
package main
import (
"context"
"errors"
"fmt"
"log"
"math/big"
"time"
"github.com/erc7824/go-nitrolite"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/prometheus/client_golang/prometheus"
"github.com/shopspring/decimal"
"gorm.io/gorm"
)
var (
custodyAbi *abi.ABI
)
// Custody implements the BlockchainClient interface using the Custody contract
type Custody struct {
client *ethclient.Client
custody *nitrolite.Custody
db *gorm.DB
custodyAddr common.Address
transactOpts *bind.TransactOpts
chainID uint32
signer *Signer
sendBalanceUpdate func(string)
sendChannelUpdate func(Channel)
}
// NewCustody initializes the Ethereum client and custody contract wrapper.
func NewCustody(signer *Signer, db *gorm.DB, sendBalanceUpdate func(string), sendChannelUpdate func(Channel), infuraURL, custodyAddressStr string, chain uint32) (*Custody, error) {
custodyAddress := common.HexToAddress(custodyAddressStr)
client, err := ethclient.Dial(infuraURL)
if err != nil {
return nil, fmt.Errorf("failed to connect to Ethereum node: %w", err)
}
chainID, err := client.ChainID(context.Background())
if err != nil {
return nil, fmt.Errorf("failed to get chain ID: %w", err)
}
// Create auth options for transactions.
auth, err := bind.NewKeyedTransactorWithChainID(signer.GetPrivateKey(), chainID)
if err != nil {
return nil, fmt.Errorf("failed to create transaction signer: %w", err)
}
auth.GasPrice = big.NewInt(30000000000) // 20 gwei.
auth.GasLimit = uint64(3000000)
custody, err := nitrolite.NewCustody(custodyAddress, client)
if err != nil {
return nil, fmt.Errorf("failed to bind custody contract: %w", err)
}
return &Custody{
client: client,
custody: custody,
db: db,
custodyAddr: custodyAddress,
transactOpts: auth,
chainID: uint32(chainID.Int64()),
signer: signer,
sendBalanceUpdate: sendBalanceUpdate,
sendChannelUpdate: sendChannelUpdate,
}, nil
}
// ListenEvents initializes event listening for the custody contract
func (c *Custody) ListenEvents(ctx context.Context) {
// TODO: store processed events in a database
listenEvents(ctx, c.client, c.custodyAddr, c.chainID, 0, c.handleBlockChainEvent)
}
// Join calls the join method on the custody contract
func (c *Custody) Join(channelID string, lastStateData []byte) error {
// Convert string channelID to bytes32
channelIDBytes := common.HexToHash(channelID)
// The broker will always join as participant with index 1 (second participant)
index := big.NewInt(1)
sig, err := c.signer.NitroSign(lastStateData)
if err != nil {
return fmt.Errorf("failed to sign data: %w", err)
}
gasPrice, err := c.client.SuggestGasPrice(context.Background())
if err != nil {
return fmt.Errorf("failed to suggest gas price: %w", err)
}
c.transactOpts.GasPrice = gasPrice.Add(gasPrice, gasPrice)
// Call the join method on the custody contract
tx, err := c.custody.Join(c.transactOpts, channelIDBytes, index, sig)
if err != nil {
return fmt.Errorf("failed to join channel: %w", err)
}
log.Println("TxHash:", tx.Hash().Hex())
return nil
}
// handleBlockChainEvent processes different event types received from the blockchain
func (c *Custody) handleBlockChainEvent(l types.Log) {
log.Printf("Received event: %+v\n", l)
eventID := l.Topics[0]
switch eventID {
case custodyAbi.Events["Created"].ID:
ev, err := c.custody.ParseCreated(l)
log.Printf("[Created] Event data: %+v\n", ev)
if err != nil {
log.Println("error parsing Created event:", err)
return
}
if len(ev.Channel.Participants) < 2 {
log.Println("[Created] Error: not enough participants in the channel")
return
}
participantA := ev.Channel.Participants[0].Hex()
nonce := ev.Channel.Nonce
participantB := ev.Channel.Participants[1]
tokenAddress := ev.Initial.Allocations[0].Token.Hex()
tokenAmount := ev.Initial.Allocations[0].Amount.Int64()
// Check if channel was created with the broker.
if participantB != c.signer.GetAddress() {
log.Printf("participantB %s is not Broker %s\n", participantB, c.signer.GetAddress().Hex())
return
}
// Check if there is already existing open channel with the broker
existingOpenChannel, err := CheckExistingChannels(c.db, participantA, tokenAddress, c.chainID)
if err != nil {
log.Printf("[Created] Error checking channels in database: %v", err)
return
}
if existingOpenChannel != nil {
log.Printf("[Created] An open channel with broker already exists: %s", existingOpenChannel.ChannelID)
return
}
channelID := common.BytesToHash(ev.ChannelId[:]).Hex()
ch, err := CreateChannel(
c.db,
channelID,
participantA,
nonce,
ev.Channel.Adjudicator.Hex(),
c.chainID,
tokenAddress,
uint64(tokenAmount),
)
if err != nil {
log.Printf("[ChannelCreated] Error creating/updating channel in database: %v", err)
return
}
encodedState, err := nitrolite.EncodeState(ev.ChannelId, nitrolite.IntentINITIALIZE, big.NewInt(0), ev.Initial.Data, ev.Initial.Allocations)
if err != nil {
log.Printf("[ChannelCreated] Error encoding state hash: %v", err)
return
}
if err := c.Join(channelID, encodedState); err != nil {
log.Printf("[ChannelCreated] Error joining channel: %v", err)
return
}
c.sendChannelUpdate(ch)
log.Printf("[ChannelCreated] Successfully initiated join for channel %s on chain %d", channelID, c.chainID)
case custodyAbi.Events["Joined"].ID:
ev, err := c.custody.ParseJoined(l)
if err != nil {
log.Println("error parsing ChannelJoined event:", err)
return
}
log.Printf("Joined event data: %+v\n", ev)
var channel Channel
channelID := common.BytesToHash(ev.ChannelId[:]).Hex()
err = c.db.Transaction(func(tx *gorm.DB) error {
result := tx.Where("channel_id = ?", channelID).First(&channel)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return fmt.Errorf("channel with ID %s not found", channelID)
}
return fmt.Errorf("error finding channel: %w", result.Error)
}
// Update the channel status to "open"
channel.Status = ChannelStatusOpen
channel.UpdatedAt = time.Now()
if err := tx.Save(&channel).Error; err != nil {
return fmt.Errorf("failed to close channel: %w", err)
}
log.Printf("Joined channel with ID: %s", channelID)
asset, err := GetAssetByToken(tx, channel.Token, c.chainID)
if err != nil {
return fmt.Errorf("DB error fetching asset: %w", err)
}
if asset == nil {
return fmt.Errorf("Asset not found in database for token: %s", channel.Token)
}
tokenAmount := decimal.NewFromBigInt(big.NewInt(int64(channel.Amount)), -int32(asset.Decimals))
ledger := GetParticipantLedger(tx, channel.Participant)
if err := ledger.Record(channel.Participant, asset.Symbol, tokenAmount); err != nil {
log.Printf("[Joined] Error recording balance update for participant A: %v", err)
return err
}
return nil
})
if err != nil {
log.Printf("[Joined] Error closing channel in database: %v", err)
return
}
c.sendBalanceUpdate(channel.Participant)
c.sendChannelUpdate(channel)
case custodyAbi.Events["Closed"].ID:
ev, err := c.custody.ParseClosed(l)
if err != nil {
log.Println("error parsing ChannelClosed event:", err)
return
}
log.Printf("Closed event data: %+v\n", ev)
var channel Channel
channelID := common.BytesToHash(ev.ChannelId[:]).Hex()
err = c.db.Transaction(func(tx *gorm.DB) error {
result := tx.Where("channel_id = ?", channelID).First(&channel)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return fmt.Errorf("channel with ID %s not found", channelID)
}
return fmt.Errorf("error finding channel: %w", result.Error)
}
asset, err := GetAssetByToken(tx, channel.Token, c.chainID)
if err != nil {
return fmt.Errorf("DB error fetching asset: %w", err)
}
if asset == nil {
return fmt.Errorf("Asset not found in database for token: %s", channel.Token)
}
tokenAmount := decimal.NewFromBigInt(big.NewInt(int64(channel.Amount)), -int32(asset.Decimals))
ledger := GetParticipantLedger(tx, channel.Participant)
if err := ledger.Record(channel.Participant, asset.Symbol, tokenAmount.Neg()); err != nil {
log.Printf("[Closed] Error recording balance update for participant: %v", err)
return err
}
// Update the channel status to "closed"
channel.Status = ChannelStatusClosed
channel.Amount = 0
channel.UpdatedAt = time.Now()
channel.Version++
if err := tx.Save(&channel).Error; err != nil {
return fmt.Errorf("failed to close channel: %w", err)
}
log.Printf("Closed channel with ID: %s", channelID)
return nil
})
if err != nil {
log.Printf("[Closed] Error closing channel: %v", err)
return
}
c.sendBalanceUpdate(channel.Participant)
c.sendChannelUpdate(channel)
case custodyAbi.Events["Resized"].ID:
ev, err := c.custody.ParseResized(l)
if err != nil {
log.Println("error parsing Resized event:", err)
return
}
log.Printf("Resized event data: %+v\n", ev)
var channel Channel
err = c.db.Transaction(func(tx *gorm.DB) error {
channelID := common.BytesToHash(ev.ChannelId[:]).Hex()
result := c.db.Where("channel_id = ?", channelID).First(&channel)
if result.Error != nil {
return fmt.Errorf("error finding channel: %w", result.Error)
}
newAmount := int64(channel.Amount)
for _, change := range ev.DeltaAllocations {
newAmount += change.Int64()
}
channel.Amount = uint64(newAmount)
channel.UpdatedAt = time.Now()
channel.Version++
if err := c.db.Save(&channel).Error; err != nil {
return fmt.Errorf("[Resized] Error saving channel in database: %w", err)
}
resizeAmount := ev.DeltaAllocations[0] // Participant deposits or withdraws.
if resizeAmount.Cmp(big.NewInt(0)) != 0 {
asset, err := GetAssetByToken(tx, channel.Token, c.chainID)
if err != nil {
return fmt.Errorf("DB error fetching asset: %w", err)
}
if asset == nil {
return fmt.Errorf("Asset not found in database for token: %s", channel.Token)
}
amount := decimal.NewFromBigInt(resizeAmount, -int32(asset.Decimals))
ledger := GetParticipantLedger(tx, channel.Participant)
if err := ledger.Record(channel.Participant, asset.Symbol, amount); err != nil {
log.Printf("[Resized] Error recording balance update for participant: %v", err)
return err
}
}
return nil
})
if err != nil {
log.Printf("[Resized] Error resizing channel: %v", err)
return
}
c.sendBalanceUpdate(channel.Participant)
c.sendChannelUpdate(channel)
default:
log.Println("Unknown event ID:", eventID.Hex())
}
}
// UpdateBalanceMetrics fetches the broker's account information from the smart contract and updates metrics
func (c *Custody) UpdateBalanceMetrics(ctx context.Context, tokens []common.Address, metrics *Metrics) {
if metrics == nil {
logger.Errorw("Metrics not initialized for custody client", "network", c.chainID)
return
}
brokerAddr := c.signer.GetAddress()
for _, token := range tokens {
// Create a call opts with the provided context
callOpts := &bind.CallOpts{
Context: ctx,
}
logger.Infow("Fetching account info", "network", c.chainID, "token", token.Hex(), "broker", brokerAddr.Hex())
// Call getAccountInfo on the custody contract
info, err := c.custody.GetAccountInfo(callOpts, brokerAddr, token)
if err != nil {
logger.Errorw("Failed to get account info", "network", c.chainID, "token", token.Hex(), "error", err)
continue
}
metrics.BrokerBalanceAvailable.With(prometheus.Labels{
"network": fmt.Sprintf("%d", c.chainID),
"token": token.Hex(),
}).Set(float64(info.Available.Int64()))
metrics.BrokerChannelCount.With(prometheus.Labels{
"network": fmt.Sprintf("%d", c.chainID),
"token": token.Hex(),
}).Set(float64(info.ChannelCount.Int64()))
logger.Infow("Updated contract balance metrics", "network", c.chainID, "token", token.Hex(), "available", info.Available.String(), "channels", info.ChannelCount.String())
}
}