namada_ibc 0.150.2

Namada IBC
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
//! IbcCommonContext implementation for IBC

use ibc::apps::nft_transfer::types::{PrefixedClassId, TokenId};
use ibc::clients::tendermint::consensus_state::ConsensusState as TmConsensusState;
use ibc::clients::tendermint::types::ConsensusState as TmConsensusStateType;
use ibc::core::channel::types::channel::ChannelEnd;
use ibc::core::channel::types::commitment::{
    AcknowledgementCommitment, PacketCommitment,
};
use ibc::core::channel::types::packet::Receipt;
use ibc::core::client::types::Height;
use ibc::core::connection::types::ConnectionEnd;
use ibc::core::host::types::error::HostError;
use ibc::core::host::types::identifiers::{
    ChannelId, ClientId, ConnectionId, PortId, Sequence,
};
use ibc::primitives::proto::{Any, Protobuf};
use ibc::primitives::{IntoHostTime, IntoTimestamp, Timestamp};
use namada_core::address::Address;
use namada_core::chain::BlockHeight;
use namada_core::storage::Key;
use namada_core::tendermint::Time as TmTime;
use namada_core::token::Amount;
use namada_state::{Error as StorageError, StorageRead, StorageWrite};
use namada_systems::trans_token;
use prost::Message;

use super::client::{AnyClientState, AnyConsensusState};
use super::storage::IbcStorageContext;
use crate::{NftClass, NftMetadata, storage, trace};

/// Result of IBC common function call
pub type Result<T> = std::result::Result<T, HostError>;

/// Context to handle typical IBC data
pub trait IbcCommonContext: IbcStorageContext {
    /// Get the ClientState
    fn client_state(&self, client_id: &ClientId) -> Result<AnyClientState> {
        let key = storage::client_state_key(client_id);
        match self.storage().read_bytes(&key)? {
            Some(value) => Any::decode(&value[..])
                .map_err(|e| HostError::FailedToRetrieve {
                    description: format!(
                        "Decoding client state failed: ID {client_id}, error \
                         {e}"
                    ),
                })?
                .try_into(),
            None => Err(HostError::FailedToRetrieve {
                description: format!("No client state: ID {client_id}"),
            }),
        }
    }

    /// Store the ClientState
    fn store_client_state(
        &mut self,
        client_id: &ClientId,
        client_state: AnyClientState,
    ) -> Result<()> {
        let key = storage::client_state_key(client_id);
        let bytes = Any::from(client_state).encode_to_vec();
        self.storage_mut()
            .write_bytes(&key, bytes)
            .map_err(HostError::from)
    }

    /// Get the ConsensusState
    fn consensus_state(
        &self,
        client_id: &ClientId,
        height: Height,
    ) -> Result<AnyConsensusState> {
        let key = storage::consensus_state_key(client_id, height);
        match self.storage().read_bytes(&key)? {
            Some(value) => Any::decode(&value[..])
                .map_err(|e| HostError::FailedToRetrieve {
                    description: format!(
                        "Decoding consensus state failed: ID {client_id}, \
                         height {height} error {e}"
                    ),
                })?
                .try_into(),
            None => Err(HostError::FailedToRetrieve {
                description: format!(
                    "No consensus state: ID {client_id}, height {height}"
                ),
            }),
        }
    }

    /// Store the ConsensusState
    fn store_consensus_state(
        &mut self,
        client_id: &ClientId,
        height: Height,
        consensus_state: AnyConsensusState,
    ) -> Result<()> {
        let key = storage::consensus_state_key(client_id, height);
        let bytes = Any::from(consensus_state).encode_to_vec();
        self.storage_mut()
            .write_bytes(&key, bytes)
            .map_err(HostError::from)
    }

    /// Delete the ConsensusState
    fn delete_consensus_state(
        &mut self,
        client_id: &ClientId,
        height: Height,
    ) -> Result<()> {
        let key = storage::consensus_state_key(client_id, height);
        self.storage_mut().delete(&key).map_err(HostError::from)
    }

