From 542e4672a279cb7ca2a83c083b641bec00f32316 Mon Sep 17 00:00:00 2001 From: TobiasBond <135626372+TobieTom@users.noreply.github.com> Date: Wed, 19 Feb 2025 11:50:38 +0100 Subject: [PATCH] docs: document `callback_unwrap` attribute 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). --- near-sdk/src/lib.rs | 57 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/near-sdk/src/lib.rs b/near-sdk/src/lib.rs index 39dab8644..4800db0d3 100644 --- a/near-sdk/src/lib.rs +++ b/near-sdk/src/lib.rs @@ -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`], 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 { +/// 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` 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) { +/// 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.