aptos-sdk 0.6.0

A user-friendly, idiomatic Rust SDK for the Aptos blockchain
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
//! Aptos Names Service (ANS) client.
//!
//! Resolves `.apt` names to addresses and back, and builds the entry-function
//! payloads needed to register names and manage their primary-name / target
//! address records. This mirrors the read/write surface of the TypeScript
//! SDK's `ans` namespace, talking to the on-chain `router` module via view
//! functions and entry functions.
//!
//! # Networks
//!
//! ANS is only deployed on mainnet, testnet, and (for development) localnet.
//! On those networks [`AnsClient::new`] picks the correct `router` contract
//! address automatically. For devnet, custom networks, or a privately deployed
//! ANS, construct the client with [`AnsClient::with_router_address`] and supply
//! the contract address yourself.
//!
//! # Name format
//!
//! Names follow the ANS validation rules (see [`AnsName`]): each segment must
//! be 3-63 characters of lowercase `a-z`, `0-9`, and hyphens, and may not start
//! or end with a hyphen. A name may have at most two segments,
//! `subdomain.domain`, and an optional trailing `.apt` which is stripped.
//!
//! # Example
//!
//! ```rust,no_run
//! use aptos_sdk::api::{AnsClient, FullnodeClient};
//! use aptos_sdk::config::AptosConfig;
//!
//! # async fn run() -> aptos_sdk::error::AptosResult<()> {
//! let fullnode = FullnodeClient::new(AptosConfig::mainnet())?;
//! let ans = AnsClient::new(fullnode);
//!
//! if let Some(address) = ans.get_target_address("greg.apt").await? {
//!     println!("greg.apt resolves to {address}");
//! }
//! # Ok(())
//! # }
//! ```

use crate::api::FullnodeClient;
use crate::config::Network;
use crate::error::{AptosError, AptosResult};
use crate::transaction::EntryFunction;
use crate::types::AccountAddress;

/// `router` contract address on mainnet.
const MAINNET_ROUTER: &str = "0x867ed1f6bf916171b1de3ee92849b8978b7d1b9e0a8cc982a3d19d535dfd9c0c";
/// `router` contract address on testnet.
const TESTNET_ROUTER: &str = "0x5f8fd2347449685cf41d4db97926ec3a096eaf381332be4f1318ad4d16a8497c";
/// Default `router` contract address used by the local ANS test deployment
/// (matches the TypeScript SDK's `LOCAL_ANS_ACCOUNT_ADDRESS`).
const LOCAL_ROUTER: &str = "0x585fc9f0f0c54183b039ffc770ca282ebd87307916c215a3e692f2f8e4305e82";

/// Minimum length of a single ANS name segment.
const MIN_SEGMENT_LEN: usize = 3;
/// Maximum length of a single ANS name segment.
const MAX_SEGMENT_LEN: usize = 63;

/// Human-readable description of the segment validation rules.
const SEGMENT_RULES: &str = "a segment must be 3-63 characters of lowercase a-z, 0-9, and hyphens, \
     and may not start or end with a hyphen";

/// A validated ANS name, split into its domain and optional subdomain.
///
/// Construct one with [`AnsName::parse`], which enforces the ANS validation
/// rules and strips a trailing `.apt`.
///
/// # Example
///
/// ```rust
/// use aptos_sdk::api::ans::AnsName;
///
/// let name = AnsName::parse("alice.apt")?;
/// assert_eq!(name.domain(), "alice");
/// assert_eq!(name.subdomain(), None);
///
/// let sub = AnsName::parse("wallet.alice.apt")?;
/// assert_eq!(sub.domain(), "alice");
/// assert_eq!(sub.subdomain(), Some("wallet"));
/// # Ok::<(), aptos_sdk::error::AptosError>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnsName {
    domain: String,
    subdomain: Option<String>,
}

impl AnsName {
    /// Parses and validates an ANS name.
    ///
    /// Accepts names with or without a trailing `.apt`, and either a bare
    /// domain (`alice`) or a `subdomain.domain` (`wallet.alice`).
    ///
    /// # Errors
    ///
    /// Returns an error if the name has more than two segments or any segment
    /// violates the ANS rules (3-63 characters of lowercase `a-z`, `0-9`, and
    /// non-leading/trailing hyphens).
    pub fn parse(name: &str) -> AptosResult<Self> {
        let trimmed = name.strip_suffix(".apt").unwrap_or(name);
        let mut parts = trimmed.split('.');
        let first = parts.next().unwrap_or("");
        let second = parts.next();
        if parts.next().is_some() {
            return Err(invalid_name(name, "a name may have at most two segments"));
        }

        if !is_valid_segment(first) {
            return Err(invalid_name(first, SEGMENT_RULES));
        }
        if let Some(second) = second
            && !is_valid_segment(second)
        {
            return Err(invalid_name(second, SEGMENT_RULES));
        }

        match second {
            // "subdomain.domain": first is the subdomain, second the domain.
            Some(domain) => Ok(Self {
                domain: domain.to_string(),
                subdomain: Some(first.to_string()),
            }),
            // "domain": no subdomain.
            None => Ok(Self {
                domain: first.to_string(),
                subdomain: None,
            }),
        }
    }