    /// Decode ConsensusState from bytes
    fn decode_consensus_state_value(
        &self,
        consensus_state: Vec<u8>,
    ) -> Result<AnyConsensusState> {
        Any::decode(&consensus_state[..])
            .map_err(|e| HostError::Other {
                description: e.to_string(),
            })?
            .try_into()
    }

    /// Get heights of all consensus states
    fn consensus_state_heights(
        &self,
        client_id: &ClientId,
    ) -> Result<Vec<Height>> {
        let prefix = storage::consensus_state_prefix(client_id);
        let mut iter = self.storage().iter_prefix(&prefix)?;
        let mut heights = Vec::new();
        while let Some((key, _)) = self.storage().iter_next(&mut iter)? {
            let key = Key::parse(key).expect("the key should be parsable");
            let height = storage::consensus_height(&key).map_err(|e| {
                HostError::FailedToRetrieve {
                    description: format!("Invalid key: key {key}, error {e}"),
                }
            })?;
            heights.push(height);
        }
        Ok(heights)
    }

    /// Get the next consensus state after the given height
    fn next_consensus_state(
        &self,
        client_id: &ClientId,
        height: &Height,
    ) -> Result<Option<AnyConsensusState>> {
        let prefix = storage::consensus_state_prefix(client_id);
        let mut iter = self.storage().iter_prefix(&prefix)?;
        let mut lowest_height_value = None;
        while let Some((key, value)) = self.storage().iter_next(&mut iter)? {
            let key = Key::parse(key).expect("the key should be parsable");
            let consensus_height = storage::consensus_height(&key)
                .expect("the key should have a height");
            if consensus_height > *height {
                lowest_height_value = match lowest_height_value {
                    Some((lowest, _)) if consensus_height < lowest => {
                        Some((consensus_height, value))
                    }
                    Some(_) => continue,
                    None => Some((consensus_height, value)),
                };
            }
        }
        lowest_height_value
            .map(|(_, value)| value.try_into())
            .transpose()
    }

    /// Get the previous consensus state before the given height
    fn prev_consensus_state(
        &self,
        client_id: &ClientId,
        height: &Height,
    ) -> Result<Option<AnyConsensusState>> {
        let prefix = storage::consensus_state_prefix(client_id);
        // for iterator
        let mut iter = self.storage().iter_prefix(&prefix)?;
        let mut highest_height_value = None;
        while let Some((key, value)) = self.storage().iter_next(&mut iter)? {
            let key = Key::parse(key).expect("the key should be parsable");
            let consensus_height = storage::consensus_height(&key)
                .expect("the key should have the height");
            if consensus_height < *height {
                highest_height_value = match highest_height_value {
                    Some((highest, _)) if consensus_height > highest => {
                        Some((consensus_height, value))
                    }
                    Some(_) => continue,
                    None => Some((consensus_height, value)),
                };
            }
        }
        highest_height_value
            .map(|(_, value)| value.try_into())
            .transpose()
    }

    /// Get the client update time
    fn client_update_meta(
        &self,
        client_id: &ClientId,
    ) -> Result<(Timestamp, Height)> {
        let key = storage::client_update_timestamp_key(client_id);
        let value = self.storage().read_bytes(&key)?.ok_or(
            HostError::FailedToRetrieve {
                description: format!(
                    "The client update time doesn't exist: ID {client_id}",
                ),
            },
        )?;
        let time = TmTime::decode_vec(&value)
            .map_err(|_| HostError::Other {
                description: format!(
                    "Decoding the client update time failed: ID {client_id}",
                ),
            })?
            .into_timestamp()
            .map_err(|_| HostError::Other {
                description: format!(
                    "Conversion of the client update time failed: ID \
                     {client_id}",
                ),
            })?;

        let key = storage::client_update_height_key(client_id);
        let value = self.storage().read_bytes(&key)?.ok_or({
            HostError::FailedToRetrieve {
                description: format!(
                    "The client update height doesn't exist: ID {client_id}",
                ),
            }
        })?;
        let height = Height::decode_vec(&value).map_err(|_| {
            HostError::FailedToRetrieve {
                description: format!(
                    "Decoding the client update height failed: ID {client_id}",
                ),
            }
        })?;

        Ok((time, height))
    }

