-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
646 lines (551 loc) · 18.2 KB
/
client.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
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
package swan
import (
"context"
"errors"
"fmt"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"log"
"math/big"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"time"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/swanchain/go-swan-sdk/contract"
)
type APIClient struct {
apiKey string
httpClient *HttpClient
contractDetail ContractDetail
instanceList []*InstanceResource
}
func NewAPIClient(apiKey string, isTestnet ...bool) (*APIClient, error) {
host := gatewayMainnet
if len(isTestnet) > 0 && isTestnet[0] {
host = gatewayTestnet
}
header := make(http.Header)
header.Add("Authorization", "Bearer "+apiKey)
var apiClient = APIClient{
apiKey: apiKey,
httpClient: NewHttpClient(host, header),
}
contractDetail, err := apiClient.getContractInfo(false)
if err != nil {
return nil, fmt.Errorf("failed to get contract detail, error: %v", err)
}
instanceList, err := apiClient.InstanceResources()
if err != nil {
return nil, fmt.Errorf("failed to get instance resources, error: %v", err)
}
chainId, netWorkName, err := getNetWorkInfo(contractDetail.RpcUrl)
if err != nil {
return nil, fmt.Errorf("failed to get chain info, error: %v", err)
}
fmt.Printf("Logging in Swan Chain %s(%d) \n", netWorkName, chainId)
apiClient.instanceList = instanceList
apiClient.contractDetail = contractDetail
return &apiClient, nil
}
func (c *APIClient) login() error {
var token string
if err := c.httpClient.PostForm(apiLogin, url.Values{"api_key": {c.apiKey}}, NewResult(&token)); err != nil {
return err
}
c.httpClient.header.Set("Authorization", "Bearer "+token)
return nil
}
func (c *APIClient) InstanceResources(available ...bool) ([]*InstanceResource, error) {
var result InstanceResult
if err := c.httpClient.Get(apiMachines, nil, NewResult(&result)); err != nil {
return nil, err
}
if len(available) > 0 && available[0] {
var data []*InstanceResource
for _, instance := range result.Instances {
instanceCp := instance
if instanceCp.Status == "available" {
data = append(data, instanceCp)
}
}
return data, nil
}
return result.Instances, nil
}
func (c *APIClient) TaskInfo(taskUUID string) (*TaskInfo, error) {
var result TaskInfo
if err := c.httpClient.Get(fmt.Sprintf("%s/%s", apiTask, taskUUID), nil, NewResult(&result)); err != nil {
return nil, err
}
return &result, nil
}
func (c *APIClient) Tasks(req *TaskQueryReq) (total int64, list []*TaskInfo, err error) {
api := apiTasks
if req != nil {
api += fmt.Sprintf("?wallet=%s&size=%d&page=%d", req.Wallet, req.Size, req.Page)
}
var result PageResult
result.List = &list
if err = c.httpClient.Get(api, nil, NewResult(&result)); err != nil {
return
}
total = result.Total
return
}
func (c *APIClient) CreateTask(req *CreateTaskReq) (*CreateTaskResp, error) {
var createTaskResp CreateTaskResp
if req.WalletAddress == "" && req.PrivateKey == "" {
return nil, fmt.Errorf("please provide WalletAddress or PrivateKey")
}
var walletAddress = req.WalletAddress
if walletAddress != "" {
walletAddress = req.WalletAddress
} else {
publicKeyAddress, err := privateKeyToPublicKey(req.PrivateKey)
if err != nil {
return nil, err
}
walletAddress = publicKeyAddress.String()
}
if req.Region == "" {
req.Region = "global"
}
if req.StartIn == 0 {
req.StartIn = 300
}
if req.Duration.Seconds() < 3600 {
return nil, fmt.Errorf("duration must be no less than 3600 seconds")
}
if strings.TrimSpace(req.InstanceType) == "" {
req.InstanceType = "C1ae.small"
}
if _, err := c.getInstanceByInstanceType(req.InstanceType); err != nil {
return nil, err
}
log.Printf("Using %s machine, region=%s duration=%.0f (seconds) \n", req.InstanceType, req.Region, req.Duration.Seconds())
if req.JobSourceUri == "" {
if req.RepoUri != "" {
sourceUri, err := c.getSourceUri(req.RepoUri, walletAddress, req.InstanceType, req.RepoBranch)
if err != nil {
return nil, fmt.Errorf("please provide JobSourceUri, or RepoUri, error: %v", err)
}
req.JobSourceUri = sourceUri
}
}
if req.JobSourceUri == "" {
return nil, fmt.Errorf("cannot get JobSourceUri. make sure `RepoUri` or `JobSourceUri` is correct")
}
var preferredCp string
if len(req.PreferredCpList) > 0 {
preferredCp = strings.Join(req.PreferredCpList, ",")
}
if !c.verifyHardwareRegion(req.InstanceType, req.Region) {
return nil, fmt.Errorf("no %s machine in %s", req.InstanceType, req.Region)
}
var params = make(url.Values)
params.Set("duration", strconv.Itoa(int(req.Duration.Seconds())))
params.Set("cfg_name", req.InstanceType)
params.Set("region", req.Region)
params.Set("start_in", strconv.Itoa(req.StartIn))
params.Set("wallet", walletAddress)
params.Set("job_source_uri", req.JobSourceUri)
if preferredCp != "" {
params.Add("preferred_cp", preferredCp)
}
if err := c.login(); err != nil {
return nil, err
}
if err := c.httpClient.PostForm(apiTask, params, NewResult(&createTaskResp)); err != nil {
return nil, fmt.Errorf("failed to create task, error: %v", err)
}
taskUuid := createTaskResp.Task.UUID
createTaskResp.TaskUuid = taskUuid
createTaskResp.InstanceType = req.InstanceType
estimatePrice, err := c.EstimatePayment(req.InstanceType, req.Duration.Seconds())
if err != nil {
return nil, err
}
createTaskResp.Price = estimatePrice
if req.PrivateKey != "" {
payment, err := c.PayAndDeployTask(taskUuid, req.PrivateKey, req.Duration, req.InstanceType)
if err != nil {
return nil, err
}
createTaskResp.ConfigOrder = payment.ConfigOrder
createTaskResp.TxHash = payment.TxHash
createTaskResp.ApproveHash = payment.ApproveHash
log.Printf("Task created successfully, taskUuid=%s", taskUuid)
}
return &createTaskResp, nil
}
func (c *APIClient) PayAndDeployTask(taskUuid, privateKey string, duration time.Duration, instanceType string) (*PaymentResult, error) {
var paymentResult PaymentResult
if strings.TrimSpace(instanceType) == "" {
return nil, fmt.Errorf("invalid instanceType")
}
if privateKey == "" {
return nil, fmt.Errorf("no privateKey provided")
}
approveTxHash, submitPaymentTx, err := c.submitPayment(taskUuid, privateKey, duration, instanceType)
if err != nil {
return nil, err
}
time.Sleep(3 * time.Second)
validatePaymentResult, err := c.validatePayment(submitPaymentTx, taskUuid)
if err != nil {
return nil, err
}
paymentResult.ConfigOrder = validatePaymentResult.ConfigOrder
paymentResult.ApproveHash = approveTxHash
return &paymentResult, nil
}
func (c *APIClient) EstimatePayment(instanceType string, duration float64) (float64, error) {
hardwareBaseInfo, err := c.getInstanceByInstanceType(instanceType)
if err != nil {
return 0, err
}
priceInt, err := strconv.ParseFloat(hardwareBaseInfo.Price, 64)
if err != nil {
return 0, err
}
return priceInt * (duration / 3600), nil
}
func (c *APIClient) RenewTask(taskUuid string, duration time.Duration, privateKey string, paidTxHash ...string) (*RenewTaskResp, error) {
if strings.TrimSpace(taskUuid) == "" {
return nil, fmt.Errorf("invalid taskUuid")
}
if privateKey == "" && len(paidTxHash) == 0 {
return nil, fmt.Errorf("provide a txHash or privateKey")
}
var txHash string
if len(paidTxHash) == 0 {
reNewPaymentTxHash, err := c.RenewPayment(taskUuid, duration, privateKey)
if err != nil {
return nil, err
}
txHash = reNewPaymentTxHash
} else {
txHash = paidTxHash[0]
log.Printf("Using given payment transaction hash, txHash=%s", txHash)
}
if txHash != "" && taskUuid != "" {
var params = make(url.Values)
params.Set("task_uuid", taskUuid)
params.Set("duration", strconv.FormatInt(int64(duration.Seconds()), 10))
params.Set("tx_hash", txHash)
var renewTaskResp RenewTaskResp
if err := c.httpClient.PostForm(apiReNewTask, params, NewResult(&renewTaskResp)); err != nil {
return nil, err
}
return &renewTaskResp, nil
} else {
return nil, fmt.Errorf("txHash or taskUuid invalid")
}
}
func (c *APIClient) RenewPayment(taskUuid string, duration time.Duration, privateKey string) (string, error) {
if strings.TrimSpace(taskUuid) == "" {
return "", fmt.Errorf("invalid taskUuid")
}
if privateKey == "" {
return "", fmt.Errorf("no privateKey provided")
}
taskInfo, err := c.TaskInfo(taskUuid)
if err != nil {
return "", fmt.Errorf("failed to get task info, taskUuid: %s, error: %v", taskUuid, err)
}
instanceType := taskInfo.Task.TaskDetail.Hardware
hardwareBaseInfo, err := c.getInstanceByInstanceType(instanceType)
if err != nil {
return "", err
}
var hardwareId = hardwareBaseInfo.ID
estimatePrice, err := c.estimatePrice(hardwareId, duration.Seconds())
if err != nil {
return "", err
}
priceBigInt, ok := new(big.Int).SetString(fmt.Sprintf("%.f", estimatePrice), 10)
if !ok {
return "", fmt.Errorf("failed to convert float64 to big.Int")
}
client, err := ethclient.Dial(c.contractDetail.RpcUrl)
if err != nil {
return "", err
}
defer client.Close()
tokenContract, err := contract.NewToken(common.HexToAddress(c.contractDetail.SwanTokenContractAddress), client)
if err != nil {
return "", err
}
paymentContract, err := contract.NewPaymentContract(common.HexToAddress(c.contractDetail.ClientContractAddress), client)
if err != nil {
return "", err
}
approveTransactOpts, err := CreateTransactOpts(client, privateKey)
if err != nil {
return "", err
}
approve, err := tokenContract.Approve(approveTransactOpts, common.HexToAddress(c.contractDetail.ClientContractAddress), priceBigInt)
if err != nil {
return "", err
}
tokenApproveHash := approve.Hash().String()
timeout := time.After(1 * time.Minute)
ticker := time.Tick(3 * time.Second)
for {
select {
case <-timeout:
return "", fmt.Errorf("timeout waiting for transaction confirmation, tx: %s", tokenApproveHash)
case <-ticker:
receipt, err := client.TransactionReceipt(context.Background(), common.HexToHash(tokenApproveHash))
if err != nil {
if errors.Is(err, ethereum.NotFound) {
continue
}
return "", fmt.Errorf("check swan token Approve tx, error: %+v", err)
}
if receipt != nil && receipt.Status == types.ReceiptStatusSuccessful {
paymentTransactOpts, err := CreateTransactOpts(client, privateKey)
if err != nil {
return "", err
}
hardwareIdBigInt := new(big.Int).SetInt64(hardwareId)
durationBigInt := new(big.Int).SetInt64(int64(duration.Seconds()))
transaction, err := paymentContract.RenewPayment(paymentTransactOpts, taskUuid, hardwareIdBigInt, durationBigInt)
if err != nil {
return "", fmt.Errorf("failed to renew payment, error: %v", err)
}
return transaction.Hash().String(), nil
} else if receipt != nil && receipt.Status == 0 {
return "", fmt.Errorf("failed to check swan token approve transaction, tx: %s", tokenApproveHash)
}
}
}
}
func (c *APIClient) TerminateTask(taskUuid string) (TerminateTaskResp, error) {
var terminateTaskResp TerminateTaskResp
if strings.TrimSpace(taskUuid) == "" {
return terminateTaskResp, fmt.Errorf("invalid taskUuid")
}
var params = make(url.Values)
params.Set("task_uuid", taskUuid)
if err := c.httpClient.PostForm(apiTerminateTask, params, NewResult(&terminateTaskResp)); err != nil {
return terminateTaskResp, err
}
return terminateTaskResp, nil
}
func (c *APIClient) GetRealUrl(taskUuid string) ([]string, error) {
if strings.TrimSpace(taskUuid) == "" {
return nil, fmt.Errorf("invalid taskUuid")
}
taskInfo, err := c.TaskInfo(taskUuid)
if err != nil {
return nil, fmt.Errorf("failed to get task info, error: %v", err)
}
var deployedUrl []string
for _, job := range taskInfo.Jobs {
if strings.TrimSpace(job.JobRealURI) != "" {
deployedUrl = append(deployedUrl, job.JobRealURI)
}
}
return deployedUrl, nil
}
func (c *APIClient) estimatePrice(hardwareId int64, duration float64) (float64, error) {
client, err := ethclient.Dial(c.contractDetail.RpcUrl)
if err != nil {
return 0, err
}
defer client.Close()
paymentContract, err := contract.NewPaymentContract(common.HexToAddress(c.contractDetail.ClientContractAddress), client)
if err != nil {
return 0, err
}
hardwarePrice, err := paymentContract.HardwareInfo(&bind.CallOpts{}, new(big.Int).SetInt64(hardwareId))
if err != nil {
return 0, err
}
return float64(hardwarePrice.PricePerHour.Int64()) * (duration / 3600), nil
}
func (c *APIClient) getSourceUri(repoUri, walletAddress string, instanceType string, repoBranch string) (string, error) {
var jobSourceUriResult JobSourceUriResult
hardwareBaseInfo, err := c.getInstanceByInstanceType(instanceType)
if err != nil {
return "", err
}
if walletAddress == "" {
return "", fmt.Errorf("no wallet_address provided")
}
var reqData = make(url.Values)
reqData.Set("repo_branch", repoBranch)
reqData.Set("wallet_address", walletAddress)
reqData.Set("hardware_id", strconv.FormatInt(hardwareBaseInfo.ID, 10))
reqData.Set("repo_uri", repoUri)
if err := c.httpClient.PostForm(apiSourceUri, reqData, NewResult(&jobSourceUriResult)); err != nil {
return "", err
}
return jobSourceUriResult.JobSourceUri, nil
}
func (c *APIClient) verifyHardwareRegion(instanceType, region string) bool {
for _, hardware := range c.instanceList {
if hardware.Type == instanceType {
for _, r := range hardware.Region {
if region == r || (strings.ToLower(region) == "global" && hardware.Status == "available") {
return true
}
}
}
}
return false
}
func (c *APIClient) submitPayment(taskUuid, privateKey string, duration time.Duration, instanceType string) (string, string, error) {
hardwareBaseInfo, err := c.getInstanceByInstanceType(instanceType)
if err != nil {
return "", "", err
}
if privateKey == "" {
return "", "", fmt.Errorf("no privateKey provided")
}
var hardwareId = hardwareBaseInfo.ID
estimatePrice, err := c.estimatePrice(hardwareId, duration.Seconds())
if err != nil {
return "", "", err
}
priceBigInt, ok := new(big.Int).SetString(fmt.Sprintf("%.f", estimatePrice), 10)
if !ok {
return "", "", fmt.Errorf("failed to convert float64 to big.Int")
}
client, err := ethclient.Dial(c.contractDetail.RpcUrl)
if err != nil {
return "", "", err
}
defer client.Close()
tokenContract, err := contract.NewToken(common.HexToAddress(c.contractDetail.SwanTokenContractAddress), client)
if err != nil {
return "", "", err
}
paymentContract, err := contract.NewPaymentContract(common.HexToAddress(c.contractDetail.ClientContractAddress), client)
if err != nil {
return "", "", err
}
approveTransactOpts, err := CreateTransactOpts(client, privateKey)
if err != nil {
return "", "", err
}
hardwareIdBigInt := new(big.Int).SetInt64(hardwareId)
durationBigInt := new(big.Int).SetInt64(int64(duration.Seconds()))
approve, err := tokenContract.Approve(approveTransactOpts, common.HexToAddress(c.contractDetail.ClientContractAddress), priceBigInt)
if err != nil {
return "", "", err
}
tokenApproveHash := approve.Hash().String()
timeout := time.After(1 * time.Minute)
ticker := time.Tick(3 * time.Second)
for {
select {
case <-timeout:
return "", "", fmt.Errorf("timeout waiting for transaction confirmation, tx: %s", tokenApproveHash)
case <-ticker:
receipt, err := client.TransactionReceipt(context.Background(), common.HexToHash(tokenApproveHash))
if err != nil {
if errors.Is(err, ethereum.NotFound) {
continue
}
return "", "", fmt.Errorf("check swan token Approve tx, error: %+v", err)
}
if receipt != nil && receipt.Status == types.ReceiptStatusSuccessful {
paymentTransactOpts, err := CreateTransactOpts(client, privateKey)
if err != nil {
return "", "", err
}
transaction, err := paymentContract.SubmitPayment(paymentTransactOpts, taskUuid, hardwareIdBigInt, durationBigInt)
if err != nil {
return "", "", fmt.Errorf("failed to submit payment, error: %v", err)
}
return tokenApproveHash, transaction.Hash().String(), nil
} else if receipt != nil && receipt.Status == 0 {
return "", "", fmt.Errorf("failed to check swan token approve transaction, tx: %s", tokenApproveHash)
}
}
}
}
func (c *APIClient) validatePayment(txHash, taskUuid string) (*ValidatePaymentResult, error) {
var validatePaymentResult ValidatePaymentResult
if txHash != "" && taskUuid != "" {
var params = make(url.Values)
params.Set("tx_hash", txHash)
params.Set("task_uuid", taskUuid)
if err := c.httpClient.PostForm(apiValidatePayment, params, NewResult(&validatePaymentResult)); err != nil {
return nil, err
}
return &validatePaymentResult, nil
} else {
return nil, fmt.Errorf("tx_hash or task_uuid invalid")
}
}
func (c *APIClient) getContractInfo(validate bool) (ContractDetail, error) {
var contractResult ContractResult
if err := c.httpClient.Get(apiContract, nil, NewResult(&contractResult)); err != nil {
return ContractDetail{}, err
}
if validate {
if !contractInfoVerified(contractResult.ContractInfo, contractResult.Signature, OrchestratorPublicAddressTestnet) {
return ContractDetail{}, fmt.Errorf("failed to verified contract")
}
}
return contractResult.ContractInfo.ContractDetail, nil
}
func (c *APIClient) getInstanceByInstanceType(instanceType string) (*InstanceBaseInfo, error) {
var baseInfo InstanceBaseInfo
if strings.TrimSpace(instanceType) == "" {
return nil, fmt.Errorf("invalid instanceType")
}
for _, hardware := range c.instanceList {
if hardware.Type == instanceType {
baseInfo = hardware.InstanceBaseInfo
break
}
}
if baseInfo.Description == "" {
return nil, fmt.Errorf("invalid instanceType: %s", instanceType)
}
return &baseInfo, nil
}
func getNetWorkInfo(rpc string) (int64, string, error) {
client, err := ethclient.Dial(rpc)
if err != nil {
return 0, "", err
}
defer client.Close()
chainId, err := client.ChainID(context.Background())
if err != nil {
return 0, "", err
}
var network = "Testnet"
if chainId.Int64() == 254 {
network = "Mainnet"
}
return chainId.Int64(), network, nil
}
type Result struct {
Data any `json:"data"`
Message string `json:"message"`
Status string `json:"status"`
}
func NewResult(dest any) *Result {
if reflect.ValueOf(dest).Kind() != reflect.Ptr {
panic("dest must be a pointer")
}
var result Result
result.Data = dest
return &result
}
func (r *Result) Check() error {
if r.Status != "success" {
return errors.New(r.Message)
}
return nil
}