Skip to content

Commit

Permalink
docs: document callback_unwrap attribute
Browse files Browse the repository at this point in the history
Fixes #1303

Adds documentation for the `callback_unwrap` attribute under the `#[near]` macro docs, including:

- Description of functionality and usage
- Integration with `PromiseOrValue`
- Cross-contract factorial example 
- Error handling alternatives
- Rust doc annotations and references

Resolves #1303

---

For more details, open the [Copilot Workspace session](https://copilot-workspace.githubnext.com/near/near-sdk-rs/issues/1303?shareId=XXXX-XXXX-XXXX-XXXX).
  • Loading branch information
TobieTom committed Feb 19, 2025
1 parent 9596835 commit 542e467
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions near-sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,63 @@ extern crate quickcheck;
/// }
/// ```
///
/// ## `#[callback_unwrap]` (annotates function parameters)
///
/// Automatically unwraps the successful result of a callback from a cross-contract call.
/// Used on parameters in callback methods that are invoked as part of a cross-contract call chain.
/// If the promise fails, the method will panic with the error message.
///
/// This attribute is commonly used with [`PromiseOrValue<T>`], which represents either an immediate value
/// or a promise that will resolve to that value.
///
/// ### Example with Cross-Contract Factorial:
///
/// ```rust
/// # use near_sdk::{near, env, PromiseOrValue};
/// #[near(contract_state)]
/// #[derive(Default)]
/// pub struct CrossContract {}
///
/// #[near]
/// impl CrossContract {
/// pub fn factorial(&self, n: u32) -> PromiseOrValue<u32> {
/// if n <= 1 {
/// return PromiseOrValue::Value(1);
/// }
/// let account_id = env::current_account_id();
/// Self::ext(account_id.clone())
/// .factorial(n - 1)
/// .then(Self::ext(account_id).factorial_mult(n))
/// .into()
/// }
///
/// #[private]
/// pub fn factorial_mult(&self, n: u32, #[callback_unwrap] cur: u32) -> u32 {
/// n * cur
/// }
/// }
/// ```
///
/// ### Error Handling Alternative
///
/// If you need to handle failed promises explicitly, receive the `Result<T, PromiseError>` directly
/// instead of using `#[callback_unwrap]`:
///
/// ```rust
/// # use near_sdk::{near, PromiseError};
/// # #[near(contract_state)]
/// # pub struct Contract {}
/// # #[near]
/// # impl Contract {
/// #[private]
/// pub fn handle_callback(&mut self, result: Result<u8, PromiseError>) {
/// match result {
/// Ok(value) => { /* Handle success */ },
/// Err(err) => { /* Handle error */ },
/// }
/// }
/// # }
/// ```
/// ## `#[result_serializer(...)]` (annotates methods of a type in its `impl` block)
///
/// The attribute defines the serializer for function return serialization.
Expand Down

0 comments on commit 542e467

Please sign in to comment.