    /// Store the client update time and height
    fn store_update_meta(
        &mut self,
        client_id: &ClientId,
        host_timestamp: Timestamp,
        host_height: Height,
    ) -> Result<()> {
        let key = storage::client_update_timestamp_key(client_id);
        let time: TmTime = host_timestamp.into_host_time().map_err(|e| {
            HostError::FailedToStore {
                description: format!(
                    "Converting to tendermint Time failed: {e}"
                ),
            }
        })?;
        self.storage_mut()
            .write_bytes(&key, time.encode_vec())
            .map_err(HostError::from)?;

        let key = storage::client_update_height_key(client_id);
        let bytes = host_height.encode_vec();
        self.storage_mut()
            .write_bytes(&key, bytes)
            .map_err(HostError::from)
    }

    /// Delete the client update time and height
    fn delete_update_meta(&mut self, client_id: &ClientId) -> Result<()> {
        let key = storage::client_update_timestamp_key(client_id);
        self.storage_mut().delete(&key).map_err(HostError::from)?;

        let key = storage::client_update_height_key(client_id);
        self.storage_mut().delete(&key).map_err(HostError::from)
    }

    /// Get the timestamp on this chain
    fn host_timestamp(&self) -> Result<Timestamp> {
        let height = self.storage().get_block_height()?;
        let header = self
            .storage()
            .get_block_header(height)?
            .or({
                if height > BlockHeight::first() {
                    // When the latest header doesn't exist before
                    // `FinalizeBlock` phase, e.g. dry-run, use the previous
                    // header's time. It should be OK though the constraints
                    // become a bit stricter when checking timeouts.
                    self.storage()
                        .get_block_header(height.prev_height().unwrap())?
                } else {
                    None
                }
            })
            .ok_or_else(|| HostError::FailedToRetrieve {
                description: "No host block header".to_string(),
            })?;
        let time = TmTime::try_from(header.time)
            .map_err(|_| HostError::FailedToRetrieve {
                description: "Converting to Tendermint time failed".to_string(),
            })?
            .into_timestamp()
            .map_err(|_| HostError::FailedToRetrieve {
                description: "Converting to timestamp failed".to_string(),
            })?;
        Ok(time)
    }

    /// Get the consensus state of this chain
    fn host_consensus_state(
        &self,
        height: &Height,
    ) -> Result<AnyConsensusState> {
        let height = BlockHeight(height.revision_height());
        let header =
            self.storage().get_block_header(height)?.ok_or_else(|| {
                HostError::FailedToRetrieve {
                    description: "No host header".to_string(),
                }
            })?;
        let commitment_root = header.hash.to_vec().into();
        let time = header
            .time
            .try_into()
            .expect("The time should be converted");
        let next_validators_hash = header.next_validators_hash.into();
        let consensus_state: TmConsensusState = TmConsensusStateType::new(
            commitment_root,
            time,
            next_validators_hash,
        )
        .into();
        Ok(consensus_state.into())
    }

    /// Get the ConnectionEnd
    fn connection_end(&self, conn_id: &ConnectionId) -> Result<ConnectionEnd> {
        let key = storage::connection_key(conn_id);
        let value = self.storage().read_bytes(&key)?.ok_or(
            HostError::FailedToRetrieve {
                description: format!("No connection end: ID {conn_id}"),
            },
        )?;
        ConnectionEnd::decode_vec(&value).map_err(|_| {
            HostError::FailedToRetrieve {
                description: format!(
                    "Decoding the connection end failed: ID {conn_id}",
                ),
            }
        })
    }

    /// Store the ConnectionEnd
    fn store_connection(
        &mut self,
        connection_id: &ConnectionId,
        connection_end: ConnectionEnd,
    ) -> Result<()> {
        let key = storage::connection_key(connection_id);
        let bytes = connection_end.encode_vec();
        self.storage_mut()
            .write_bytes(&key, bytes)
            .map_err(HostError::from)
    }

