Sha256: b777ac7c70a95036b228232b03461e301cf9044d0eb14fbf95151c7e5ee25da3

Contents?: true

Size: 1.51 KB

Versions: 4

Compression:

Stored size: 1.51 KB

Contents

require 'eth'

module Etherlite
  module Account
    class PrivateKey < Base
      def initialize(_connection, _pk)
        @key = Eth::Key.new priv: _pk
        super _connection, Etherlite::Utils.normalize_address(@key.address)
      end

      def build_raw_transaction(_options = {})
        nonce = nonce_manager.next_nonce_for(normalized_address, _options.slice(:replace, :nonce))

        tx = Eth::Tx.new(
          value: _options.fetch(:value, 0),
          data: _options.fetch(:data, ''),
          gas_limit: _options.fetch(:gas, 90_000),
          gas_price: _options.fetch(:gas_price, gas_price),
          to: (Etherlite::Utils.encode_address_param(_options[:to]) if _options.key?(:to)),
          nonce: nonce
        )

        sign_with_connection_chain tx

        tx
      end

      def send_transaction(_options = {})
        tx = build_raw_transaction(_options)

        nonce_manager.with_next_nonce_for(normalized_address, nonce: tx.nonce) do |nonce|
          Etherlite::Transaction.new @connection, @connection.eth_send_raw_transaction(tx.hex)
        end
      end

      private

      @@eth_mutex = Mutex.new

      def gas_price
        # TODO: improve on this
        @gas_price ||= connection.eth_gas_price
      end

      def nonce_manager
        Etherlite::NonceManager.new @connection
      end

      def sign_with_connection_chain(_tx)
        @@eth_mutex.synchronize do
          Eth.configure { |c| c.chain_id = @connection.chain_id }
          _tx.sign @key
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
etherlite-0.5.3 lib/etherlite/account/private_key.rb
etherlite-0.5.2 lib/etherlite/account/private_key.rb
etherlite-0.5.1 lib/etherlite/account/private_key.rb
etherlite-0.5.0 lib/etherlite/account/private_key.rb