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

[dont merge] feat: offchain vault instantiate/subscribe/redeem examples #154

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
134 changes: 134 additions & 0 deletions examples/chain/40_OffchainSpotVaults/create_vault/example.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package main

import (
"context"
"encoding/hex"
"fmt"
"os"
"time"

"cosmossdk.io/math"
"github.com/InjectiveLabs/sdk-go/client/common"
"github.com/cosmos/cosmos-sdk/types/tx"

rpchttp "github.com/cometbft/cometbft/rpc/client/http"

"github.com/CosmWasm/wasmd/x/wasm/types"
chainclient "github.com/InjectiveLabs/sdk-go/client/chain"
cosmtypes "github.com/cosmos/cosmos-sdk/types"
)

func main() {
// network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

k8s should no longer be used

tmRPC, err := rpchttp.New(network.TmEndpoint, "/websocket")

if err != nil {
fmt.Println(err)
return
}

senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring(
os.Getenv("HOME")+"/.injectived",
"injectived",
"file",
"inj-user",
"12345678",
"5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided
false,
)

if err != nil {
panic(err)
}

clientCtx, err := chainclient.NewClientContext(
network.ChainId,
senderAddress.String(),
cosmosKeyring,
)

if err != nil {
panic(err)
}

clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmRPC)

chainClient, err := chainclient.NewChainClient(
clientCtx,
network.ChainGrpcEndpoint,
common.OptionTLSCert(network.ChainTlsCert),
common.OptionGasPrices("500000000inj"),
)
Comment on lines +57 to +62
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NewChainClient now should receive the network instance instead of only the endpoint. And the certs are taken from the network directly inside the ChainClient.

Suggested change
chainClient, err := chainclient.NewChainClient(
clientCtx,
network.ChainGrpcEndpoint,
common.OptionTLSCert(network.ChainTlsCert),
common.OptionGasPrices("500000000inj"),
)
chainClient, err := chainclient.NewChainClient(
clientCtx,
network,
common.OptionGasPrices("500000000inj"),
)


if err != nil {
panic(err)
}

msgInstantiateContract := &types.MsgInstantiateContract{
Sender: senderAddress.String(),
Admin: senderAddress.String(),
CodeID: 2711,
Label: "spot-offchain-vault example",
Msg: types.RawContractMessage(
fmt.Sprintf(`{
"admin":"%s",
"vault_type":
{"Spot":
{"oracle_type":9,
"base_oracle_symbol":"0x2d9315a88f3019f8efa88dfe9c0f0843712da0bac814461e27733f6b83eb51b3",
"quote_oracle_symbol":"0x1fc18861232290221461220bd4e2acd1dcdfbc89c84092c93c18bdc7756c1588",
"base_decimals":18,"quote_decimals":6}
},
"market_id":"0x0611780ba69656949525013d947713300f56c37b6175e02f26bffa495c3208fe",
"oracle_stale_time":3600,
"notional_value_cap":"5000000000000"
}`, senderAddress.String()),
),
Funds: cosmtypes.NewCoins(cosmtypes.NewCoin("inj", math.NewIntFromBigInt(cosmtypes.MustNewDecFromStr("10").BigInt()))),
}

//AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg
broadcastResult, err := chainClient.SyncBroadcastMsg(msgInstantiateContract)
if err != nil {
panic(err)
}
fmt.Println("instantiate tx hash:", broadcastResult.TxResponse.TxHash)

retryTime := 5
var (
lastErr error
txResponse *tx.GetTxResponse
)
for i := 0; i < retryTime; i++ {
txResponse, lastErr = chainClient.GetTx(context.Background(), broadcastResult.TxResponse.TxHash)
if lastErr == nil {
break
}
time.Sleep(200 * time.Millisecond)
}

if lastErr != nil {
panic(err)
}

dataHex, err := hex.DecodeString(txResponse.TxResponse.Data)
if err != nil {
panic(err)
}

var txResult cosmtypes.TxMsgData
err = clientCtx.Codec.Unmarshal(dataHex, &txResult)
if err != nil {
panic(err)
}