    /// Append the connection ID to the connection list of the client
    fn append_connection(
        &mut self,
        client_id: &ClientId,
        conn_id: ConnectionId,
    ) -> Result<()> {
        let key = storage::client_connections_key(client_id);
        let list = match self.storage().read::<String>(&key)? {
            Some(list) => format!("{list},{conn_id}"),
            None => conn_id.to_string(),
        };
        self.storage_mut()
            .write(&key, list)
            .map_err(HostError::from)
    }

    /// Get the ChannelEnd
    fn channel_end(
        &self,
        port_id: &PortId,
        channel_id: &ChannelId,
    ) -> Result<ChannelEnd> {
        let key = storage::channel_key(port_id, channel_id);
        let value = self.storage().read_bytes(&key)?.ok_or(
            HostError::FailedToRetrieve {
                description: format!(
                    "No channel end: port {port_id}, channel {channel_id}"
                ),
            },
        )?;
        ChannelEnd::decode_vec(&value).map_err(|_| {
            HostError::FailedToRetrieve {
                description: format!(
                    "Decoding the channel end failed: port {port_id}, channel \
                     {channel_id}",
                ),
            }
        })
    }

    /// Store the ChannelEnd
    fn store_channel(
        &mut self,
        port_id: &PortId,
        channel_id: &ChannelId,
        channel_end: ChannelEnd,
    ) -> Result<()> {
        let key = storage::channel_key(port_id, channel_id);
        let bytes = channel_end.encode_vec();
        self.storage_mut()
            .write_bytes(&key, bytes)
            .map_err(HostError::from)
    }

    /// Get the NextSequenceSend
    fn get_next_sequence_send(
        &self,
        port_id: &PortId,
        channel_id: &ChannelId,
    ) -> Result<Sequence> {
        let key = storage::next_sequence_send_key(port_id, channel_id);
        read_sequence(self.storage(), &key).map_err(HostError::from)
    }

    /// Store the NextSequenceSend
    fn store_next_sequence_send(
        &mut self,
        port_id: &PortId,
        channel_id: &ChannelId,
        seq: Sequence,
    ) -> Result<()> {
        let key = storage::next_sequence_send_key(port_id, channel_id);
        self.store_sequence(&key, seq)
    }

    /// Get the NextSequenceRecv
    fn get_next_sequence_recv(
        &self,
        port_id: &PortId,
        channel_id: &ChannelId,
    ) -> Result<Sequence> {
        let key = storage::next_sequence_recv_key(port_id, channel_id);
        read_sequence(self.storage(), &key).map_err(HostError::from)
    }

    /// Store the NextSequenceRecv
    fn store_next_sequence_recv(
        &mut self,
        port_id: &PortId,
        channel_id: &ChannelId,
        seq: Sequence,
    ) -> Result<()> {
        let key = storage::next_sequence_recv_key(port_id, channel_id);
        self.store_sequence(&key, seq)
    }

    /// Get the NextSequenceAck
    fn get_next_sequence_ack(
        &self,
        port_id: &PortId,
        channel_id: &ChannelId,
    ) -> Result<Sequence> {
        let key = storage::next_sequence_ack_key(port_id, channel_id);
        read_sequence(self.storage(), &key).map_err(HostError::from)
    }

    /// Store the NextSequenceAck
    fn store_next_sequence_ack(
        &mut self,
        port_id: &PortId,
        channel_id: &ChannelId,
        seq: Sequence,
    ) -> Result<()> {
        let key = storage::next_sequence_ack_key(port_id, channel_id);
        self.store_sequence(&key, seq)
    }

    /// Store the sequence
    fn store_sequence(&mut self, key: &Key, sequence: Sequence) -> Result<()> {
        let bytes = u64::from(sequence).to_be_bytes().to_vec();
        self.storage_mut()
            .write_bytes(key, bytes)
            .map_err(HostError::from)
    }

    /// Get the packet commitment
    fn packet_commitment(
        &self,
        port_id: &PortId,
        channel_id: &ChannelId,
        sequence: Sequence,
    ) -> Result<PacketCommitment> {
        let key = storage::commitment_key(port_id, channel_id, sequence);
        match self.storage().read_bytes(&key)? {
            Some(value) => Ok(value.into()),
            None => Err(HostError::FailedToRetrieve {
                description: format!(
                    "No packet commitment: port {port_id}, channel \
                     {channel_id}, sequence {sequence}"
                ),
            }),
        }
    }

