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
_20import { extractImports } from "@onflow/flow-cadut";
_20 import Message from 0x01
_20 import Utilities from 0x02
_20 Utilities.log(Message.hello)
_20const imports = extractImports(code);
_20 * Line above shall show the following:
_20 * "Utilities": "0x02"
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
_13import { missingImports } from "@onflow/flow-cadut";
_13 import Message from 0x01
_13 import Utilities from 0x02
_13 Utilities.log(Message.hello)
_13const missing = missingImports(code, {});
_13console.log({ missing });
report(list, prefix)
Reports missing imports via console.error
with format:
_10[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
_10import { missingImports, report } from "@onflow/flow-cadut";
_10 import Message from 0x01
_10const list = missingImports(code, {});
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
Name | Type | Optional | Description |
---|
code | string | | Cadence template code to check |
addressMap | AddressMap | ✅ | addressMap for imported contracts. Default: {} |
prefix | string | ✅ | message prefix. Default: "" |
Usage
_10import { missingImports, report } from "@onflow/flow-cadut";
_10 import Message from 0x01
_10reportMissingImports(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
_12import { replaceImportAddresses } from "@onflow/flow-cadut";
_12 import Messages from 0x01
_12 Message: "0xf8d6e0586b0a20c7",
_12const replaced = replaceImportAddresses(code, addressMap);
_12console.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
_22import { query, config } from "@onflow/fcl";
_22import { mapArgument } from "@onflow/flow-cadut";
_22 config().put("accessNode.api", "https://rest-testnet.onflow.org");
_22 pub fun main(message: String): String{
_22 // Script expects a single argument of type "String"
_22 const message = mapArgument("String", "Hello from Cadence!");
_22 // "args" shall return array of arguments.
_22 // We will pass "message" value into it
_22 const args = () => [message];
_22 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
_23import { query, config } from "@onflow/fcl";
_23import { mapArgument } from "@onflow/flow-cadut";
_23 config().put("accessNode.api", "https://rest-testnet.onflow.org");
_23 pub fun main(message: String, amount: Int): Int{
_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 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
_23import { query, config } from "@onflow/fcl";
_23import { mapValuesToCode } from "@onflow/flow-cadut";
_23 config().put("accessNode.api", "https://rest-testnet.onflow.org");
_23 pub fun main(metadata: {String:String}, key: String):String {
_23 return metadata[key]!
_23 const result = await query({
_23 mapValuesToCode(cadence, [
_23 { 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
_17import { getTemplateInfo } from "@onflow/flow-cadut";
_17 pub fun main(message:String):String{
_17const info = getTemplateInfo(script);
_17 * "info" will contain an object:
_17 * args: [ 'message:String' ]
_17console.log({ info });
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
_10import { extractSigners } from "@onflow/flow-cadut";
_10 log("nothing to see here :)")
_10const signers = extractSigners(script);
_10console.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
_10import { extractScriptArguments } from "@onflow/flow-cadut";
_10 pub fun main(message: String, metadata: {String:String}){
_10const args = extractScriptArguments(script);
_10console.log({ args });
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
_11import { extractTransactionArguments } from "@onflow/flow-cadut";
_11 transaction(message: String, metadata: {String:String}){
_11 prepare(signer:AuthAccount){
_11const args = extractTransactionArguments(tx);
_11console.log({ args });
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
_10import { extractContractName } from "@onflow/flow-cadut";
_10 pub contract HelloWorld{
_10const name = extractContractName(contract);
_10console.log({ name });
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
_10import { splitArgs } from "@onflow/flow-cadut";
_10const simplePair = "message:String";
_10const metaPair = "metadata: {String:String}";
_10const simple = splitArgs(simplePair);
_10const meta = splitArgs(metaPair);
_10console.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
_10import { argType } from "@onflow/flow-cadut";
_10const simplePair = "message:String";
_10const metaPair = "metadata: {String:String}";
_10const simple = argType(simplePair);
_10const meta = argType(metaPair);
_10console.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
_10import { getArrayType } from "@onflow/flow-cadut";
_10const simpleType = getArrayType("[String]");
_10const complexType = getArrayType("[{String: String}]");
_10console.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
_10import { getDictionaryTypes } from "@onflow/flow-cadut";
_10const type = "{String: UFix64}";
_10const types = getDictionaryTypes(type);
_10const [keyType, valueType] = types;
_10console.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
_10import path from "path";
_10import { processFolder } from "@onflow/flow-cadut";
_10 const input = path.resolve("./cadence");
_10 const output = path.resolve("./src/generated/localRegistry");
_10 await processFolder(input, output);
_10 console.log("✅ Done!");
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
_10import path from "path";
_10import { processGitRepo } from "@onflow/flow-cadut";
_10 const url = path.resolve("https://github.com/onflow/flow-core-contracts");
_10 const output = path.resolve("./src/generated/localRegistry");
_10 await processGitRepo(url, output);
_10 console.log("✅ Done!");
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
_10import { setEnvironment } from "@onflow/flow-cadut";
_10 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
_10import { setEnvironment, getEnvironment } from "@onflow/flow-cadut";
_10 await setEnvironment("mainnet");
_10 const addressMap = await getEnvironment();
_10 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
_10import { hexContract } from "@onflow/flow-cadut";
_10 pub contract HelloWorld{
_10const 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
_12import { executeScript } from "@onflow/flow-cadut";
_12 const [result, err] = executeScript({ code });
_12 console.log({ result });
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
_23import { authenticate, currentUser, authz, config } from "@onflow/fcl";
_23import { sendTransaction } from "@onflow/flow-cadut";
_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 currentUser().subscribe(async (user) => {
_23 prepare(currentUser: AuthAccount) {
_23 const [result] = await sendTransaction({ code, payer: authz });
_23 console.log({ result });
Alias
This method is also available under alias mutate