Skip to content

Commit

Permalink
v6: sdkmath support (#897)
Browse files Browse the repository at this point in the history
* CoinDecimals, cosmossdk.io/math

* touchups

* ubuntu-latest runners

* fix test equalvalues

* add `GetRelayerCodecs` via the relayer

* Revert "add `GetRelayerCodecs` via the relayer"

This reverts commit aa62728.

* conformance/test.go:540
  • Loading branch information
Reecepbcups authored Dec 6, 2023
1 parent 9fdddb2 commit 8f0bb15
Show file tree
Hide file tree
Showing 46 changed files with 884 additions and 1,735 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/e2e-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ concurrency:
jobs:
test-conformance:
name: test-conformance
runs-on: [self-hosted, linux]
runs-on: ubuntu-latest
steps:
# Install and setup go
- name: Set up Go 1.19
Expand All @@ -32,7 +32,7 @@ jobs:
run: (go test -race -timeout 30m -failfast -v -p 2 ./cmd/interchaintest) || (echo "\n\n*****CHAIN and RELAYER LOGS*****" && cat "$HOME/.interchaintest/logs/interchaintest.log" && exit 1)
test-ibc-examples:
name: test-ibc-examples
runs-on: [self-hosted, linux]
runs-on: ubuntu-latest
steps:
# Install and setup go
- name: Set up Go 1.19
Expand All @@ -54,7 +54,7 @@ jobs:
run: go test -race -timeout 30m -failfast -v -p 2 ./examples/ibc
test-cosmos-examples:
name: test-cosmos-examples
runs-on: [self-hosted, linux]
runs-on: ubuntu-latest
steps:
# Install and setup go
- name: Set up Go 1.19
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ concurrency:
jobs:
test-unit:
name: unit-tests
runs-on: [self-hosted, linux]
runs-on: ubuntu-latest
steps:
# Install and setup go
- name: Set up Go 1.19
Expand Down
43 changes: 38 additions & 5 deletions chain/cosmos/chain_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -664,7 +664,7 @@ func (tn *ChainNode) AddGenesisAccount(ctx context.Context, address string, gene
if i != 0 {
amount += ","
}
amount += fmt.Sprintf("%d%s", coin.Amount.Int64(), coin.Denom)
amount += fmt.Sprintf("%s%s", coin.Amount.String(), coin.Denom)
}

tn.lock.Lock()
Expand Down Expand Up @@ -701,7 +701,7 @@ func (tn *ChainNode) Gentx(ctx context.Context, name string, genesisSelfDelegati
command = append(command, "genesis")
}

command = append(command, "gentx", valKey, fmt.Sprintf("%d%s", genesisSelfDelegation.Amount.Int64(), genesisSelfDelegation.Denom),
command = append(command, "gentx", valKey, fmt.Sprintf("%s%s", genesisSelfDelegation.Amount.String(), genesisSelfDelegation.Denom),
"--keyring-backend", keyring.BackendTest,
"--chain-id", tn.Chain.Config().ChainID)

Expand Down Expand Up @@ -740,7 +740,7 @@ func (tn *ChainNode) SendIBCTransfer(
) (string, error) {
command := []string{
"ibc-transfer", "transfer", "transfer", channelID,
amount.Address, fmt.Sprintf("%d%s", amount.Amount, amount.Denom),
amount.Address, fmt.Sprintf("%s%s", amount.Amount.String(), amount.Denom),
}
if options.Timeout != nil {
if options.Timeout.NanoSeconds > 0 {
Expand All @@ -758,7 +758,7 @@ func (tn *ChainNode) SendIBCTransfer(
func (tn *ChainNode) SendFunds(ctx context.Context, keyName string, amount ibc.WalletAmount) error {
_, err := tn.ExecTx(ctx,
keyName, "bank", "send", keyName,
amount.Address, fmt.Sprintf("%d%s", amount.Amount, amount.Denom),
amount.Address, fmt.Sprintf("%s%s", amount.Amount.String(), amount.Denom),
)
return err
}
Expand Down Expand Up @@ -790,6 +790,39 @@ type CodeInfosResponse struct {
CodeInfos []CodeInfo `json:"code_infos"`
}

// StoreContract takes a file path to smart contract and stores it on-chain. Returns the contracts code id.
func (tn *ChainNode) StoreContract(ctx context.Context, keyName string, fileName string, extraExecTxArgs ...string) (string, error) {
_, file := filepath.Split(fileName)
err := tn.CopyFile(ctx, fileName, file)
if err != nil {
return "", fmt.Errorf("writing contract file to docker volume: %w", err)
}

cmd := []string{"wasm", "store", path.Join(tn.HomeDir(), file), "--gas", "auto"}
cmd = append(cmd, extraExecTxArgs...)

if _, err := tn.ExecTx(ctx, keyName, cmd...); err != nil {
return "", err
}

err = testutil.WaitForBlocks(ctx, 5, tn.Chain)
if err != nil {
return "", fmt.Errorf("wait for blocks: %w", err)
}

stdout, _, err := tn.ExecQuery(ctx, "wasm", "list-code", "--reverse")
if err != nil {
return "", err
}

res := CodeInfosResponse{}
if err := json.Unmarshal([]byte(stdout), &res); err != nil {
return "", err
}

return res.CodeInfos[0].CodeID, nil
}

func (tn *ChainNode) getTransaction(clientCtx client.Context, txHash string) (*types.TxResponse, error) {
// Retry because sometimes the tx is not committed to state yet.
var txResp *types.TxResponse
Expand Down Expand Up @@ -1187,7 +1220,7 @@ func (tn *ChainNode) SendICABankTransfer(ctx context.Context, connectionID, from
"amount": []map[string]any{
{
"denom": amount.Denom,
"amount": amount.Amount,
"amount": amount.Amount.String(),
},
},
})
Expand Down
23 changes: 23 additions & 0 deletions chain/cosmos/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package cosmos

import (
sdk "github.com/cosmos/cosmos-sdk/types"
)

func SetSDKConfig(bech32Prefix string) *sdk.Config {
var (
bech32MainPrefix = bech32Prefix
bech32PrefixAccAddr = bech32MainPrefix
bech32PrefixAccPub = bech32MainPrefix + sdk.PrefixPublic
bech32PrefixValAddr = bech32MainPrefix + sdk.PrefixValidator + sdk.PrefixOperator
bech32PrefixValPub = bech32MainPrefix + sdk.PrefixValidator + sdk.PrefixOperator + sdk.PrefixPublic
bech32PrefixConsAddr = bech32MainPrefix + sdk.PrefixValidator + sdk.PrefixConsensus
bech32PrefixConsPub = bech32MainPrefix + sdk.PrefixValidator + sdk.PrefixConsensus + sdk.PrefixPublic
)

cfg := sdk.GetConfig()
cfg.SetBech32PrefixForAccount(bech32PrefixAccAddr, bech32PrefixAccPub)
cfg.SetBech32PrefixForValidator(bech32PrefixValAddr, bech32PrefixValPub)
cfg.SetBech32PrefixForConsensusNode(bech32PrefixConsAddr, bech32PrefixConsPub)
return cfg
}
24 changes: 17 additions & 7 deletions chain/cosmos/cosmos_chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import (
"context"
"fmt"
"io"
"math"
"os"
"strconv"
"strings"
"sync"

sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
Expand All @@ -33,6 +35,8 @@ import (
"google.golang.org/grpc/credentials/insecure"
)

var _ ibc.Chain = (*CosmosChain)(nil)

// CosmosChain is a local docker testnet for a Cosmos SDK chain.
// Implements the ibc.Chain interface.
type CosmosChain struct {
Expand Down Expand Up @@ -185,6 +189,10 @@ func (c *CosmosChain) getFullNode() *ChainNode {
return c.Validators[0]
}

func (c *CosmosChain) GetNode() *ChainNode {
return c.Validators[0]
}

// Exec implements ibc.Chain.
func (c *CosmosChain) Exec(ctx context.Context, cmd []string, env []string) (stdout, stderr []byte, err error) {
return c.getFullNode().Exec(ctx, cmd, env)
Expand Down Expand Up @@ -428,23 +436,23 @@ func (c *CosmosChain) ExportState(ctx context.Context, height int64) (string, er

// GetBalance fetches the current balance for a specific account address and denom.
// Implements Chain interface
func (c *CosmosChain) GetBalance(ctx context.Context, address string, denom string) (int64, error) {
func (c *CosmosChain) GetBalance(ctx context.Context, address string, denom string) (sdkmath.Int, error) {
params := &bankTypes.QueryBalanceRequest{Address: address, Denom: denom}
grpcAddress := c.getFullNode().hostGRPCPort
conn, err := grpc.Dial(grpcAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return 0, err
return sdkmath.Int{}, err
}
defer conn.Close()

queryClient := bankTypes.NewQueryClient(conn)
res, err := queryClient.Balance(ctx, params)

if err != nil {
return 0, err
return sdkmath.Int{}, err
}

return res.Balance.Amount.Int64(), nil
return res.Balance.Amount, nil
}

// AllBalances fetches an account address's balance for all denoms it holds
Expand Down Expand Up @@ -715,13 +723,15 @@ type ValidatorWithIntPower struct {
func (c *CosmosChain) Start(testName string, ctx context.Context, additionalGenesisWallets ...ibc.WalletAmount) error {
chainCfg := c.Config()

decimalPow := int64(math.Pow10(int(*chainCfg.CoinDecimals)))

genesisAmount := types.Coin{
Amount: types.NewInt(10_000_000_000_000),
Amount: sdkmath.NewInt(10_000_000).MulRaw(decimalPow),
Denom: chainCfg.Denom,
}

genesisSelfDelegation := types.Coin{
Amount: types.NewInt(5_000_000_000_000),
Amount: sdkmath.NewInt(5_000_000).MulRaw(decimalPow),
Denom: chainCfg.Denom,
}

Expand Down Expand Up @@ -830,7 +840,7 @@ func (c *CosmosChain) Start(testName string, ctx context.Context, additionalGene
}

for _, wallet := range additionalGenesisWallets {
if err := validator0.AddGenesisAccount(ctx, wallet.Address, []types.Coin{{Denom: wallet.Denom, Amount: types.NewInt(wallet.Amount)}}); err != nil {
if err := validator0.AddGenesisAccount(ctx, wallet.Address, []types.Coin{{Denom: wallet.Denom, Amount: wallet.Amount}}); err != nil {
return err
}
}
Expand Down
7 changes: 7 additions & 0 deletions chain/cosmos/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ type GenesisKV struct {
Value interface{} `json:"value"`
}

func NewGenesisKV(key string, value interface{}) GenesisKV {
return GenesisKV{
Key: key,
Value: value,
}
}

func ModifyGenesis(genesisKV []GenesisKV) func(ibc.ChainConfig, []byte) ([]byte, error) {
return func(chainConfig ibc.ChainConfig, genbz []byte) ([]byte, error) {
g := make(map[string]interface{})
Expand Down
4 changes: 2 additions & 2 deletions chain/cosmos/poll.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ func PollForBalance(ctx context.Context, chain *CosmosChain, deltaBlocks uint64,
if err != nil {
return nil, err
}
if bal != balance.Amount {
return nil, fmt.Errorf("balance (%d) does not match expected: (%d)", bal, balance.Amount)
if !bal.Equal(balance.Amount) {
return nil, fmt.Errorf("balance (%s) does not match expected: (%s)", bal.String(), balance.Amount.String())
}
return nil, nil
}
Expand Down
2 changes: 1 addition & 1 deletion chain/penumbra/penumbra_app_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ func (p *PenumbraAppNode) GenerateGenesisFile(
}
allocationsCsv := []byte(`"amount","denom","address"\n`)
for _, allocation := range allocations {
allocationsCsv = append(allocationsCsv, []byte(fmt.Sprintf(`"%d","%s","%s"\n`, allocation.Amount, allocation.Denom, allocation.Address))...)
allocationsCsv = append(allocationsCsv, []byte(fmt.Sprintf(`"%s","%s","%s"\n`, allocation.Amount.String(), allocation.Denom, allocation.Address))...)
}
if err := fw.WriteFile(ctx, p.VolumeName, "allocations.csv", allocationsCsv); err != nil {
return fmt.Errorf("error writing allocations to file: %w", err)
Expand Down
13 changes: 7 additions & 6 deletions chain/penumbra/penumbra_chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"strconv"
"strings"

"cosmossdk.io/math"
"github.com/BurntSushi/toml"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
Expand Down Expand Up @@ -67,9 +68,9 @@ type PenumbraValidatorFundingStream struct {
}

type PenumbraGenesisAppStateAllocation struct {
Amount int64 `json:"amount"`
Denom string `json:"denom"`
Address string `json:"address"`
Amount math.Int `json:"amount"`
Denom string `json:"denom"`
Address string `json:"address"`
}

func NewPenumbraChain(log *zap.Logger, testName string, chainConfig ibc.ChainConfig, numValidators int, numFullNodes int) *PenumbraChain {
Expand Down Expand Up @@ -235,7 +236,7 @@ func (c *PenumbraChain) Height(ctx context.Context) (uint64, error) {
}

// Implements Chain interface
func (c *PenumbraChain) GetBalance(ctx context.Context, address string, denom string) (int64, error) {
func (c *PenumbraChain) GetBalance(ctx context.Context, address string, denom string) (math.Int, error) {
panic("implement me")
}

Expand Down Expand Up @@ -433,13 +434,13 @@ func (c *PenumbraChain) Start(testName string, ctx context.Context, additionalGe

// self delegation
allocations[2*i] = PenumbraGenesisAppStateAllocation{
Amount: 100_000_000_000,
Amount: math.NewInt(100_000_000_000),
Denom: fmt.Sprintf("udelegation_%s", validatorTemplateDefinition.IdentityKey),
Address: validatorTemplateDefinition.FundingStreams[0].Address,
}
// liquid
allocations[2*i+1] = PenumbraGenesisAppStateAllocation{
Amount: 1_000_000_000_000,
Amount: math.NewInt(1_000_000_000_000),
Denom: chainCfg.Denom,
Address: validatorTemplateDefinition.FundingStreams[0].Address,
}
Expand Down
15 changes: 8 additions & 7 deletions chain/polkadot/parachain_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import (
"encoding/json"
"fmt"
"path/filepath"
"strconv"
"strings"

"cosmossdk.io/math"
"github.com/avast/retry-go/v4"
gsrpc "github.com/centrifuge/go-substrate-rpc-client/v4"
sdktypes "github.com/cosmos/cosmos-sdk/types"
Expand Down Expand Up @@ -152,7 +152,7 @@ func (pn *ParachainNode) GenerateParachainGenesisFile(ctx context.Context, addit

for _, wallet := range additionalGenesisWallets {
balances = append(balances,
[]interface{}{wallet.Address, wallet.Amount * parachainScaling},
[]interface{}{wallet.Address, wallet.Amount.MulRaw(parachainScaling)},
)
}
if err := dyno.Set(chainSpec, balances, "genesis", "runtime", "balances", "balances"); err != nil {
Expand Down Expand Up @@ -305,8 +305,9 @@ func (pn *ParachainNode) Exec(ctx context.Context, cmd []string, env []string) d
return job.Run(ctx, cmd, opts)
}

func (pn *ParachainNode) GetBalance(ctx context.Context, address string, denom string) (int64, error) {
return GetBalance(pn.api, address)
func (pn *ParachainNode) GetBalance(ctx context.Context, address string, denom string) (math.Int, error) {
amt, err := GetBalance(pn.api, address)
return math.NewInt(amt), err
}

// GetIbcBalance returns the Coins type of ibc coins in account
Expand All @@ -331,7 +332,7 @@ func (pn *ParachainNode) SendFunds(ctx context.Context, keyName string, amount i
"ParachainNode SendFunds",
zap.String("From", kp.Address),
zap.String("To", amount.Address),
zap.String("Amount", strconv.FormatInt(amount.Amount, 10)),
zap.String("Amount", amount.Amount.String()),
)
hash, err := SendFundsTx(pn.api, kp, amount)
if err != nil {
Expand Down Expand Up @@ -359,7 +360,7 @@ func (pn *ParachainNode) SendIbcFunds(
"ParachainNode SendIbcFunds",
zap.String("From", kp.Address),
zap.String("To", amount.Address),
zap.String("Amount", strconv.FormatInt(amount.Amount, 10)),
zap.String("Amount", amount.Amount.String()),
)
hash, err := SendIbcFundsTx(pn.api, kp, channelID, amount, options)
if err != nil {
Expand All @@ -385,7 +386,7 @@ func (pn *ParachainNode) MintFunds(
"ParachainNode MintFunds",
zap.String("From", kp.Address),
zap.String("To", amount.Address),
zap.String("Amount", strconv.FormatInt(amount.Amount, 10)),
zap.String("Amount", amount.Amount.String()),
)
hash, err := MintFundsTx(pn.api, kp, amount)
if err != nil {
Expand Down
Loading

0 comments on commit 8f0bb15

Please sign in to comment.