emulator

package
v0.62.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 12, 2024 License: Apache-2.0 Imports: 42 Imported by: 12

Documentation

Overview

Package emulator provides an emulated version of the Flow emulator that can be used for development purposes.

This package can be used as a library or as a standalone application.

When used as a library, this package provides tools to write programmatic tests for Flow applications.

When used as a standalone application, this package implements the Flow Access API and is fully-compatible with Flow gRPC client libraries.

  • Flow Emulator *
  • Copyright Dapper Labs, Inc. *
  • Licensed under the Apache License, Version 2.0 (the "License");
  • you may not use this file except in compliance with the License.
  • You may obtain a copy of the License at *
  • http://www.apache.org/licenses/LICENSE-2.0 *
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an "AS IS" BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.

Index

Constants

View Source
const DefaultServiceKeyHashAlgo = sdkcrypto.SHA3_256
View Source
const DefaultServiceKeySigAlgo = sdkcrypto.ECDSA_P256
View Source
const MaxViewIncrease = 3

MaxViewIncrease represents the largest difference in view number between two consecutive blocks. The minimum view increment is 1.

Variables

View Source
var (
	PragmaDebug      = "debug"
	PragmaSourceFile = "sourceFile"
)
View Source
var CommonContracts = NewCommonContracts(flowgo.Emulator.Chain())

Functions

func DeployContracts

func DeployContracts(b *Blockchain, deployments []ContractDescription) error

Types

type AccessProvider

type AccessProvider interface {
	Ping() error
	GetNetworkParameters() access.NetworkParameters

	GetLatestBlock() (*flowgo.Block, error)
	GetBlockByID(id flowgo.Identifier) (*flowgo.Block, error)
	GetBlockByHeight(height uint64) (*flowgo.Block, error)

	GetCollectionByID(colID flowgo.Identifier) (*flowgo.LightCollection, error)

	GetTransaction(txID flowgo.Identifier) (*flowgo.TransactionBody, error)
	GetTransactionResult(txID flowgo.Identifier) (*access.TransactionResult, error)
	GetTransactionsByBlockID(blockID flowgo.Identifier) ([]*flowgo.TransactionBody, error)
	GetTransactionResultsByBlockID(blockID flowgo.Identifier) ([]*access.TransactionResult, error)

	GetAccount(address flowgo.Address) (*flowgo.Account, error)
	GetAccountAtBlockHeight(address flowgo.Address, blockHeight uint64) (*flowgo.Account, error)
	GetAccountByIndex(uint) (*flowgo.Account, error)

	GetEventsByHeight(blockHeight uint64, eventType string) ([]flowgo.Event, error)
	GetEventsForBlockIDs(eventType string, blockIDs []flowgo.Identifier) ([]flowgo.BlockEvents, error)
	GetEventsForHeightRange(eventType string, startHeight, endHeight uint64) ([]flowgo.BlockEvents, error)

	ExecuteScript(script []byte, arguments [][]byte) (*types.ScriptResult, error)
	ExecuteScriptAtBlockHeight(script []byte, arguments [][]byte, blockHeight uint64) (*types.ScriptResult, error)
	ExecuteScriptAtBlockID(script []byte, arguments [][]byte, id flowgo.Identifier) (*types.ScriptResult, error)

	SendTransaction(tx *flowgo.TransactionBody) error
	AddTransaction(tx flowgo.TransactionBody) error
}

type AutoMineCapable

type AutoMineCapable interface {
	EnableAutoMine()
	DisableAutoMine()
}

type BasicPragma added in v0.54.0

type BasicPragma struct {
	// contains filtered or unexported fields
}

func (*BasicPragma) Argument added in v0.54.0

func (p *BasicPragma) Argument() string

func (*BasicPragma) Name added in v0.54.0

func (p *BasicPragma) Name() string

type Blockchain

type Blockchain struct {
	// contains filtered or unexported fields
}

Blockchain emulates the functionality of the Flow emulator.

func New

