Class: Ethereum::Contract

Inherits:
Object
  • Object
show all
Defined in:
lib/ethereum/contract.rb

Constant Summary collapse

DEFAULT_GAS_PRICE =
60000000000
DEFAULT_GAS =
3000000

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, code, abi) ⇒ Contract

Returns a new instance of Contract.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/ethereum/contract.rb', line 10

def initialize(name, code, abi)
  @name = name
  @code = code
  @abi = abi
  @functions = []
  @events = []
  @constructor_inputs = @abi.detect {|x| x["type"] == "constructor"}["inputs"] rescue nil
  @abi.select {|x| x["type"] == "function" }.each do |abifun|
    @functions << Ethereum::Function.new(abifun) 
  end
  @abi.select {|x| x["type"] == "event" }.each do |abievt|
    @events << Ethereum::ContractEvent.new(abievt)
  end
end

Instance Attribute Details

#abiObject

Returns the value of attribute abi.



8
9
10
# File 'lib/ethereum/contract.rb', line 8

def abi
  @abi
end

#class_objectObject

Returns the value of attribute class_object.



8
9
10
# File 'lib/ethereum/contract.rb', line 8

def class_object
  @class_object
end

#codeObject

Returns the value of attribute code.



8
9
10
# File 'lib/ethereum/contract.rb', line 8

def code
  @code
end

#constructor_inputsObject

Returns the value of attribute constructor_inputs.



8
9
10
# File 'lib/ethereum/contract.rb', line 8

def constructor_inputs
  @constructor_inputs
end

#eventsObject

Returns the value of attribute events.



8
9
10
# File 'lib/ethereum/contract.rb', line 8

def events
  @events
end

#functionsObject

Returns the value of attribute functions.



8
9
10
# File 'lib/ethereum/contract.rb', line 8

def functions
  @functions
end

#nameObject

Returns the value of attribute name.



8
9
10
# File 'lib/ethereum/contract.rb', line 8

def name
  @name
end

Class Method Details

.from_blockchain(name, address, abi, client = Ethereum::Singleton.instance) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/ethereum/contract.rb', line 32

def self.from_blockchain(name, address, abi, client = Ethereum::Singleton.instance)
  contract = Ethereum::Contract.new(name, nil, abi)
  contract.build(client)
  contract_instance = contract.class_object.new
  contract_instance.at address
  contract_instance
end

.from_file(path, client = Ethereum::Singleton.instance) ⇒ Object



25
26
27
28
29
30
# File 'lib/ethereum/contract.rb', line 25

def self.from_file(path, client = Ethereum::Singleton.instance)
  @init = Ethereum::Initializer.new(path, client)
  contracts = @init.build_all
  raise "No contracts complied" if contracts.empty?
  contracts.first.class_object.new
end

Instance Method Details

#build(connection) ⇒ Object



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
86
87
88
89
90
91
92
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/ethereum/contract.rb', line 40