    /// Returns the domain (top-level) segment, e.g. `alice` for `alice.apt`.
    #[must_use]
    pub fn domain(&self) -> &str {
        &self.domain
    }

    /// Returns the subdomain segment, if any.
    #[must_use]
    pub fn subdomain(&self) -> Option<&str> {
        self.subdomain.as_deref()
    }

    /// Returns `true` if this name has a subdomain.
    #[must_use]
    pub fn is_subdomain(&self) -> bool {
        self.subdomain.is_some()
    }

    /// Returns the fully qualified name (without the `.apt` suffix), e.g.
    /// `wallet.alice` or `alice`.
    #[must_use]
    pub fn full_name(&self) -> String {
        match &self.subdomain {
            Some(sub) => format!("{sub}.{}", self.domain),
            None => self.domain.clone(),
        }
    }
}

impl std::fmt::Display for AnsName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.apt", self.full_name())
    }
}

fn invalid_name(value: &str, reason: &str) -> AptosError {
    AptosError::Other(anyhow::anyhow!("invalid ANS name '{value}': {reason}"))
}

/// Validates a single ANS segment against the ANS naming rules.
fn is_valid_segment(segment: &str) -> bool {
    let len = segment.len();
    if !(MIN_SEGMENT_LEN..=MAX_SEGMENT_LEN).contains(&len) {
        return false;
    }
    let bytes = segment.as_bytes();
    let is_alnum = |b: u8| b.is_ascii_lowercase() || b.is_ascii_digit();
    // First and last characters must be alphanumeric (no leading/trailing hyphen).
    if !is_alnum(bytes[0]) || !is_alnum(bytes[len - 1]) {
        return false;
    }
    bytes.iter().all(|&b| is_alnum(b) || b == b'-')
}

/// Builds the standard `(domain: String, subdomain: Option<String>)` argument
/// pair used by most `router` functions.
fn domain_subdomain_args(name: &AnsName) -> AptosResult<Vec<Vec<u8>>> {
    Ok(vec![
        bcs_string(name.domain())?,
        bcs_option_string(name.subdomain())?,
    ])
}

/// Client for the Aptos Names Service.
///
/// Cheap to clone (wraps a [`FullnodeClient`]). See the [module docs](self) for
/// usage and network support.
#[derive(Debug, Clone)]
pub struct AnsClient {
    fullnode: FullnodeClient,
    /// Explicit router contract address. When `None`, the address is resolved
    /// from the fullnode's configured network.
    router_override: Option<AccountAddress>,
}

impl AnsClient {
    /// Constructs an ANS client that resolves the `router` contract address
    /// from the fullnode's configured network (mainnet / testnet / localnet).
    ///
    /// For networks without a built-in ANS deployment (devnet, custom), use
    /// [`with_router_address`](Self::with_router_address) instead; calls on a
    /// client built with [`new`](Self::new) for such a network return an error.
    #[must_use]
    pub fn new(fullnode: FullnodeClient) -> Self {
        Self {
            fullnode,
            router_override: None,
        }
    }

    /// Constructs an ANS client pinned to an explicit `router` contract
    /// address.
    ///
    /// Use this for devnet, custom networks, or a privately deployed ANS where
    /// the contract address is not built in.
    #[must_use]
    pub fn with_router_address(fullnode: FullnodeClient, router_address: AccountAddress) -> Self {
        Self {
            fullnode,
            router_override: Some(router_address),
        }
    }

    /// Returns the resolved `router` contract address for this client.
    ///
    /// # Errors
    ///
    /// Returns [`AptosError::Config`] if no override was supplied and the
    /// configured network has no known ANS deployment.
    pub fn router_address(&self) -> AptosResult<AccountAddress> {
        if let Some(addr) = self.router_override {
            return Ok(addr);
        }
        let hex = match self.fullnode.config().network() {
            Network::Mainnet => MAINNET_ROUTER,
            Network::Testnet => TESTNET_ROUTER,
            Network::Local => LOCAL_ROUTER,
            other => {
                return Err(AptosError::Config(format!(
                    "ANS is not deployed on {}; construct the client with \
                     AnsClient::with_router_address to supply the router contract address",
                    other.as_str()
                )));
            }
        };
        AccountAddress::from_hex(hex)
    }

