Execute Scripts

How to execute scripts

It is often the case that you need to query current state of the network. For example, to check balance of the account, read public value of the contract or ensure that user has specific resource in their storage.

We abstract this interaction into single method called executeScript. Method have 2 different signatures.

⚠️ Required: Your project must follow the required structure it must be initialized to use the following functions.

executeScript(props)

Provides explicit control over how you pass values.

Arguments

props object accepts following fields:

NameTypeOptionalDescription
codestringstring representation of Cadence script
namestringname of the file in scripts folder to use (sans .cdc extension)
args[any]an array of arguments to pass to script. Optional if script does not expect any arguments.
transformers[CadenceTransformer]an array of operators to modify the code, before submitting it to network

⚠️ Required: Either code or name field shall be specified. Method will throw an error if both of them are empty. If name field provided, framework will source code from file and override value passed via code field.

Returns

TypeDescription
ResponseObjectScript result

Usage

1
import path from "path"
2
import {init, emulator, executeScript} from "@onflow/flow-js-testing"
3
4
const main = async () => {
5
const basePath = path.resolve(__dirname, "../cadence")
6
7
// Init framework
8
init(basePath)
9
// Start emulator
10
await emulator.start()
11
12
// Define code and arguments we want to pass
13
const code = `
14
pub fun main(message: String): Int{
15
log(message)
16
17
return 42
18
}
19
`
20
const args = ["Hello, from Cadence"]
21
22
const [result, error, logs] = await executeScript({code, args})
23
console.log({result}, {error}, {logs})
24
25
// Stop emulator instance
26
await emulator.stop()
27
}
28
29
main()

executeScript(name: string, args: [any])

This signature provides simplified way of executing a script, since most of the time you will utilize existing Cadence files.

Arguments

NameTypeOptionalDescription
namestringname of the file in scripts folder to use (sans .cdc extension)
args[any]an array of arguments to pass to script. Optional if scripts don't expect any arguments. Default: []

Returns

TypeDescription
ResponseObjectScript result

Usage

1
import path from "path"
2
import {init, emulator, executeScript} from "@onflow/flow-js-testing"
3
4
const main = async () => {
5
const basePath = path.resolve(__dirname, "../cadence")
6
7
// Init framework
8
init(basePath)
9
// Start emulator
10
await emulator.start()
11
12
// Define arguments we want to pass
13
const args = ["Hello, from Cadence"]
14
15
// We assume there is a file `scripts/log-message.cdc` under base path
16
const [result, error, logs] = await executeScript("log-message", args)
17
console.log({result}, {error}, {logs})
18
19
await emulator.stop()
20
}
21
22
main()