How to pass in `Type` to transactions and scripts in Flow CLI

303 views Asked by At

Given a script:

pub fun main(type: Type): Type {
    return type
}

How do you pass in a Type param to the script using Flow CLI?

Using this command:

flow scripts execute ./cadence/scripts/test.cdc --args-json '[{"type":"Type","value":{"staticType":"Int"}}]'

The command fails with the following error:

Command Error: failed to submit executable script: client: rpc error: code = Unknown desc = [Error Code: 1101] cadence runtime error Execution failed:
error: invalid argument at index 0: cannot import value of type cadence.TypeValue
--> 6136ed6c98f85c642aca23dc50ce10eec81e48ccb5556ccf21f002b861ecf371
2

There are 2 answers

0
pho_pho On

The command in the question above uses the JSON-Cadence object specified in the docs: https://docs.onflow.org/cadence/json-cadence-spec/#type

Currently (2022/3/31) the docs are incorrect, as indicated by this issue here:

https://github.com/onflow/cadence/issues/1511

The solution is to include an key/value in the JSON object, as demonstrated by the above issue:

{ "type" : "Type", "value" : { "staticType" : { "kind" : "Int" } } }

Notice the addition of { "kind": "Int" }

If you need to pass in more complex types to the Flow CLI, then refer to this link, where the resource type is highlighted:

https://github.com/onflow/cadence/blob/314f5fa8a5da8c452d23a42148a1d7927915d613/encoding/json/encoding_test.go#L1180-L1193

You will see that passing in more complex types to Flow CLI quickly becomes protracted and error prone for anything but the simplest types. There is currently no simple solution for passing in complex types to Flow CLI.

If your script/tx can accommodate values hardcoded in the body, then there is a solution.

Assuming you have a contract that has a resource called NFT, and the contract is called MyNFT, and MyNFT has been deployed to 0x1234567890 on Testnet, then:

import MyNFT from 0x1234567890

pub fun main(): Type {
    let type = Type<@MyNFT.NFT>() 
    return type
}
0
bjartek On

Another way you can solve your problem is to send in a type identifier to your script and then use the functions describe in runtime types to create the actual type in cadence

pub fun main(type: String): Type {
    return CompositeType(type)
}

Then you would call the script with a normal string in the cli.