web3swift icon indicating copy to clipboard operation
web3swift copied to clipboard

Implementing proper generics for ABI encoding/decoding

Open JeneaVranceanu opened this issue 2 years ago • 0 comments

What context is your feature request related to?

Implementing proper generics across the library instead of using Any for encoding and decoding functions. This task is based on discussions from https://github.com/web3swift-team/web3swift/pull/725

What solution would you like?

An example of using multiple types for encoding is RLP.encode function. This function accepts an array that can hold by itself single values like Data but also nested arrays.

For example lets imagine this solution:

internal static func encode<T: Web3DataType>(_ elements: [T?]) -> Data? {
    ...
}

Where Web3DataType is the protocol that has:

/// Binary representation. Used in the ABI encoding process.
func serialize() -> Data

But we still must account for nested arrays, like in the case of RLP.encode. It can legally be [T, T, [T, [T]]] and we must be able to encode it.

@yaroslavyaroslav has suggested using the feature added in Swift 5.7:

also worth to say that swift 5.7 provides a solution for exact that cases (scroll to the "Unlock existentials for all protocols"), but I'd suggest to not belongs on it yet, since it's not having backward capability. But in 5.7 the following code are legal:

let tvShow: [any Equatable] = ["Brooklyn", 99]

I've got a post right about that https://yaroslavyaroslav.github.io/posts/generic-protocol-workaround/ based on the solution that I've implemented whithin 3.0.0 release.

Any additional context?

No response

JeneaVranceanu avatar Jan 22 '23 21:01 JeneaVranceanu