Skip to content

fix: attempt to encode uint with a negative value results in a crash #752

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 4 additions & 12 deletions Sources/Web3Core/EthereumABI/ABIEncoding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -218,19 +218,11 @@ public struct ABIEncoder {
public static func encodeSingleType(type: ABI.Element.ParameterType, value: AnyObject) -> Data? {
switch type {
case .uint:
if let biguint = convertToBigUInt(value) {
return biguint.abiEncode(bits: 256)
}
if let bigint = convertToBigInt(value) {
return bigint.abiEncode(bits: 256)
}
let biguint = convertToBigUInt(value)
return biguint == nil ? nil : biguint!.abiEncode(bits: 256)
case .int:
if let biguint = convertToBigUInt(value) {
return biguint.abiEncode(bits: 256)
}
if let bigint = convertToBigInt(value) {
return bigint.abiEncode(bits: 256)
}
let bigint = convertToBigInt(value)
return bigint == nil ? nil : bigint!.abiEncode(bits: 256)
case .address:
if let string = value as? String {
guard let address = EthereumAddress(string) else {return nil}
Expand Down
10 changes: 10 additions & 0 deletions Tests/web3swiftTests/localTests/ABIEncoderTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ import BigInt

class ABIEncoderTest: XCTestCase {

func testEncodeInt() {
XCTAssertEqual(ABIEncoder.encodeSingleType(type: .int(bits: 32), value: -10 as AnyObject)?.toHexString(), "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6")
XCTAssertEqual(ABIEncoder.encodeSingleType(type: .int(bits: 32), value: 10 as AnyObject)?.toHexString(), "000000000000000000000000000000000000000000000000000000000000000a")
}

func testEncodeUInt() {
XCTAssertEqual(ABIEncoder.encodeSingleType(type: .uint(bits: 32), value: -10 as AnyObject), nil)
XCTAssertEqual(ABIEncoder.encodeSingleType(type: .uint(bits: 32), value: 10 as AnyObject)?.toHexString(), "000000000000000000000000000000000000000000000000000000000000000a")
}

func testSoliditySha3() throws {
var hex = try ABIEncoder.soliditySha3(true).toHexString().addHexPrefix()
assert(hex == "0x5fe7f977e71dba2ea1a68e21057beebb9be2ac30c6410aa38d4f3fbe41dcffd2")
Expand Down