func New(opts ...Option) (*Blockchain, error)

New instantiates a new emulated emulator with the provided options.

func (*Blockchain) AddTransaction

func (b *Blockchain) AddTransaction(tx flowgo.TransactionBody) error

AddTransaction validates a transaction and adds it to the current pending block.

func (*Blockchain) Broadcaster added in v0.58.0

func (b *Blockchain) Broadcaster() *engine.Broadcaster

func (*Blockchain) CommitBlock

func (b *Blockchain) CommitBlock() (*flowgo.Block, error)

CommitBlock seals the current pending block and saves it to storage.

This function clears the pending transaction pool and resets the pending block.

func (*Blockchain) CoverageReport

func (b *Blockchain) CoverageReport() *runtime.CoverageReport

func (*Blockchain) CreateSnapshot

func (b *Blockchain) CreateSnapshot(name string) error

func (*Blockchain) CurrentScript

func (b *Blockchain) CurrentScript() (string, string)

func (*Blockchain) DisableAutoMine

func (b *Blockchain) DisableAutoMine()

func (*Blockchain) EnableAutoMine

func (b *Blockchain) EnableAutoMine()

func (*Blockchain) EndDebugging

func (b *Blockchain) EndDebugging()

func (*Blockchain) ExecuteAndCommitBlock

func (b *Blockchain) ExecuteAndCommitBlock() (*flowgo.Block, []*types.TransactionResult, error)

ExecuteAndCommitBlock is a utility that combines ExecuteBlock with CommitBlock.

func (*Blockchain) ExecuteBlock

func (b *Blockchain) ExecuteBlock() ([]*types.TransactionResult, error)

ExecuteBlock executes the remaining transactions in pending block.

func (*Blockchain) ExecuteNextTransaction

func (b *Blockchain) ExecuteNextTransaction() (*types.TransactionResult, error)

ExecuteNextTransaction executes the next indexed transaction in pending block.

func (*Blockchain) ExecuteScript

func (b *Blockchain) ExecuteScript(
	script []byte,
	arguments [][]byte,
) (*types.ScriptResult, error)

ExecuteScript executes a read-only script against the world state and returns the result.

func (*Blockchain) ExecuteScriptAtBlockHeight

func (b *Blockchain) ExecuteScriptAtBlockHeight(
	script []byte,
	arguments [][]byte,
	blockHeight uint64,
) (*types.ScriptResult, error)

func (*Blockchain) ExecuteScriptAtBlockID

func (b *Blockchain) ExecuteScriptAtBlockID(script []byte, arguments [][]byte, id flowgo.Identifier) (*types.ScriptResult, error)

func (*Blockchain) GetAccount

func (b *Blockchain) GetAccount(address flowgo.Address) (*flowgo.Account, error)

GetAccount returns the account for the given address.

func (*Blockchain) GetAccountAtBlockHeight

func (b *Blockchain) GetAccountAtBlockHeight(address flowgo.Address, blockHeight uint64) (*flowgo.Account, error)

GetAccountAtBlockHeight returns the account for the given address at specified block height.

func (*Blockchain) GetAccountByIndex

func (b *Blockchain) GetAccountByIndex(index uint) (*flowgo.Account, error)

GetAccountByIndex returns the account for the given address.

func (*Blockchain) GetAccountUnsafe deprecated

func (b *Blockchain) GetAccountUnsafe(address flowgo.Address) (*flowgo.Account, error)

Deprecated: Needed for the debugger right now, do NOT use for other purposes. TODO: refactor

func (*Blockchain) GetBlockByHeight

func (b *Blockchain) GetBlockByHeight(height uint64) (*flowgo.Block, error)

GetBlockByHeight gets a block by height.

func (*Blockchain) GetBlockByID

func (b *Blockchain) GetBlockByID(id flowgo.Identifier) (*flowgo.Block, error)

GetBlockByID gets a block by ID.

func (*Blockchain) GetChain

func (b *Blockchain) GetChain() flowgo.Chain