    /// Store the packet commitment
    fn store_packet_commitment(
        &mut self,
        port_id: &PortId,
        channel_id: &ChannelId,
        sequence: Sequence,
        commitment: PacketCommitment,
    ) -> Result<()> {
        let key = storage::commitment_key(port_id, channel_id, sequence);
        let bytes = commitment.into_vec();
        self.storage_mut()
            .write_bytes(&key, bytes)
            .map_err(HostError::from)
    }

    /// Delete the packet commitment
    fn delete_packet_commitment(
        &mut self,
        port_id: &PortId,
        channel_id: &ChannelId,
        sequence: Sequence,
    ) -> Result<()> {
        let key = storage::commitment_key(port_id, channel_id, sequence);
        self.storage_mut().delete(&key).map_err(HostError::from)
    }

    /// Get the packet receipt
    fn packet_receipt(
        &self,
        port_id: &PortId,
        channel_id: &ChannelId,
        sequence: Sequence,
    ) -> Result<Receipt> {
        let key = storage::receipt_key(port_id, channel_id, sequence);
        match self.storage().read_bytes(&key)? {
            Some(_) => Ok(Receipt::Ok),
            None => Ok(Receipt::None),
        }
    }

    /// Store the packet receipt
    fn store_packet_receipt(
        &mut self,
        port_id: &PortId,
        channel_id: &ChannelId,
        sequence: Sequence,
    ) -> Result<()> {
        let key = storage::receipt_key(port_id, channel_id, sequence);
        // the value is the same as ibc-go
        let bytes = [1_u8].to_vec();
        self.storage_mut()
            .write_bytes(&key, bytes)
            .map_err(HostError::from)
    }

    /// Get the packet acknowledgement
    fn packet_ack(
        &self,
        port_id: &PortId,
        channel_id: &ChannelId,
        sequence: Sequence,
    ) -> Result<Option<AcknowledgementCommitment>> {
        let key = storage::ack_key(port_id, channel_id, sequence);
        match self.storage().read_bytes(&key)? {
            Some(value) => Ok(Some(value.into())),
            None => Ok(None),
        }
    }

    /// Store the packet acknowledgement
    fn store_packet_ack(
        &mut self,
        port_id: &PortId,
        channel_id: &ChannelId,
        sequence: Sequence,
        ack_commitment: AcknowledgementCommitment,
    ) -> Result<()> {
        let key = storage::ack_key(port_id, channel_id, sequence);
        let bytes = ack_commitment.into_vec();
        self.storage_mut()
            .write_bytes(&key, bytes)
            .map_err(HostError::from)
    }

    /// Delete the packet acknowledgement
    fn delete_packet_ack(
        &mut self,
        port_id: &PortId,
        channel_id: &ChannelId,
        sequence: Sequence,
    ) -> Result<()> {
        let key = storage::ack_key(port_id, channel_id, sequence);
        self.storage_mut().delete(&key).map_err(HostError::from)
    }

    /// Read a counter
    fn read_counter(&self, key: &Key) -> Result<u64> {
        match self.storage().read::<u64>(key)? {
            Some(counter) => Ok(counter),
            None => unreachable!("the counter should be initialized"),
        }
    }

    /// Increment the counter
    fn increment_counter(&mut self, key: &Key) -> Result<()> {
        let count = self.read_counter(key)?;
        let count = u64::checked_add(count, 1).ok_or_else(|| {
            HostError::FailedToStore {
                description: format!("The counter overflow: Key {key}"),
            }
        })?;
        self.storage_mut()
            .write(key, count)
            .map_err(HostError::from)
    }

    /// Write the IBC trace. The given address could be a non-Namada token.
    fn store_ibc_trace(
        &mut self,
        addr: impl AsRef<str>,
        trace_hash: impl AsRef<str>,
        trace: impl AsRef<str>,
    ) -> Result<()> {
        let key = storage::ibc_trace_key(addr, trace_hash.as_ref());
        let has_key = self.storage().has_key(&key)?;
        if !has_key {
            self.storage_mut().write(&key, trace.as_ref())?;
        }
        Ok(())
    }

