Skip to content

Commit

Permalink
feat(gosdk): migrate golang sdk into nibiru
Browse files Browse the repository at this point in the history
  • Loading branch information
Unique-Divine committed May 23, 2024
1 parent 10cff9e commit 6844015
Show file tree
Hide file tree
Showing 21 changed files with 1,032 additions and 13 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- [#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
- [#1xxx](https://github.com/NibiruChain/nibiru/pull/1xxx) - 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
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,12 @@ require (

require (
cosmossdk.io/collections v0.4.0
cosmossdk.io/tools/rosetta v0.2.1
github.com/davecgh/go-spew v1.1.1
github.com/gorilla/websocket v1.5.0
github.com/rs/cors v1.8.3
golang.org/x/exp v0.0.0-20230711153332-06a737ee72cb
golang.org/x/net v0.23.0
golang.org/x/text v0.14.0
)

Expand All @@ -66,7 +69,6 @@ require (
cosmossdk.io/core v0.10.0 // indirect
cosmossdk.io/depinject v1.0.0-alpha.4 // indirect
cosmossdk.io/log v1.3.1 // indirect
cosmossdk.io/tools/rosetta v0.2.1 // indirect
filippo.io/edwards25519 v1.0.0 // indirect
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
github.com/99designs/keyring v1.2.1 // indirect
Expand Down Expand Up @@ -184,7 +186,6 @@ require (
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
github.com/rjeczalik/notify v0.9.1 // indirect
github.com/rogpeppe/go-internal v1.11.0 // indirect
github.com/rs/cors v1.8.3 // indirect
github.com/rs/zerolog v1.32.0 // indirect
github.com/sasha-s/go-deadlock v0.3.1 // indirect
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect
Expand All @@ -208,7 +209,6 @@ require (
go.opentelemetry.io/otel/metric v1.19.0 // indirect
go.opentelemetry.io/otel/trace v1.19.0 // indirect
golang.org/x/crypto v0.21.0 // indirect
golang.org/x/net v0.23.0 // indirect
golang.org/x/oauth2 v0.16.0 // indirect
golang.org/x/sync v0.5.0 // indirect
golang.org/x/sys v0.18.0 // indirect
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -422,8 +422,6 @@ github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSV
github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk=
github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis=
github.com/cosmos/cosmos-db v1.0.0 h1:EVcQZ+qYag7W6uorBKFPvX6gRjw6Uq2hIh4hCWjuQ0E=
github.com/cosmos/cosmos-db v1.0.0/go.mod h1:iBvi1TtqaedwLdcrZVYRSSCb6eSy61NLj4UNmdIgs0U=
github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAKs=
github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA=
github.com/cosmos/cosmos-proto v1.0.0-beta.4 h1:aEL7tU/rLOmxZQ9z4i7mzxcLbSCY48OdY7lIWTLG7oU=
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: 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 6844015

Please sign in to comment.