-
Notifications
You must be signed in to change notification settings - Fork 0
/
lock.go
85 lines (69 loc) · 1.93 KB
/
lock.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
package lock
import (
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/fox-one/hodl/config"
"github.com/fox-one/hodl/core"
"github.com/fox-one/hodl/invoker"
"github.com/fox-one/hodl/writer"
"github.com/fox-one/mixin-sdk-go"
"github.com/shopspring/decimal"
"github.com/spf13/cobra"
)
// NewCmd returns a new instance of the lock command.
func NewCmd(cfg *config.Config) *cobra.Command {
client, err := mixin.NewFromKeystore(&cfg.Dapp)
if err != nil {
panic(fmt.Errorf("create mixin client failed: %w", err))
}
ivk := invoker.New(client, invoker.Config{
Process: cfg.System.ProcessID,
Members: cfg.Group.Members,
Threshold: cfg.Group.Threshold,
})
cmd := &cobra.Command{
Use: "lock",
Example: "lock 10 btc 24h",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
amount, _ := decimal.NewFromString(args[0])
amount = amount.Truncate(8)
if !amount.IsPositive() {
return errors.New("amount must be positive")
}
symbol := strings.ToLower(args[1])
assets, err := mixin.ReadNetworkAssetsBySymbol(ctx, symbol)
if err != nil {
return fmt.Errorf("read assets by symbol %q failed", symbol)
}
if len(assets) == 0 {
return fmt.Errorf("assets %q not found", symbol)
}
sort.Slice(assets, func(i, j int) bool {
return assets[i].PriceUSD.GreaterThan(assets[j].PriceUSD)
})
asset := assets[0]
exp, err := time.ParseDuration(args[2])
if err != nil {
return fmt.Errorf("parse expire duration %q failed", args[2])
}
event := core.Event{
Action: core.ActionLock,
Exp: uint64(exp),
}
code, err := ivk.Payment(ctx, asset.AssetID, amount, event.Encode())
if err != nil {
return fmt.Errorf("payment failed: %w", err)
}
action := mixin.URL.Codes(code)
label := fmt.Sprintf("lock %s %s", amount, symbol)
cmd.Println(writer.WithLabel(action, label))
return nil
},
}
return cmd
}