From a89936e045cf4f323438de1eb0b46c54821dd1f6 Mon Sep 17 00:00:00 2001 From: Chris Wawer Date: Sun, 23 Jun 2024 21:52:24 +0200 Subject: [PATCH] Support negative number from JSON RPC (#267) --- lib/eth/abi/decoder.rb | 2 +- lib/eth/abi/encoder.rb | 2 +- spec/eth/abi_spec.rb | 7 +++++++ 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/eth/abi/decoder.rb b/lib/eth/abi/decoder.rb index 45da7f46..35cf6baa 100644 --- a/lib/eth/abi/decoder.rb +++ b/lib/eth/abi/decoder.rb @@ -125,7 +125,7 @@ def primitive_type(type, data) Util.deserialize_big_endian_to_int data when "int" u = Util.deserialize_big_endian_to_int data - i = u >= 2 ** (type.sub_type.to_i - 1) ? (u - 2 ** type.sub_type.to_i) : u + i = u >= 2 ** (type.sub_type.to_i - 1) ? (u - 2 ** 256) : u # decoded integer i diff --git a/lib/eth/abi/encoder.rb b/lib/eth/abi/encoder.rb index eb7d4d62..4b4247ec 100644 --- a/lib/eth/abi/encoder.rb +++ b/lib/eth/abi/encoder.rb @@ -138,7 +138,7 @@ def int(arg, type) real_size = type.sub_type.to_i i = arg.to_i raise ValueOutOfBounds, arg unless i >= -2 ** (real_size - 1) and i < 2 ** (real_size - 1) - Util.zpad_int(i % 2 ** type.sub_type.to_i) + Util.zpad_int(i < 0 ? (i + 2 ** 256) : i % 2 ** type.sub_type.to_i) end # Properly encodes booleans. diff --git a/spec/eth/abi_spec.rb b/spec/eth/abi_spec.rb index 3d623233..044b2c1a 100644 --- a/spec/eth/abi_spec.rb +++ b/spec/eth/abi_spec.rb @@ -387,5 +387,12 @@ def assert(data, types, args) pending("https://github.com/q9f/eth.rb/issues/102") assert(data, types, args) end + + it "test negative number" do + types = ["int24"] + args = [-887220] + data = Util.hex_to_bin "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff2764c" + assert(data, types, args) + end end end