    // === Reads ===

    /// Resolves the **target address** a name points to (where it resolves to),
    /// or `None` if the name is unregistered or has no target set.
    ///
    /// This is the address callers usually want when "looking up a name". It is
    /// distinct from the owner address (see
    /// [`get_owner_address`](Self::get_owner_address)).
    ///
    /// # Errors
    ///
    /// Returns an error if the network has no ANS deployment, the name is
    /// invalid, or the underlying view call fails.
    pub async fn get_target_address(&self, name: &str) -> AptosResult<Option<AccountAddress>> {
        let name = AnsName::parse(name)?;
        let values = self
            .view_router("get_target_addr", domain_subdomain_args(&name)?)
            .await?;
        option_address(values.first())
    }

    /// Resolves the **owner address** of a name (the account that controls the
    /// registration), or `None` if the name is unregistered.
    ///
    /// # Errors
    ///
    /// Returns an error if the network has no ANS deployment, the name is
    /// invalid, or the underlying view call fails.
    pub async fn get_owner_address(&self, name: &str) -> AptosResult<Option<AccountAddress>> {
        let name = AnsName::parse(name)?;
        let values = self
            .view_router("get_owner_addr", domain_subdomain_args(&name)?)
            .await?;
        option_address(values.first())
    }

    /// Returns the primary name registered to an address (as a fully qualified
    /// name without the `.apt` suffix, e.g. `wallet.alice` or `alice`), or
    /// `None` if the address has no primary name.
    ///
    /// # Errors
    ///
    /// Returns an error if the network has no ANS deployment or the underlying
    /// view call fails.
    pub async fn get_primary_name(&self, address: AccountAddress) -> AptosResult<Option<String>> {
        let args = vec![bcs_address(address)?];
        let values = self.view_router("get_primary_name", args).await?;

        // The router returns exactly (Option<String> subdomain, Option<String>
        // domain). A shorter response is a malformed reply, not "no primary
        // name", so surface it rather than masking a node/router bug.
        if values.len() < 2 {
            return Err(AptosError::Internal(format!(
                "ANS get_primary_name returned {} value(s); expected 2 (subdomain, domain)",
                values.len()
            )));
        }
        let subdomain = option_string(&values[0])?;
        let domain = option_string(&values[1])?;

        Ok(domain.map(|domain| match subdomain {
            Some(sub) => format!("{sub}.{domain}"),
            None => domain,
        }))
    }

    /// Returns the expiration timestamp of a name in **seconds since the Unix
    /// epoch**, or `None` if the name is unregistered.
    ///
    /// Note: the TypeScript SDK returns milliseconds; this returns the raw
    /// on-chain value in seconds. Multiply by 1000 for millisecond parity.
    ///
    /// # Errors
    ///
    /// Returns an error if the network has no ANS deployment, the name is
    /// invalid, or the view call fails. A missing name is reported as
    /// `Ok(None)`, not an error: the Move view aborts, which the node surfaces
    /// as an HTTP 400 carrying the abort code. Other API failures (rate limits,
    /// 5xx, malformed requests) propagate so transient/operational problems are
    /// not mistaken for an unregistered name.
    pub async fn get_expiration(&self, name: &str) -> AptosResult<Option<u64>> {
        let name = AnsName::parse(name)?;
        let args = domain_subdomain_args(&name)?;
        match self.view_router("get_expiration", args).await {
            // A successful response must carry exactly one `u64`. The missing-
            // name case is handled by the Move-abort branch below, so an empty
            // or non-`u64` *successful* response is a malformed reply, not "no
            // expiration".
            Ok(values) => {
                let raw = values.first().ok_or_else(|| {
                    AptosError::Internal("ANS get_expiration returned no value".into())
                })?;
                let secs = parse_u64(raw).ok_or_else(|| {
                    AptosError::Internal(format!(
                        "ANS get_expiration returned a non-u64 value: {raw}"
                    ))
                })?;
                Ok(Some(secs))
            }
            // A missing name aborts in the Move view, which the node surfaces as
            // an HTTP 400 carrying the Move abort code (`vm_error_code`). Treat
            // *only* that as "no expiration"; propagate everything else (rate
            // limits, 5xx, malformed requests) so operational failures are not
            // mistaken for an unregistered name.
            Err(AptosError::Api {
                status_code: 400,
                vm_error_code: Some(_),
                ..
            }) => Ok(None),
            Err(e) => Err(e),
        }
    }

