Method: Eth::Abi#decode

Defined in:
lib/eth/abi.rb

#decode(types, data) ⇒ Array

Decodes Application Binary Interface (ABI) data. It accepts multiple arguments and decodes using the head/tail mechanism.

Raises:



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
# File 'lib/eth/abi.rb', line 98

def decode(types, data)

  # accept hex abi but decode it first
  data = Util.hex_to_bin data if Util.hex? data

  # parse all types
  parsed_types = types.map { |t| Type.parse(t) }

  # prepare output data
  outputs = [nil] * types.size
  start_positions = [nil] * types.size + [data.size]
  pos = 0
  parsed_types.each_with_index do |t, i|
    if t.dynamic?

      # record start position for dynamic type
      start_positions[i] = Util.deserialize_big_endian_to_int(data[pos, 32])
      j = i - 1
      while j >= 0 and start_positions[j].nil?
        start_positions[j] = start_positions[i]
        j -= 1
      end
      pos += 32
    else

      # get data directly for static types
      outputs[i] = data[pos, t.size]
      pos += t.size
    end
  end

  # add start position equal the length of the entire data
  j = types.size - 1
  while j >= 0 and start_positions[j].nil?
    start_positions[j] = start_positions[types.size]
    j -= 1
  end
  raise DecodingError, "Not enough data for head" unless pos <= data.size

  # add dynamic types
  parsed_types.each_with_index do |t, i|
    if t.dynamic?
      offset, next_offset = start_positions[i, 2]
      outputs[i] = data[offset...next_offset]
    end
  end

  # return the decoded ABI types and data
  parsed_types.zip(outputs).map { |(type, out)| Abi::Decoder.type(type, out) }
end