def build(connection)
  class_name = @name.camelize
  functions = @functions
  constructor_inputs = @constructor_inputs
  binary = @code
  events = @events
  abi = @abi

  class_methods = Class.new do

    define_method "connection".to_sym do
      connection
    end

    define_method :deploy do |*params|
      formatter = Ethereum::Formatter.new
      deploy_code = binary
      deploy_arguments = ""
      if constructor_inputs.present?
        raise "Missing constructor parameter" and return if params.length != constructor_inputs.length
        constructor_inputs.each_index do |i|
          args = [constructor_inputs[i]["type"], params[i]]
          deploy_arguments << formatter.to_payload(args)
        end
      end
      deploy_payload = deploy_code + deploy_arguments
      deploytx = connection.eth_send_transaction({from: self.sender, data: "0x" + deploy_payload})["result"]
      raise "Failed to deploy, did you unlock #{self.sender} account? Transaction hash: #{deploytx}" if deploytx.nil? || deploytx == "0x0000000000000000000000000000000000000000000000000000000000000000"
      instance_variable_set("@deployment", Ethereum::Deployment.new(deploytx, connection))
    end

    define_method :estimate do |*params|
      formatter = Ethereum::Formatter.new
      deploy_code = binary
      deploy_arguments = ""
      if constructor_inputs.present?
        raise "Missing constructor parameter" and return if params.length != constructor_inputs.length
        constructor_inputs.each_index do |i|
          args = [constructor_inputs[i]["type"], params[i]]
          deploy_arguments << formatter.to_payload(args)
        end
      end
      deploy_payload = deploy_code + deploy_arguments
      deploytx = connection.eth_estimate_gas({from: self.sender, data: "0x" + deploy_payload})["result"]
    end

    define_method :events do
      return events
    end

    define_method :abi do
      return abi
    end

    define_method :deployment do
      instance_variable_get("@deployment")
    end

    define_method :deploy_and_wait do |time = 200.seconds, *params, **args, &block|
      self.deploy(*params)
      self.deployment.wait_for_deployment(time, **args, &block)
      instance_variable_set("@address", self.deployment.contract_address)
      self.events.each do |event|
        event.set_address(self.deployment.contract_address)
        event.set_client(connection)
      end
      self.deployment.contract_address
    end

    define_method :at do |addr|
      instance_variable_set("@address", addr) 
      self.events.each do |event|
        event.set_address(addr)
        event.set_client(connection)
      end
    end

    define_method :address do
      instance_variable_get("@address")
    end

    define_method :as do |addr|
      instance_variable_set("@sender", addr)
    end

    define_method :sender do
      instance_variable_get("@sender") || connection.
    end

    define_method :set_gas_price do |gp|
      instance_variable_set("@gas_price", gp)
    end

    define_method :gas_price do
      instance_variable_get("@gas_price") || DEFAULT_GAS_PRICE
    end

    define_method :set_gas do |gas|
      instance_variable_set("@gas", gas)
    end

    define_method :gas do 
      instance_variable_get("@gas") || DEFAULT_GAS
    end

    events.each do |evt|
      define_method "nf_#{evt.name.underscore}".to_sym do |params = {}|
        params[:to_block] ||= "latest"
        params[:from_block] ||= "0x0"
        params[:address] ||=  instance_variable_get("@address")
        params[:topics] = evt.signature
        payload = {topics: [params[:topics]], fromBlock: params[:from_block], toBlock: params[:to_block], address: params[:address]}
        filter_id = connection.new_filter(payload)
        return filter_id["result"]
      end

      define_method "gfl_#{evt.name.underscore}".to_sym do |filter_id|
        formatter = Ethereum::Formatter.new
        logs = connection.get_filter_logs(filter_id)
        collection = []
        logs["result"].each do |result|
          inputs = evt.input_types
          outputs = inputs.zip(result["topics"][1..-1])
          data = {blockNumber: result["blockNumber"].hex, transactionHash: result["transactionHash"], blockHash: result["blockHash"], transactionIndex: result["transactionIndex"].hex, topics: []} 
          outputs.each do |output|
            data[:topics] << formatter.from_payload(output)
          end
          collection << data 
        end
        return collection
      end

      define_method "gfc_#{evt.name.underscore}".to_sym do |filter_id|
        formatter = Ethereum::Formatter.new
        logs = connection.get_filter_changes(filter_id)
        collection = []
        logs["result"].each do |result|
          inputs = evt.input_types
          outputs = inputs.zip(result["topics"][1..-1])
          data = {blockNumber: result["blockNumber"].hex, transactionHash: result["transactionHash"], blockHash: result["blockHash"], transactionIndex: result["transactionIndex"].hex, topics: []} 
          outputs.each do |output|
            data[:topics] << formatter.from_payload(output)
          end
          collection << data 
        end
        return collection
      end

    end

    functions.each do |fun|

      fun_count = functions.select {|x| x.name == fun.name }.count
      derived_function_name = (fun_count == 1) ? "#{fun.name.underscore}" : "#{fun.name.underscore}__#{fun.inputs.collect {|x| x.type}.join("__")}"
      call_function_name = "call_#{derived_function_name}".to_sym
      call_function_name_alias = "c_#{derived_function_name}".to_sym
      call_raw_function_name = "call_raw_#{derived_function_name}".to_sym
      call_raw_function_name_alias = "cr_#{derived_function_name}".to_sym
      transact_function_name = "transact_#{derived_function_name}".to_sym
      transact_function_name_alias = "t_#{derived_function_name}".to_sym
      transact_and_wait_function_name = "transact_and_wait_#{derived_function_name}".to_sym
      transact_and_wait_function_name_alias = "tw_#{derived_function_name}".to_sym

      define_method call_raw_function_name do |*args|
        formatter = Ethereum::Formatter.new
        arg_types = fun.inputs.collect(&:type)
        connection = self.connection
        return {result: :error, message: "missing parameters for #{fun.function_string}" } if arg_types.length != args.length
        payload = []
        payload << fun.signature
        arg_types.zip(args).each do |arg|
          payload << formatter.to_payload(arg)
        end
        raw_result = connection.eth_call({to: self.address, from: self.sender, data: "0x" + payload.join()})
        raw_result = raw_result["result"]
        formatted_result = fun.outputs.collect {|x| x.type }.zip(raw_result.gsub(/^0x/,'').scan(/.{64}/))
        output = formatted_result.collect {|x| formatter.from_payload(x) }
        return {data: "0x" + payload.join(), raw: raw_result, formatted: output}
      end

      define_method call_function_name do |*args|
        data = self.send(call_raw_function_name, *args)
        output = data[:formatted]
        if output.length == 1 
          return output[0]
        else 
          return output
        end
      end

      define_method transact_function_name do |*args|
        formatter = Ethereum::Formatter.new
        arg_types = fun.inputs.collect(&:type)
        connection = self.connection
        return {result: :error, message: "missing parameters for #{fun.function_string}" } if arg_types.length != args.length
        payload = []
        payload << fun.signature
        arg_types.zip(args).each do |arg|
          payload << formatter.to_payload(arg)
        end
        txid = connection.eth_send_transaction({to: self.address, from: self.sender, data: "0x" + payload.join()})["result"]
        return Ethereum::Transaction.new(txid, self.connection, payload.join(), args)
      end

      define_method transact_and_wait_function_name do |*args|
        function_name = "transact_#{derived_function_name}".to_sym
        tx = self.send(function_name, *args)
        tx.wait_for_miner
        return tx
      end

      alias_method call_function_name_alias, call_function_name
      alias_method call_raw_function_name_alias, call_raw_function_name
      alias_method transact_function_name_alias, transact_function_name
      alias_method transact_and_wait_function_name_alias, transact_and_wait_function_name

    end
  end
  if Object.const_defined?(class_name)
    Object.send(:remove_const, class_name)
  end
  Object.const_set(class_name, class_methods)
  @class_object = class_methods
end