    /// Resolves a name to its target address, erroring if it does not resolve.
    ///
    /// This is a convenience wrapper over
    /// [`get_target_address`](Self::get_target_address) for callers that treat
    /// an unresolved name as an error.
    ///
    /// # Errors
    ///
    /// Returns [`AptosError::NotFound`] if the name does not resolve to an
    /// address, plus any error from
    /// [`get_target_address`](Self::get_target_address).
    pub async fn lookup(&self, name: &str) -> AptosResult<AccountAddress> {
        self.get_target_address(name).await?.ok_or_else(|| {
            AptosError::NotFound(format!("ANS name '{name}' does not resolve to an address"))
        })
    }

    /// Returns the primary name registered to an address, if any.
    ///
    /// Alias for [`get_primary_name`](Self::get_primary_name).
    ///
    /// # Errors
    ///
    /// Returns an error if the network has no ANS deployment or the underlying
    /// view call fails.
    pub async fn reverse_lookup(&self, address: AccountAddress) -> AptosResult<Option<String>> {
        self.get_primary_name(address).await
    }

    // === Writes (entry-function builders) ===

    /// Builds the payload to register a top-level domain for the given
    /// duration (in seconds).
    ///
    /// `target_address` is the address the name will resolve to (defaults to
    /// the sender on-chain when `None`); `to_address` is the account that will
    /// own the registration (defaults to the sender when `None`).
    ///
    /// # Errors
    ///
    /// Returns an error if the network has no ANS deployment, the name is
    /// invalid, the name has a subdomain (use a subdomain-specific flow), or
    /// argument encoding fails.
    pub fn register_domain_payload(
        &self,
        name: &str,
        registration_duration_secs: u64,
        target_address: Option<AccountAddress>,
        to_address: Option<AccountAddress>,
    ) -> AptosResult<EntryFunction> {
        let name = AnsName::parse(name)?;
        if name.is_subdomain() {
            return Err(invalid_name(
                &name.full_name(),
                "register_domain_payload expects a top-level domain, not a subdomain",
            ));
        }
        let args = vec![
            bcs_string(name.domain())?,
            bcs_u64(registration_duration_secs)?,
            bcs_option_address(target_address)?,
            bcs_option_address(to_address)?,
        ];
        self.router_entry("register_domain", args)
    }

    /// Builds the payload to set the sender's primary name to `name`.
    ///
    /// # Errors
    ///
    /// Returns an error if the network has no ANS deployment, the name is
    /// invalid, or argument encoding fails.
    pub fn set_primary_name_payload(&self, name: &str) -> AptosResult<EntryFunction> {
        let name = AnsName::parse(name)?;
        self.router_entry("set_primary_name", domain_subdomain_args(&name)?)
    }

    /// Builds the payload to clear the sender's primary name.
    ///
    /// # Errors
    ///
    /// Returns an error if the network has no ANS deployment.
    pub fn clear_primary_name_payload(&self) -> AptosResult<EntryFunction> {
        self.router_entry("clear_primary_name", vec![])
    }

    /// Builds the payload to point `name` at `address` (set its target
    /// address).
    ///
    /// # Errors
    ///
    /// Returns an error if the network has no ANS deployment, the name is
    /// invalid, or argument encoding fails.
    pub fn set_target_address_payload(
        &self,
        name: &str,
        address: AccountAddress,
    ) -> AptosResult<EntryFunction> {
        let name = AnsName::parse(name)?;
        let mut args = domain_subdomain_args(&name)?;
        args.push(bcs_address(address)?);
        self.router_entry("set_target_addr", args)
    }

    /// Builds the payload to clear the target address of `name`.
    ///
    /// # Errors
    ///
    /// Returns an error if the network has no ANS deployment, the name is
    /// invalid, or argument encoding fails.
    pub fn clear_target_address_payload(&self, name: &str) -> AptosResult<EntryFunction> {
        let name = AnsName::parse(name)?;
        self.router_entry("clear_target_addr", domain_subdomain_args(&name)?)
    }

    // === Internal helpers ===

    /// Calls a `router::<function>` view function with BCS-encoded args.
    async fn view_router(
        &self,
        function: &str,
        args: Vec<Vec<u8>>,
    ) -> AptosResult<Vec<serde_json::Value>> {
        let router = self.router_address()?;
        let function_id = format!("{router}::router::{function}");
        let response = self
            .fullnode
            .view_bcs_args(&function_id, vec![], args)
            .await?;
        Ok(response.into_inner())
    }

    /// Builds an entry-function payload targeting `router::<function>`.
    fn router_entry(&self, function: &str, args: Vec<Vec<u8>>) -> AptosResult<EntryFunction> {
        let router = self.router_address()?;
        let function_id = format!("{router}::router::{function}");
        EntryFunction::from_function_id(&function_id, vec![], args)
    }
}

