Skip to content

Commit

Permalink
refactor: use cosmos sdk Int type for balances/token amounts (#679)
Browse files Browse the repository at this point in the history
* refactor: use csdk Int type for balances/token amounts

* chore: use ZeroInt func

(cherry picked from commit 8e02aef)

# Conflicts:
#	chain/polkadot/query.go
#	conformance/flush.go
#	conformance/test.go
#	examples/cosmos/light_client_test.go
#	examples/hyperspace/hyperspace_test.go
#	examples/ibc/interchain_accounts_test.go
#	examples/ibc/learn_ibc_test.go
#	examples/ibc/packet_forward_test.go
#	examples/ibc/wasm/wasm_ibc_test.go
#	examples/ibc/wasm/wasm_icq_test.go
#	examples/polkadot/polkadot_chain_test.go
#	examples/polkadot/push_wasm_client_code_test.go
#	go.mod
#	ibc/types.go
#	interchain_test.go
#	internal/blockdb/messages_view_test.go
#	test_user.go
  • Loading branch information
jtieri authored and mergify[bot] committed Aug 2, 2023
1 parent e768e7b commit 59a2d31
Show file tree
Hide file tree
Showing 28 changed files with 1,511 additions and 159 deletions.
6 changes: 3 additions & 3 deletions chain/cosmos/chain_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -674,7 +674,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 @@ -692,7 +692,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 @@ -1097,7 +1097,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
11 changes: 6 additions & 5 deletions chain/cosmos/cosmos_chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"strings"
"sync"

"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 Down Expand Up @@ -411,23 +412,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) (math.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 math.Int{}, err
}
defer conn.Close()

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

