onflow / cadence

Cadence, the resource-oriented smart contract programming language 🏃‍♂️
https://developers.flow.com/cadence
Apache License 2.0
530 stars 139 forks source link

Convert cadence.Value <> interface{} #2504

Open bjartek opened 1 year ago

bjartek commented 1 year ago

Issue to be solved

cadence.Value and cadence-json is verbose and holds type information. Often you want a terse representation of the values and to then transform this into your own go type.

If you have a go type you might want to transform that into a cadence.Value

Suggested Solution

Move https://github.com/bjartek/overflow/blob/main/cadence.go or part of it to cadence.

Or should this be in flow-go-sdk?

The only import this code has it cadence.Value so ideally the method could just be put on that interface

I can do the work here as long as I know what repo it should belong in.

turbolent commented 1 year ago

From what I can tell, this is the purpose of cadence.Value.ToGoValue. What is missing / how does overflow's conversion code differ?

bjartek commented 1 year ago

Good question! I just modified one of the tests to assert cadenceToValue vs just using ToGoValue. The pr here here: https://github.com/bjartek/overflow/actions/runs/5149063757

Expected in these failing test is overflow while actual is ToGoValue. https://github.com/bjartek/overflow/actions/runs/5149063757/jobs/9271589188

A design choice i made in this code is that something that is empty is treated as nil, and if the value of a struct/dict key is nil it is skipped. It is meant to be a terse representation, so not sure if it can be ported 100% in its current form. Or maybe there can be options to the code or something.

turbolent commented 1 year ago

There is no specific/defined behaviour for the ToGoValue function, it's mostly just a convenience, so it should be fine to change. If you feel like improving or extending it, PRs are very welcome!

bluesign commented 1 year ago

@turbolent related to this, can we add to Cadence Marshal/UnMarshal to/from struct? Like maybe with annotations like json?

bjartek commented 1 year ago

Ii have that in Overflow @bluesign with support for marshalling strings as addresses with a cadence:address tag. So in overflow i can marshal a Cadence Struct <> go struct. You need a mapper function to map Struct names in go to struct names in cadence for nested things but it works pretty great.

bjartek commented 1 year ago

@turbolent related to this, can we add to Cadence Marshal/UnMarshal to/from struct? Like maybe with annotations like json?

I will def look into that then, but it will take some time as I am a bit busy.