var instantiateResponse types.MsgInstantiateContractResponse
err = clientCtx.Codec.Unmarshal(txResult.MsgResponses[0].Value, &instantiateResponse)
if err != nil {
panic(err)
}

fmt.Println("offchain contract address:", instantiateResponse.Address)
fmt.Println("gas used:", txResponse.TxResponse.GasUsed, ", fee:", cosmtypes.NewDecCoinFromCoin(txResponse.Tx.AuthInfo.Fee.Amount[0]).Amount.Quo(cosmtypes.NewDec(10).Power(18)).String()+"INJ")
}
97 changes: 97 additions & 0 deletions examples/chain/40_OffchainSpotVaults/redeem/example.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package main

import (
"fmt"
"os"

"github.com/InjectiveLabs/sdk-go/client/common"

rpchttp "github.com/cometbft/cometbft/rpc/client/http"

exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types"
chainclient "github.com/InjectiveLabs/sdk-go/client/chain"
cosmtypes "github.com/cosmos/cosmos-sdk/types"
)

func mustNewIntFromString(s string) cosmtypes.Int {
newInt, ok := cosmtypes.NewIntFromString(s)
if !ok {
panic(fmt.Errorf("cannot new int from %s", s))
}

return newInt
}

func main() {
// network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment here

tmRPC, err := rpchttp.New(network.TmEndpoint, "/websocket")
if err != nil {
fmt.Println(err)
return
}

senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring(
os.Getenv("HOME")+"/.injectived",
"injectived",
"file",
"inj-user",
"12345678",
"5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided
false,
)
if err != nil {
panic(err)
}

clientCtx, err := chainclient.NewClientContext(
network.ChainId,
senderAddress.String(),
cosmosKeyring,
)

if err != nil {
panic(err)
}
clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmRPC)
chainClient, err := chainclient.NewChainClient(
clientCtx,
network.ChainGrpcEndpoint,
common.OptionTLSCert(network.ChainTlsCert),
common.OptionGasPrices("500000000inj"),
)
Comment on lines +56 to +62
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment here

Suggested change
clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmRPC)
chainClient, err := chainclient.NewChainClient(
clientCtx,
network.ChainGrpcEndpoint,
common.OptionTLSCert(network.ChainTlsCert),
common.OptionGasPrices("500000000inj"),
)
clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmRPC)
chainClient, err := chainclient.NewChainClient(
clientCtx,
network,
common.OptionGasPrices("500000000inj"),
)

if err != nil {
panic(err)
}

defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress)
offchainContract := "inj1ckmdhdz7r8glfurckgtg0rt7x9uvner4ygqhlv"
// redeem 1.2 offchain vault LP token
msgSubscribe := &exchangetypes.MsgPrivilegedExecuteContract{
Sender: senderAddress.String(),
ContractAddress: offchainContract,
Data: fmt.Sprintf(`
{
"args": {
"Redeem": {
"args":{
"redeemer_subaccount_id":"%s",
"redemption_type": {"SpotRedemptionType":"FixedBaseAndQuote"}
}
}
},
"name":"VaultRedeem",
"origin":"%s"
}`, defaultSubaccountID.String(), senderAddress.String()),
Funds: cosmtypes.NewCoins(
cosmtypes.NewCoin(fmt.Sprintf("factory/%s/lp", offchainContract), mustNewIntFromString("1200000000000000000")),
).String(),
}

broadcastResult, err := chainClient.SyncBroadcastMsg(msgSubscribe)
if err != nil {
panic(err)
}

fmt.Println("offchain redeem tx:", broadcastResult.TxResponse.TxHash)
}
143 changes: 143 additions & 0 deletions examples/chain/40_OffchainSpotVaults/subscribe/example.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
package main

import (
"context"
"fmt"
"os"
"time"

"github.com/InjectiveLabs/sdk-go/client/common"

rpchttp "github.com/cometbft/cometbft/rpc/client/http"

exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types"
chainclient "github.com/InjectiveLabs/sdk-go/client/chain"
cometbfttypes "github.com/cometbft/cometbft/abci/types"
cosmtypes "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx"
)

