[#404] morph/client: Add awaiting function

Awaiting function locks execution for N blocks.
Useful to wait for notary deposit.

Signed-off-by: Alex Vanin <alexey@nspcc.ru>
This commit is contained in:
Alex Vanin 2021-02-25 19:50:10 +03:00 committed by Alex Vanin
parent 4b10e82685
commit ddf1ac0f28
2 changed files with 62 additions and 8 deletions

View file

@ -1,6 +1,9 @@
package client package client
import ( import (
"context"
"time"
"github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/core/transaction"
"github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn"
"github.com/nspcc-dev/neo-go/pkg/rpc/client" "github.com/nspcc-dev/neo-go/pkg/rpc/client"
@ -29,6 +32,8 @@ type Client struct {
gas util.Uint160 // native gas script-hash gas util.Uint160 // native gas script-hash
waitInterval time.Duration
notary *notary notary *notary
} }
@ -136,6 +141,48 @@ func (c *Client) TransferGas(receiver util.Uint160, amount fixedn.Fixed8) error
return nil return nil
} }
// Wait function blocks routing execution until there
// are `n` new blocks in the chain.
func (c *Client) Wait(ctx context.Context, n uint32) {
var (
err error
height, newHeight uint32
)
height, err = c.client.GetBlockCount()
if err != nil {
c.logger.Error("can't get blockchain height",
zap.String("error", err.Error()))
return
}
for {
select {
case <-ctx.Done():
return
default:
}
newHeight, err = c.client.GetBlockCount()
if err != nil {
c.logger.Error("can't get blockchain height",
zap.String("error", err.Error()))
return
}
if newHeight >= height+n {
return
}
time.Sleep(c.waitInterval)
}
}
// GasBalance returns GAS amount in the client's wallet.
func (c *Client) GasBalance() (int64, error) {
return c.client.NEP17BalanceOf(c.gas, c.acc.PrivateKey().GetScriptHash())
}
func toStackParameter(value interface{}) (sc.Parameter, error) { func toStackParameter(value interface{}) (sc.Parameter, error) {
var result = sc.Parameter{ var result = sc.Parameter{
Value: value, Value: value,

View file

@ -27,15 +27,21 @@ type cfg struct {
logger *logger.Logger // logging component logger *logger.Logger // logging component
gas util.Uint160 // native gas script-hash gas util.Uint160 // native gas script-hash
waitInterval time.Duration
} }
const defaultDialTimeout = 5 * time.Second const (
defaultDialTimeout = 5 * time.Second
defaultWaitInterval = 500 * time.Millisecond
)
func defaultConfig() *cfg { func defaultConfig() *cfg {
return &cfg{ return &cfg{
ctx: context.Background(), ctx: context.Background(),
dialTimeout: defaultDialTimeout, dialTimeout: defaultDialTimeout,
logger: zap.L(), logger: zap.L(),
waitInterval: defaultWaitInterval,
} }
} }
@ -99,6 +105,7 @@ func New(key *ecdsa.PrivateKey, endpoint string, opts ...Option) (*Client, error
client: cli, client: cli,
acc: account, acc: account,
gas: gas, gas: gas,
waitInterval: cfg.waitInterval,
}, nil }, nil
} }