func (*Blockchain) GetCollectionByID

func (b *Blockchain) GetCollectionByID(colID flowgo.Identifier) (*flowgo.LightCollection, error)

func (*Blockchain) GetEventsByHeight

func (b *Blockchain) GetEventsByHeight(blockHeight uint64, eventType string) ([]flowgo.Event, error)

GetEventsByHeight returns the events in the block at the given height, optionally filtered by type.

func (*Blockchain) GetEventsForBlockIDs

func (b *Blockchain) GetEventsForBlockIDs(eventType string, blockIDs []flowgo.Identifier) (result []flowgo.BlockEvents, err error)

func (*Blockchain) GetEventsForHeightRange

func (b *Blockchain) GetEventsForHeightRange(eventType string, startHeight, endHeight uint64) (result []flowgo.BlockEvents, err error)

func (*Blockchain) GetLatestBlock

func (b *Blockchain) GetLatestBlock() (*flowgo.Block, error)

GetLatestBlock gets the latest sealed block.

func (*Blockchain) GetLogs added in v0.53.0

func (b *Blockchain) GetLogs(identifier flowgo.Identifier) ([]string, error)

func (*Blockchain) GetNetworkParameters

func (b *Blockchain) GetNetworkParameters() access.NetworkParameters

func (*Blockchain) GetSourceFile added in v0.54.0

func (b *Blockchain) GetSourceFile(location common.Location) string

func (*Blockchain) GetTransaction

func (b *Blockchain) GetTransaction(txID flowgo.Identifier) (*flowgo.TransactionBody, error)

GetTransaction gets an existing transaction by ID.

The function first looks in the pending block, then the current emulator state.

func (*Blockchain) GetTransactionResult

func (b *Blockchain) GetTransactionResult(txID flowgo.Identifier) (*access.TransactionResult, error)

func (*Blockchain) GetTransactionResultsByBlockID

func (b *Blockchain) GetTransactionResultsByBlockID(blockID flowgo.Identifier) ([]*access.TransactionResult, error)

func (*Blockchain) GetTransactionsByBlockID

func (b *Blockchain) GetTransactionsByBlockID(blockID flowgo.Identifier) ([]*flowgo.TransactionBody, error)

func (*Blockchain) LoadSnapshot

func (b *Blockchain) LoadSnapshot(name string) error

func (*Blockchain) NewScriptEnvironment added in v0.56.0

func (b *Blockchain) NewScriptEnvironment() environment.Environment

NewScriptEnvironment returns an environment.Environment by using as a storage snapshot the blockchain's ledger state. Useful for tools that use the emulator's blockchain as a library.

func (*Blockchain) PendingBlockID

func (b *Blockchain) PendingBlockID() flowgo.Identifier

PendingBlockID returns the ID of the pending block.

func (*Blockchain) PendingBlockTimestamp

func (b *Blockchain) PendingBlockTimestamp() time.Time

PendingBlockTimestamp returns the Timestamp of the pending block.

func (*Blockchain) PendingBlockView

func (b *Blockchain) PendingBlockView() uint64

PendingBlockView returns the view of the pending block.

func (*Blockchain) Ping

func (b *Blockchain) Ping() error

func (*Blockchain) ReloadBlockchain

func (b *Blockchain) ReloadBlockchain() error

func (*Blockchain) ResetCoverageReport

func (b *Blockchain) ResetCoverageReport()

func (*Blockchain) ResetPendingBlock

func (b *Blockchain) ResetPendingBlock() error

ResetPendingBlock clears the transactions in pending block.

func (*Blockchain) RollbackToBlockHeight

func (b *Blockchain) RollbackToBlockHeight(height uint64) error

func (*Blockchain) SendTransaction

func (b *Blockchain) SendTransaction(flowTx *flowgo.TransactionBody) error

SendTransaction submits a transaction to the network.

func (*Blockchain) ServiceKey

func (b *Blockchain) ServiceKey() ServiceKey

