Class: Peatio::Bitgo::Wallet

Inherits:
Wallet::Abstract
  • Object
show all
Defined in:
lib/peatio/bitgo/wallet.rb

Constant Summary collapse

TIME_DIFFERENCE_IN_MINUTES =
10
XLM_MEMO_TYPES =
{ 'memoId': 'id', 'memoText': 'text', 'memoHash': 'hash', 'memoReturn': 'return' }
DEFAULT_FEATURES =
{ skip_deposit_collection: false }.freeze

Instance Method Summary collapse

Constructor Details

#initialize(custom_features = {}) ⇒ Wallet

Returns a new instance of Wallet.



9
10
11
12
# File 'lib/peatio/bitgo/wallet.rb', line 9

def initialize(custom_features = {})
  @features = DEFAULT_FEATURES.merge(custom_features).slice(*SUPPORTED_FEATURES)
  @settings = {}
end

Instance Method Details

#address_confirmation_webhook(url) ⇒ Object



230
231
232
233
234
235
236
237
238
# File 'lib/peatio/bitgo/wallet.rb', line 230

def address_confirmation_webhook(url)
  client.rest_api(:post, "#{currency_id}/wallet/#{wallet_id}/webhooks", {
    type: 'address_confirmation',
    allToken: true,
    url: url,
    label: "webhook for #{url}",
    listenToFailureStates: false
  })
end

#build_raw_transaction(transaction) ⇒ Object



84
85
86
87
88
89
90
91
# File 'lib/peatio/bitgo/wallet.rb', line 84

def build_raw_transaction(transaction)
  client.rest_api(:post, "#{currency_id}/wallet/#{wallet_id}/tx/build", {
    recipients: [{
      address: transaction.to_address,
      amount: convert_to_base_unit(transaction.amount).to_s
    }]
  }.compact)
end

#configure(settings = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/peatio/bitgo/wallet.rb', line 14

def configure(settings = {})
  # Clean client state during configure.
  @client = nil

  @settings.merge!(settings.slice(*SUPPORTED_SETTINGS))

  @wallet = @settings.fetch(:wallet) do
    raise Peatio::Wallet::MissingSettingError, :wallet
  end.slice(:uri, :address, :secret, :access_token, :wallet_id, :testnet)

   @currency = @settings.fetch(:currency) do
    raise Peatio::Wallet::MissingSettingError, :currency
   end.slice(:id, :base_factor, :code, :options)
end

#create_address!(options = {}) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/peatio/bitgo/wallet.rb', line 29

def create_address!(options = {})
  currency = erc20_currency_id
  options.deep_symbolize_keys!

  if options.dig(:pa_details, :address_id).present? &&
     options.dig(:pa_details, :updated_at).present? &&
     time_difference_in_minutes(options.dig(:pa_details, :updated_at)) >= TIME_DIFFERENCE_IN_MINUTES

    response = client.rest_api(:get, "#{currency}/wallet/#{wallet_id}/address/#{options.dig(:pa_details, :address_id)}")
    { address: response['address'], secret: bitgo_wallet_passphrase }
  elsif options.dig(:pa_details, :address_id).blank?
    response = client.rest_api(:post, "#{currency}/wallet/#{wallet_id}/address")
    { address: response['address'], secret: bitgo_wallet_passphrase, details: { address_id: response['id'] }}
  end
rescue Bitgo::Client::Error => e
  raise Peatio::Wallet::ClientError, e
end

#create_eth_transaction(transaction, options = {}) ⇒ Object



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
# File 'lib/peatio/bitgo/wallet.rb', line 93

def create_eth_transaction(transaction, options = {})
  amount = convert_to_base_unit(transaction.amount)
  hop = true unless options.slice(:gas_price).present?

  fee_estimate = fee_estimate(amount.to_s, hop)

  if transaction.options.present? && transaction.options[:gas_price].present?
    options[:gas_price] = transaction.options[:gas_price]
  else
    options[:gas_price] = fee_estimate['minGasPrice'].to_i
  end

  response = client.rest_api(:post, "#{currency_id}/wallet/#{wallet_id}/sendcoins", {
    address: transaction.to_address.to_s,
    amount: amount.to_s,
    walletPassphrase: bitgo_wallet_passphrase,
    gas: options.fetch(:gas_limit).to_i,
    gasPrice: options.fetch(:gas_price).to_i,
    hop: hop
  }.compact)

  if response['feeString'].present?
    fee = convert_from_base_unit(response['feeString'])
    transaction.fee = fee
  end

  transaction.hash = normalize_txid(response['txid'])
  transaction.fee_currency_id = erc20_currency_id
  transaction.options = options
  transaction
end

#create_transaction!(transaction, options = {}) ⇒ Object



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
# File 'lib/peatio/bitgo/wallet.rb', line 47

def create_transaction!(transaction, options = {})
  currency_options = @currency.fetch(:options).slice(:gas_limit, :gas_price, :erc20_contract_address)

  if currency_options[:gas_limit].present? && currency_options[:gas_price].present?
    options.merge!(currency_options)
    create_eth_transaction(transaction, options)
  else
    amount = convert_to_base_unit(transaction.amount)

    if options[:subtract_fee].to_s == 'true'
      fee = build_raw_transaction(transaction)
      baseFeeInfo = fee.dig('feeInfo','fee')
      fee = baseFeeInfo.present? ? baseFeeInfo : fee.dig('txInfo','Fee')
      amount -= fee.to_i
    end

    response = client.rest_api(:post, "#{currency_id}/wallet/#{wallet_id}/sendcoins", {
                           address: normalize_address(transaction.to_address.to_s),
                           amount: amount.to_s,
                           walletPassphrase: bitgo_wallet_passphrase,
                           memo: xlm_memo(transaction.to_address.to_s)
    }.compact)

    if response['feeString'].present?
      fee = convert_from_base_unit(response['feeString'])
      transaction.fee = fee
    end

    transaction.hash = normalize_txid(response['txid'])
    transaction.fee_currency_id = erc20_currency_id
    transaction
  end
