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

CLI tool for querying smart contract state #6725

Closed
zees-dev opened this issue Nov 14, 2024 · 1 comment
Closed

CLI tool for querying smart contract state #6725

zees-dev opened this issue Nov 14, 2024 · 1 comment
Assignees
Labels
enhancement New feature or request

Comments

@zees-dev
Copy link
Contributor

Proposal: CLI tool for querying smart contract state

Problem

Currently querying smart contract state requires multiple manual steps:

  • Retrieving the contract's ABI
  • Writing custom Rust/TypeScript scripts
  • Setting up development environment
  • Managing dependencies

This process is time-consuming and creates unnecessary friction for developers.

Proposed Solution

A CLI tool that simplifies smart contract state queries:

forc call <contract-ID> <function-name/sig> [--args key=value]

Key Features

  • Automatic ABI fetching from verified contracts
  • Interactive mode for exploring available functions
  • Output formatting options (JSON, table, raw)

Benefits

  • Lower barrier to entry for quickly validating contract state
  • Faster debugging and monitoring
  • No need for custom script maintenance

Example usage

Proposed CLI
# > forc call --help
Perform a call on a contract without publishing a transaction

Usage: forc call [OPTIONS] [TO] [SIG] [ARGS]... [COMMAND]

Commands:

Arguments:
    [TO]
    The destination of the transaction

    [SIG]
    The signature of the function to call

    [ARGS]...
    The arguments of the function to call

Options:
    --data <DATA>
        Data for the transaction

    -b, --block <BLOCK>
        The block height to query at.
        
        Can also be the tags earliest, finalized, safe, latest, or pending.

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

Display options:
    -j, --json
        Print the decoded output as JSON

Transaction options:
    --value <VALUE>
        Ether to send in the transaction, either specified in wei, or as a string with a unit type.
        Examples: 1ether, 10gwei, 0.01ether

Fuel options:
    -r, --rpc-url <URL>
        The RPC endpoint

        [env: FUEL_RPC_URL=]
        [default: "http://127.0.0.1:4000/v1/graphql"]

Wallet options - raw:
    -f, --from <ADDRESS>
        The sender account

        [env: FUEL_FROM=]

    --private-key <RAW_PRIVATE_KEY>
        Use the provided private key

    --mnemonic <MNEMONIC>
        Use the mnemonic phrase of mnemonic file at the specified path

    --mnemonic-passphrase <PASSPHRASE>
        Use a BIP39 passphrase for the mnemonic

    --mnemonic-derivation-path <PATH>
        The wallet derivation path.

        Works with both --mnemonic-path and hardware wallets.

        [default: "m/44'/1179993420'/0'/0/0"]

    --mnemonic-index <INDEX>
        Use the private key from the given mnemonic index.

        Used with --mnemonic-path.

        [default: 0]

Wallet options - wallet:
    --wallet <PATH>
        Use the forc-wallet in the given folder or file

        [env: FUEL_WALLET=]
        [default: "~/.fuel/wallets"]

    --account-index <ACCOUNT_NAME>
        Use a wallet from the default wallets folder (~/.fuel/wallets) by its filename

        [env: FUEL_WALLET_INDEX=]
        [default: 0]

    --password <PASSWORD>
        The wallet password.

        Used with --wallet.

Inspirations

This tool is inspired by cast; a cast call like command is envisioned here - but for sway contracts on the fuel network.

@zees-dev zees-dev added enhancement New feature or request forc labels Nov 14, 2024
@zees-dev zees-dev self-assigned this Nov 18, 2024
@zees-dev zees-dev mentioned this issue Dec 17, 2024
8 tasks
JoshuaBatty added a commit that referenced this issue Feb 7, 2025
## 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`](https://book.getfoundry.sh/reference/cast/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.

<details>
  <summary>Forc Call CLI</summary>
  
  ```sh
  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
  ```
</details>

### Example usage

```sh
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:

```sway
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](https://github.com/FuelLabs/fuels-rs).

## Live example on testnet

### Example 1

The example contract above with `add` function has been deployed on
testnet - with ABI file available
[here](https://pastebin.com/raw/XY3awY3T).
The add function can be called via the CLI:

```sh
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

```sh
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](https://docs.mira.ly/developer-guides/developer-overview#testnet-deployment)

## 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) }` |

<details>
  <summary>Encoding cheat-sheet</summary>

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
</details>

## 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

- [x] I have linked to any relevant issues.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: zees-dev <[email protected]>
Co-authored-by: Sophie Dankel <[email protected]>
Co-authored-by: Joshua Batty <[email protected]>
@zees-dev
Copy link
Contributor Author

zees-dev commented Feb 9, 2025

Implemented initial version: #6791
This single tool contains both the functionality to query and call (perform tx/state-changes) smart contracts.
^ It combines functionalities of both cast call and cast send; but for fuel.

@zees-dev zees-dev closed this as completed Feb 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant