nervosnetwork / ckb-sdk-go

MIT License
21 stars 23 forks source link

Using molecule-generated types that depend on blockchain.mol #205

Open janbormet opened 1 year ago

janbormet commented 1 year ago

If you want to generate go-code for molecule types that depend on and import types from blockchain.mol, the moleculec-go backend (version 0.1.11) produces code that needs to import the generated blockchain types and functions from the molecule package (essentially types/molecule/type.go).

There are two (related) issues with this:

1. The generated code does not qualify the names from the imported molecule package.

You could get around this by e.g. importing as follows:

import (
    ...
    . "github.com/nervosnetwork/ckb-sdk-go/v2/types/molecule"
    ...
)

One would still face problems, if one wanted to include types from different source packages (as there can be at most one dot-import as far as I know).

2. The moleculec-go backend produces and uses unexported functions (e.g. func packNumber(num Number) []byte).

As far as I know there is no way to "extend" remote packages in go and thereby make such functions visible and callable. The result is that the generated code (located in our project) that depends on ckb-sdk-go's molecule package's generated types for blockchain.mol will not compile. A naive solution would be to just copy the type.go file into your local package, but this heavily restricts interoperability with the functionality in ckb-sdk-go as they would obviously be different types as far as the compiler is concerned.

Our current (unsatisfactory) solution for this is forking the ckb-sdk-go and placing our generated types directly next to type.go in the sdk's molecule package. See: https://github.com/perun-network/ckb-sdk-go/tree/perun-types/types/molecule In the go.mod of our project using this we then do the following:

require github.com/nervosnetwork/ckb-sdk-go/v2 v2.2.0

replace github.com/nervosnetwork/ckb-sdk-go/v2 v2.2.0 => github.com/perun-network/ckb-sdk-go/v2 v2.2.1-0.20230427093811-05bc15078e36

FYI: If you want to try and reproduce this, you can find our types here

This solution also "solves" the first problem. It works for the compiler, but the disadvantages are apparent...

Our questions are:

I feel like the best fix for this is through the moleculec-go backend. One could (a) qualify imported types with a package name and (b) avoid using non-exported function names.

code-monad commented 1 year ago

I have a WIP PR to moleculec-go that may help this: https://github.com/driftluo/moleculec-go/pull/7

This PR will help people to get a more generic way to generate type interfaces for realworld usage, reduce hand wrting type reflection(?) codes, and is convinent to use as the example shows. Will push to finish it soon.

Once this pr was merged, ckb-sdk-go will updates its molecule package