rescue Bitgo::Client::Error => e
  raise Peatio::Wallet::ClientError, e
end

#fee_estimate(amount, hop) ⇒ Object



125
126
127
# File 'lib/peatio/bitgo/wallet.rb', line 125

def fee_estimate(amount, hop)
  client.rest_api(:get, "#{erc20_currency_id}/tx/fee", { amount: amount, hop: hop }.compact)
end

#fetch_address_id(address) ⇒ Object



173
174
175
176
177
178
179
# File 'lib/peatio/bitgo/wallet.rb', line 173

def fetch_address_id(address)
  currency = erc20_currency_id
  client.rest_api(:get, "#{currency}/wallet/#{wallet_id}/address/#{address}")
        .fetch('id')
rescue Bitgo::Client::Error => e
  raise Peatio::Wallet::ClientError, e
end

#fetch_transfer!(id) ⇒ Object



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
# File 'lib/peatio/bitgo/wallet.rb', line 181

def fetch_transfer!(id)
  response = client.rest_api(:get, "#{currency_id}/wallet/#{wallet_id}/transfer/#{id}")
  parse_entries(response['entries']).map do |entry|
    to_address =  if response.dig('coinSpecific', 'memo').present?
                    memo = response.dig('coinSpecific', 'memo')
                    memo_type = memo.kind_of?(Array) ? memo.first  : memo
                    build_address(entry['address'], memo_type)
                  else
                    entry['address']
                  end
    state = define_transaction_state(response['state'])

    if response['outputs'].present?
      output = response['outputs'].find { |out| out['address'] == to_address }
      txout = output['index'] if output.present?
    end

    if response['feeString'].present?
      fee = convert_from_base_unit(response['feeString']) / response['entries'].count
    end

    transaction = Peatio::Transaction.new(
      currency_id: @currency.fetch(:id),
      amount: convert_from_base_unit(entry['valueString']),
      fee: fee,
      fee_currency_id: erc20_currency_id,
      hash: normalize_txid(response['txid']),
      to_address: to_address,
      block_number: response['height'],
      txout: txout.to_i,
      status: state
    )

    transaction if transaction.valid?
  end.compact
rescue Bitgo::Client::Error => e
  raise Peatio::Wallet::ClientError, e
end

#load_balance!Object



129
130
131
132
133
134
135
136
137
138
# File 'lib/peatio/bitgo/wallet.rb', line 129

def load_balance!
  if @currency.fetch(:options).slice(:erc20_contract_address).present?
    load_erc20_balance!
  else
    response = client.rest_api(:get, "#{currency_id}/wallet/#{wallet_id}")
    convert_from_base_unit(response.fetch('balanceString'))
  end
rescue Bitgo::Client::Error => e
  raise Peatio::Wallet::ClientError, e
end

#load_erc20_balance!Object



140
141
142
143
144
145
# File 'lib/peatio/bitgo/wallet.rb', line 140

def load_erc20_balance!
  response = client.rest_api(:get, "#{erc20_currency_id}/wallet/#{wallet_id}?allTokens=true")
  convert_from_base_unit(response.dig('tokens', currency_id, 'balanceString'))
rescue Bitgo::Client::Error => e
  raise Peatio::Wallet::ClientError, e
end

#parse_entries(entries) ⇒ Object



240
241
242
243
244
# File 'lib/peatio/bitgo/wallet.rb', line 240

def parse_entries(entries)
  entries.map do |e|
    e if e["valueString"].to_i.positive?
  end.compact
end

#register_webhooks!(url) ⇒ Object



168
169
170
171
# File 'lib/peatio/bitgo/wallet.rb', line 168

def register_webhooks!(url)
  transfer_webhook(url)
  address_confirmation_webhook(url)
end

#transfer_webhook(url) ⇒ Object



220
221
222
223
224
225
226
227
228
# File 'lib/peatio/bitgo/wallet.rb', line 220

def transfer_webhook(url)
  client.rest_api(:post, "#{currency_id}/wallet/#{wallet_id}/webhooks", {
    type: 'transfer',
    allToken: true,
    url: url,
    label: "webhook for #{url}",
    listenToFailureStates: false
  })
end

#trigger_webhook_event(request) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/peatio/bitgo/wallet.rb', line 147

def trigger_webhook_event(request)
  # Retrieve testnet status
  testnet_status = @wallet.fetch(:testnet)
  # Determine if the 't' prefix should be applied
  currency = (testnet_status == false || testnet_status.nil? || (testnet_status.is_a?(String) && testnet_status.downcase == "false")) ? @currency.fetch(:id) : 't' + @currency.fetch(:id)
  if request.params['type'] == 'transfer'
    return unless currency == request.params['coin'] &&
                  @wallet.fetch(:wallet_id) == request.params['wallet']
  else
    return unless @wallet.fetch(:wallet_id) == request.params['walletId']
  end

  if request.params['type'] == 'transfer'
    transactions = fetch_transfer!(request.params['transfer'])
    return transactions
  elsif request.params['type'] == 'address_confirmation'
    address_id = fetch_address_id(request.params['address'])
    return { address_id: address_id, address: request.params['address'], currency_id: currency_id }
  end
end