Skip to content

Conversation

@mootz12
Copy link
Contributor

@mootz12 mootz12 commented Jan 2, 2026

What

Adds a try_as_contract fn that gracefully returns errors like try_invoke_contract.

Why

Fixes #1434

Known limitations

Copy link
Member

@leighmcculloch leighmcculloch left a comment

Choose a reason for hiding this comment

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

Some feedback inline.

///
/// Used to write or read contract data, or take other actions in tests for
/// setting up tests or asserting on internal state.
pub fn try_as_contract<T>(&self, id: &Address, f: impl FnOnce() -> T) -> Result<T, HostError> {
Copy link
Member

@leighmcculloch leighmcculloch Jan 4, 2026

Choose a reason for hiding this comment

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

For the return value I think this function should return an InvokeError and the same Result<Result<>, Result<>> structure for consistency with the try_invoke_contract function.

pub fn try_invoke_contract<T, E>(
&self,
contract_address: &Address,
func: &crate::Symbol,
args: Vec<Val>,
) -> Result<Result<T, T::Error>, Result<E, InvokeError>>

Why: So the dev has the same error handling experience as for invoking. The as_contract fn is basically like calling invoke_contract on a contract function. Also, like the other try_ functions the case where T is the wrong type should be handable as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

*_as_contract extracts the result of the closure without converting it to a Val. Thus, I kept the Ok result as T, otherwise we need to convert it to a val and back which felt weird.

Good call on the error, updated it to match the try_invoke method and added tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants