Skip to main content

Flow Cadence Utilities API Reference

Imports

extractImports(code)

Arguments

NameTypeDescription
codestringCadence template code

Returns

TypeDescription
objectcontract name as key and import address as value

Usage


_20
import { extractImports } from '@onflow/flow-cadut';
_20
_20
const code = `
_20
import Message from 0x01
_20
import Utilities from 0x02
_20
_20
pub fun main(){
_20
Utilities.log(Message.hello)
_20
}
_20
`;
_20
const imports = extractImports(code);
_20
_20
console.log(imports);
_20
/*
_20
* Line above shall show the following:
_20
* {
_20
* "Message": "0x01",
_20
* "Utilities": "0x02"
_20
* }
_20
* */

missingImports(code, addressMap)

Given Cadence code template and addressMap, returns an array of missing contract imports

Arguments

NameTypeDescription
codestringCadence template code
addressMapAddressMapaddressMap for provided template

Returns

TypeDescription
arrayarray strings, representing names of missing contract imports

Usage


_13
import { missingImports } from '@onflow/flow-cadut';
_13
_13
const code = `
_13
import Message from 0x01
_13
import Utilities from 0x02
_13
_13
pub fun main(){
_13
Utilities.log(Message.hello)
_13
}
_13
`;
_13
_13
const missing = missingImports(code, {});
_13
console.log({ missing });

report(list, prefix)

Reports missing imports via console.error with format:


_10
[prefix] Missing Imports for contracts: [ Contract_1, Contract_2 ]

Arguments

NameTypeOptionalDescription
listarraylist of missing contract imports
prefixstringDefault: ""

Usage


_10
import { missingImports, report } from '@onflow/flow-cadut';
_10
const code = `
_10
import Message from 0x01
_10
_10
pub fun main(){}
_10
`;
_10
const list = missingImports(code, {});
_10
report(list);

reportMissingImports(code, addressMap, prefix)

Checks and reports missing contracts by matching code and addressMap in format:


_10
[prefix] Missing Imports for contracts: [ Contract_1, Contract_2 ]

Arguments

NameTypeOptionalDescription
codestringCadence template code to check
addressMapAddressMapaddressMap for imported contracts. Default: {}
prefixstringmessage prefix. Default: ""

Usage


_10
import { missingImports, report } from '@onflow/flow-cadut';
_10
_10
const code = `
_10
import Message from 0x01
_10
_10
pub fun main(){}
_10
`;
_10
_10
reportMissingImports(code);

replaceImportAddresses(code, addressMap)

Replaces import statements in provided Cadence templates with corresponding values from addressMap

Arguments

NameTypeDescription
codestringCadence template code
addressMapAddressMapAddressMap to use map contract names to addresses

Returns

TypeDescription
stringUpdated template with replaced addresses

Usage


_12
import { replaceImportAddresses } from '@onflow/flow-cadut';
_12
_12
const code = `
_12
import Messages from 0x01
_12
_12
pub fun main(){}
_12
`;
_12
const addressMap = {
_12
Message: '0xf8d6e0586b0a20c7',
_12
};
_12
const replaced = replaceImportAddresses(code, addressMap);
_12
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

NameTypeDescription
typestringCadence type represented as string
valueanycorrespondent value to use for conversion

Returns

TypeDescription
Argumentsdk argument

Usage


_22
import { query, config } from '@onflow/fcl';
_22
import { mapArgument } from '@onflow/flow-cadut';
_22
_22
(async () => {
_22
config().put('accessNode.api', 'https://rest-testnet.onflow.org');
_22
_22
const cadence = `
_22
pub fun main(message: String): String{
_22
return message
_22
}
_22
`;
_22
_22
// Script expects a single argument of type "String"
_22
const message = mapArgument('String', 'Hello from Cadence!');
_22
_22
// "args" shall return array of arguments.
_22
// We will pass "message" value into it
_22
const args = () => [message];
_22
_22
const result = await query({ cadence, args });
_22
console.log(result);
_22
})();

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

NameTypeDescription
schemaarray[string]Array of Cadence types represented as string
valuesarray[any]array of correspondent values to use for conversion

Returns

TypeDescription
array[Argument]array of sdk arguments

Usage


_23
import { query, config } from '@onflow/fcl';
_23
import { mapArgument } from '@onflow/flow-cadut';
_23
_23
(async () => {
_23
config().put('accessNode.api', 'https://rest-testnet.onflow.org');
_23
_23
const cadence = `
_23
pub fun main(message: String, amount: Int): Int{
_23
log(message)
_23
return amount
_23
}
_23
`;
_23
_23
// Script expects multiple arguments - "String" and "Int"
_23
const schema = ['String', 'Int'];
_23
// These are the values we will convert to arguments
_23
const values = ['Hello from Cadence', 1337];
_23
// mapArguments will return an array, no extra steps are required
_23
const args = () => mapArguments(schema, values);
_23
_23
const result = await query({ cadence, args });
_23
console.log(result);
_23
})();

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

NameTypeDescription
codestringCadence template code
valuesarrayarray of values to process

Returns

TypeDescription
arrayarray of sdk arguments

Throws

This method will throw an error if user would fail to provide required amount of arguments


_23
import { query, config } from '@onflow/fcl';
_23
import { mapValuesToCode } from '@onflow/flow-cadut';
_23
_23
(async () => {
_23
config().put('accessNode.api', 'https://rest-testnet.onflow.org');
_23
_23
const cadence = `
_23
pub fun main(metadata: {String:String}, key: String):String {
_23
return metadata[key]!
_23
}
_23
`;
_23
_23
const result = await query({
_23
cadence,
_23
args: () =>
_23
mapValuesToCode(cadence, [
_23
{ language: 'Cadence', languageRating: 'Cadence is Awesome 🤟' },
_23
'languageRating',
_23
]),
_23
});
_23
_23
console.log(result);
_23
})();

Parser

getTemplateInfo(code)

Parses the code and returns TemplateInfo

Arguments

NameTypeDescription
codestringCadence template code to process

Usage


_17
import { getTemplateInfo } from '@onflow/flow-cadut';
_17
_17
const script = `
_17
pub fun main(message:String):String{
_17
return 42
_17
}
_17
`;
_17
const info = getTemplateInfo(script);
_17
_17
/*
_17
* "info" will contain an object:
_17
* {
_17
* type: "script",
_17
* args: [ 'message:String' ]
_17
* }
_17
*/
_17
console.log({ info });

extractSigners(code)

Parses the code and returns array of SignerPair

Arguments

NameTypeDescription
codestringCadence template code to process

Returns

TypeDescription
SignerPairString representation of signer pair

Usage


_10
import { extractSigners } from '@onflow/flow-cadut';
_10
_10
const script = `
_10
pub fun main(){
_10
log("nothing to see here :)")
_10
}
_10
`;
_10
const signers = extractSigners(script);
_10
console.log({ signers });

extractScriptArguments(code)

Parses the code and returns array of ArgumentPair

Arguments

NameTypeDescription
codestringCadence template code to process

Returns

TypeDescription
ArgumentPairString representation of argument pair

Usage


_10
import { extractScriptArguments } from '@onflow/flow-cadut';
_10
_10
const script = `
_10
pub fun main(message: String, metadata: {String:String}){
_10
log(message)
_10
}
_10
`;
_10
const args = extractScriptArguments(script);
_10
console.log({ args });

extractTransactionArguments(code)

Parses the code and returns array of ArgumentPair

Arguments

NameTypeDescription
codestringCadence template code to process

Returns

TypeDescription
ArgumentPairString representation of argument pair

Usage


_11
import { extractTransactionArguments } from '@onflow/flow-cadut';
_11
_11
const tx = `
_11
transaction(message: String, metadata: {String:String}){
_11
prepare(signer:AuthAccount){
_11
_11
}
_11
}
_11
`;
_11
const args = extractTransactionArguments(tx);
_11
console.log({ args });

extractContractName(code)

Parses the code and returns contract name

Arguments

NameTypeDescription
codestringCadence template code to process

Returns

TypeDescription
stringname of the contract defined in template code

Usage


_10
import { extractContractName } from '@onflow/flow-cadut';
_10
_10
const contract = `
_10
pub contract HelloWorld{
_10
init(){}
_10
}
_10
`;
_10
const name = extractContractName(contract);
_10
console.log({ name });

splitArgs(pair)

Splits ArgumentPair into array of two items

Arguments

NameTypeDescription
pairArgumentPairargument pair in form of a string

Returns

TypeDescription
arrayfirst item is a name, second - string representation of type

Usage


_10
import { splitArgs } from '@onflow/flow-cadut';
_10
const simplePair = 'message:String';
_10
const metaPair = 'metadata: {String:String}';
_10
_10
const simple = splitArgs(simplePair);
_10
const meta = splitArgs(metaPair);
_10
_10
console.log({ simple, meta });

argType(pair)

Splits ArgumentPair and returns type of the argument

Arguments

NameTypeDescription
`pairArgumentPairargument pair in form of a string

Returns

TypeDescription
stringstring representation of argument type

Usage


_10
import { argType } from '@onflow/flow-cadut';
_10
_10
const simplePair = 'message:String';
_10
const metaPair = 'metadata: {String:String}';
_10
_10
const simple = argType(simplePair);
_10
const meta = argType(metaPair);
_10
_10
console.log({ simple, meta });

getArrayType(type)

Extracts item type from array type

Arguments

NameTypeDescription
typestringstring representation of Array type

Returns

TypeDescription
stringstring representation of item type

Usage


_10
import { getArrayType } from '@onflow/flow-cadut';
_10
_10
const simpleType = getArrayType('[String]');
_10
const complexType = getArrayType('[{String: String}]');
_10
_10
console.log({ simpleType, complexType });

getDictionaryTypes(type)

Extracts key and value types from Dictionary type

Arguments

NameTypeDescription
typestringstring representation of Dictionary type

Returns

TypeDescription
arrayarray of strings - first item for the key type, second for the value type

Usage


_10
import { getDictionaryTypes } from '@onflow/flow-cadut';
_10
_10
const type = '{String: UFix64}';
_10
const types = getDictionaryTypes(type);
_10
const [keyType, valueType] = types;
_10
_10
console.log({ keyType, valueType });

Generator

processFolder(input, output, options)

Recursively goes through input folder and generates code for found contracts, transactions and scripts. Write files under output path.

Arguments

NameTypeOptionalDescription
inputstringpath to the input folder
outputstringpath to output folder
optionsobjectadditional options. Default: {}

Options

NameTypeOptionalDescription
dependencystringinteractions dependency. Default: flow-cadut

Usage


_10
import path from 'path';
_10
import { processFolder } from '@onflow/flow-cadut';
_10
_10
(async () => {
_10
const input = path.resolve('./cadence');
_10
const output = path.resolve('./src/generated/localRegistry');
_10
_10
await processFolder(input, output);
_10
console.log('✅ Done!');
_10
})();

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

NameTypeOptionalDescription
urlstringurl to GitHub repo
outputstringpath to output folder
branchstringbranch to use. Default: main
optionsobjectadditional options. Default: {}

Options

NameTypeOptionalDescription
dependencystringinteractions dependency. Default: flow-cadut

Usage


_10
import path from 'path';
_10
import { processGitRepo } from '@onflow/flow-cadut';
_10
_10
(async () => {
_10
const url = path.resolve('https://github.com/onflow/flow-core-contracts');
_10
const output = path.resolve('./src/generated/localRegistry');
_10
_10
await processGitRepo(url, output);
_10
console.log('✅ Done!');
_10
})();

Interactions

setEnvironment(network, options)

Sets flow.network config value

Arguments

NameTypeOptionalDescription
networkstringnetwork to use. Default: emulator
optionsobjectextra options to adjust config

Network Variants

VariantsDescription
emulatorEmulator instance running locally at http://localhost:8080
testnetTestnet access node at https://access-testnet.onflow.org
mainnetMainnet access node at https://access.mainnet.onflow.org

Options

NameTypeOptionalDescription
options.portnumberport for emulator. Default: 8080
options.endpointstringAccess API endpoint.

⚠️ Attention: endpoint will override port and provided network. Don't mix endpoint from different network - it might lead to unexpected result.

Usage


_10
import { setEnvironment } from '@onflow/flow-cadut';
_10
_10
(async () => {
_10
await setEnvironment('testnet');
_10
})();

getEnvironment()

Returns a set of deployed contracts for current environment

Returns

TypeDescription
objectAddressMap for known contracts deployed in current environment

Usage


_10
import { setEnvironment, getEnvironment } from '@onflow/flow-cadut';
_10
_10
(async () => {
_10
await setEnvironment('mainnet');
_10
const addressMap = await getEnvironment();
_10
console.log({ addressMap });
_10
})();

hexContract(code)

Prepares Cadence template code to pass into deployment transaction. Syntax sugar for Buffer.from(code, "utf8").toString("hex");

Arguments

NameTypeDescription
codestringCadence template code

Returns

TypeDescription
stringhex representation of template code

Usage


_10
import { hexContract } from '@onflow/flow-cadut';
_10
_10
const code = `
_10
pub contract HelloWorld{
_10
init(){}
_10
}
_10
`;
_10
const hexed = hexContract(code);

executeScript(args)

Sends script to the network

Arguments

NameTypeDescription
argsScriptArgumentsscript arguments

Returns

TypeDescription
ScriptResultResult of script execution.
ScriptArguments
NameTypeOptionalDescription
codestringCadence code to execute
argsarrayInteractionArgumentOptional if script does not expect arguments. Default: []
addressMapAddressMapaddress map to use for import replacement. Default: {}
limitnumbergas limit. Default: 100
ScriptResult

Script result is represented as a tuple [result, error]

NameTypeDescription
resultanyresult of script execution. Type of this value depends on script return value
errorerrorCaught error. This will be null if script executed successfully

Usage


_12
import { executeScript } from '@onflow/flow-cadut';
_12
_12
(async () => {
_12
const code = `
_12
pub fun main():Int{
_12
return 42
_12
}
_12
`;
_12
_12
const [result, err] = executeScript({ code });
_12
console.log({ result });
_12
})();

Alias

This method is also available under alias query

sendTransaction

Sends script to the network

Arguments

NameTypeOptionalDescription
argsTransactionArgumentstransaction arguments
waitForExecutionbooleanwait 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

TypeDescription
TransactionResultResult of script execution.

TransactionArguments

NameTypeOptionalDescription
codestringCadence code to execute
payerAuthorizationFunctionThe authorization function that returns a valid AuthorizationObject for the payer role.
signers[AuthorizationFunction]an array of AuthorizationObject representing transaction authorizers. Default: same as payer
proposerAuthorizationFunctionThe 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: []
addressMapAddressMapaddress map to use for import replacement. Default: {}
limitnumbergas 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]

NameTypeDescription
ResponseObjectanyresult of transaction execution. Type of this value depends on script return value
errorerrorCaught error. This will be null if script executed successfully

Usage


_23
import { authenticate, currentUser, authz, config } from '@onflow/fcl';
_23
import { sendTransaction } from '@onflow/flow-cadut';
_23
_23
config()
_23
.put('accessNode.api', 'https://rest-testnet.onflow.org') // Configure FCL's Access Node
_23
.put('challenge.handshake', 'https://fcl-discovery.onflow.org/testnet/authn') // Configure FCL's Wallet Discovery mechanism
_23
.put('0xProfile', '0xba1132bc08f82fe2'); // Will let us use `0xProfile` in our Cadence
_23
_23
(async () => {
_23
currentUser().subscribe(async (user) => {
_23
const code = `
_23
transaction {
_23
prepare(currentUser: AuthAccount) {
_23
log("hello")
_23
}
_23
}`;
_23
_23
const [result] = await sendTransaction({ code, payer: authz });
_23
console.log({ result });
_23
});
_23
_23
authenticate();
_23
})();

Alias

This method is also available under alias mutate