Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

plugin: forc-call #6791

Open
wants to merge 36 commits into
base: master
Choose a base branch
from
Open

plugin: forc-call #6791

wants to merge 36 commits into from

Conversation

zees-dev
Copy link
Contributor

@zees-dev zees-dev commented Dec 17, 2024

Description

The following PR introduces a new forc plugin; forc-call.

This plugin allows users to call functions on deployed contracts using the forc call command.
This is ideal for quickly querying the state of a deployed contract.

In this first implementation; the contract ABI is required (as a path to a local JSON file or a URL to a remote JSON file).

This is inspired by the cast call tool; which is a popular tool for interacting with deployed contracts on Ethereum.
The implementation is based on the following Github issue: #6725

In the current implementation, you can query a contract state using the forc call command by providing the target contract ID, it's respective ABI file, and the function name (selector) and arguments.

Forc Call CLI
forc call --help
Call a contract function

Usage: forc call [OPTIONS] <CONTRACT_ID> <FUNCTION> [ARGS]...

Arguments:
<CONTRACT_ID>
        The contract ID to call

<FUNCTION>
        The function signature to call. When ABI is provided, this should be a selector (e.g. "transfer") When no ABI is provided, this should be the full function signature (e.g. "transfer(address,u64)")

[ARGS]...
        Arguments to pass into main function with forc run

Options:
    --abi <ABI>
        Optional path or URI to a JSON ABI file

    --node-url <NODE_URL>
        The URL of the Fuel node to which we're submitting the transaction. If unspecified, checks the manifest's `network` table, then falls back to `http://127.0.0.1:4000`
        
        You can also use `--target`, `--testnet`, or `--mainnet` to specify the Fuel node.
        
        [env: FUEL_NODE_URL=]

    --target <TARGET>
        Use preset configurations for deploying to a specific target.
        
        You can also use `--node-url`, `--testnet`, or `--mainnet` to specify the Fuel node.
        
        Possible values are: [local, testnet, mainnet]

    --testnet
        Use preset configuration for testnet.
        
        You can also use `--node-url`, `--target`, or `--mainnet` to specify the Fuel node.

    --mainnet
        Use preset configuration for mainnet.
        
        You can also use `--node-url`, `--target`, or `--testnet` to specify the Fuel node.

    --signing-key <SIGNING_KEY>
        Derive an account from a secret key to make the call
        
        [env: SIGNING_KEY=]

    --wallet
        Use forc-wallet to make the call

    --amount <AMOUNT>
        Amount of native assets to forward with the call
        
        [default: 0]

    --asset-id <ASSET_ID>
        Asset ID to forward with the call

    --gas-forwarded <GAS_FORWARDED>
        Amount of gas to forward with the call

    --mode <MODE>
        The execution mode to use for the call; defaults to dry-run; possible values: dry-run, simulate, live
        
        [default: dry-run]

    --gas-price <PRICE>
        Gas price for the transaction

    --script-gas-limit <SCRIPT_GAS_LIMIT>
        Gas limit for the transaction

    --max-fee <MAX_FEE>
        Max fee for the transaction

    --tip <TIP>
        The tip for the transaction

    --external-contracts <EXTERNAL_CONTRACTS>
        The external contract addresses to use for the call If none are provided, the call will automatically extract contract addresses from the function arguments and use them for the call as external contracts

-h, --help
        Print help (see a summary with '-h')

-V, --version
        Print version

Example usage

forc call 0xe18de7c7c8c61a1c706dccb3533caa00ba5c11b5230da4428582abf1b6831b4d --abi ./out/debug/counter-contract-abi.json add 1 2
  • where 0xe18de7c7c8c61a1c706dccb3533caa00ba5c11b5230da4428582abf1b6831b4d is the contract ID
  • where ./out/debug/counter-contract-abi.json is the path to the ABI file
  • where add is the function name (selector)
  • where 1 2 are the arguments to the function

^ the sway code for the add function could be:

contract;
abi MyContract {
    fn add(a: u64, b: u64) -> u64;
}
impl MyContract for Contract {
    fn add(a: u64, b: u64) -> u64 {
        a + b
    }
}