ServiceKey returns the service private key for this emulator.

func (*Blockchain) SetClock added in v0.53.0

func (b *Blockchain) SetClock(clock Clock)

SetClock sets the given clock on blockchain's pending block. After this block is committed, the block timestamp will contain the value of clock.Now().

func (*Blockchain) Snapshots

func (b *Blockchain) Snapshots() ([]string, error)

func (*Blockchain) StartDebugger

func (b *Blockchain) StartDebugger() *interpreter.Debugger

type BlocksTicker

type BlocksTicker struct {
	// contains filtered or unexported fields
}

func NewBlocksTicker

func NewBlocksTicker(
	emulator Emulator,
	blockTime time.Duration,
) *BlocksTicker

func (*BlocksTicker) Start

func (t *BlocksTicker) Start() error

func (*BlocksTicker) Stop

func (t *BlocksTicker) Stop()

type CadenceHook

type CadenceHook struct {
	MainLogger *zerolog.Logger
}

func (CadenceHook) Run

func (h CadenceHook) Run(_ *zerolog.Event, level zerolog.Level, msg string)

type Clock added in v0.53.0

type Clock interface {
	Now() time.Time
}

type ContractDescription

type ContractDescription struct {
	Name        string
	Address     flowsdk.Address
	Description string
	Source      []byte
}

func NewCommonContracts added in v0.51.0

func NewCommonContracts(chain flowgo.Chain) []ContractDescription

type CoverageReportCapable

type CoverageReportCapable interface {
	CoverageReport() *runtime.CoverageReport
	ResetCoverageReport()
}

type CoverageReportedRuntime added in v0.50.1

type CoverageReportedRuntime struct {
	runtime.Runtime
	runtime.Environment
	*runtime.CoverageReport
}

func (CoverageReportedRuntime) ExecuteScript added in v0.50.1

func (crr CoverageReportedRuntime) ExecuteScript(
	script runtime.Script,
	context runtime.Context,
) (
	cadence.Value,
	error,
)

func (CoverageReportedRuntime) ExecuteTransaction added in v0.50.1

func (crr CoverageReportedRuntime) ExecuteTransaction(
	script runtime.Script,
	context runtime.Context,
) error

func (CoverageReportedRuntime) InvokeContractFunction added in v0.50.1

func (crr CoverageReportedRuntime) InvokeContractFunction(
	contractLocation common.AddressLocation,
	functionName string,
	arguments []cadence.Value,
	argumentTypes []sema.Type,
	context runtime.Context,
) (
	cadence.Value,
	error,
)

func (CoverageReportedRuntime) NewContractFunctionExecutor added in v0.50.1

func (crr CoverageReportedRuntime) NewContractFunctionExecutor(
	contractLocation common.AddressLocation,
	functionName string,
	arguments []cadence.Value,
	argumentTypes []sema.Type,
	context runtime.Context,
) runtime.Executor

func (CoverageReportedRuntime) NewScriptExecutor added in v0.50.1

func (crr CoverageReportedRuntime) NewScriptExecutor(
	script runtime.Script,
	context runtime.Context,
) runtime.Executor

func (CoverageReportedRuntime) NewTransactionExecutor added in v0.50.1

func (crr CoverageReportedRuntime) NewTransactionExecutor(
	script runtime.Script,
	context runtime.Context,
) runtime.Executor

func (CoverageReportedRuntime) ParseAndCheckProgram added in v0.50.1

func (crr CoverageReportedRuntime) ParseAndCheckProgram(
	source []byte,
	context runtime.Context,
) (
	*interpreter.Program,
	error,
)

func (CoverageReportedRuntime) ReadLinked added in v0.50.1

func (crr CoverageReportedRuntime) ReadLinked(
	address common.Address,
	path cadence.Path,
	context runtime.Context,
) (
	cadence.Value,
	error,
)

func (CoverageReportedRuntime) ReadStored added in v0.50.1

