nexus-sdk 2.0.0

Rust SDK for Nexus protocol types, RPC access, and transaction construction.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! Input schema generation for Move onchain tools.

use {
    super::types::{
        convert_move_signature_to_schema,
        is_agent_vertex_authorization_proof_param,
        is_hidden_internal_tool_param,
        is_onchain_tool_result_param,
        is_proof_of_uid_param,
        is_uid_requirements_param,
    },
    crate::{sui, types::OnchainToolMode},
    anyhow::{anyhow, bail, Result as AnyResult},
    serde_json::{Map, Value},
    std::sync::Arc,
};

/// Generate input schema by introspecting the execute function's parameters.
///
/// This function fetches the Move module from the chain and analyzes the
/// execute function's parameters to generate a JSON schema. It automatically
/// skips internal parameters such as `UIDRequirements`, `ProvenValue<AgentVertexAuthorization>`,
/// and `TxContext`.
pub async fn generate_input_schema(
    client: Arc<sui::grpc::Client>,
    package_address: sui::types::Address,
    module_name: &str,
    execute_function: &str,
) -> AnyResult<String> {
    let (schema, _) =
        generate_input_schema_with_mode(client, package_address, module_name, execute_function)
            .await?;
    Ok(schema)
}

/// Generate an input schema and derive its [`OnchainToolMode`].
pub async fn generate_input_schema_with_mode(
    client: Arc<sui::grpc::Client>,
    package_address: sui::types::Address,
    module_name: &str,
    execute_function: &str,
) -> AnyResult<(String, OnchainToolMode)> {
    let request = sui::grpc::GetPackageRequest::default().with_package_id(package_address);
    let mut client = client.as_ref().clone();

    // Fetch all normalized Move modules for the package.
    let Some(package) = client
        .package_client()
        .get_package(request)
        .await
        .map(|resp| resp.into_inner().package)?
    else {
        bail!("Package '{package_address}' not found")
    };
    let all_modules = package.modules();

    // Find the specific module.
    let normalized_module = all_modules
        .iter()
        .find(|m| m.name() == module_name)
        .ok_or_else(|| {
            anyhow!("Module '{module_name}' not found in package '{package_address}'")
        })?;

    // Find the execute function.
    let execute_func = normalized_module
        .functions()
        .iter()
        .find(|f| f.name() == execute_function)
        .ok_or_else(|| {
            anyhow!("Function '{execute_function}' not found in module '{module_name}'")
        })?;
    let mode = validate_execute_signature(execute_func, module_name, execute_function)?;

    // Parse function parameters.
    let mut schema_map = Map::new();
    let mut param_index = 0;

    for param_type in execute_func.parameters() {
        let body = param_type.body_opt().ok_or_else(|| {
            anyhow!("Parameter type missing body in function '{execute_function}' of module '{module_name}'")
        })?;

        if is_hidden_internal_tool_param(body) {
            continue;
        }

        // Convert the full signature (includes reference/mutability info).
        let param_schema = convert_move_signature_to_schema(param_type)?;

        // Store parameter information with index as the default name.
        let mut param_obj = match param_schema {
            Value::Object(obj) => obj,
            other => {
                let mut new_obj = Map::new();
                new_obj.insert("type".to_string(), other);
                new_obj
            }
        };

        let reference_kind = param_type
            .reference
            .and_then(|reference| sui::grpc::open_signature::Reference::try_from(reference).ok())
            .unwrap_or(sui::grpc::open_signature::Reference::Unknown);

        if param_obj.get("type").and_then(|v| v.as_str()) == Some("object")
            && reference_kind != sui::grpc::open_signature::Reference::Unknown
        {
            param_obj.insert(
                "mutable".to_string(),
                Value::Bool(reference_kind == sui::grpc::open_signature::Reference::Mutable),
            );
        }
        schema_map.insert(param_index.to_string(), Value::Object(param_obj));
        param_index += 1;
    }

    let schema_json = Value::Object(schema_map);
    let schema_string = serde_json::to_string(&schema_json)?;

    Ok((schema_string, mode))
}

