Class: MixinBot::CLI

Inherits:
Thor
  • Object
show all
Defined in:
lib/mixin_bot/cli.rb,
lib/mixin_bot/cli/api.rb,
lib/mixin_bot/cli/utils.rb

Constant Summary collapse

UI =
::CLI::UI

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ CLI

Returns a new instance of CLI.



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
# File 'lib/mixin_bot/cli.rb', line 22

def initialize(*args)
  super
  if options[:keystore].blank?
    @api_instance = MixinBot::API.new
    return
  end

  keystore =
    if File.file? options[:keystore]
      File.read options[:keystore]
    else
      options[:keystore]
    end

  @keystore =
    begin
      JSON.parse keystore
    rescue JSON::ParserError
      log UI.fmt(
        format(
          '{{x}} falied to parse keystore.json: %<keystore>s',
          keystore: options[:keystore]
        )
      )
    end

  return unless @keystore

  MixinBot.config.api_host = options[:apihost]
  @api_instance ||=
    begin
      MixinBot::API.new(
        app_id: @keystore['app_id'] || @keystore['client_id'],
        session_id: @keystore['session_id'],
        server_public_key: @keystore['server_public_key'] || @keystore['pin_token'],
        session_private_key: @keystore['session_private_key'] || @keystore['private_key']
      )
    rescue StandardError => e
      log UI.fmt '{{x}}: Failed to initialize api, maybe your keystore is incorrect: %<error>s', error: e.message
    end
end

Instance Attribute Details

#api_instanceObject (readonly)

Returns the value of attribute api_instance.



20
21
22
# File 'lib/mixin_bot/cli.rb', line 20

def api_instance
  @api_instance
end

#keystoreObject (readonly)

Returns the value of attribute keystore.



20
21
22
# File 'lib/mixin_bot/cli.rb', line 20

def keystore
  @keystore
end

Class Method Details

.exit_on_failure?Boolean

Returns:

  • (Boolean)


72
73
74
# File 'lib/mixin_bot/cli.rb', line 72

def self.exit_on_failure?
  true
end

Instance Method Details

#api(path) ⇒ Object



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
# File 'lib/mixin_bot/cli/api.rb', line 26

def api(path)
  path = "#{path}?#{URI.encode_www_form(options[:params])}" if options[:params].present?
  payload =
    begin
      JSON.parse options[:data]
    rescue JSON::ParserError => e
      log UI.fmt("{{x}} #{e.inspect}")
      {}
    end

  access_token = options[:accesstoken] || api_instance.access_token(options[:method].upcase, path, payload.blank? ? '' : payload.to_json)
  authorization = format('Bearer %<access_token>s', access_token:)
  res = {}

  CLI::UI::Spinner.spin("#{options[:method]} #{path}, payload: #{payload}") do |_spinner|
    res =
      case options[:method].downcase.to_sym
      when :post
        api_instance.client.post(path, headers: { Authorization: authorization }, json: payload)
      when :get
        api_instance.client.get(path, headers: { Authorization: authorization })
      end
  end

  log res['data']
end

#authcodeObject



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/mixin_bot/cli/api.rb', line 57

def authcode
  res = {}
  CLI::UI::Spinner.spin('POST /oauth/authorize') do |_spinner|
    res =
      api_instance.authorize_code(
        user_id: options[:app_id],
        scope: options[:scope],
        pin: keystore['pin']
      )
  end
  log res['data']
end

#decodetx(transaction) ⇒ Object



23
24
25
# File 'lib/mixin_bot/cli/utils.rb', line 23

def decodetx(transaction)
  log MixinBot.utils.decode_raw_transaction(transaction)
end

#ed25519Object



41
42
43
# File 'lib/mixin_bot/cli/utils.rb', line 41

def ed25519
  log MixinBot.utils.generate_ed25519_key
end

#encrypt(pin) ⇒ Object



8
9
10
# File 'lib/mixin_bot/cli/utils.rb', line 8

def encrypt(pin)
  log api_instance.encrypt_pin pin.to_s, iterator: options[:iterator]
end

#generatetrace(hash) ⇒ Object



18
19
20
# File 'lib/mixin_bot/cli/utils.rb', line 18

def generatetrace(hash)
  log MixinBot.utils.generate_trace_from_hash(hash)
end

#nftmemoObject



31
32
33
# File 'lib/mixin_bot/cli/utils.rb', line 31

def nftmemo
  log MixinBot.utils.nft(options[:collection], options[:token], options[:hash])
end

#payObject



140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/mixin_bot/cli/api.rb', line 140