// === BCS argument encoders ===

fn bcs_string(value: &str) -> AptosResult<Vec<u8>> {
    aptos_bcs::to_bytes(&value.to_string()).map_err(AptosError::bcs)
}

fn bcs_option_string(value: Option<&str>) -> AptosResult<Vec<u8>> {
    aptos_bcs::to_bytes(&value.map(ToString::to_string)).map_err(AptosError::bcs)
}

fn bcs_address(value: AccountAddress) -> AptosResult<Vec<u8>> {
    aptos_bcs::to_bytes(&value).map_err(AptosError::bcs)
}

fn bcs_option_address(value: Option<AccountAddress>) -> AptosResult<Vec<u8>> {
    aptos_bcs::to_bytes(&value).map_err(AptosError::bcs)
}

fn bcs_u64(value: u64) -> AptosResult<Vec<u8>> {
    aptos_bcs::to_bytes(&value).map_err(AptosError::bcs)
}

// === JSON result decoders ===

/// Unwraps a Move `Option<T>` from its JSON form.
///
/// The node renders `0x1::option::Option<T>` as `{"vec": []}` (none) or
/// `{"vec": [value]}` (some); a bare array is also accepted defensively.
/// `Ok(None)` is a genuine `Option::none()`. A value that is not Option-shaped
/// at all is a malformed reply and yields an error rather than being silently
/// treated as "not found".
fn unwrap_option(value: &serde_json::Value) -> AptosResult<Option<&serde_json::Value>> {
    if let Some(vec) = value.get("vec").and_then(serde_json::Value::as_array) {
        return Ok(vec.first());
    }
    if let Some(arr) = value.as_array() {
        return Ok(arr.first());
    }
    Err(AptosError::Internal(format!(
        "ANS view returned a value that is not a Move Option: {value}"
    )))
}

/// Decodes an `Option<address>` view result into an [`AccountAddress`].
///
/// A Move `Option::none()` (an unregistered or unset record) yields `Ok(None)`.
/// A malformed reply -- a missing return value, a non-Option value, a
/// non-string entry, or an undecodable address -- is surfaced as an error
/// rather than being silently treated as "not found".
fn option_address(value: Option<&serde_json::Value>) -> AptosResult<Option<AccountAddress>> {
    let value = value.ok_or_else(|| {
        AptosError::Internal(
            "ANS view returned no value where an Option<address> was expected".into(),
        )
    })?;
    let Some(inner) = unwrap_option(value)? else {
        return Ok(None);
    };
    let s = inner.as_str().ok_or_else(|| {
        AptosError::Internal(format!("ANS view returned a non-string address: {inner}"))
    })?;
    let address = AccountAddress::from_hex(s).map_err(|e| {
        AptosError::Internal(format!("ANS view returned a malformed address '{s}': {e}"))
    })?;
    Ok(Some(address))
}

/// Decodes an `Option<String>` view result, mapping an empty string to `None`.
///
/// A genuine `Option::none()` (or an empty string) yields `Ok(None)`; a
/// non-Option or non-string value is a malformed reply and yields an error.
fn option_string(value: &serde_json::Value) -> AptosResult<Option<String>> {
    let Some(inner) = unwrap_option(value)? else {
        return Ok(None);
    };
    let s = inner.as_str().ok_or_else(|| {
        AptosError::Internal(format!("ANS view returned a non-string value: {inner}"))
    })?;
    Ok(if s.is_empty() {
        None
    } else {
        Some(s.to_string())
    })
}

