Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add gno.land/pkg/gnoclient (Gno.land Go client) #1047

Merged
merged 28 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
0d235f0
feat: add gno.land/pkg/gnoclient (Gno.land Go client)
moul Aug 11, 2023
f4d7b73
chore: wip
moul Sep 11, 2023
588dfba
chore: fixup
moul Sep 11, 2023
e11919b
chore: fixup
moul Sep 11, 2023
f28ff5d
chore: fixup
moul Sep 13, 2023
2f6721e
chore: fixup
moul Sep 14, 2023
1cd0b1d
chore: fixup
moul Sep 14, 2023
3deec7c
chore: fixup
moul Sep 14, 2023
96c9076
chore: fixup
moul Sep 14, 2023
3f63f40
chore: fixup
moul Sep 14, 2023
89e9b48
chore: fixup
moul Sep 14, 2023
5cd1252
chore: fixup
moul Sep 14, 2023
e9901a6
chore: fixup
moul Sep 14, 2023
795f017
chore: fixup
moul Sep 14, 2023
208c61f
chore: wip
moul Sep 14, 2023
60e05e8
Update example_test.go
moul Sep 15, 2023
35e86bd
chore: In gnoclient.Client, add methods Render and QEval.
jefft0 Nov 23, 2023
dcb7d43
chore: In gnoclient.Signer.Validate, sign a blank transaction to veri…
jefft0 Nov 23, 2023
8abebbe
chore: In gnoclient.Client.QueryAccount, param addr should be crypto.…
jefft0 Nov 23, 2023
29af0b9
Merge pull request #18 from jefft0/chore/gnoclient-updates-for-PR-1047
moul Nov 23, 2023
8d451c0
Merge branch 'master' into dev/moul/gnoclient
gfanton Nov 23, 2023
e2537eb
feat: add basic integration test to gnoclient
gfanton Nov 23, 2023
89f112c
chore: add test placeholder
gfanton Nov 23, 2023
f1059c7
fix: In gnoclient Render and QEval, need to check Response.Error
jefft0 Nov 30, 2023
902c95b
Merge pull request #19 from jefft0/fix/gnoclient-Render-QEval-errors
moul Nov 30, 2023
5f0290f
fix: fix rebase
gfanton Jan 18, 2024
74bd901
Merge remote-tracking branch 'master' into dev/moul/gnoclient
gfanton Jan 18, 2024
19f90c1
fix: update simple test
gfanton Jan 18, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions gno.land/pkg/gnoclient/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Gno.land Go Client

The Gno.land Go client is a dedicated library for interacting seamlessly with the Gno.land RPC API.
This library simplifies the process of querying or sending transactions to the Gno.land RPC API and interpreting the responses.

## Installation

Integrate this library into your Go project with the following command:

go get github.com/gnolang/gno/gno.land/pkg/gnoclient

## Development Plan

The roadmap for the Gno.land Go client includes:

- **Initial Development:** Kickstart the development specifically for Gno.land. Subsequently, transition the generic functionalities to other modules like `tm2`, `gnovm`, `gnosdk`.
- **Integration:** Begin incorporating this library within various components such as `gno.land/cmd/*` and other external clients, including `gnoblog-client`, the Discord community faucet bot, and [GnoMobile](https://github.com/gnolang/gnomobile).
- **Enhancements:** Once the generic client establishes a robust foundation, we aim to utilize code generation for contracts. This will streamline the creation of type-safe, contract-specific clients.

## Usage

TODO: Documentation for usage is currently in development and will be available soon.
28 changes: 28 additions & 0 deletions gno.land/pkg/gnoclient/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package gnoclient

import (
rpcclient "github.com/gnolang/gno/tm2/pkg/bft/rpc/client"
"github.com/gnolang/gno/tm2/pkg/errors"
)

// Client provides an interface for interacting with the blockchain.
type Client struct {
Signer Signer // Signer for transaction authentication
RPCClient rpcclient.Client // RPC client for blockchain communication
}

// validateSigner checks that the signer is correctly configured.
func (c Client) validateSigner() error {
if c.Signer == nil {
return errors.New("missing Signer")
}
return nil
}

// validateRPCClient checks that the RPCClient is correctly configured.
func (c Client) validateRPCClient() error {
if c.RPCClient == nil {
return errors.New("missing RPCClient")
}
return nil
}
124 changes: 124 additions & 0 deletions gno.land/pkg/gnoclient/client_queries.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package gnoclient

import (
"fmt"

"github.com/gnolang/gno/tm2/pkg/amino"
rpcclient "github.com/gnolang/gno/tm2/pkg/bft/rpc/client"
ctypes "github.com/gnolang/gno/tm2/pkg/bft/rpc/core/types"
"github.com/gnolang/gno/tm2/pkg/crypto"
"github.com/gnolang/gno/tm2/pkg/errors"
"github.com/gnolang/gno/tm2/pkg/std"
)

// QueryCfg contains configuration options for performing queries.
type QueryCfg struct {
Path string // Query path
Data []byte // Query data
rpcclient.ABCIQueryOptions // ABCI query options
}

// Query performs a generic query on the blockchain.
func (c Client) Query(cfg QueryCfg) (*ctypes.ResultABCIQuery, error) {
if err := c.validateRPCClient(); err != nil {
return nil, err
}
qres, err := c.RPCClient.ABCIQueryWithOptions(cfg.Path, cfg.Data, cfg.ABCIQueryOptions)
if err != nil {
return nil, errors.Wrap(err, "query error")
}

if qres.Response.Error != nil {
return qres, errors.Wrap(qres.Response.Error, "deliver transaction failed: log:%s", qres.Response.Log)
}

return qres, nil
}

// QueryAccount retrieves account information for a given address.
func (c Client) QueryAccount(addr crypto.Address) (*std.BaseAccount, *ctypes.ResultABCIQuery, error) {
if err := c.validateRPCClient(); err != nil {
return nil, nil, err
}

path := fmt.Sprintf("auth/accounts/%s", crypto.AddressToBech32(addr))
data := []byte{}

qres, err := c.RPCClient.ABCIQuery(path, data)
if err != nil {
return nil, nil, errors.Wrap(err, "query account")
}
if qres.Response.Data == nil || len(qres.Response.Data) == 0 || string(qres.Response.Data) == "null" {
return nil, nil, std.ErrUnknownAddress("unknown address: " + crypto.AddressToBech32(addr))
}

var qret struct{ BaseAccount std.BaseAccount }
err = amino.UnmarshalJSON(qres.Response.Data, &qret)
if err != nil {
return nil, nil, err
}

return &qret.BaseAccount, qres, nil
}

func (c Client) QueryAppVersion() (string, *ctypes.ResultABCIQuery, error) {
if err := c.validateRPCClient(); err != nil {
return "", nil, err
}

path := ".app/version"
data := []byte{}

qres, err := c.RPCClient.ABCIQuery(path, data)
if err != nil {
return "", nil, errors.Wrap(err, "query app version")
}

version := string(qres.Response.Value)
return version, qres, nil
}

// Render calls the Render function for pkgPath with optional args. The pkgPath should
// include the prefix like "gno.land/". This is similar to using a browser URL
// <testnet>/<pkgPath>:<args> where <pkgPath> doesn't have the prefix like "gno.land/".
func (c Client) Render(pkgPath string, args string) (string, *ctypes.ResultABCIQuery, error) {
if err := c.validateRPCClient(); err != nil {
return "", nil, err
}

path := "vm/qrender"
data := []byte(fmt.Sprintf("%s\n%s", pkgPath, args))

qres, err := c.RPCClient.ABCIQuery(path, data)
if err != nil {
return "", nil, errors.Wrap(err, "query render")
}
if qres.Response.Error != nil {
return "", nil, errors.Wrap(qres.Response.Error, "Render failed: log:%s", qres.Response.Log)
}

return string(qres.Response.Data), qres, nil
}

// QEval evaluates the given expression with the realm code at pkgPath. The pkgPath should
// include the prefix like "gno.land/". The expression is usually a function call like
// "GetBoardIDFromName(\"testboard\")". The return value is a typed expression like
// "(1 gno.land/r/demo/boards.BoardID)\n(true bool)".
func (c Client) QEval(pkgPath string, expression string) (string, *ctypes.ResultABCIQuery, error) {
if err := c.validateRPCClient(); err != nil {
return "", nil, err
}

path := "vm/qeval"
data := []byte(fmt.Sprintf("%s\n%s", pkgPath, expression))

qres, err := c.RPCClient.ABCIQuery(path, data)
if err != nil {
return "", nil, errors.Wrap(err, "query qeval")
}
if qres.Response.Error != nil {
return "", nil, errors.Wrap(qres.Response.Error, "QEval failed: log:%s", qres.Response.Log)
}

return string(qres.Response.Data), qres, nil
}
52 changes: 52 additions & 0 deletions gno.land/pkg/gnoclient/client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package gnoclient

import (
"testing"

"github.com/gnolang/gno/gno.land/pkg/integration"
"github.com/gnolang/gno/gnovm/pkg/gnoenv"
rpcclient "github.com/gnolang/gno/tm2/pkg/bft/rpc/client"
"github.com/gnolang/gno/tm2/pkg/crypto/keys"
"github.com/gnolang/gno/tm2/pkg/log"
"github.com/jaekwon/testify/require"
)

func newInMemorySigner(t *testing.T, chainid string) *SignerFromKeybase {
t.Helper()

mmeonic := integration.DefaultAccount_Seed
name := integration.DefaultAccount_Name

kb := keys.NewInMemory()
_, err := kb.CreateAccount(name, mmeonic, "", "", uint32(0), uint32(0))
require.NoError(t, err)

return &SignerFromKeybase{
Keybase: kb, // Stores keys in memory or on disk
Account: name, // Account name or bech32 format
Password: "", // Password for encryption
ChainID: chainid, // Chain ID for transaction signing
}
}

func TestClient_Request(t *testing.T) {
config, _ := integration.TestingNodeConfig(t, gnoenv.RootDir())
node, remoteAddr := integration.TestingInMemoryNode(t, log.NewNopLogger(), config)
defer node.Stop()

signer := newInMemorySigner(t, config.TMConfig.ChainID())

client := Client{
Signer: signer,
RPCClient: rpcclient.NewHTTP(remoteAddr, "/websocket"),
}

data, res, err := client.Render("gno.land/r/demo/boards", "")
require.NoError(t, err)
require.NotEmpty(t, data)

require.NotNil(t, res)
require.NotEmpty(t, res.Response.Data)

// XXX: need more test
}
127 changes: 127 additions & 0 deletions gno.land/pkg/gnoclient/client_txs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
package gnoclient

import (
"github.com/gnolang/gno/gno.land/pkg/sdk/vm"
"github.com/gnolang/gno/tm2/pkg/amino"
ctypes "github.com/gnolang/gno/tm2/pkg/bft/rpc/core/types"
"github.com/gnolang/gno/tm2/pkg/errors"
"github.com/gnolang/gno/tm2/pkg/std"
)

// CallCfg contains configuration options for executing a contract call.
type CallCfg struct {
PkgPath string // Package path
FuncName string // Function name
Args []string // Function arguments
GasFee string // Gas fee
GasWanted int64 // Gas wanted
Send string // Send amount
AccountNumber uint64 // Account number
SequenceNumber uint64 // Sequence number
Memo string // Memo
}

// Call executes a contract call on the blockchain.
func (c *Client) Call(cfg CallCfg) (*ctypes.ResultBroadcastTxCommit, error) {
// Validate required client fields.
if err := c.validateSigner(); err != nil {
return nil, errors.Wrap(err, "validate signer")
}
if err := c.validateRPCClient(); err != nil {
return nil, errors.Wrap(err, "validate RPC client")
}

pkgPath := cfg.PkgPath
funcName := cfg.FuncName
args := cfg.Args
gasWanted := cfg.GasWanted
gasFee := cfg.GasFee
send := cfg.Send
sequenceNumber := cfg.SequenceNumber
accountNumber := cfg.AccountNumber
memo := cfg.Memo

// Validate config.
if pkgPath == "" {
return nil, errors.New("missing PkgPath")
}
if funcName == "" {
return nil, errors.New("missing FuncName")
}

// Parse send amount.
sendCoins, err := std.ParseCoins(send)
if err != nil {
return nil, errors.Wrap(err, "parsing send coins")
}

// Parse gas wanted & fee.
gasFeeCoins, err := std.ParseCoin(gasFee)
if err != nil {
return nil, errors.Wrap(err, "parsing gas fee coin")
}

caller := c.Signer.Info().GetAddress()

// Construct message & transaction and marshal.
msg := vm.MsgCall{
Caller: caller,
Send: sendCoins,
PkgPath: pkgPath,
Func: funcName,
Args: args,
}
tx := std.Tx{
Msgs: []std.Msg{msg},
Fee: std.NewFee(gasWanted, gasFeeCoins),
Signatures: nil,
Memo: memo,
}

return c.signAndBroadcastTxCommit(tx, accountNumber, sequenceNumber)
}

// signAndBroadcastTxCommit signs a transaction and broadcasts it, returning the result.
func (c Client) signAndBroadcastTxCommit(tx std.Tx, accountNumber, sequenceNumber uint64) (*ctypes.ResultBroadcastTxCommit, error) {
thehowl marked this conversation as resolved.
Show resolved Hide resolved
caller := c.Signer.Info().GetAddress()

if sequenceNumber == 0 || accountNumber == 0 {
account, _, err := c.QueryAccount(caller)
if err != nil {
return nil, errors.Wrap(err, "query account")
}
accountNumber = account.AccountNumber
sequenceNumber = account.Sequence
}

signCfg := SignCfg{
UnsignedTX: tx,
SequenceNumber: sequenceNumber,
AccountNumber: accountNumber,
}
signedTx, err := c.Signer.Sign(signCfg)
if err != nil {
return nil, errors.Wrap(err, "sign")
}

bz, err := amino.Marshal(signedTx)
if err != nil {
return nil, errors.Wrap(err, "marshaling tx binary bytes")
}

bres, err := c.RPCClient.BroadcastTxCommit(bz)
if err != nil {
return nil, errors.Wrap(err, "broadcasting bytes")
}

if bres.CheckTx.IsErr() {
return bres, errors.Wrap(bres.CheckTx.Error, "check transaction failed: log:%s", bres.CheckTx.Log)
}
if bres.DeliverTx.IsErr() {
return bres, errors.Wrap(bres.DeliverTx.Error, "deliver transaction failed: log:%s", bres.DeliverTx.Log)
}

return bres, nil
}

// TODO: Add more functionality, examples, and unit tests.
Loading
Loading