-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
386 lines (357 loc) · 11.7 KB
/
client.go
File metadata and controls
386 lines (357 loc) · 11.7 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
package hcs11
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/hashgraph-online/standards-sdk-go/pkg/hcs14"
"github.com/hashgraph-online/standards-sdk-go/pkg/mirror"
"github.com/hashgraph-online/standards-sdk-go/pkg/shared"
hedera "github.com/hashgraph/hedera-sdk-go/v2"
)
type Client struct {
hederaClient *hedera.Client
mirrorClient *mirror.Client
operatorAccountID string
operatorPrivateKey string
network string
keyType string
inscriberBaseURL string
inscriberAuthURL string
inscriberAPIURL string
}
// NewClient creates a new Client.
func NewClient(config ClientConfig) (*Client, error) {
network, err := shared.NormalizeNetwork(config.Network)
if err != nil {
return nil, err
}
injectedClient := config.HederaClient
hederaClient := injectedClient
if hederaClient == nil {
hederaClient, err = shared.NewHederaClient(network)
if err != nil {
return nil, err
}
}
operatorAccountID := strings.TrimSpace(config.Auth.OperatorID)
operatorPrivateKey := strings.TrimSpace(config.Auth.PrivateKey)
if operatorAccountID == "" && operatorPrivateKey != "" {
return nil, fmt.Errorf("operator account ID is required when private key is provided")
}
if operatorAccountID != "" && operatorPrivateKey == "" {
return nil, fmt.Errorf("operator private key is required when operator account ID is provided")
}
if injectedClient == nil && operatorAccountID != "" && operatorPrivateKey != "" {
accountID, parseErr := hedera.AccountIDFromString(operatorAccountID)
if parseErr != nil {
return nil, fmt.Errorf("invalid operator account ID: %w", parseErr)
}
privateKey, keyErr := shared.ParsePrivateKey(operatorPrivateKey)
if keyErr != nil {
return nil, keyErr
}
hederaClient.SetOperator(accountID, privateKey)
}
if injectedClient != nil {
injectedOperatorID := hederaClient.GetOperatorAccountID()
if injectedOperatorID.IsZero() {
return nil, fmt.Errorf("injected Hedera client must have an operator configured")
}
injectedOperatorAccountID := injectedOperatorID.String()
if operatorAccountID != "" && operatorAccountID != injectedOperatorAccountID {
return nil, fmt.Errorf(
"injected Hedera client operator account ID %s does not match provided operator account ID %s",
injectedOperatorAccountID,
operatorAccountID,
)
}
operatorAccountID = injectedOperatorAccountID
if operatorPrivateKey != "" {
parsedKey, keyErr := shared.ParsePrivateKey(operatorPrivateKey)
if keyErr != nil {
return nil, keyErr
}
if parsedKey.PublicKey().String() != hederaClient.GetOperatorPublicKey().String() {
return nil, fmt.Errorf("provided operator private key does not match the injected Hedera client operator")
}
}
}
mirrorClient, err := mirror.NewClient(mirror.Config{
Network: network,
BaseURL: config.MirrorBaseURL,
})
if err != nil {
return nil, err
}
keyType := strings.TrimSpace(config.KeyType)
if keyType == "" {
keyType = "ed25519"
}
inscriberBaseURL := strings.TrimSpace(config.InscriberBaseURL)
if inscriberBaseURL == "" {
inscriberBaseURL = strings.TrimSpace(config.KiloScribeBaseURL)
}
if inscriberBaseURL == "" {
inscriberBaseURL = "https://kiloscribe.com"
}
return &Client{
hederaClient: hederaClient,
mirrorClient: mirrorClient,
operatorAccountID: operatorAccountID,
operatorPrivateKey: operatorPrivateKey,
network: network,
keyType: keyType,
inscriberBaseURL: strings.TrimRight(inscriberBaseURL, "/"),
inscriberAuthURL: strings.TrimSpace(config.InscriberAuthURL),
inscriberAPIURL: strings.TrimSpace(config.InscriberAPIURL),
}, nil
}
// HederaClient returns the configured Hedera SDK client.
func (c *Client) HederaClient() *hedera.Client {
return c.hederaClient
}
// OperatorID returns the configured operator account ID.
func (c *Client) OperatorID() string {
return c.operatorAccountID
}
// MirrorClient returns the configured mirror node client.
func (c *Client) MirrorClient() *mirror.Client {
return c.mirrorClient
}
// CreatePersonalProfile creates the requested resource.
func (c *Client) CreatePersonalProfile(
displayName string,
options map[string]any,
) HCS11Profile {
profile := HCS11Profile{
Version: "1.0",
Type: ProfileTypePersonal,
DisplayName: strings.TrimSpace(displayName),
}
assignProfileOptions(&profile, options)
return profile
}
// CreateAIAgentProfile creates the requested resource.
func (c *Client) CreateAIAgentProfile(
displayName string,
agentType AIAgentType,
capabilities []AIAgentCapability,
model string,
options map[string]any,
) (HCS11Profile, error) {
profile := HCS11Profile{
Version: "1.0",
Type: ProfileTypeAIAgent,
DisplayName: strings.TrimSpace(displayName),
AIAgent: &AIAgentDetails{
Type: agentType,
Capabilities: append([]AIAgentCapability{}, capabilities...),
Model: strings.TrimSpace(model),
},
}
assignProfileOptions(&profile, options)
validation := c.ValidateProfile(profile)
if !validation.Valid {
return HCS11Profile{}, fmt.Errorf("invalid AI Agent Profile: %s", strings.Join(validation.Errors, ", "))
}
return profile, nil
}
// CreateMCPServerProfile creates the requested resource.
func (c *Client) CreateMCPServerProfile(
displayName string,
serverDetails MCPServerDetails,
options map[string]any,
) (HCS11Profile, error) {
profile := HCS11Profile{
Version: "1.0",
Type: ProfileTypeMCPServer,
DisplayName: strings.TrimSpace(displayName),
MCPServer: &serverDetails,
}
assignProfileOptions(&profile, options)
validation := c.ValidateProfile(profile)
if !validation.Valid {
return HCS11Profile{}, fmt.Errorf("invalid MCP Server Profile: %s", strings.Join(validation.Errors, ", "))
}
return profile, nil
}
// ValidateProfile validates the provided input value.
func (c *Client) ValidateProfile(profile HCS11Profile) ValidationResult {
errors := make([]string, 0)
if strings.TrimSpace(profile.Version) == "" {
errors = append(errors, "version is required")
}
if strings.TrimSpace(profile.DisplayName) == "" {
errors = append(errors, "display_name is required")
}
switch profile.Type {
case ProfileTypePersonal:
case ProfileTypeAIAgent:
if profile.AIAgent == nil {
errors = append(errors, "aiAgent is required for AI_AGENT profile")
} else {
if len(profile.AIAgent.Capabilities) == 0 {
errors = append(errors, "aiAgent.capabilities must not be empty")
}
if strings.TrimSpace(profile.AIAgent.Model) == "" {
errors = append(errors, "aiAgent.model is required")
}
}
case ProfileTypeMCPServer:
if profile.MCPServer == nil {
errors = append(errors, "mcpServer is required for MCP_SERVER profile")
} else {
if strings.TrimSpace(profile.MCPServer.Version) == "" {
errors = append(errors, "mcpServer.version is required")
}
if strings.TrimSpace(profile.MCPServer.ConnectionInfo.URL) == "" {
errors = append(errors, "mcpServer.connectionInfo.url is required")
}
transport := strings.TrimSpace(profile.MCPServer.ConnectionInfo.Transport)
if transport == "" {
errors = append(errors, "mcpServer.connectionInfo.transport is required")
} else if transport != "stdio" && transport != "sse" {
errors = append(errors, "mcpServer.connectionInfo.transport must be stdio or sse")
}
if len(profile.MCPServer.Services) == 0 {
errors = append(errors, "mcpServer.services must not be empty")
}
if strings.TrimSpace(profile.MCPServer.Description) == "" {
errors = append(errors, "mcpServer.description is required")
}
if profile.MCPServer.Verification != nil {
switch profile.MCPServer.Verification.Type {
case VerificationTypeDNS, VerificationTypeSignature, VerificationTypeChallenge:
default:
errors = append(errors, "mcpServer.verification.type is invalid")
}
}
}
case ProfileTypeFlora:
if len(profile.Members) == 0 {
errors = append(errors, "flora members are required")
}
if profile.Threshold < 1 {
errors = append(errors, "flora threshold must be at least 1")
}
if profile.Topics == nil {
errors = append(errors, "flora topics are required")
}
default:
errors = append(errors, "profile type is invalid")
}
return ValidationResult{
Valid: len(errors) == 0,
Errors: errors,
}
}
// ProfileToJSONString performs the requested operation.
func (c *Client) ProfileToJSONString(profile HCS11Profile) (string, error) {
encodedProfile, err := json.Marshal(profile)
if err != nil {
return "", err
}
return string(encodedProfile), nil
}
// ParseProfileFromString parses the provided input value.
func (c *Client) ParseProfileFromString(profileString string) (*HCS11Profile, error) {
var profile HCS11Profile
if err := json.Unmarshal([]byte(profileString), &profile); err != nil {
return nil, err
}
validation := c.ValidateProfile(profile)
if !validation.Valid {
return nil, fmt.Errorf("invalid profile format: %s", strings.Join(validation.Errors, ", "))
}
return &profile, nil
}
// SetProfileForAccountMemo sets the requested value.
func (c *Client) SetProfileForAccountMemo(topicID string, topicStandard int) string {
if topicStandard == 0 {
topicStandard = 1
}
return fmt.Sprintf("hcs-11:hcs://%d/%s", topicStandard, strings.TrimSpace(topicID))
}
// GetCapabilitiesFromTags returns the requested value.
func (c *Client) GetCapabilitiesFromTags(capabilityNames []string) []int {
if len(capabilityNames) == 0 {
return []int{int(AIAgentCapabilityTextGeneration)}
}
capabilities := make([]int, 0)
for _, capabilityName := range capabilityNames {
capability, ok := CapabilityNameToCapabilityMap[strings.ToLower(strings.TrimSpace(capabilityName))]
if ok && !containsInt(capabilities, int(capability)) {
capabilities = append(capabilities, int(capability))
}
}
if len(capabilities) == 0 {
return []int{int(AIAgentCapabilityTextGeneration)}
}
return capabilities
}
// GetAgentTypeFromMetadata returns the requested value.
func (c *Client) GetAgentTypeFromMetadata(metadata AgentMetadata) AIAgentType {
if strings.EqualFold(metadata.Type, "autonomous") {
return AIAgentTypeAutonomous
}
return AIAgentTypeManual
}
// AttachUAIDIfMissing attaches the requested value when required.
func (c *Client) AttachUAIDIfMissing(_ context.Context, profile *HCS11Profile) error {
if profile == nil || strings.TrimSpace(profile.UAID) != "" {
return nil
}
if strings.TrimSpace(c.operatorAccountID) == "" {
return nil
}
nativeID := fmt.Sprintf("hedera:%s:%s", c.network, c.operatorAccountID)
uid := c.operatorAccountID
if strings.TrimSpace(profile.InboundTopicID) != "" {
uid = fmt.Sprintf("%s@%s", profile.InboundTopicID, c.operatorAccountID)
}
uaid, err := hcs14.CreateUAIDFromDID(
fmt.Sprintf("did:hedera:%s:%s", c.network, c.operatorAccountID),
hcs14.RoutingParams{
UID: uid,
Proto: "hcs-10",
NativeID: nativeID,
},
)
if err != nil {
return err
}
profile.UAID = uaid
return nil
}
func containsInt(input []int, target int) bool {
for _, value := range input {
if value == target {
return true
}
}
return false
}
func assignProfileOptions(profile *HCS11Profile, options map[string]any) {
if profile == nil || options == nil {
return
}
if alias, ok := options["alias"].(string); ok {
profile.Alias = strings.TrimSpace(alias)
}
if bio, ok := options["bio"].(string); ok {
profile.Bio = strings.TrimSpace(bio)
}
if profileImage, ok := options["profileImage"].(string); ok {
profile.ProfileImage = strings.TrimSpace(profileImage)
}
if inboundTopicID, ok := options["inboundTopicId"].(string); ok {
profile.InboundTopicID = strings.TrimSpace(inboundTopicID)
}
if outboundTopicID, ok := options["outboundTopicId"].(string); ok {
profile.OutboundTopicID = strings.TrimSpace(outboundTopicID)
}
if baseAccount, ok := options["baseAccount"].(string); ok {
profile.BaseAccount = strings.TrimSpace(baseAccount)
}
}