-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient.go
More file actions
273 lines (241 loc) · 9.01 KB
/
client.go
File metadata and controls
273 lines (241 loc) · 9.01 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
package tnclient
import (
"context"
"time"
"github.com/go-playground/validator/v10"
"github.com/pkg/errors"
"github.com/trufnetwork/kwil-db/core/crypto/auth"
"github.com/trufnetwork/kwil-db/core/gatewayclient"
"github.com/trufnetwork/kwil-db/core/log"
kwilType "github.com/trufnetwork/kwil-db/core/types"
"github.com/trufnetwork/kwil-db/node/types"
tn_api "github.com/trufnetwork/sdk-go/core/contractsapi"
"github.com/trufnetwork/sdk-go/core/logging"
clientType "github.com/trufnetwork/sdk-go/core/types"
"github.com/trufnetwork/sdk-go/core/util"
"go.uber.org/zap"
)
type Client struct {
signer auth.Signer `validate:"required"`
logger *log.Logger
transport Transport `validate:"required"`
}
var _ clientType.Client = (*Client)(nil)
type Option func(*Client)
func NewClient(ctx context.Context, provider string, options ...Option) (*Client, error) {
c := &Client{}
// Apply user-provided options
for _, option := range options {
option(c)
}
// Create default HTTPTransport if no transport was provided via options
if c.transport == nil {
var logger log.Logger
if c.logger != nil {
logger = *c.logger
}
transport, err := NewHTTPTransport(ctx, provider, c.signer, logger)
if err != nil {
return nil, errors.Wrap(err, "failed to create default HTTP transport")
}
c.transport = transport
}
// Validate the client
if err := c.Validate(); err != nil {
return nil, errors.WithStack(err)
}
return c, nil
}
func (c *Client) Validate() error {
validate := validator.New()
return validate.Struct(c)
}
func WithSigner(signer auth.Signer) Option {
return func(c *Client) {
c.signer = signer
}
}
func WithLogger(logger log.Logger) Option {
return func(c *Client) {
c.logger = &logger
}
}
// WithTransport configures the client to use a custom transport implementation.
//
// By default, the SDK uses HTTPTransport which communicates via standard net/http.
// This option allows you to substitute a different transport (e.g., for Chainlink CRE,
// mock testing, or custom protocols).
//
// Example:
//
// transport, _ := NewHTTPTransport(ctx, endpoint, signer, logger)
// client, err := NewClient(ctx, endpoint,
// tnclient.WithTransport(transport),
// )
//
// Note: When using WithTransport, the provider URL passed to NewClient is ignored
// since the transport is already configured.
func WithTransport(transport Transport) Option {
return func(c *Client) {
c.transport = transport
}
}
func (c *Client) GetSigner() auth.Signer {
return c.transport.Signer()
}
func (c *Client) WaitForTx(ctx context.Context, txHash kwilType.Hash, interval time.Duration) (*kwilType.TxQueryResponse, error) {
return c.transport.WaitTx(ctx, txHash, interval)
}
// GetKwilClient returns the underlying GatewayClient if using HTTPTransport.
//
// This method provides direct access to the GatewayClient for advanced use cases
// that require low-level control. For most scenarios, prefer using the Client's
// high-level methods (ListStreams, DeployStream, etc.) which are transport-agnostic.
//
// Returns nil if using a non-HTTP transport (e.g., CRE transport).
//
// Example:
//
// if gwClient := client.GetKwilClient(); gwClient != nil {
// // Direct GatewayClient access for advanced use cases
// result, err := gwClient.Call(ctx, "", "custom_action", args)
// }
func (c *Client) GetKwilClient() *gatewayclient.GatewayClient {
if httpTransport, ok := c.transport.(*HTTPTransport); ok {
return httpTransport.gatewayClient
}
return nil
}
func (c *Client) DeployStream(ctx context.Context, streamId util.StreamId, streamType clientType.StreamType) (types.Hash, error) {
// For HTTP transport, use the existing implementation (backwards compatible)
// For custom transports (CRE, etc.), use transport.Execute directly
if httpTransport, ok := c.transport.(*HTTPTransport); ok {
return tn_api.DeployStream(ctx, tn_api.DeployStreamInput{
StreamId: streamId,
StreamType: streamType,
KwilClient: httpTransport.gatewayClient,
})
}
// Use transport.Execute directly for custom transports
return c.transport.Execute(ctx, "", "create_stream", [][]any{{
streamId.String(),
streamType.String(),
}})
}
func (c *Client) DestroyStream(ctx context.Context, streamId util.StreamId) (types.Hash, error) {
// For HTTP transport, use the existing implementation (backwards compatible)
// For custom transports (CRE, etc.), use transport.Execute directly
if httpTransport, ok := c.transport.(*HTTPTransport); ok {
return tn_api.DestroyStream(ctx, tn_api.DestroyStreamInput{
StreamId: streamId,
KwilClient: httpTransport.gatewayClient,
})
}
// Use transport.Execute directly for custom transports
// Derive address from signer for delete_stream call
addr, _ := auth.EthSecp256k1Authenticator{}.Identifier(c.signer.CompactID())
return c.transport.Execute(ctx, "", "delete_stream", [][]any{{
addr,
streamId.String(),
}})
}
func (c *Client) LoadActions() (clientType.IAction, error) {
// For HTTP transport, use the full-featured GatewayClient implementation
// For custom transports (CRE, etc.), use the minimal transport-aware implementation
if httpTransport, ok := c.transport.(*HTTPTransport); ok {
return tn_api.LoadAction(tn_api.NewActionOptions{
Client: httpTransport.gatewayClient,
})
}
// Return transport-aware implementation for custom transports
return &TransportAction{transport: c.transport}, nil
}
func (c *Client) LoadPrimitiveActions() (clientType.IPrimitiveAction, error) {
// For HTTP transport, use the full-featured GatewayClient implementation
// For custom transports (CRE, etc.), use the minimal transport-aware implementation
if httpTransport, ok := c.transport.(*HTTPTransport); ok {
return tn_api.LoadPrimitiveActions(tn_api.NewActionOptions{
Client: httpTransport.gatewayClient,
})
}
// Return transport-aware implementation for custom transports
return &TransportPrimitiveAction{
TransportAction: TransportAction{transport: c.transport},
}, nil
}
func (c *Client) LoadComposedActions() (clientType.IComposedAction, error) {
return tn_api.LoadComposedActions(tn_api.NewActionOptions{
Client: c.GetKwilClient(),
})
}
func (c *Client) LoadRoleManagementActions() (clientType.IRoleManagement, error) {
return tn_api.LoadRoleManagementActions(tn_api.NewRoleManagementOptions{
Client: c.GetKwilClient(),
})
}
func (c *Client) LoadAttestationActions() (clientType.IAttestationAction, error) {
return tn_api.LoadAttestationActions(tn_api.AttestationActionOptions{
Client: c.GetKwilClient(),
})
}
// LoadTransactionActions loads the transaction ledger query interface
//
// Example:
//
// txActions, err := client.LoadTransactionActions()
// if err != nil {
// log.Fatal(err)
// }
// txEvent, err := txActions.GetTransactionEvent(ctx, ...)
func (c *Client) LoadTransactionActions() (clientType.ITransactionAction, error) {
return tn_api.LoadTransactionActions(tn_api.TransactionActionOptions{
Client: c.GetKwilClient(),
})
}
func (c *Client) OwnStreamLocator(streamId util.StreamId) clientType.StreamLocator {
return clientType.StreamLocator{
StreamId: streamId,
DataProvider: c.Address(),
}
}
func (c *Client) Address() util.EthereumAddress {
addr, err := auth.EthSecp256k1Authenticator{}.Identifier(c.transport.Signer().CompactID())
if err != nil {
// should never happen
logging.Logger.Panic("failed to get address from signer", zap.Error(err))
}
address, err := util.NewEthereumAddressFromString(addr)
if err != nil {
logging.Logger.Panic("failed to create address from string", zap.Error(err))
}
return address
}
// BatchDeployStreams deploys multiple streams (primitive and composed).
// It returns the transaction hash of the batch operation.
func (c *Client) BatchDeployStreams(ctx context.Context, streamDefs []clientType.StreamDefinition) (kwilType.Hash, error) {
// Assuming SchemaName for "create_streams" is obtained from somewhere or is a known constant.
// For now, using an empty string as a placeholder if it's a root/global procedure.
schemaName := "" // Or c.config.SchemaName, etc.
return tn_api.BatchDeployStreams(ctx, tn_api.BatchDeployStreamsInput{
KwilClient: c.GetKwilClient(),
Definitions: streamDefs,
SchemaName: schemaName,
})
}
// BatchStreamExists checks for the existence of multiple streams.
func (c *Client) BatchStreamExists(ctx context.Context, streams []clientType.StreamLocator) ([]clientType.StreamExistsResult, error) {
actions, err := c.LoadActions()
if err != nil {
return nil, errors.Wrap(err, "failed to load actions for BatchStreamExists")
}
return actions.BatchStreamExists(ctx, streams)
}
// BatchFilterStreamsByExistence filters a list of streams based on their existence in the database.
// Use this instead of BatchStreamExists if you want less data returned.
func (c *Client) BatchFilterStreamsByExistence(ctx context.Context, streams []clientType.StreamLocator, returnExisting bool) ([]clientType.StreamLocator, error) {
actions, err := c.LoadActions()
if err != nil {
return nil, errors.Wrap(err, "failed to load actions for BatchFilterStreamsByExistence")
}
return actions.BatchFilterStreamsByExistence(ctx, streams, returnExisting)
}