func (crr CoverageReportedRuntime) ReadStored(
	address common.Address,
	path cadence.Path,
	context runtime.Context,
) (
	cadence.Value,
	error,
)

func (CoverageReportedRuntime) Storage added in v0.50.1

type DebuggingCapable

type DebuggingCapable interface {
	StartDebugger() *interpreter.Debugger
	EndDebugging()
	// Deprecated: Needed for the debugger right now, do NOT use for other purposes.
	// TODO: refactor
	GetAccountUnsafe(address flowgo.Address) (*flowgo.Account, error)
}

type Emulator

Emulator defines the method set of an emulated emulator.

type ExecutionCapable

type ExecutionCapable interface {
	ExecuteAndCommitBlock() (*flowgo.Block, []*types.TransactionResult, error)
	ExecuteNextTransaction() (*types.TransactionResult, error)
	ExecuteBlock() ([]*types.TransactionResult, error)
	CommitBlock() (*flowgo.Block, error)
}

type IndexedTransactionResult

type IndexedTransactionResult struct {
	fvm.ProcedureOutput
	Index uint32
}

type LogProvider added in v0.53.0

type LogProvider interface {
	GetLogs(flowgo.Identifier) ([]string, error)
}

type Option

type Option func(*config)

Option is a function applying a change to the emulator config.

func Contracts

func Contracts(contracts []ContractDescription) Option

Contracts allows users to deploy the given contracts. Some default common contracts are pre-configured in the `CommonContracts` global variable. It includes contracts such as: NonFungibleToken, MetadataViews, NFTStorefront, NFTStorefrontV2, ExampleNFT The default value is []ContractDescription{}.

func WithChainID

func WithChainID(chainID flowgo.ChainID) Option

WithChainID sets chain type for address generation The default is emulator.

func WithContractRemovalEnabled

func WithContractRemovalEnabled(enabled bool) Option

WithContractRemovalEnabled restricts/allows removal of already deployed contracts.

The default is provided by on-chain value.

func WithCoverageReport

func WithCoverageReport(coverageReport *runtime.CoverageReport) Option

WithCoverageReport injects a CoverageReport to collect coverage information.

The default is nil.

func WithEVMEnabled added in v0.58.0

func WithEVMEnabled(enabled bool) Option

WithEVMEnabled enables/disables evm.

func WithGenesisTokenSupply

func WithGenesisTokenSupply(supply cadence.UFix64) Option

WithGenesisTokenSupply sets the genesis token supply.

func WithLogger

func WithLogger(
	logger zerolog.Logger,
) Option

WithLogger sets the fvm logger

func WithMinimumStorageReservation

func WithMinimumStorageReservation(minimumStorageReservation cadence.UFix64) Option

WithMinimumStorageReservation sets the minimum account balance.

The cost of creating new accounts is also set to this value. The default is taken from fvm.DefaultMinimumStorageReservation

func WithScriptGasLimit

func WithScriptGasLimit(limit uint64) Option

WithScriptGasLimit sets the gas limit for scripts.

This limit does not affect transactions, which declare their own limit. Use WithTransactionMaxGasLimit to set the maximum gas limit for transactions.

func WithServerLogger

func WithServerLogger(
	logger zerolog.Logger,
) Option

WithServerLogger sets the logger

func WithServicePrivateKey

func WithServicePrivateKey(
	privateKey sdkcrypto.PrivateKey,
	sigAlgo sdkcrypto.SignatureAlgorithm,
	hashAlgo sdkcrypto.HashAlgorithm,
) Option

WithServicePrivateKey sets the service key from private key.

func WithServicePublicKey

func WithServicePublicKey(
	servicePublicKey sdkcrypto.PublicKey,
	sigAlgo sdkcrypto.SignatureAlgorithm,
	hashAlgo sdkcrypto.HashAlgorithm,
) Option

WithServicePublicKey sets the service key from a public key.

func WithSimpleAddresses

func WithSimpleAddresses() Option

WithSimpleAddresses enables simple addresses, which are sequential starting with 0x01.

