Flow Cadence Utilities API Reference
Imports
Arguments
Name Type Description code
string Cadence template code
Returns
Type Description object
contract name as key and import address as value
Usage
import { extractImports } from ' @onflow/flow-cadut ' ;
import Utilities from 0x02
Utilities.log(Message.hello)
const imports = extractImports ( code ) ;
* Line above shall show the following:
missingImports(code, addressMap)
Given Cadence code template and addressMap, returns an array of missing contract imports
Arguments
Name Type Description code
string Cadence template code addressMap
AddressMap addressMap for provided template
Returns
Type Description array
array strings, representing names of missing contract imports
Usage
import { missingImports } from ' @onflow/flow-cadut ' ;
import Utilities from 0x02
Utilities.log(Message.hello)
const missing = missingImports ( code , {} ) ;
console . log ( { missing } ) ;
report(list, prefix)
Reports missing imports via console.error
with format:
[prefix] Missing Imports for contracts: [ Contract_1, Contract_2 ]
Arguments
Name Type Optional Description list
array list of missing contract imports prefix
string ✅ Default: ""
Usage
import { missingImports , report } from ' @onflow/flow-cadut ' ;
const list = missingImports ( code , {} ) ;
reportMissingImports(code, addressMap, prefix)
Checks and reports missing contracts by matching code and addressMap in format:
[prefix] Missing Imports for contracts: [ Contract_1, Contract_2 ]
Arguments
Name Type Optional Description code
string Cadence template code to check addressMap
AddressMap ✅ addressMap for imported contracts. Default: {}
prefix
string ✅ message prefix. Default: ""
Usage
import { missingImports , report } from ' @onflow/flow-cadut ' ;
reportMissingImports ( code ) ;
replaceImportAddresses(code, addressMap)
Replaces import statements in provided Cadence templates with corresponding values from addressMap
Arguments
Name Type Description code
string Cadence template code addressMap
AddressMap AddressMap to use map contract names to addresses
Returns
Type Description string Updated template with replaced addresses
Usage
import { replaceImportAddresses } from ' @onflow/flow-cadut ' ;
import Messages from 0x01
Message : ' 0xf8d6e0586b0a20c7 ',
const replaced = replaceImportAddresses ( code , addressMap ) ;
console . log ( { replaced } ) ;
Arguments
mapArgument(type, value)
Converts provided value to sdk
argument.
📣 Best usage of this method is with combination of query
/mutate
methods from Javascript SDK.
Arguments
Name Type Description type
string Cadence type represented as string value
any correspondent value to use for conversion
Returns
Usage
import { query , config } from ' @onflow/fcl ' ;
import { mapArgument } from ' @onflow/flow-cadut ' ;
config () . put ( ' accessNode.api ', ' https://rest-testnet.onflow.org ' ) ;
pub fun main(message: String): String{
// Script expects a single argument of type "String"
const message = mapArgument ( ' String ', ' Hello from Cadence! ' ) ;
// "args" shall return array of arguments.
// We will pass "message" value into it
const args = () => [ message ] ;
const result = await query ( { cadence , args } ) ;
mapArguments(schema, values)
Converts provided values to sdk
arguments.
📣 Best usage of this method is with combination of query
/mutate
methods from Javascript SDK.
Arguments
Name Type Description schema
array[string] Array of Cadence types represented as string values
array[any] array of correspondent values to use for conversion
Returns
Type Description array[Argument ] array of sdk
arguments
Usage
import { query , config } from ' @onflow/fcl ' ;
import { mapArgument } from ' @onflow/flow-cadut ' ;
config () . put ( ' accessNode.api ', ' https://rest-testnet.onflow.org ' ) ;
pub fun main(message: String, amount: Int): Int{
// Script expects multiple arguments - "String" and "Int"
const schema = [ ' String ', ' Int ' ] ;
// These are the values we will convert to arguments
const values = [ ' Hello from Cadence ', 1337 ] ;
// mapArguments will return an array, no extra steps are required
const args = () => mapArguments ( schema , values ) ;
const result = await query ( { cadence , args } ) ;
mapValuesToCode(code, values)
This method will extract argument types from provided Cadence code and then converts
values to corresponding types, preparing them to be passed into sdk.send
📣 Best usage of this method is with combination of query
/mutate
methods from Javascript SDK.
Arguments
Name Type Description code
string Cadence template code values
array array of values to process
Returns
Type Description array array of sdk
arguments
Throws
This method will throw an error if user would fail to provide required amount of arguments
import { query , config } from ' @onflow/fcl ' ;
import { mapValuesToCode } from ' @onflow/flow-cadut ' ;
config () . put ( ' accessNode.api ', ' https://rest-testnet.onflow.org ' ) ;
pub fun main(metadata: {String:String}, key: String):String {
const result = await query ( {
mapValuesToCode ( cadence , [
{ language : ' Cadence ', languageRating : ' Cadence is Awesome 🤟 ' },
Parser
getTemplateInfo(code)
Parses the code and returns TemplateInfo
Arguments
Name Type Description code
string Cadence template code to process
Usage
import { getTemplateInfo } from ' @onflow/flow-cadut ' ;
pub fun main(message:String):String{
const info = getTemplateInfo ( script ) ;
* "info" will contain an object:
* args: [ 'message:String' ]
Parses the code and returns array of SignerPair
Arguments
Name Type Description code
string Cadence template code to process
Returns
Type Description SignerPair String representation of signer pair
Usage
import { extractSigners } from ' @onflow/flow-cadut ' ;
log("nothing to see here :)")
const signers = extractSigners ( script ) ;
console . log ( { signers } ) ;
Parses the code and returns array of ArgumentPair
Arguments
Name Type Description code
string Cadence template code to process
Returns
Type Description ArgumentPair String representation of argument pair
Usage
import { extractScriptArguments } from ' @onflow/flow-cadut ' ;
pub fun main(message: String, metadata: {String:String}){
const args = extractScriptArguments ( script ) ;
Parses the code and returns array of ArgumentPair
Arguments
Name Type Description code
string Cadence template code to process
Returns
Type Description ArgumentPair String representation of argument pair
Usage
import { extractTransactionArguments } from ' @onflow/flow-cadut ' ;
transaction(message: String, metadata: {String:String}){
prepare(signer:AuthAccount){
const args = extractTransactionArguments ( tx ) ;
Parses the code and returns contract name
Arguments
Name Type Description code
string Cadence template code to process
Returns
Type Description string name of the contract defined in template code
Usage
import { extractContractName } from ' @onflow/flow-cadut ' ;
const name = extractContractName ( contract ) ;
splitArgs(pair)
Splits ArgumentPair into array of two items
Arguments
Name Type Description pair
ArgumentPair argument pair in form of a string
Returns
Type Description array first item is a name, second - string representation of type
Usage
import { splitArgs } from ' @onflow/flow-cadut ' ;
const simplePair = ' message:String ' ;
const metaPair = ' metadata: {String:String} ' ;
const simple = splitArgs ( simplePair ) ;
const meta = splitArgs ( metaPair ) ;
console . log ( { simple , meta } ) ;
argType(pair)
Splits ArgumentPair and returns type of the argument
Arguments
Name Type Description `pair ArgumentPair argument pair in form of a string
Returns
Type Description string string representation of argument type
Usage
import { argType } from ' @onflow/flow-cadut ' ;
const simplePair = ' message:String ' ;
const metaPair = ' metadata: {String:String} ' ;
const simple = argType ( simplePair ) ;
const meta = argType ( metaPair ) ;
console . log ( { simple , meta } ) ;
getArrayType(type)
Extracts item type from array type
Arguments
Name Type Description type
string string representation of Array type
Returns
Type Description string string representation of item type
Usage
import { getArrayType } from ' @onflow/flow-cadut ' ;
const simpleType = getArrayType ( ' [String] ' ) ;
const complexType = getArrayType ( ' [{String: String}] ' ) ;
console . log ( { simpleType , complexType } ) ;
getDictionaryTypes(type)
Extracts key and value types from Dictionary type
Arguments
Name Type Description type
string string representation of Dictionary type
Returns
Type Description array array of strings - first item for the key
type, second for the value
type
Usage
import { getDictionaryTypes } from ' @onflow/flow-cadut ' ;
const type = ' {String: UFix64} ' ;
const types = getDictionaryTypes ( type ) ;
const [ keyType , valueType ] = types ;
console . log ( { keyType , valueType } ) ;
Generator
Recursively goes through input
folder and generates code for found contracts, transactions and scripts.
Write files under output
path.
Arguments
Name Type Optional Description input
string path to the input folder output
string path to output folder options
object ✅ additional options. Default: {}
Options
Name Type Optional Description dependency
string ✅ interactions dependency. Default: flow-cadut
Usage
import { processFolder } from ' @onflow/flow-cadut ' ;
const input = path . resolve ( ' ./cadence ' ) ;
const output = path . resolve ( ' ./src/generated/localRegistry ' ) ;
await processFolder ( input , output ) ;
processGitRepo(url, output, branch, options)
Fetches GitHub repository from provided url
and branch
. Then generates code for found contracts, transactions and scripts.
Write files under output
path.
Arguments
Name Type Optional Description url
string url to GitHub repo output
string path to output folder branch
string ✅ branch to use. Default: main
options
object ✅ additional options. Default: {}
Options
Name Type Optional Description dependency
string ✅ interactions dependency. Default: flow-cadut
Usage
import { processGitRepo } from ' @onflow/flow-cadut ' ;
const url = path . resolve ( ' https://github.com/onflow/flow-core-contracts ' ) ;
const output = path . resolve ( ' ./src/generated/localRegistry ' ) ;
await processGitRepo ( url , output ) ;
Interactions
setEnvironment(network, options)
Sets flow.network
config value
Arguments
Name Type Optional Description network
string ✅ network to use. Default: emulator
options
object ✅ extra options to adjust config
Network Variants
Options
Name Type Optional Description options.port
number ✅ port for emulator. Default: 8080
options.endpoint
string ✅ Access API endpoint.
⚠️ Attention: endpoint
will override port
and provided network
. Don't mix endpoint from different network
- it might lead to unexpected result.
Usage
import { setEnvironment } from ' @onflow/flow-cadut ' ;
await setEnvironment ( ' testnet ' ) ;
getEnvironment()
Returns a set of deployed contracts for current environment
Returns
Type Description object AddressMap for known contracts deployed in current environment
Usage
import { setEnvironment , getEnvironment } from ' @onflow/flow-cadut ' ;
await setEnvironment ( ' mainnet ' ) ;
const addressMap = await getEnvironment () ;
console . log ( { addressMap } ) ;
hexContract(code)
Prepares Cadence template code to pass into deployment transaction.
Syntax sugar for Buffer.from(code, "utf8").toString("hex");
Arguments
Name Type Description code
string Cadence template code
Returns
Type Description string hex representation of template code
Usage
import { hexContract } from ' @onflow/flow-cadut ' ;
const hexed = hexContract ( code ) ;
executeScript(args)
Sends script to the network
Arguments
Returns
ScriptArguments
Name Type Optional Description code
string Cadence code to execute args
arrayInteractionArgument ✅ Optional if script does not expect arguments. Default: []
addressMap
AddressMap ✅ address map to use for import replacement. Default: {}
limit
number ✅ gas limit. Default: 100
ScriptResult
Script result is represented as a tuple [result, error]
Name Type Description result
any result of script execution. Type of this value depends on script return value error
error Caught error. This will be null
if script executed successfully
Usage
import { executeScript } from ' @onflow/flow-cadut ' ;
const [ result , err ] = executeScript ( { code } ) ;
Alias
This method is also available under alias query
sendTransaction
Sends script to the network
Arguments
Name Type Optional Description args
TransactionArguments transaction arguments waitForExecution
boolean ✅ wait for transaction execution or not
If waitForExecution
flag is set to true, method will not return result until fcl.tx(hash).onceExecuted()
is resolved
Returns
TransactionArguments
Name Type Optional Description code
string Cadence code to execute payer
AuthorizationFunction The authorization function that returns a valid AuthorizationObject for the payer role. signers
[AuthorizationFunction] ✅ an array of AuthorizationObject representing transaction authorizers. Default: same as payer
proposer
AuthorizationFunction ✅ The authorization function that returns a valid AuthorizationObject for the proposer role. Default: same as payer
args
[Any] ✅ Optional if transactions does not expect arguments. Default: []
addressMap
AddressMap ✅ address map to use for import replacement. Default: {}
limit
number ✅ gas limit. Default: 100
When being used in the browser, you can pass built-in fcl.authz
function to produce the authorization (signatures) for the current user.
When calling this method from Node.js, you will need to supply your own custom authorization functions.
TransactionResult
Transaction result is represented as a tuple [result, error]
Name Type Description ResponseObject any result of transaction execution. Type of this value depends on script return value error
error Caught error. This will be null
if script executed successfully
Usage
import { authenticate , currentUser , authz , config } from ' @onflow/fcl ' ;
import { sendTransaction } from ' @onflow/flow-cadut ' ;
. put ( ' accessNode.api ', ' https://rest-testnet.onflow.org ' ) // Configure FCL's Access Node
. put ( ' challenge.handshake ', ' https://fcl-discovery.onflow.org/testnet/authn ' ) // Configure FCL's Wallet Discovery mechanism
. put ( ' 0xProfile ', ' 0xba1132bc08f82fe2 ' ) ; // Will let us use `0xProfile` in our Cadence
currentUser () . subscribe ( async ( user ) => {
prepare(currentUser: AuthAccount) {
const [ result ] = await sendTransaction ( { code , payer : authz } ) ;
Alias
This method is also available under alias mutate