if err != nil {
return 0, err
return math.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 @@ -719,7 +720,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
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 !balance.Amount.Equal(bal) {
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
12 changes: 6 additions & 6 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,7 +305,7 @@ 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) {
func (pn *ParachainNode) GetBalance(ctx context.Context, address string, denom string) (math.Int, error) {
return GetBalance(pn.api, address)
}

Expand All @@ -331,7 +331,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 +359,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 +385,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
5 changes: 3 additions & 2 deletions chain/polkadot/polkadot_chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"io"
"strings"

"cosmossdk.io/math"
"github.com/99designs/keyring"
"github.com/StirlingMarketingGroup/go-namecase"
"github.com/centrifuge/go-substrate-rpc-client/v4/signature"
Expand Down Expand Up @@ -340,7 +341,7 @@ func (c *PolkadotChain) modifyRelayChainGenesis(ctx context.Context, chainSpec i
}
for _, wallet := range additionalGenesisWallets {
balances = append(balances,
[]interface{}{wallet.Address, wallet.Amount * polkadotScaling},
[]interface{}{wallet.Address, wallet.Amount.MulRaw(polkadotScaling)},
)
}

Expand Down Expand Up @@ -778,7 +779,7 @@ func (c *PolkadotChain) SendIBCTransfer(

// GetBalance fetches the current balance for a specific account address and denom.
// Implements Chain interface.
func (c *PolkadotChain) GetBalance(ctx context.Context, address string, denom string) (int64, error) {
func (c *PolkadotChain) GetBalance(ctx context.Context, address string, denom string) (math.Int, error) {
// If denom == polkadot denom, it is a relay chain query, else parachain query
if denom == c.cfg.Denom {
return c.RelayChainNodes[0].GetBalance(ctx, address, denom)
Expand Down
20 changes: 13 additions & 7 deletions chain/polkadot/query.go
Original file line number Diff line number Diff line change
@@ -1,33 +1,39 @@
package polkadot

import (
<<<<<<< HEAD
gsrpc "github.com/centrifuge/go-substrate-rpc-client/v4"
gstypes "github.com/centrifuge/go-substrate-rpc-client/v4/types"
=======
"cosmossdk.io/math"
gsrpc "github.com/misko9/go-substrate-rpc-client/v4"
gstypes "github.com/misko9/go-substrate-rpc-client/v4/types"
>>>>>>> 8e02aef (refactor: use cosmos sdk Int type for balances/token amounts (#679))
)

// GetBalance fetches the current balance for a specific account address using the SubstrateAPI
func GetBalance(api *gsrpc.SubstrateAPI, address string) (int64, error) {
func GetBalance(api *gsrpc.SubstrateAPI, address string) (math.Int, error) {
meta, err := api.RPC.State.GetMetadataLatest()
if err != nil {
return -1, err
return math.Int{}, err
}
pubKey, err := DecodeAddressSS58(address)
if err != nil {
return -2, err
return math.Int{}, err
}
key, err := gstypes.CreateStorageKey(meta, "System", "Account", pubKey, nil)
if err != nil {
return -3, err
return math.Int{}, err
}

var accountInfo AccountInfo
ok, err := api.RPC.State.GetStorageLatest(key, &accountInfo)
if err != nil {
return -4, err
return math.Int{}, err
}
if !ok {
return -5, nil
return math.Int{}, nil
}

return accountInfo.Data.Free.Int64(), nil
return math.NewIntFromBigInt(accountInfo.Data.Free.Int), nil
}
3 changes: 2 additions & 1 deletion chain/polkadot/relay_chain_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strings"
"time"

"cosmossdk.io/math"
"github.com/avast/retry-go/v4"
gsrpc "github.com/centrifuge/go-substrate-rpc-client/v4"
"github.com/docker/docker/client"
Expand Down Expand Up @@ -294,6 +295,6 @@ func (p *RelayChainNode) SendFunds(ctx context.Context, keyName string, amount i

// GetBalance fetches the current balance for a specific account address and denom.
// Implements Chain interface.
func (p *RelayChainNode) GetBalance(ctx context.Context, address string, denom string) (int64, error) {
func (p *RelayChainNode) GetBalance(ctx context.Context, address string, denom string) (math.Int, error) {
return GetBalance(p.api, address)
}
6 changes: 3 additions & 3 deletions chain/polkadot/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func SendFundsTx(api *gsrpc.SubstrateAPI, senderKeypair signature.KeyringPair, a
return hash, err
}

call, err := gstypes.NewCall(meta, "Balances.transfer", receiver, gstypes.NewUCompactFromUInt(uint64(amount.Amount)))
call, err := gstypes.NewCall(meta, "Balances.transfer", receiver, gstypes.NewUCompact(amount.Amount.BigInt()))
if err != nil {
return hash, err
}
Expand Down Expand Up @@ -85,7 +85,7 @@ func SendIbcFundsTx(
timestamp := gstypes.NewOptionU64(gstypes.NewU64(0))
height := gstypes.NewOptionU64(gstypes.NewU64(3000)) // Must set timestamp or height
assetId := gstypes.NewU128(*big.NewInt(assetNum))
amount2 := gstypes.NewU128(*big.NewInt(amount.Amount))
amount2 := gstypes.NewU128(*amount.Amount.BigInt())
memo := gstypes.NewU8(0)

call, err := gstypes.NewCall(meta, "Ibc.transfer", raw, size, to, channel, timeout, timestamp, height, assetId, amount2, memo)
Expand Down Expand Up @@ -124,7 +124,7 @@ func MintFundsTx(
}

assetId := gstypes.NewU128(*big.NewInt(assetNum))
amount2 := gstypes.NewUCompactFromUInt(uint64(amount.Amount))
amount2 := gstypes.NewUCompact(amount.Amount.BigInt())

call, err := gstypes.NewCall(meta, "Assets.mint", assetId, receiver, amount2)
if err != nil {
Expand Down
11 changes: 10 additions & 1 deletion conformance/flush.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,21 @@ import (
"fmt"
"testing"

"cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/types"
<<<<<<< HEAD
interchaintest "github.com/strangelove-ventures/interchaintest/v6"
"github.com/strangelove-ventures/interchaintest/v6/ibc"
"github.com/strangelove-ventures/interchaintest/v6/relayer"
"github.com/strangelove-ventures/interchaintest/v6/testreporter"
"github.com/strangelove-ventures/interchaintest/v6/testutil"
=======
"github.com/strangelove-ventures/interchaintest/v7"
"github.com/strangelove-ventures/interchaintest/v7/ibc"
"github.com/strangelove-ventures/interchaintest/v7/relayer"
"github.com/strangelove-ventures/interchaintest/v7/testreporter"
"github.com/strangelove-ventures/interchaintest/v7/testutil"
>>>>>>> 8e02aef (refactor: use cosmos sdk Int type for balances/token amounts (#679))
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -77,7 +86,7 @@ func TestRelayerFlushing(t *testing.T, ctx context.Context, cf interchaintest.Ch
tx, err := c0.SendIBCTransfer(ctx, c0ChannelID, interchaintest.FaucetAccountKeyName, ibc.WalletAmount{
Address: c1FaucetAddr,
Denom: c0.Config().Denom,
Amount: txAmount,
Amount: math.NewInt(txAmount),
}, ibc.TransferOptions{})
req.NoError(err)
req.NoError(tx.Validate())
Expand Down
Loading

0 comments on commit 59a2d31

Please sign in to comment.