func mustNewIntFromString(s string) cosmtypes.Int {
newInt, ok := cosmtypes.NewIntFromString(s)
if !ok {
panic(fmt.Errorf("cannot new int from %s", s))
}

return newInt
}

func mintAmountFromResponse(resp *tx.GetTxResponse) cosmtypes.Int {
var lpBalanceChangeEvent cometbfttypes.Event
for _, ev := range resp.TxResponse.Events {
if ev.Type == "wasm-lp_balance_changed" {
lpBalanceChangeEvent = ev
break
}
}

for _, attribute := range lpBalanceChangeEvent.Attributes {
if attribute.Key == "mint_amount" {
return mustNewIntFromString(attribute.Value)
}
}
return cosmtypes.ZeroInt()
}

func main() {
// network := common.LoadNetwork("mainnet", "k8s")
network := common.LoadNetwork("testnet", "k8s")
Comment on lines +47 to +48
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment here

tmRPC, err := rpchttp.New(network.TmEndpoint, "/websocket")

if err != nil {
fmt.Println(err)
return
}

senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring(
os.Getenv("HOME")+"/.injectived",
"injectived",
"file",
"inj-user",
"12345678",
"5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided
false,
)

if err != nil {
panic(err)
}

clientCtx, err := chainclient.NewClientContext(
network.ChainId,
senderAddress.String(),
cosmosKeyring,
)

if err != nil {
panic(err)
}

clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmRPC)

chainClient, err := chainclient.NewChainClient(
clientCtx,
network.ChainGrpcEndpoint,
common.OptionTLSCert(network.ChainTlsCert),
common.OptionGasPrices("500000000inj"),
)
Comment on lines +82 to +87
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment here

Suggested change
chainClient, err := chainclient.NewChainClient(
clientCtx,
network.ChainGrpcEndpoint,
common.OptionTLSCert(network.ChainTlsCert),
common.OptionGasPrices("500000000inj"),
)
chainClient, err := chainclient.NewChainClient(
clientCtx,
network,
common.OptionGasPrices("500000000inj"),
)


if err != nil {
panic(err)
}

defaultSubaccountID := chainClient.DefaultSubaccount(senderAddress)
offchainContract := "inj1ckmdhdz7r8glfurckgtg0rt7x9uvner4ygqhlv"

// deposit 10 INJ and 80 USDT (testnet)
msgSubscribe := &exchangetypes.MsgPrivilegedExecuteContract{
Sender: senderAddress.String(),
ContractAddress: offchainContract,
Data: fmt.Sprintf(`
{
"origin":"%s",
"name":"Subscribe",
"args":{
"Subscribe":{
"args":{
"subscriber_subaccount_id":"%s"
}
}
}
}`, senderAddress.String(), defaultSubaccountID.String()),
Funds: cosmtypes.NewCoins(
cosmtypes.NewCoin("inj", mustNewIntFromString("10000000000000000000")),
cosmtypes.NewCoin("peggy0x87aB3B4C8661e07D6372361211B96ed4Dc36B1B5", mustNewIntFromString("80000000")),
).String(),
}

broadcastResult, err := chainClient.SyncBroadcastMsg(msgSubscribe)
if err != nil {
panic(err)
}

fmt.Println("offchain subscribe tx:", broadcastResult.TxResponse.TxHash)

// tx result -> minted amount
retryTime := 5
var (
lastErr error
txResponse *tx.GetTxResponse
)
for i := 0; i < retryTime; i++ {
txResponse, lastErr = chainClient.GetTx(context.Background(), broadcastResult.TxResponse.TxHash)
if lastErr == nil {
break
}
time.Sleep(200 * time.Millisecond)
}
if lastErr != nil {
panic(err)
}

fmt.Println("minted amount:", mintAmountFromResponse(txResponse).String()+fmt.Sprintf("lp/%s/lp", offchainContract))
}
Loading