Skip to content

Commit

Permalink
feat(gosdk): migrate Go-sdk into the Nibiru blockchain repo. (#1893)
Browse files Browse the repository at this point in the history
* feat(gosdk): migrate golang sdk into nibiru

* changelog PR number

* add gh ticket to TODO comment
  • Loading branch information
Unique-Divine authored May 25, 2024
1 parent fa77747 commit 9c7d8ce
Show file tree
Hide file tree
Showing 19 changed files with 1,030 additions and 8 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ mockdata/
docs/static
dist
coverage.txt
coverage.html
temp
temp*
txout.json
vote.json
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Non-breaking/Compatible Improvements

- [#1818](https://github.com/NibiruChain/nibiru/pull/1818) - feat: add pebbledb support
- [#1859](https://github.com/NibiruChain/nibiru/pull/1859) - refactor(oracle): add oracle slashing events
- [#1893](https://github.com/NibiruChain/nibiru/pull/1893) - feat(gosdk): migrate Go-sdk into the Nibiru blockchain repo.

### Dependencies

Expand Down
1 change: 0 additions & 1 deletion app/server/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,6 @@ func startStandAlone(ctx *server.Context, opts StartOptions) error {

traceWriterFile := ctx.Viper.GetString(TraceStore)
traceWriter, err := openTraceWriter(traceWriterFile)

if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion app/server/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func AddCommands(
sdkserver.NewRollbackCmd(opts.AppCreator, opts.DefaultNodeHome),

// custom tx indexer command
//NewIndexTxCmd(), TODO: check indexer tx command
// NewIndexTxCmd(), TODO: check indexer tx command
)
}

Expand Down
61 changes: 61 additions & 0 deletions gosdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Nibiru Go SDK - NibiruChain/nibiru/gosdk

A Golang client for interacting with the Nibiru blockchain.

The Nibiru Go SDK extends the core blockchain logic with extensions to build
external clients for the Nibiru blockchain and easily access its query and
transaction types.

---

## Dev Notes - Nibiru Go SDK

### Finalizing "v1"

- [ ] Migrate to the [Nibiru repo](https://github.com/NibiruChain/nibiru) and archive this one.
- [ ] feat: add in transaction broadcasting
- [x] initialize keyring obj with mnemonic
- [x] initialize keyring obj with priv key
- [x] write a test that sends a bank transfer.
- [ ] write a test that submits a text gov proposal.
- [x] docs: for grpc.go
- [ ] docs: for clients.go

### Usage Guides & Dev Ex

- [ ] Create a quick start guide: Connecting to Nibiru, querying Nibiru, sending
transactions on Nibiru
- [ ] Write usage examples
- [ ] Creating an account and keyring
- [ ] Querying balanaces
- [ ] Broadcasting txs to transfer funds
- [ ] Querying Wasm smart contracts
- [ ] Broadcasting txs to transfer funds
- [x] impl Tendermint RPC client
- [x] refactor: DRY improvements on the QueryClient initialization
- [x] ci: Add go tests to CI
- [x] ci: Add code coverage to CI
- [x] ci: Add linting to CI

### Feature Backlog

- [ ] impl wallet abstraction for the keyring
- [ ] epic: storing transaction history storage

### Question Brain-dump

Q: Should gosdk run as a binary?

No, or at least, not initially. Since the software required to operate a full
node has more cumbersome dependencies like RocksDB that involve C-Go and compled
build steps, we may benefit from splitting "start" command from the bulk of the
subcommands available on teh Nibiru CLI. This would make it much easier to have a
command line tool that builds on Linux, Windows, Mac.

Q: Should there be a way to run queries with JSON-RPC 2 instead of GRPC?

We [implemented this in
python](https://github.com/NibiruChain/py-sdk/tree/v0.21.12/nibiru/jsonrpc)
without too much trouble, and it's not taxing to maintain. If we're going to
prioritize adding APIs for the CometBFT JSON-RPC methods, it should be in the
[Nibiru TypeScript SDK](https://github.com/NibiruChain/ts-sdk) first.
198 changes: 198 additions & 0 deletions gosdk/broadcast.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
package gosdk

import (
"context"

cmtrpc "github.com/cometbft/cometbft/rpc/client"
sdkclient "github.com/cosmos/cosmos-sdk/client"
sdkclienttx "github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
sdktypestx "github.com/cosmos/cosmos-sdk/types/tx"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"google.golang.org/grpc"

"github.com/NibiruChain/nibiru/x/common"
"github.com/NibiruChain/nibiru/x/common/denoms"
)

func BroadcastMsgsWithSeq(
args BroadcastArgs,
from sdk.AccAddress,
seq uint64,
msgs ...sdk.Msg,
) (*sdk.TxResponse, error) {
broadcaster := args.Broadcaster

info, err := args.kring.KeyByAddress(from)
if err != nil {
return nil, err
}

txBuilder := args.txCfg.NewTxBuilder()
err = txBuilder.SetMsgs(msgs...)
if err != nil {
return nil, err
}

bondDenom := denoms.NIBI
txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(bondDenom, sdk.NewInt(1000))))
txBuilder.SetGasLimit(uint64(2 * common.TO_MICRO))

nums, err := args.gosdk.GetAccountNumbers(from.String())
if err != nil {
return nil, err
}

var accRetriever sdkclient.AccountRetriever = authtypes.AccountRetriever{}
txFactory := sdkclienttx.Factory{}.
WithChainID(args.chainID).
WithKeybase(args.kring).
WithTxConfig(args.txCfg).
WithAccountRetriever(accRetriever).
WithAccountNumber(nums.Number).
WithSequence(seq)

overwriteSig := true
err = sdkclienttx.Sign(txFactory, info.Name, txBuilder, overwriteSig)
if err != nil {
return nil, err
}

txBytes, err := args.txCfg.TxEncoder()(txBuilder.GetTx())
if err != nil {
return nil, err
}

return broadcaster.BroadcastTxSync(txBytes)
}

func BroadcastMsgs(
args BroadcastArgs,
from sdk.AccAddress,
msgs ...sdk.Msg,
) (*sdk.TxResponse, error) {
nums, err := args.gosdk.GetAccountNumbers(from.String())
if err != nil {
return nil, err
}
return BroadcastMsgsWithSeq(args, from, nums.Sequence, msgs...)
}

type Broadcaster interface {
BroadcastTxSync(txBytes []byte) (*sdk.TxResponse, error)
}

var (
_ Broadcaster = (*BroadcasterTmRpc)(nil)
_ Broadcaster = (*BroadcasterGrpc)(nil)
)

type BroadcasterTmRpc struct {
RPC cmtrpc.Client
}

func (b BroadcasterTmRpc) BroadcastTxSync(
txBytes []byte,
) (*sdk.TxResponse, error) {
respRaw, err := b.RPC.BroadcastTxSync(context.Background(), txBytes)
if err != nil {
return nil, err
}

return sdk.NewResponseFormatBroadcastTx(respRaw), err
}

type BroadcasterGrpc struct {
GRPC *grpc.ClientConn
}

func (b BroadcasterGrpc) BroadcastTx(
txBytes []byte, mode sdktypestx.BroadcastMode,
) (*sdk.TxResponse, error) {
txClient := sdktypestx.NewServiceClient(b.GRPC)
respRaw, err := txClient.BroadcastTx(
context.Background(), &sdktypestx.BroadcastTxRequest{
TxBytes: txBytes,
Mode: mode,
})
return respRaw.TxResponse, err
}

func (b BroadcasterGrpc) BroadcastTxSync(
txBytes []byte,
) (*sdk.TxResponse, error) {
return b.BroadcastTx(txBytes, sdktypestx.BroadcastMode_BROADCAST_MODE_SYNC)
}

func (b BroadcasterGrpc) BroadcastTxAsync(
txBytes []byte,
) (*sdk.TxResponse, error) {
return b.BroadcastTx(txBytes, sdktypestx.BroadcastMode_BROADCAST_MODE_ASYNC)
}

// func GetTxBytes() ([]byte, error) {
// return txBytes, err
// }

type BroadcastArgs struct {
kring keyring.Keyring
txCfg sdkclient.TxConfig
gosdk NibiruSDK
// clientCtx sdkclient.Context // TODO: implement
Broadcaster Broadcaster
rpc cmtrpc.Client
chainID string
}

func initBroadcastArgs(
nc *NibiruSDK, broadcaster Broadcaster,
) (args BroadcastArgs) {
txConfig := nc.EncCfg.TxConfig
return BroadcastArgs{
kring: nc.Keyring,
txCfg: txConfig,
gosdk: *nc,
Broadcaster: broadcaster,
rpc: nc.CometRPC,
chainID: nc.ChainId,
}
}

func (nc *NibiruSDK) BroadcastMsgs(
from sdk.AccAddress,
msgs ...sdk.Msg,
) (*sdk.TxResponse, error) {
broadcaster := BroadcasterTmRpc{RPC: nc.CometRPC}
args := initBroadcastArgs(nc, broadcaster)
return BroadcastMsgs(args, from, msgs...)
}

func (nc *NibiruSDK) BroadcastMsgsWithSeq(
from sdk.AccAddress,
seq uint64,
msgs ...sdk.Msg,
) (*sdk.TxResponse, error) {
broadcaster := BroadcasterTmRpc{RPC: nc.CometRPC}
args := initBroadcastArgs(nc, broadcaster)
return BroadcastMsgsWithSeq(args, from, seq, msgs...)
}

func (nc *NibiruSDK) BroadcastMsgsGrpc(
from sdk.AccAddress,
msgs ...sdk.Msg,
) (*sdk.TxResponse, error) {
broadcaster := BroadcasterGrpc{GRPC: nc.Querier.ClientConn}
args := initBroadcastArgs(nc, broadcaster)
return BroadcastMsgs(args, from, msgs...)
}

func (nc *NibiruSDK) BroadcastMsgsGrpcWithSeq(
from sdk.AccAddress,
seq uint64,
msgs ...sdk.Msg,
) (*sdk.TxResponse, error) {
broadcaster := BroadcasterGrpc{GRPC: nc.Querier.ClientConn}
args := initBroadcastArgs(nc, broadcaster)
return BroadcastMsgsWithSeq(args, from, seq, msgs...)
}
42 changes: 42 additions & 0 deletions gosdk/clientctx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package gosdk

// import (
// "github.com/NibiruChain/nibiru/app"
// sdkclient "github.com/cosmos/cosmos-sdk/client"
// authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
// )

// TODO: https://github.com/NibiruChain/nibiru/issues/1894
// Make a way to instantiate a NibiruSDK from a (*cli.Network, *cli.Validator)

// ClientCtx: Docs for args
//
// - tmCfgRootDir: /node0/simd
// - Validator.Dir: /node0
// - Validator.ClientCtx.KeyringDir: /node0/simcli

// func NewNibiruSDKFromClientCtx(
// clientCtx sdkclient.Context, grpcUrl, cometRpcUrl string,
// ) (gosdk NibiruSDK, err error) {
// grpcConn, err := GetGRPCConnection(grpcUrl, true, 5)
// if err != nil {
// return
// }
// cometRpc, err := NewRPCClient(cometRpcUrl, "/websocket")
// if err != nil {
// return
// }
// querier, err := NewQuerier(grpcConn)
// if err != nil {
// return
// }
// return NibiruSDK{
// ChainId: clientCtx.ChainID,
// Keyring: clientCtx.Keyring,
// EncCfg: app.MakeEncodingConfig(),
// Querier: querier,
// CometRPC: cometRpc,
// AccountRetriever: authtypes.AccountRetriever{},
// GrpcClient: grpcConn,
// }, err
// }
Loading

0 comments on commit 9c7d8ce

Please sign in to comment.