Skip to content

Commit

Permalink
Init SDK once per process to avoid client panics (#352)
Browse files Browse the repository at this point in the history
  • Loading branch information
krehermann authored Aug 11, 2023
1 parent 0b0d052 commit 2299ce6
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
8 changes: 8 additions & 0 deletions pkg/cosmos/params/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package params

import (
"fmt"
"sync"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
Expand Down Expand Up @@ -40,7 +41,14 @@ func makeEncodingConfig() encodingConfig {
// TODO: import as params.MakeEncoding config
var config = makeEncodingConfig()

var initOnce sync.Once

// Initialize the cosmos sdk at most one time
func InitCosmosSdk(bech32Prefix, token string) {
initOnce.Do(func() { initCosmosSdk(bech32Prefix, token) })
}

func initCosmosSdk(bech32Prefix, token string) {
// copied from wasmd https://github.com/CosmWasm/wasmd/blob/88e01a98ab8a87b98dc26c03715e6aef5c92781b/app/app.go#L163-L174
// NOTE: Bech32 is configured globally, blocked on https://github.com/cosmos/cosmos-sdk/issues/13140
var (
Expand Down
24 changes: 24 additions & 0 deletions pkg/cosmos/params/params_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package params

import (
"testing"

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/assert"
)

func TestInitCosmosSdk(t *testing.T) {
// sdk initialized only once
assert.NotPanics(t, func() { InitCosmosSdk("wasm", "atom") })
assert.NotPanics(t, func() { InitCosmosSdk("notwasm", "cosmos") })
// calling the internal implementation panics when called a second time
assert.Panics(t, func() { initCosmosSdk("wasm", "cosmos") })

// first call to Init wins
sdkConfig := sdk.GetConfig()
assert.Equal(t, sdkConfig.GetBech32AccountAddrPrefix(), "wasm")
_, ok := sdk.GetDenomUnit("atom")
assert.True(t, ok)
_, ok = sdk.GetDenomUnit("cosmos")
assert.False(t, ok)
}
5 changes: 4 additions & 1 deletion pkg/cosmos/relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,14 @@ func (r *Relayer) Start(context.Context) error {
if r.chainSet == nil {
return errors.New("Cosmos unavailable")
}
// TODO(BCI-915): Make this configurable.

// TODO(BCI-915): Make this configurable and relayer-specific
// when doing so, core side will have to run each relayer in a LOOPP
params.InitCosmosSdk(
/* bech32Prefix= */ "wasm",
/* token= */ "cosm",
)

return nil
}

Expand Down

0 comments on commit 2299ce6

Please sign in to comment.