    /// Get the NFT class
    fn nft_class(
        &self,
        class_id: &PrefixedClassId,
    ) -> Result<Option<NftClass>> {
        let key = storage::nft_class_key(class_id);
        self.storage().read(&key).map_err(HostError::from)
    }

    /// Store the NFT class
    fn store_nft_class(&mut self, class: NftClass) -> Result<()> {
        let key = storage::nft_class_key(&class.class_id);
        self.storage_mut()
            .write(&key, class)
            .map_err(HostError::from)
    }

    /// Get the NFT metadata
    fn nft_metadata(
        &self,
        class_id: &PrefixedClassId,
        token_id: &TokenId,
    ) -> Result<Option<NftMetadata>> {
        let key = storage::nft_metadata_key(class_id, token_id);
        self.storage().read(&key).map_err(HostError::from)
    }

    /// Store the NFT metadata
    fn store_nft_metadata(&mut self, metadata: NftMetadata) -> Result<()> {
        let key =
            storage::nft_metadata_key(&metadata.class_id, &metadata.token_id);
        self.storage_mut()
            .write(&key, metadata)
            .map_err(HostError::from)
    }

    /// Return true if the NFT is owned by the owner
    fn is_nft_owned<Token>(
        &self,
        class_id: &PrefixedClassId,
        token_id: &TokenId,
        owner: &Address,
    ) -> Result<bool>
    where
        Token: trans_token::Keys,
    {
        let ibc_token = trace::ibc_token_for_nft(class_id, token_id);
        let balance_key = Token::balance_key(&ibc_token, owner);
        let amount = self.storage().read::<Amount>(&balance_key)?;
        Ok(amount == Some(Amount::from_u64(1)))
    }

    /// Read the mint amount of the given token
    fn mint_amount(&self, token: &Address) -> Result<Amount> {
        let key = storage::mint_amount_key(token);
        Ok(self.storage().read::<Amount>(&key)?.unwrap_or_default())
    }

    /// Write the mint amount of the given token
    fn store_mint_amount(
        &mut self,
        token: &Address,
        amount: Amount,
    ) -> Result<()> {
        let key = storage::mint_amount_key(token);
        self.storage_mut()
            .write(&key, amount)
            .map_err(HostError::from)
    }

    /// Read the per-epoch deposit of the given token
    fn deposit(&self, token: &Address) -> Result<Amount> {
        let key = storage::deposit_key(token);
        Ok(self.storage().read::<Amount>(&key)?.unwrap_or_default())
    }

    /// Write the per-epoch deposit of the given token
    fn store_deposit(&mut self, token: &Address, amount: Amount) -> Result<()> {
        let key = storage::deposit_key(token);
        self.storage_mut()
            .write(&key, amount)
            .map_err(HostError::from)
    }

    /// Read the per-epoch withdraw of the given token
    fn withdraw(&self, token: &Address) -> Result<Amount> {
        let key = storage::withdraw_key(token);
        Ok(self.storage().read::<Amount>(&key)?.unwrap_or_default())
    }

    /// Write the per-epoch withdraw of the given token
    fn store_withdraw(
        &mut self,
        token: &Address,
        amount: Amount,
    ) -> Result<()> {
        let key = storage::withdraw_key(token);
        self.storage_mut()
            .write(&key, amount)
            .map_err(HostError::from)
    }
}

/// Read and decode the IBC sequence
pub fn read_sequence<S: StorageRead + ?Sized>(
    storage: &S,
    key: &Key,
) -> std::result::Result<Sequence, StorageError> {
    match storage.read_bytes(key)? {
        Some(value) => {
            let value: [u8; 8] = value.try_into().map_err(|_| {
                StorageError::new_alloc(format!(
                    "The sequence value wasn't u64: Key {key}",
                ))
            })?;
            Ok(u64::from_be_bytes(value).into())
        }
        // when the sequence has never been used, returns the initial value
        None => Ok(1.into()),
    }
}