Scripts
Scripts let you run non-permanent Cadence scripts on the Flow blockchain. They can return data.
They always need to contain a access(all) fun main()
function as an entry point to the script.
fcl.query
is a function that sends Cadence scripts to the chain and receives back decoded responses.
The cadence
key inside the object sent to the query
function is a JavaScript Tagged Template Literal that we can pass Cadence code into.
Sending your first Script
In the following code snippet we are going to send a script to the Flow blockchain. The script is going to add two numbers, and return them.
_11import * as fcl from "@onflow/fcl"_11_11const response = await fcl.query({_11 cadence: `_11 access(all) fun main(): Int {_11 return 1 + 2_11 }_11 `_11})_11_11console.log(response) // 3
A more complicated Script
Things like Resources and Structs are fairly common place in Cadence.
In the following code snippet, our script defines a struct called Point
, it then returns a list of them.
The closest thing to a Structure in JavaScript is an object. In this case when we decode this response, we would be expecting to get back an array of objects, where the objects have an x
and y
value.
_21import * as fcl from "@onflow/fcl"_21_21const response = await fcl.query({_21 cadence: `_21 access(all) struct Point {_21 access(all) var x: Int_21 access(all) var y: Int_21_21 init(x: Int, y: Int) {_21 self.x = x_21 self.y = y_21 }_21 }_21_21 access(all) fun main(): [Point] {_21 return [Point(x: 1, y: 1), Point(x: 2, y: 2)]_21 }_21 `_21})_21_21console.log(response) // [{x:1, y:1}, {x:2, y:2}]
Transforming the data we get back with custom decoders.
In our dapp, we probably have a way of representing these Cadence values internally. In the above example it might be a Point
class.
FCL enables us to provide custom decoders that we can use to transform the data we receive from the Flow blockchain at the edge, before anything else in our dapp gets a chance to look at it.
We add these custom decoders by Configuring FCL. This lets us set it once when our dapp starts up and use our normalized data through out the rest of our dapp.
In the below example we will use the concept of a Point
again, but this time, we will add a custom decoder, that enables fcl.decode
to transform it into a custom JavaScript Point
class.
_31import * as fcl from "@onflow/fcl"_31_31class Point {_31 constructor({ x, y }) {_31 this.x = x_31 this.y = y_31 }_31}_31_31fcl.config()_31 .put("decoder.Point", point => new Point(point))_31_31const response = await fcl.query({_31 cadence: `_31 access(all) struct Point {_31 access(all) var x: Int_31 access(all) var y: Int_31_31 init(x: Int, y: Int) {_31 self.x = x_31 self.y = y_31 }_31 }_31_31 access(all) fun main(): [Point] {_31 return [Point(x: 1, y: 1), Point(x: 2, y: 2)]_31 }_31 `_31})_31_31console.log(response) // [Point{x:1, y:1}, Point{x:2, y:2}]
To learn more about query
, check out the API documentation.