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

doc: impl details of #[callback_unwrap] #1319

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

Conversation

dj8yfo
Copy link
Collaborator

@dj8yfo dj8yfo commented Feb 27, 2025

@@ -29,9 +29,16 @@ impl Adder {
&self,
#[callback_unwrap] a: DoublePair,
#[callback_unwrap] b: DoublePair,
#[callback_vec] others: Vec<DoublePair>,
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

#[callback_vec] isn't really compatible with #[callback_unwrap] to be used in this manner, due to a feature??/bug??, because it revisits the same promise indices, already visited by callback_unwrap,
so others vector in this example contained a and b as first elements

Copy link
Collaborator

Choose a reason for hiding this comment

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

So I don't get it. It worked before and now it does not?

Comment on lines 482 to 494
/// 1. arguments, annotated with `#[callback_unwrap]`, are no longer expected to be included into `input`,
/// deserialized in (step **3**, [`#[near]` on mutating method](near#for-above-mutating-method-near-macro-defines-the-following-function)).
/// 2. for each argument, annotated with `#[callback_unwrap]`:
/// 1. [`env::promise_result`] host function is called with corresponding index, starting from 0
/// (`0u64` for argument `one`, `1u64` for argument `two` above), and saved into `promise_result` variable
/// 2. if the `promise_result` is a [`PromiseResult::Failed`] error, then [`env::panic_str`] host function is called to signal callback computation error
/// 3. otherwise, if the `promise_result` is a [`PromiseResult::Successful`], it's unwrapped and saved to a `data` variable
/// 4. `data` is deserialized similar to that as usual (step **3**, [`#[near]` on mutating method](near#for-above-mutating-method-near-macro-defines-the-following-function)),
/// and saved to `deserialized_n_promise` variable
/// 3. counterpart of (step **7**, [`#[near]` on mutating method](near#for-above-mutating-method-near-macro-defines-the-following-function)):
/// original method is called `Contract::method(&mut state, deserialized_input_success.regular, deserialized_0_promise, deserialized_1_promise)`,
/// as defined in `#[near]` annotated impl block
///
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

this section is roughly based on the following expansion diff:

142c142
<     pub fn factorial_mult(self, n: u32, cur: u32) -> ::near_sdk::Promise {
---
>     pub fn factorial_mult(self, n: u32) -> ::near_sdk::Promise {
147d146
<                 cur: &'nearinput u32,
165c164
<                             false as usize + 1 + 1,
---
>                             false as usize + 1,
172,176d170
<                         _serde::ser::SerializeStruct::serialize_field(
<                             &mut __serde_state,
<                             "cur",
<                             &self.cur,
<                         )?;
181c175
<             let __args = Input { n: &n, cur: &cur };
---
>             let __args = Input { n: &n };
459d452
<         cur: u32,
477d469
<                     __field1,
503d494
<                             1u64 => _serde::__private::Ok(__Field::__field1),
516d506
<                             "cur" => _serde::__private::Ok(__Field::__field1),
529d518
<                             b"cur" => _serde::__private::Ok(__Field::__field1),
582,595c571
<                                         &"struct Input with 2 elements",
<                                     ),
<                                 );
<                             }
<                         };
<                         let __field1 = match _serde::de::SeqAccess::next_element::<
<                             u32,
<                         >(&mut __seq)? {
<                             _serde::__private::Some(__value) => __value,
<                             _serde::__private::None => {
<                                 return _serde::__private::Err(
<                                     _serde::de::Error::invalid_length(
<                                         1usize,
<                                         &"struct Input with 2 elements",
---
>                                         &"struct Input with 1 element",
600,603c576
<                         _serde::__private::Ok(Input {
<                             n: __field0,
<                             cur: __field1,
<                         })
---
>                         _serde::__private::Ok(Input { n: __field0 })
614d586
<                         let mut __field1: _serde::__private::Option<u32> = _serde::__private::None;
629,638d600
<                                 __Field::__field1 => {
<                                     if _serde::__private::Option::is_some(&__field1) {
<                                         return _serde::__private::Err(
<                                             <__A::Error as _serde::de::Error>::duplicate_field("cur"),
<                                         );
<                                     }
<                                     __field1 = _serde::__private::Some(
<                                         _serde::de::MapAccess::next_value::<u32>(&mut __map)?,
<                                     );
<                                 }
652,661c614
<                         let __field1 = match __field1 {
<                             _serde::__private::Some(__field1) => __field1,
<                             _serde::__private::None => {
<                                 _serde::__private::de::missing_field("cur")?
<                             }
<                         };
<                         _serde::__private::Ok(Input {
<                             n: __field0,
<                             cur: __field1,
<                         })
---
>                         _serde::__private::Ok(Input { n: __field0 })
665c618
<                 const FIELDS: &'static [&'static str] = &["n", "cur"];
---
>                 const FIELDS: &'static [&'static str] = &["n"];
678c631
<     let Input { n, cur }: Input = match ::near_sdk::env::input() {
---
>     let Input { n }: Input = match ::near_sdk::env::input() {
687a641,648
>     };
>     let data: ::std::vec::Vec<u8> = match ::near_sdk::env::promise_result(0u64) {
>         ::near_sdk::PromiseResult::Successful(x) => x,
>         _ => ::near_sdk::env::panic_str("Callback computation 0 was not successful"),
>     };
>     let cur: u32 = match ::near_sdk::serde_json::from_slice(&data) {
>         Ok(deserialized) => deserialized,
>         Err(_) => ::near_sdk::env::panic_str("Failed to deserialize callback using JSON"),

/// }
/// ```
///
/// For above `method` using the attribute on arguments, changes the body of function generated in [`#[near]` on mutating method](near#for-above-mutating-method-near-macro-defines-the-following-function)
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

this pr depends on #1307, as the doc anchor is first added there.
the broken link is not detected by

        RUSTDOCFLAGS: -D warnings
      run: |
        cargo doc -p near-sdk --features unstable,legacy,unit-testing,__macro-docs,__abi-generate

rust-lang/rust#137740

Copy link

codecov bot commented Feb 27, 2025

Codecov Report

Attention: Patch coverage is 0% with 4 lines in your changes missing coverage. Please review.

Project coverage is 80.32%. Comparing base (746e428) to head (022c9af).

Files with missing lines Patch % Lines
near-sdk/src/utils/mod.rs 0.00% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1319      +/-   ##
==========================================
- Coverage   80.33%   80.32%   -0.02%     
==========================================
  Files         104      104              
  Lines       14829    14831       +2     
==========================================
  Hits        11913    11913              
- Misses       2916     2918       +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@dj8yfo
Copy link
Collaborator Author

dj8yfo commented Feb 27, 2025

@race-of-sloths include

@race-of-sloths
Copy link

@dj8yfo Thank you for your contribution! Your pull request is now a part of the Race of Sloths!
King of Sloths shakes your hand! Yellow leader's jersey is yours deservedly!

Shows inviting banner with latest news.

Shows profile picture for the author of the PR

Current status: waiting for scoring

We're waiting for maintainer to score this pull request with @race-of-sloths score [0,1,2,3,5,8,13] command. Alternatively, autoscoring [1,2] will be applied for this pull request

What is the Race of Sloths

Race of Sloths is a friendly competition where you can participate in challenges and compete with other open-source contributors within your normal workflow

For contributors:

  • Tag @race-of-sloths inside your pull requests
  • Wait for the maintainer to review and score your pull request
  • Check out your position in the Leaderboard
  • Keep weekly and monthly streaks to reach higher positions
  • Boast your contributions with a dynamic picture of your Profile

For maintainers:

  • Score pull requests that participate in the Race of Sloths and receive a reward
  • Engage contributors with fair scoring and fast responses so they keep their streaks
  • Promote the Race to the point where the Race starts promoting you
  • Grow the community of your contributors

Feel free to check our website for additional details!

Bot commands
  • For contributors
    • Include a PR: @race-of-sloths include to enter the Race with your PR
  • For maintainers:
    • Invite contributor @race-of-sloths invite to invite the contributor to participate in a race or include it, if it's already a runner.
    • Assign points: @race-of-sloths score [1/2/3/5/8/13] to award points based on your assessment.
    • Reject this PR: @race-of-sloths exclude to send this PR back to the drawing board.
    • Exclude repo: @race-of-sloths pause to stop bot activity in this repo until @race-of-sloths unpause command is called

@dj8yfo dj8yfo marked this pull request as ready for review February 27, 2025 21:11
@@ -29,9 +29,16 @@ impl Adder {
&self,
#[callback_unwrap] a: DoublePair,
#[callback_unwrap] b: DoublePair,
#[callback_vec] others: Vec<DoublePair>,
Copy link
Collaborator

Choose a reason for hiding this comment

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

So I don't get it. It worked before and now it does not?

/// 3. otherwise, if the `promise_result` is a [`PromiseResult::Successful`], it's unwrapped and saved to a `data` variable
/// 4. `data` is deserialized similar to that as usual (step **3**, [`#[near]` on mutating method](near#for-above-mutating-method-near-macro-defines-the-following-function)),
/// and saved to `deserialized_n_promise` variable
/// 3. counterpart of (step **7**, [`#[near]` on mutating method](near#for-above-mutating-method-near-macro-defines-the-following-function)):
Copy link
Collaborator

Choose a reason for hiding this comment

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

I would make it more compact:
2.1

[`env::promise_result`] host function is called with corresponding index

2.2

if the `promise_result` is a [`PromiseResult::Failed`] error, then [`env::panic_str`] is called

2.3 can be removed

2.4 otherwise, promise_result is deserialized ...

But your variant is also lgtm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
3 participants