Skip to content

Commit df935fb

Browse files
Merge pull request #752 from JeneaVranceanu/fix/abi-encoder-uint
fix: attempt to encode uint with a negative value results in a crash
2 parents 2a25ffa + 44e5965 commit df935fb

File tree

2 files changed

+14
-12
lines changed

2 files changed

+14
-12
lines changed

Sources/Web3Core/EthereumABI/ABIEncoding.swift

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -218,19 +218,11 @@ public struct ABIEncoder {
218218
public static func encodeSingleType(type: ABI.Element.ParameterType, value: Any) -> Data? {
219219
switch type {
220220
case .uint:
221-
if let biguint = convertToBigUInt(value) {
222-
return biguint.abiEncode(bits: 256)
223-
}
224-
if let bigint = convertToBigInt(value) {
225-
return bigint.abiEncode(bits: 256)
226-
}
221+
let biguint = convertToBigUInt(value)
222+
return biguint == nil ? nil : biguint!.abiEncode(bits: 256)
227223
case .int:
228-
if let biguint = convertToBigUInt(value) {
229-
return biguint.abiEncode(bits: 256)
230-
}
231-
if let bigint = convertToBigInt(value) {
232-
return bigint.abiEncode(bits: 256)
233-
}
224+
let bigint = convertToBigInt(value)
225+
return bigint == nil ? nil : bigint!.abiEncode(bits: 256)
234226
case .address:
235227
if let string = value as? String {
236228
guard let address = EthereumAddress(string) else {return nil}

Tests/web3swiftTests/localTests/ABIEncoderTest.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,16 @@ import BigInt
1414

1515
class ABIEncoderTest: XCTestCase {
1616

17+
func testEncodeInt() {
18+
XCTAssertEqual(ABIEncoder.encodeSingleType(type: .int(bits: 32), value: -10 as AnyObject)?.toHexString(), "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6")
19+
XCTAssertEqual(ABIEncoder.encodeSingleType(type: .int(bits: 32), value: 10 as AnyObject)?.toHexString(), "000000000000000000000000000000000000000000000000000000000000000a")
20+
}
21+
22+
func testEncodeUInt() {
23+
XCTAssertEqual(ABIEncoder.encodeSingleType(type: .uint(bits: 32), value: -10 as AnyObject), nil)
24+
XCTAssertEqual(ABIEncoder.encodeSingleType(type: .uint(bits: 32), value: 10 as AnyObject)?.toHexString(), "000000000000000000000000000000000000000000000000000000000000000a")
25+
}
26+
1727
func testSoliditySha3() throws {
1828
var hex = try ABIEncoder.soliditySha3(true).toHexString().addHexPrefix()
1929
assert(hex == "0x5fe7f977e71dba2ea1a68e21057beebb9be2ac30c6410aa38d4f3fbe41dcffd2")

0 commit comments

Comments
 (0)