fn validate_execute_signature(
    execute_func: &sui::grpc::FunctionDescriptor,
    module_name: &str,
    execute_function: &str,
) -> AnyResult<OnchainToolMode> {
    let visibility = execute_func
        .visibility
        .and_then(|visibility| {
            sui::grpc::function_descriptor::Visibility::try_from(visibility).ok()
        })
        .unwrap_or(sui::grpc::function_descriptor::Visibility::Unknown);
    if visibility != sui::grpc::function_descriptor::Visibility::Public {
        bail!("Onchain tool function '{module_name}::{execute_function}' must be public");
    }
    if !execute_func.returns().is_empty() {
        bail!(
            "Onchain tool function '{module_name}::{execute_function}' must not return values; finalize output through an owned OnchainToolResult argument"
        );
    }
    let has_owned_result_arg = execute_func.parameters().iter().any(|param| {
        param.reference.is_none()
            && param
                .body_opt()
                .map(is_onchain_tool_result_param)
                .unwrap_or(false)
    });
    if !has_owned_result_arg {
        bail!(
            "Onchain tool function '{module_name}::{execute_function}' must accept result: OnchainToolResult"
        );
    }

    let parameters = execute_func.parameters();
    let (mode, fixed_prefix_len) = match parameters {
        [authorization, worksheet, result, ..]
            if is_owned_param(authorization, is_agent_vertex_authorization_proof_param)
                && is_owned_param(worksheet, is_uid_requirements_param)
                && is_owned_param(result, is_onchain_tool_result_param) =>
        {
            (OnchainToolMode::WorkflowAuthorization, 3)
        }
        [worksheet, result, ..]
            if is_owned_param(worksheet, is_uid_requirements_param)
                && is_owned_param(result, is_onchain_tool_result_param) =>
        {
            (OnchainToolMode::Standard, 2)
        }
        _ => bail!(
            "Onchain tool function '{module_name}::{execute_function}' must begin with owned UIDRequirements and OnchainToolResult parameters, optionally preceded by an owned AgentVertexAuthorization proof"
        ),
    };
    if parameters[fixed_prefix_len..]
        .iter()
        .filter_map(sui::grpc::OpenSignature::body_opt)
        .any(|body| {
            is_agent_vertex_authorization_proof_param(body)
                || is_proof_of_uid_param(body)
                || is_uid_requirements_param(body)
                || is_onchain_tool_result_param(body)
        })
    {
        bail!(
            "Onchain tool function '{module_name}::{execute_function}' must contain internal parameters only in its fixed prefix"
        );
    }

    Ok(mode)
}

fn is_owned_param(
    parameter: &sui::grpc::OpenSignature,
    predicate: impl FnOnce(&sui::grpc::OpenSignatureBody) -> bool,
) -> bool {
    parameter.reference.is_none() && parameter.body_opt().is_some_and(predicate)
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        sui::grpc::{function_descriptor::Visibility, open_signature_body::Type},
    };

    fn owned_onchain_tool_result_signature() -> sui::grpc::OpenSignature {
        sui::grpc::OpenSignature::default().with_body(
            sui::grpc::OpenSignatureBody::default()
                .with_type(Type::Datatype)
                .with_type_name("0x42::onchain_tool_result::OnchainToolResult"),
        )
    }

    fn referenced_onchain_tool_result_signature(
        reference: sui::grpc::open_signature::Reference,
    ) -> sui::grpc::OpenSignature {
        owned_onchain_tool_result_signature().with_reference(reference)
    }

    fn owned_proof_of_uid_signature() -> sui::grpc::OpenSignature {
        sui::grpc::OpenSignature::default().with_body(
            sui::grpc::OpenSignatureBody::default()
                .with_type(Type::Datatype)
                .with_type_name("0x42::proof_of_uid::ProofOfUID"),
        )
    }

    fn owned_uid_requirements_signature() -> sui::grpc::OpenSignature {
        sui::grpc::OpenSignature::default().with_body(
            sui::grpc::OpenSignatureBody::default()
                .with_type(Type::Datatype)
                .with_type_name("0x42::proof_of_uid::UIDRequirements"),
        )
    }

    fn owned_authorization_signature() -> sui::grpc::OpenSignature {
        sui::grpc::OpenSignature::default().with_body(
            sui::grpc::OpenSignatureBody::default()
                .with_type(Type::Datatype)
                .with_type_name(
                    "0x42::authorization::ProvenValue<0x43::authorization::AgentVertexAuthorization>",
                ),
        )
    }

    fn valid_execute_descriptor() -> sui::grpc::FunctionDescriptor {
        sui::grpc::FunctionDescriptor::default()
            .with_visibility(Visibility::Public)
            .with_is_entry(true)
            .with_parameters(vec![
                owned_uid_requirements_signature(),
                owned_onchain_tool_result_signature(),
            ])
    }

    fn authorized_execute_descriptor() -> sui::grpc::FunctionDescriptor {
        sui::grpc::FunctionDescriptor::default()
            .with_visibility(Visibility::Public)
            .with_is_entry(true)
            .with_parameters(vec![
                owned_authorization_signature(),
                owned_uid_requirements_signature(),
                owned_onchain_tool_result_signature(),
            ])
    }

    #[test]
    fn validate_execute_signature_rejects_private_function() {
        let descriptor = valid_execute_descriptor().with_visibility(Visibility::Private);
        let err = validate_execute_signature(&descriptor, "tool", "execute").unwrap_err();
        assert!(err.to_string().contains("must be public"));
    }

    #[test]
    fn validate_execute_signature_accepts_public_nonentry_function() {
        let descriptor = valid_execute_descriptor().with_is_entry(false);
        validate_execute_signature(&descriptor, "tool", "execute").unwrap();
    }

    #[test]
    fn validate_execute_signature_rejects_return_values() {
        let descriptor =
            valid_execute_descriptor().with_returns(vec![sui::grpc::OpenSignature::default()
                .with_body(sui::grpc::OpenSignatureBody::default().with_type(Type::U64))]);
        let err = validate_execute_signature(&descriptor, "tool", "execute").unwrap_err();
        assert!(err.to_string().contains("must not return values"));
    }

    #[test]
    fn validate_execute_signature_rejects_referenced_onchain_tool_result() {
        let descriptor = sui::grpc::FunctionDescriptor::default()
            .with_visibility(Visibility::Public)
            .with_is_entry(true)
            .with_parameters(vec![
                owned_uid_requirements_signature(),
                referenced_onchain_tool_result_signature(
                    sui::grpc::open_signature::Reference::Immutable,
                ),
            ]);
        let err = validate_execute_signature(&descriptor, "tool", "execute").unwrap_err();
        assert!(err
            .to_string()
            .contains("must accept result: OnchainToolResult"));
    }

    #[test]
    fn validate_execute_signature_rejects_missing_requirements() {
        let descriptor = sui::grpc::FunctionDescriptor::default()
            .with_visibility(Visibility::Public)
            .with_is_entry(true)
            .with_parameters(vec![owned_onchain_tool_result_signature()]);
        let err = validate_execute_signature(&descriptor, "tool", "execute").unwrap_err();
        assert!(err.to_string().contains("must begin with"));
    }

    #[test]
    fn validate_execute_signature_rejects_proof_in_place_of_requirements() {
        let descriptor = sui::grpc::FunctionDescriptor::default()
            .with_visibility(Visibility::Public)
            .with_is_entry(true)
            .with_parameters(vec![
                owned_proof_of_uid_signature(),
                owned_onchain_tool_result_signature(),
            ]);
        let err = validate_execute_signature(&descriptor, "tool", "execute").unwrap_err();
        assert!(err.to_string().contains("UIDRequirements"));
    }

    #[test]
    fn validate_execute_signature_rejects_misplaced_authorization() {
        let descriptor = sui::grpc::FunctionDescriptor::default()
            .with_visibility(Visibility::Public)
            .with_is_entry(true)
            .with_parameters(vec![
                owned_uid_requirements_signature(),
                owned_authorization_signature(),
                owned_onchain_tool_result_signature(),
            ]);
        let err = validate_execute_signature(&descriptor, "tool", "execute").unwrap_err();
        assert!(err.to_string().contains("must begin with"));
    }

    #[test]
    fn validate_execute_signature_rejects_duplicate_internal_parameter() {
        let descriptor = sui::grpc::FunctionDescriptor::default()
            .with_visibility(Visibility::Public)
            .with_is_entry(true)
            .with_parameters(vec![
                owned_uid_requirements_signature(),
                owned_onchain_tool_result_signature(),
                owned_authorization_signature(),
            ]);
        let err = validate_execute_signature(&descriptor, "tool", "execute").unwrap_err();
        assert!(err.to_string().contains("fixed prefix"));
    }

    #[test]
    fn validate_execute_signature_accepts_entry_no_return_owned_result() {
        validate_execute_signature(&valid_execute_descriptor(), "tool", "execute").unwrap();
    }

    #[test]
    fn validate_execute_signature_detects_standard_mode() {
        assert_eq!(
            validate_execute_signature(&valid_execute_descriptor(), "tool", "execute").unwrap(),
            OnchainToolMode::Standard
        );
    }

    #[test]
    fn validate_execute_signature_detects_workflow_authorization() {
        assert_eq!(
            validate_execute_signature(&authorized_execute_descriptor(), "tool", "execute")
                .unwrap(),
            OnchainToolMode::WorkflowAuthorization
        );
    }

    #[tokio::test]
    #[cfg(feature = "test_utils")]
    async fn test_generate_input_schema_from_published_package() {
        use crate::test_utils;

        // Spin up the Sui instance.
        let test_utils::containers::SuiInstance {
            rpc_port,
            faucet_port,
            container: _container,
            ..
        } = test_utils::containers::setup_sui_instance().await;

        let rpc_url = format!("http://127.0.0.1:{rpc_port}");
        let faucet_url = format!("http://127.0.0.1:{faucet_port}/gas");

        let mut rng = rand::thread_rng();

        // Create a wallet and request some gas tokens.
        let pk = sui::crypto::Ed25519PrivateKey::generate(&mut rng);
        let addr = pk.public_key().derive_address();

        test_utils::faucet::request_tokens(&faucet_url, addr)
            .await
            .expect("Failed to request tokens from faucet.");

        let (gas_coin, _) = test_utils::gas::fetch_gas_coins(&rpc_url, addr)
            .await
            .expect("Failed to fetch gas coin.")
            .into_iter()
            .next()
            .unwrap();

        let package = crate::integration_test_support::compile_move_package(
            &std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/move/onchain_tool_test"),
        )
        .expect("failed to compile Move package");
        let response =
            test_utils::contracts::publish_move_package(&pk, &rpc_url, package, gas_coin).await;

        let pkg_id = response
            .objects
            .iter()
            .find_map(|c| match c.data() {
                sui::types::ObjectData::Package(m) => Some(m.id),
                _ => None,
            })
            .expect("Move package must be published");

        let client = Arc::new(
            sui::grpc::client(format!("http://127.0.0.1:{rpc_port}"))
                .expect("Could not create gRPC client"),
        );

        // Generate input schema for the onchain_tool::execute function.
        let schema_str = generate_input_schema(
            client,
            pkg_id.to_string().parse().unwrap(),
            "onchain_tool",
            "execute",
        )
        .await
        .expect("Failed to generate input schema");

        // Parse the schema.
        let schema: serde_json::Value =
            serde_json::from_str(&schema_str).expect("Failed to parse schema JSON");

        // Verify schema structure.
        // The execute function has hidden internal parameters:
        // execute(requirements: UIDRequirements, result: OnchainToolResult, current_execution: &mut DAGExecution, counter: &mut RandomCounter, increase_with: u64, _ctx: &mut TxContext)
        // After skipping hidden internal parameters, we should have:
        // - Parameter 0: current_execution (&mut DAGExecution) - object type, mutable
        // - Parameter 1: counter (&mut RandomCounter) - object type, mutable
        // - Parameter 2: increase_with (u64).

        // Check parameter 0 (current_execution).
        let param0 = schema
            .get("0")
            .expect("Schema should have parameter 0 (current_execution)");
        assert_eq!(param0["type"], "object");
        assert_eq!(param0["mutable"], true);
        assert!(param0["description"]
            .as_str()
            .unwrap()
            .contains("DAGExecution"));

        // Check parameter 1 (counter).
        let param1 = schema
            .get("1")
            .expect("Schema should have parameter 1 (counter)");
        assert_eq!(param1["type"], "object");
        assert_eq!(param1["mutable"], true);
        assert!(param1["description"]
            .as_str()
            .unwrap()
            .contains("RandomCounter"));

        // Check parameter 2 (increase_with).
        let param2 = schema
            .get("2")
            .expect("Schema should have parameter 2 (increase_with)");
        assert_eq!(param2["type"], "u64");
        assert_eq!(param2["description"], "64-bit unsigned integer");
        assert!(param2.get("mutable").is_none());

        // Verify only 3 user inputs remain after internal params are skipped.
        assert_eq!(schema.as_object().unwrap().len(), 3);
    }
}