/// Parses a `u64` view result, which the node renders as a JSON string.
fn parse_u64(value: &serde_json::Value) -> Option<u64> {
    if let Some(n) = value.as_u64() {
        return Some(n);
    }
    value.as_str().and_then(|s| s.parse().ok())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::AptosConfig;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn ans_for(server: &MockServer) -> AnsClient {
        let url = format!("{}/v1", server.uri());
        let config = AptosConfig::custom(&url).unwrap().without_retry();
        let fullnode = FullnodeClient::new(config).unwrap();
        // Custom network has no built-in ANS deployment; pin a router address.
        AnsClient::with_router_address(fullnode, AccountAddress::from_hex("0x1").unwrap())
    }

    #[test]
    fn parse_plain_domain() {
        let name = AnsName::parse("alice.apt").unwrap();
        assert_eq!(name.domain(), "alice");
        assert_eq!(name.subdomain(), None);
        assert!(!name.is_subdomain());
        assert_eq!(name.full_name(), "alice");
        assert_eq!(name.to_string(), "alice.apt");
    }

    #[test]
    fn parse_without_suffix() {
        let name = AnsName::parse("alice").unwrap();
        assert_eq!(name.domain(), "alice");
        assert_eq!(name.subdomain(), None);
    }

    #[test]
    fn parse_subdomain() {
        let name = AnsName::parse("wallet.alice.apt").unwrap();
        assert_eq!(name.domain(), "alice");
        assert_eq!(name.subdomain(), Some("wallet"));
        assert!(name.is_subdomain());
        assert_eq!(name.full_name(), "wallet.alice");
    }

    #[test]
    fn parse_rejects_invalid_names() {
        // Too short.
        assert!(AnsName::parse("ab").is_err());
        // Leading hyphen.
        assert!(AnsName::parse("-abc").is_err());
        // Trailing hyphen.
        assert!(AnsName::parse("abc-").is_err());
        // Uppercase.
        assert!(AnsName::parse("Alice").is_err());
        // Three segments.
        assert!(AnsName::parse("a.b.c").is_err());
        // Invalid characters.
        assert!(AnsName::parse("ali_ce").is_err());
    }

    #[test]
    fn segment_validation_boundaries() {
        assert!(is_valid_segment("abc"));
        assert!(is_valid_segment("a-c"));
        assert!(is_valid_segment("a1c"));
        assert!(is_valid_segment(&"a".repeat(63)));
        assert!(!is_valid_segment(&"a".repeat(64)));
        assert!(!is_valid_segment("ab"));
        assert!(!is_valid_segment("-bc"));
        assert!(!is_valid_segment("ab-"));
    }

    #[test]
    fn router_address_unsupported_network_errors() {
        // Devnet has no built-in ANS deployment.
        let fullnode = FullnodeClient::new(AptosConfig::devnet()).unwrap();
        let ans = AnsClient::new(fullnode);
        assert!(matches!(ans.router_address(), Err(AptosError::Config(_))));
    }

    #[test]
    fn router_address_known_networks() {
        let mainnet = AnsClient::new(FullnodeClient::new(AptosConfig::mainnet()).unwrap());
        assert_eq!(
            mainnet.router_address().unwrap(),
            AccountAddress::from_hex(MAINNET_ROUTER).unwrap()
        );
        let testnet = AnsClient::new(FullnodeClient::new(AptosConfig::testnet()).unwrap());
        assert_eq!(
            testnet.router_address().unwrap(),
            AccountAddress::from_hex(TESTNET_ROUTER).unwrap()
        );
    }

    #[tokio::test]
    async fn get_target_address_resolves() {
        let server = MockServer::start().await;
        let addr = "0x0000000000000000000000000000000000000000000000000000000000000abc";
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!([{"vec": [addr]}])),
            )
            .expect(1)
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let resolved = ans.get_target_address("alice.apt").await.unwrap();
        assert_eq!(resolved, Some(AccountAddress::from_hex(addr).unwrap()));
    }

    #[tokio::test]
    async fn get_target_address_none_when_unregistered() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!([{"vec": []}])),
            )
            .expect(1)
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let resolved = ans.get_target_address("alice.apt").await.unwrap();
        assert_eq!(resolved, None);
    }

    #[tokio::test]
    async fn get_primary_name_combines_subdomain_and_domain() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(ResponseTemplate::new(200).set_body_json(
                // (subdomain, domain)
                serde_json::json!([{"vec": ["wallet"]}, {"vec": ["alice"]}]),
            ))
            .expect(1)
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let name = ans.get_primary_name(AccountAddress::ONE).await.unwrap();
        assert_eq!(name, Some("wallet.alice".to_string()));
    }

    #[tokio::test]
    async fn get_primary_name_domain_only() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!([{"vec": []}, {"vec": ["alice"]}])),
            )
            .expect(1)
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let name = ans.get_primary_name(AccountAddress::ONE).await.unwrap();
        assert_eq!(name, Some("alice".to_string()));
    }

    #[tokio::test]
    async fn get_primary_name_none() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!([{"vec": []}, {"vec": []}])),
            )
            .expect(1)
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let name = ans.get_primary_name(AccountAddress::ONE).await.unwrap();
        assert_eq!(name, None);
    }

    #[tokio::test]
    async fn get_expiration_parses_seconds() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!(["1700000000"])),
            )
            .expect(1)
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let expiration = ans.get_expiration("alice.apt").await.unwrap();
        assert_eq!(expiration, Some(1_700_000_000));
    }

    #[tokio::test]
    async fn get_expiration_none_on_move_abort() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(ResponseTemplate::new(400).set_body_json(serde_json::json!({
                "message": "Move abort",
                "error_code": "invalid_input",
                "vm_error_code": 196609
            })))
            .expect(1)
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let expiration = ans.get_expiration("alice.apt").await.unwrap();
        assert_eq!(expiration, None);
    }

    #[tokio::test]
    async fn lookup_errors_when_unresolved() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!([{"vec": []}])),
            )
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let err = ans.lookup("alice.apt").await.unwrap_err();
        assert!(matches!(err, AptosError::NotFound(_)));
    }

    #[test]
    fn set_primary_name_payload_encodes_arguments() {
        let router = AccountAddress::from_hex("0x1").unwrap();
        let fullnode = FullnodeClient::new(AptosConfig::mainnet()).unwrap();
        let ans = AnsClient::with_router_address(fullnode, router);

        let payload = ans.set_primary_name_payload("alice.apt").unwrap();
        assert_eq!(payload.module.address, router);
        assert_eq!(payload.module.name.as_str(), "router");
        assert_eq!(payload.function, "set_primary_name");
        // (domain: String "alice", subdomain: Option<String>::None)
        assert_eq!(payload.args.len(), 2);
        assert_eq!(
            payload.args[0],
            aptos_bcs::to_bytes(&"alice".to_string()).unwrap()
        );
        assert_eq!(
            payload.args[1],
            aptos_bcs::to_bytes(&Option::<String>::None).unwrap()
        );
    }

    #[test]
    fn set_target_address_payload_encodes_arguments() {
        let router = AccountAddress::from_hex("0x1").unwrap();
        let target = AccountAddress::from_hex("0xabc").unwrap();
        let fullnode = FullnodeClient::new(AptosConfig::mainnet()).unwrap();
        let ans = AnsClient::with_router_address(fullnode, router);

        let payload = ans
            .set_target_address_payload("wallet.alice.apt", target)
            .unwrap();
        assert_eq!(payload.function, "set_target_addr");
        // (domain "alice", subdomain Some("wallet"), address target)
        assert_eq!(payload.args.len(), 3);
        assert_eq!(
            payload.args[0],
            aptos_bcs::to_bytes(&"alice".to_string()).unwrap()
        );
        assert_eq!(
            payload.args[1],
            aptos_bcs::to_bytes(&Some("wallet".to_string())).unwrap()
        );
        assert_eq!(payload.args[2], aptos_bcs::to_bytes(&target).unwrap());
    }

    #[test]
    fn register_domain_payload_rejects_subdomain() {
        let fullnode = FullnodeClient::new(AptosConfig::mainnet()).unwrap();
        let ans =
            AnsClient::with_router_address(fullnode, AccountAddress::from_hex("0x1").unwrap());
        let result = ans.register_domain_payload("wallet.alice.apt", 31_536_000, None, None);
        assert!(matches!(result, Err(AptosError::Other(_))));
    }

    #[test]
    fn register_domain_payload_encodes_arguments() {
        let router = AccountAddress::from_hex("0x1").unwrap();
        let target = AccountAddress::from_hex("0xabc").unwrap();
        let fullnode = FullnodeClient::new(AptosConfig::mainnet()).unwrap();
        let ans = AnsClient::with_router_address(fullnode, router);

        let payload = ans
            .register_domain_payload("alice.apt", 31_536_000, Some(target), None)
            .unwrap();
        assert_eq!(payload.function, "register_domain");
        // (domain "alice", duration u64, target Some(addr), to None)
        assert_eq!(payload.args.len(), 4);
        assert_eq!(
            payload.args[0],
            aptos_bcs::to_bytes(&"alice".to_string()).unwrap()
        );
        assert_eq!(
            payload.args[1],
            aptos_bcs::to_bytes(&31_536_000u64).unwrap()
        );
        assert_eq!(payload.args[2], aptos_bcs::to_bytes(&Some(target)).unwrap());
        assert_eq!(
            payload.args[3],
            aptos_bcs::to_bytes(&Option::<AccountAddress>::None).unwrap()
        );
    }

    #[test]
    fn clear_primary_name_payload_has_no_args() {
        let fullnode = FullnodeClient::new(AptosConfig::mainnet()).unwrap();
        let ans =
            AnsClient::with_router_address(fullnode, AccountAddress::from_hex("0x1").unwrap());
        let payload = ans.clear_primary_name_payload().unwrap();
        assert_eq!(payload.function, "clear_primary_name");
        assert!(payload.args.is_empty());
    }

    #[tokio::test]
    async fn get_owner_address_resolves() {
        let server = MockServer::start().await;
        let addr = "0x0000000000000000000000000000000000000000000000000000000000000abc";
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!([{"vec": [addr]}])),
            )
            .expect(1)
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let owner = ans.get_owner_address("alice.apt").await.unwrap();
        assert_eq!(owner, Some(AccountAddress::from_hex(addr).unwrap()));
    }

    #[tokio::test]
    async fn lookup_resolves_to_target_address() {
        let server = MockServer::start().await;
        let addr = "0x0000000000000000000000000000000000000000000000000000000000000abc";
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!([{"vec": [addr]}])),
            )
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let resolved = ans.lookup("alice.apt").await.unwrap();
        assert_eq!(resolved, AccountAddress::from_hex(addr).unwrap());
    }

    #[tokio::test]
    async fn reverse_lookup_returns_primary_name() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!([{"vec": []}, {"vec": ["alice"]}])),
            )
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let name = ans.reverse_lookup(AccountAddress::ONE).await.unwrap();
        assert_eq!(name, Some("alice".to_string()));
    }

    #[test]
    fn clear_target_address_payload_encodes_arguments() {
        let router = AccountAddress::from_hex("0x1").unwrap();
        let fullnode = FullnodeClient::new(AptosConfig::mainnet()).unwrap();
        let ans = AnsClient::with_router_address(fullnode, router);

        let payload = ans.clear_target_address_payload("alice.apt").unwrap();
        assert_eq!(payload.function, "clear_target_addr");
        // (domain "alice", subdomain Option<String>::None)
        assert_eq!(payload.args.len(), 2);
        assert_eq!(
            payload.args[0],
            aptos_bcs::to_bytes(&"alice".to_string()).unwrap()
        );
        assert_eq!(
            payload.args[1],
            aptos_bcs::to_bytes(&Option::<String>::None).unwrap()
        );
    }

    #[tokio::test]
    async fn get_expiration_propagates_server_error() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(ResponseTemplate::new(500).set_body_json(serde_json::json!({
                "message": "internal error"
            })))
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        // A 5xx (or any non-abort API error) must surface as an error rather
        // than being silently coerced to `None`.
        let result = ans.get_expiration("alice.apt").await;
        assert!(matches!(
            result,
            Err(AptosError::Api {
                status_code: 500,
                ..
            })
        ));
    }

    #[tokio::test]
    async fn get_target_address_errors_on_malformed_address() {
        let server = MockServer::start().await;
        // A present-but-undecodable address must surface as an error, not be
        // silently treated as "unregistered" (which would let `lookup` report
        // a spurious NotFound).
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!([{"vec": ["not-an-address"]}])),
            )
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let err = ans.get_target_address("alice.apt").await.unwrap_err();
        assert!(matches!(err, AptosError::Internal(_)));
    }

    #[tokio::test]
    async fn get_expiration_errors_on_malformed_success() {
        let server = MockServer::start().await;
        // A successful response with no return value is malformed and must not
        // be confused with a missing name (which arrives as a Move-abort 400).
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([])))
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let err = ans.get_expiration("alice.apt").await.unwrap_err();
        assert!(matches!(err, AptosError::Internal(_)));
    }

    #[tokio::test]
    async fn get_target_address_none_on_move_option_none() {
        let server = MockServer::start().await;
        // A genuine Move `Option::none()` (empty `vec`) is an unset record and
        // must remain `Ok(None)`.
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!([{"vec": []}])),
            )
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        assert_eq!(ans.get_target_address("alice.apt").await.unwrap(), None);
    }

    #[tokio::test]
    async fn get_target_address_errors_on_non_option_value() {
        let server = MockServer::start().await;
        // A value that is not Move-Option-shaped (here a bare string instead of
        // `{"vec": [...]}`) is a malformed reply and must error, not be coerced
        // to "unregistered".
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!(["0x1"])))
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let err = ans.get_target_address("alice.apt").await.unwrap_err();
        assert!(matches!(err, AptosError::Internal(_)));
    }

    #[tokio::test]
    async fn get_primary_name_errors_on_short_response() {
        let server = MockServer::start().await;
        // The router view returns two values; a one-value response is malformed
        // and must surface as an error rather than "no primary name".
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!([{"vec": ["alice"]}])),
            )
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let err = ans.get_primary_name(AccountAddress::ONE).await.unwrap_err();
        assert!(matches!(err, AptosError::Internal(_)));
    }

    #[tokio::test]
    async fn get_primary_name_errors_on_non_string_value() {
        let server = MockServer::start().await;
        // A non-string inside the domain Option is a malformed reply.
        Mock::given(method("POST"))
            .and(path("/v1/view"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!([{"vec": []}, {"vec": [42]}])),
            )
            .mount(&server)
            .await;

        let ans = ans_for(&server);
        let err = ans.get_primary_name(AccountAddress::ONE).await.unwrap_err();
        assert!(matches!(err, AptosError::Internal(_)));
    }
}