def pay
  url = api_instance.safe_pay_url(
    members: options[:members],
    threshold: options[:threshold],
    asset_id: options[:asset],
    amount: options[:amount],
    trace_id: options[:trace],
    memo: options[:memo]
  )

  log UI.fmt "{{v}} #{url}"
end

#rsaObject



36
37
38
# File 'lib/mixin_bot/cli/utils.rb', line 36

def rsa
  log MixinBot.utils.generate_rsa_key
end

#saferegisterObject



128
129
130
131
# File 'lib/mixin_bot/cli/api.rb', line 128

def saferegister
  res = api_instance.safe_register options[:spend_key]
  log res
end

#safetransfer(user_id) ⇒ Object



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
# File 'lib/mixin_bot/cli/api.rb', line 159

def safetransfer(user_id)
  amount = options[:amount].to_d
  asset = options[:asset]
  memo = options[:memo] || ''

  # step 1: select inputs
  outputs = api_instance.safe_outputs(state: 'unspent', asset_id: asset, limit: 500)['data'].sort_by { |o| o['amount'].to_d }
  balance = outputs.sum(&->(output) { output['amount'].to_d })

  utxos = []
  outputs.each do |output|
    break if utxos.sum { |o| o['amount'].to_d } >= amount

    utxos.shift if utxos.size >= 255
    utxos << output
  end

  log UI.fmt "Step 1/7: {{v}} Found #{outputs.count} unspent outputs, balance: #{balance}, selected #{utxos.count} outputs"

  # step 2: build transaction
  tx = api_instance.build_safe_transaction(
    utxos:,
    receivers: [
      members: [user_id],
      threshold: 1,
      amount:
    ],
    extra: memo
  )
  raw = MixinBot::Utils.encode_raw_transaction tx
  log UI.fmt "Step 2/5: {{v}} Built raw: #{raw}"

  # step 3: verify transaction
  request_id = SecureRandom.uuid
  request = api_instance.create_safe_transaction_request(request_id, raw)['data']
  log UI.fmt "Step 3/5: {{v}} Verified transaction, request_id: #{request[0]['request_id']}"

  # step 4: sign transaction
  signed_raw = api_instance.sign_safe_transaction(
    raw:,
    utxos:,
    request: request[0]
  )
  log UI.fmt "Step 4/5: {{v}} Signed transaction: #{signed_raw}"

  # step 5: submit transaction
  r = api_instance.send_safe_transaction(
    request_id,
    signed_raw
  )
  log UI.fmt "Step 5/5: {{v}} Submit transaction, hash: #{r['data'].first['transaction_hash']}"
rescue StandardError => e
  log UI.fmt "{{x}} #{e.inspect}"
end

#transfer(user_id) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/mixin_bot/cli/api.rb', line 105

def transfer(user_id)
  res = {}

  CLI::UI::Spinner.spin "Try to transfer #{options[:amount]} #{options[:asset]} to #{user_id}" do |_spinner|
    res = api_instance.create_transfer(
      keystore['pin'],
      {
        asset_id: options[:asset],
        opponent_id: user_id,
        amount: options[:amount],
        memo: options[:memo]
      }
    )
  end

  return unless res['snapshot_id'].present?

  log UI.fmt "{{v}} Finished: https://mixin.one/snapshots/#{res['snapshot_id']}"
end

#unique(*uuids) ⇒ Object



13
14
15
# File 'lib/mixin_bot/cli/utils.rb', line 13

def unique(*uuids)
  log MixinBot.utils.unique_uuid(*uuids)
end

#updatetip(pin) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/mixin_bot/cli/api.rb', line 72

def updatetip(pin)
  profile = api_instance.me
  log UI.fmt "{{v}} #{profile['full_name']}, TIP counter: #{profile['tip_counter']}"

  counter = profile['tip_counter']
  key = api_instance.prepare_tip_key counter
  log UI.fmt "{{v}} Generated key: #{key[:private_key]}"

  res = api_instance.update_pin old_pin: pin.to_s, pin: key[:public_key]

  log({
        pin: key[:private_key],
        tip_key_base64: res['tip_key_base64']
      })
rescue StandardError => e
  log UI.fmt "{{x}} #{e.inspect}"
end

#verifypin(pin) ⇒ Object



92
93
94
95
96
97
98
# File 'lib/mixin_bot/cli/api.rb', line 92

def verifypin(pin)
  res = api_instance.verify_pin pin.to_s

  log res
rescue StandardError => e
  log UI.fmt "{{x}} #{e.inspect}"
end

#versionObject



68
69
70
# File 'lib/mixin_bot/cli.rb', line 68

def version
  log MixinBot::VERSION
end