Implementation details

  1. The provided ABI file downloaded (unless local path is provided)
  2. The ABI is parsed into internal representation
  3. The provided function selector e.g. add is matched with the extracted functions from the ABI
  4. The provided arguments are parsed into the appropriate types which match the extracted function's inputs
  5. The function selector and args are then converted into the Token enum, which is then ABI encoded as part of the ContractCall struct
  6. The ContractCall struct is then used to make a request to the node to call the function
  7. The response is then decoded into the appropriate type (based on matched function's output type)

^ In the implementation, we don't use the abigen! macro since this is a compile time parser of the ABI file; instead we make use of the lower level encoding and decoding primitives and functions from the Rust SDK.

Live example on testnet

Example 1

The example contract above with add function has been deployed on testnet - with ABI file available here.
The add function can be called via the CLI:

cargo run -p forc-client --bin call -- \
  --testnet \
  --abi https://pastebin.com/raw/XY3awY3T \
  0xe18de7c7c8c61a1c706dccb3533caa00ba5c11b5230da4428582abf1b6831b4d \
  add 1 2

Example 2 - get owner of Mira DEX contract

cargo run -p forc-client --bin call -- \
  --testnet \
  --abi https://raw.githubusercontent.com/mira-amm/mira-v1-periphery/refs/heads/main/fixtures/mira-amm/mira_amm_contract-abi.json \
  0xd5a716d967a9137222219657d7877bd8c79c64e1edb5de9f2901c98ebe74da80 \
  owner

Note: Testnet contract address here

Encoding of primitive types

When passing in function arguments, the following types are encoded as follows:

Types Example input Notes
bool true or false
u8, u16, u32, u64, u128, u256 42
b256 0x0000000000000000000000000000000000000000000000000000000000000042 or 0000000000000000000000000000000000000000000000000000000000000042 0x prefix is optional
bytes, RawSlice 0x42 or 42 0x prefix is optional
String, StringSlice, StringArray (Fixed-size) "abc"
Tuple (42, true) The types in tuple can be different
Array (Fixed-size), Vector (Dynamic) [42, 128] The types in array or vector must be the same; i.e. you cannot have [42, true]
Struct {42, 128} Since structs are packed encoded, the attribute names are not encoded; i.e. {42, 128}; this could represent the following struct Polygon { x: u64, y: u64 }
Enum (Active: true) or (1: true) Enums are key-val pairs with keys as being variant name (case-sensitive) or variant index (starting from 0) and values as being the variant value; this could represent the following enum MyEnum { Inactive, Active(bool) }
Encoding cheat-sheet

A few of the common types are encoded as follows:

Types Encoding Description Example
bool, u8 Encoded as a single byte. bool: 0x00 (false) or 0x01 (true); u8 is the byte itself. bool(true) = 0x01, u8(42) = 0x2A
u16 2-byte, big-endian u16(42) = 0x002A
u32 4-byte, big-endian u32(42) = 0x0000002A
u64 8-byte, big-endian u64(42) = 0x000000000000002A
u128 16-byte, big-endian u128(42) = 0x0000000000000000000000000000002A
u256, b256 32-byte value. For u256: big-endian integer; For b256: raw 32 bytes u256(42) = 32-bytes ending with ...0000002A, b256(...) = exactly the 32-byte array
Tuples, Arrays, Structs (Fixed-size) Concatenate the encodings of each element/field with no extra padding (u8(1), bool(true)) = 0x01 0x01; [u16;2]: [42,100] = 0x002A0064; struct {u8,u8}: 0x0102
Enums u64 variant index + encoded variant data with no extra padding MySumType::X(42): 0x0000000000000000 000000000000002A
Bytes, String, RawSlice, Vector (Dynamic) u64 length prefix + raw data, no padding "abc" = length=3: 0x0000000000000003 0x61 0x62 0x63

^ This is based on the docs here: https://docs.fuel.network/docs/specs/abi/argument-encoding

Future improvements

  1. Support for function signature based calls without ABI
  2. Support for raw calldata input
  3. Function selector completion - given ABI file

Checklist

  • I have linked to any relevant issues.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have updated the documentation where relevant (API docs, the reference, and the Sway book).
  • I have added tests that prove my fix is effective or that my feature works.
  • I have added (or requested a maintainer to add) the necessary Breaking* or New Feature labels where relevant.
  • I have done my best to ensure that my PR adheres to the Fuel Labs Code Review Standards.
  • I have requested a review from the relevant team or maintainers.

@zees-dev zees-dev self-assigned this Dec 17, 2024
@zees-dev zees-dev added ABI Everything to do the ABI, especially the JSON representation forc-client Everything related to the `forc-client` crate. labels Dec 17, 2024
if is_temp_file {
std::fs::remove_file(file_path).expect("Failed to remove ABI file");
}
let parsed_abi = UnifiedProgramABI::from_json_abi(&abi_str)?;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we add validation to ensure ABI files are well-formed and compatible before progressing?

// Validate minimum required fields
if parsed_abi.functions.is_empty() {
    bail!("Invalid ABI: No functions found in ABI file");
}

...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking we may want to support calling a contract without any functions - where you may want to only specify an amount.
In the case of solidity, this calls the default fallback or receive function - allowing the contract to receive funds.

I was unsure whether sway has an equivalent default function - or an approach where the contract can receive funds without calling an explicit function.

Copy link
Member

@Voxelot Voxelot Jan 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is indeed possible, rather than using a CALL instruction, you can use a TR or transfer instruction to send funds into a contract.

https://docs.fuel.network/docs/nightly/fuels-ts/wallets/wallet-transferring/#transferring-assets-to-contracts

Sway also has a notion of default functions which are used by proxy contracts to pass-through calls and args to an implementation contract, but its not necessary to call functions to send funds into a contract.


forc_util::cli_examples! {
super::Command {
[ Call a contract with function parameters => "forc call <CONTRACT_ID> <FUNCTION_SIGNATURE> <ARGS>" ]
Copy link
Member

@JoshuaBatty JoshuaBatty Jan 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i wonder if being a bit more explicit on what these calls look like might be easier for people to reference? maybe the above could be

[ Call a simple contract function => "forc call 0x123..abc add 1 2" ]

thoughts?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agreed; makes sense 👍

@zees-dev
Copy link
Contributor Author

Note: Currently CI fails since there is reliance on new release from rust sdk - which contains the relevant changes:

@zees-dev zees-dev added the forc-call Everything related to the `forc-call` plugin in `forc-client` package label Jan 13, 2025
@zees-dev zees-dev marked this pull request as ready for review January 14, 2025 07:25
@zees-dev zees-dev requested review from a team as code owners January 14, 2025 07:25
Copy link
Member

@sdankel sdankel left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Impressive work! It's still rough around the edges but I'm excited to use this.

forc-plugins/forc-client/src/util/node_url.rs Outdated Show resolved Hide resolved
forc-plugins/forc-client/src/util/tx.rs Show resolved Hide resolved
@@ -0,0 +1,2363 @@
use crate::{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I'd prefer to break up this file into several files under forc-plugins/forc-client/src/op/call/ to make it easier to navigate. Perhaps like parse_tokens.rs and missing_contracts.rs

forc-plugins/forc-client/Cargo.toml Show resolved Hide resolved
forc-plugins/forc-client/src/cmd/call.rs Show resolved Hide resolved
forc-plugins/forc-client/src/op/call.rs Show resolved Hide resolved
if let Some(abi) = abi {
// If ABI is provided, ensure function signature is just the selector
let cmd::call::FuncType::Selector(selector) = function else {
bail!("Function must be a selector");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be good to provide an example here:

Suggested change
bail!("Function must be a selector");
bail!("Function must be a selector, e.g \"transfer\"");

Even better would be if we could try to correctly print the function name that they entered.

sdankel and others added 7 commits January 15, 2025 15:22
## Description


## Checklist

- [ ] I have linked to any relevant issues.
- [ ] I have commented my code, particularly in hard-to-understand
areas.
- [ ] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] I have added tests that prove my fix is effective or that my
feature works.
- [ ] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [ ] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [ ] I have requested a review from the relevant team or maintainers.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ABI Everything to do the ABI, especially the JSON representation forc-call Everything related to the `forc-call` plugin in `forc-client` package forc-client Everything related to the `forc-client` crate.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants