Class: Etherlite::NonceManager

Inherits:
Object
  • Object
show all
Defined in:
lib/etherlite/nonce_manager.rb

Constant Summary collapse

@@nonce_cache =
{}
@@nonce_mutex =
Mutex.new

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(_connection) ⇒ NonceManager

Returns a new instance of NonceManager.



10
11
12
# File 'lib/etherlite/nonce_manager.rb', line 10

def initialize(_connection)
  @connection = _connection
end

Class Method Details

.clear_cacheObject



6
7
8
# File 'lib/etherlite/nonce_manager.rb', line 6

def self.clear_cache
  @@nonce_cache = {}
end

Instance Method Details

#last_nonce_for(_normalized_address) ⇒ Object



14
15
16
17
18
# File 'lib/etherlite/nonce_manager.rb', line 14

def last_nonce_for(_normalized_address)
  last_nonce = @@nonce_cache[_normalized_address]
  last_nonce = last_observed_nonce_for(_normalized_address) if last_nonce.nil?
  last_nonce
end

#next_nonce_for(_normalized_address, replace: false, nonce: nil) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/etherlite/nonce_manager.rb', line 20

def next_nonce_for(_normalized_address, replace: false, nonce: nil)
  if nonce.nil?
    nonce = last_nonce_for(_normalized_address)
    nonce += 1 if nonce.negative? || !replace # if first tx, don't replace
  end

  nonce
end

#with_next_nonce_for(_normalized_address, _options = {}) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/etherlite/nonce_manager.rb', line 29

def with_next_nonce_for(_normalized_address, _options = {})
  @@nonce_mutex.synchronize do
    nonce = next_nonce_for(_normalized_address, _options)

    begin
      result = yield nonce
      @@nonce_cache[_normalized_address] = nonce if caching_enabled?
      return result
    rescue
      # if yield fails, cant be sure about transaction status so must rely again on observing.
      @@nonce_cache.delete _normalized_address if caching_enabled?
      raise
    end
  end
end