func WithStorageLimitEnabled

func WithStorageLimitEnabled(enabled bool) Option

WithStorageLimitEnabled enables/disables limiting account storage used to their storage capacity.

If set to false, accounts can store any amount of data, otherwise they can only store as much as their storage capacity. The default is true.

func WithStorageMBPerFLOW

func WithStorageMBPerFLOW(storageMBPerFLOW cadence.UFix64) Option

WithStorageMBPerFLOW sets the cost of a megabyte of storage in FLOW

the default is taken from fvm.DefaultStorageMBPerFLOW

func WithStore

func WithStore(store storage.Store) Option

WithStore sets the persistent storage provider.

func WithTransactionExpiry

func WithTransactionExpiry(expiry uint) Option

WithTransactionExpiry sets the transaction expiry measured in blocks.

If set to zero, transaction expiry is disabled and the reference block ID field is not required.

func WithTransactionFeesEnabled

func WithTransactionFeesEnabled(enabled bool) Option

WithTransactionFeesEnabled enables/disables transaction fees.

If set to false transactions don't cost any flow. The default is false.

func WithTransactionMaxGasLimit

func WithTransactionMaxGasLimit(maxLimit uint64) Option

WithTransactionMaxGasLimit sets the maximum gas limit for transactions.

Individual transactions will still be bounded by the limit they declare. This function sets the maximum limit that any transaction can declare.

This limit does not affect script executions. Use WithScriptGasLimit to set the gas limit for script executions.

func WithTransactionValidationEnabled

func WithTransactionValidationEnabled(enabled bool) Option

WithTransactionValidationEnabled enables/disables transaction validation.

If set to false, the emulator will not verify transaction signatures or validate sequence numbers.

The default is true.

type Pragma added in v0.54.0

type Pragma interface {
	Name() string
	Argument() string
}

type PragmaList added in v0.54.0

type PragmaList []Pragma

func ExtractPragmas added in v0.54.0

func ExtractPragmas(code string) (result PragmaList)

func (PragmaList) Contains added in v0.54.0

func (l PragmaList) Contains(name string) bool

func (PragmaList) Count added in v0.54.0

func (l PragmaList) Count(name string) int

func (PragmaList) FilterByName added in v0.54.0

func (l PragmaList) FilterByName(name string) (result PragmaList)

func (PragmaList) First added in v0.54.0

func (l PragmaList) First() Pragma

type RollbackCapable

type RollbackCapable interface {
	RollbackToBlockHeight(height uint64) error
}

type ServiceKey

type ServiceKey struct {
	Index          int
	Address        flowgosdk.Address
	SequenceNumber uint64
	PrivateKey     sdkcrypto.PrivateKey
	PublicKey      sdkcrypto.PublicKey
	HashAlgo       sdkcrypto.HashAlgorithm
	SigAlgo        sdkcrypto.SignatureAlgorithm
	Weight         int
}

func DefaultServiceKey

func DefaultServiceKey() ServiceKey

func GenerateDefaultServiceKey

func GenerateDefaultServiceKey(
	sigAlgo sdkcrypto.SignatureAlgorithm,
	hashAlgo sdkcrypto.HashAlgorithm,
) ServiceKey

func (ServiceKey) AccountKey

func (s ServiceKey) AccountKey() *flowgosdk.AccountKey

func (ServiceKey) Signer

func (s ServiceKey) Signer() (sdkcrypto.Signer, error)

type SnapshotCapable

type SnapshotCapable interface {
	Snapshots() ([]string, error)
	CreateSnapshot(name string) error
	LoadSnapshot(name string) error
}

type SourceMapCapable added in v0.54.0

type SourceMapCapable interface {
	GetSourceFile(location common.Location) string
}

type SystemClock added in v0.53.0

type SystemClock struct{}

func NewSystemClock added in v0.53.0

func NewSystemClock() SystemClock

func (SystemClock) Now added in v0.53.0

func (sc SystemClock) Now() time.Time

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL