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
// Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

use crate::convert::{from_address_v2_to_v3, from_address_v2_to_v4};
use crate::convert::{
    from_address_v3_to_v2, from_address_v4_to_v2, from_padded_piece_size_v3_to_v2,
    from_padded_piece_size_v4_to_v2, from_token_v3_to_v2, from_token_v4_to_v2,
};
use anyhow::Context;
use cid::Cid;
use fil_actor_market_state::v10::balance_table::BalanceTable as V10BalanceTable;
use fil_actor_market_state::v10::DealArray as V10DealArray;
use fil_actor_market_state::v10::DealMetaArray as V10DealMetaArray;
use fil_actor_market_state::v11::balance_table::BalanceTable as V11BalanceTable;
use fil_actor_market_state::v11::DealArray as V11DealArray;
use fil_actor_market_state::v11::DealMetaArray as V11DealMetaArray;
use fil_actor_market_state::v12::balance_table::BalanceTable as V12BalanceTable;
use fil_actor_market_state::v12::DealArray as V12DealArray;
use fil_actor_market_state::v12::DealMetaArray as V12DealMetaArray;
use fil_actor_market_state::v13::balance_table::BalanceTable as V13BalanceTable;
use fil_actor_market_state::v13::DealArray as V13DealArray;
use fil_actor_market_state::v13::DealMetaArray as V13DealMetaArray;
use fil_actor_market_state::v8::balance_table::BalanceTable as V8BalanceTable;
use fil_actor_market_state::v9::balance_table::BalanceTable as V9BalanceTable;
use fil_actor_market_state::v9::DealArray as V9DealArray;
use fil_actor_market_state::v9::DealMetaArray as V9DealMetaArray;
use fil_actors_shared::v10::{AsActorError as V10AsActorError, DealWeight};
use fil_actors_shared::v11::AsActorError as V11AsActorError;
use fil_actors_shared::v12::AsActorError as V12AsActorError;
use fil_actors_shared::v12::AsActorError as V13AsActorError;
use fil_actors_shared::v9::AsActorError as V9AsActorError;
use fvm_ipld_blockstore::Blockstore;
use fvm_shared::error::ExitCode as FVMExitCode;
use fvm_shared::{address::Address, clock::ChainEpoch, econ::TokenAmount, piece::PaddedPieceSize};
use fvm_shared3::error::ExitCode as FVM3ExitCode;
use fvm_shared4::error::ExitCode as FVM4ExitCode;
use serde::{Deserialize, Serialize};

use crate::io::get_obj;

/// Market actor address.
pub const ADDRESS: Address = Address::new_id(5);

/// Market actor method.
pub type Method = fil_actor_market_state::v8::Method;

pub type AllocationID = u64;

pub fn is_v8_market_cid(cid: &Cid) -> bool {
    crate::KNOWN_CIDS.actor.market.v8.contains(cid)
}

pub fn is_v9_market_cid(cid: &Cid) -> bool {
    crate::KNOWN_CIDS.actor.market.v9.contains(cid)
}

pub fn is_v10_market_cid(cid: &Cid) -> bool {
    crate::KNOWN_CIDS.actor.market.v10.contains(cid)
}

pub fn is_v11_market_cid(cid: &Cid) -> bool {
    crate::KNOWN_CIDS.actor.market.v11.contains(cid)
}

pub fn is_v12_market_cid(cid: &Cid) -> bool {
    crate::KNOWN_CIDS.actor.market.v12.contains(cid)
}

pub fn is_v13_market_cid(cid: &Cid) -> bool {
    crate::KNOWN_CIDS.actor.market.v13.contains(cid)
}

/// Market actor state.
#[derive(Serialize, Debug)]
#[serde(untagged)]
pub enum State {
    V8(fil_actor_market_state::v8::State),
    V9(fil_actor_market_state::v9::State),
    V10(fil_actor_market_state::v10::State),
    V11(fil_actor_market_state::v11::State),
    V12(fil_actor_market_state::v12::State),
    V13(fil_actor_market_state::v13::State),
}

impl State {
    pub fn load<BS>(store: &BS, code: Cid, state: Cid) -> anyhow::Result<State>
    where
        BS: Blockstore,
    {
        if is_v8_market_cid(&code) {
            return get_obj(store, &state)?
                .map(State::V8)
                .context("Actor state doesn't exist in store");
        }
        if is_v9_market_cid(&code) {
            return get_obj(store, &state)?
                .map(State::V9)
                .context("Actor state doesn't exist in store");
        }
        if is_v10_market_cid(&code) {
            return get_obj(store, &state)?
                .map(State::V10)
                .context("Actor state doesn't exist in store");
        }
        if is_v11_market_cid(&code) {
            return get_obj(store, &state)?
                .map(State::V11)
                .context("Actor state doesn't exist in store");
        }
        if is_v12_market_cid(&code) {
            return get_obj(store, &state)?
                .map(State::V12)
                .context("Actor state doesn't exist in store");
        }
        if is_v13_market_cid(&code) {
            return get_obj(store, &state)?
                .map(State::V13)
                .context("Actor state doesn't exist in store");
        }
        Err(anyhow::anyhow!("Unknown market actor code {}", code))
    }

    /// Loads escrow table
    pub fn escrow_table<'bs, BS>(&self, store: &'bs BS) -> anyhow::Result<BalanceTable<'bs, BS>>
    where
        BS: Blockstore,
    {
        Ok(match self {
            Self::V8(s) => s.escrow_table(store)?.into(),
            Self::V9(s) => s.escrow_table(store)?.into(),
            Self::V10(s) => s.escrow_table(store)?.into(),
            Self::V11(s) => s.escrow_table(store)?.into(),
            Self::V12(s) => s.escrow_table(store)?.into(),
            Self::V13(s) => s.escrow_table(store)?.into(),
        })
    }

    /// Loads locked funds table
    pub fn locked_table<'bs, BS>(&self, store: &'bs BS) -> anyhow::Result<BalanceTable<'bs, BS>>
    where
        BS: Blockstore,
    {
        Ok(match self {
            Self::V8(s) => s.locked_table(store)?.into(),
            Self::V9(s) => s.locked_table(store)?.into(),
            Self::V10(s) => s.locked_table(store)?.into(),
            Self::V11(s) => s.locked_table(store)?.into(),
            Self::V12(s) => s.locked_table(store)?.into(),
            Self::V13(s) => s.locked_table(store)?.into(),
        })
    }

    /// Deal proposals
    pub fn proposals<'bs, BS>(&'bs self, store: &'bs BS) -> anyhow::Result<DealProposals<'bs, BS>>
    where
        BS: Blockstore,
    {
        match self {
            // `get_proposal_array` does not exist for V8
            State::V8(_st) => anyhow::bail!("unimplemented"),
            // `get_proposal_array` does not exist for V9
            State::V9(_st) => anyhow::bail!("unimplemented"),
            State::V10(st) => Ok(DealProposals::V10(st.get_proposal_array(store)?)),
            State::V11(st) => Ok(DealProposals::V11(st.get_proposal_array(store)?)),
            State::V12(st) => Ok(DealProposals::V12(st.get_proposal_array(store)?)),
            State::V13(st) => Ok(DealProposals::V13(st.load_proposals(store)?)),
        }
    }

    /// Deal proposal meta data.
    pub fn states<'bs, BS>(&self, store: &'bs BS) -> anyhow::Result<DealStates<'bs, BS>>
    where
        BS: Blockstore,
    {
        match self {
            // `DealMetaArray::load` does not exist for V8
            State::V8(_st) => anyhow::bail!("unimplemented"),
            State::V9(st) => Ok(DealStates::V9(V9AsActorError::context_code(
                V9DealMetaArray::load(&st.states, store),
                FVMExitCode::USR_ILLEGAL_STATE,
                "failed to load deal state array",
            )?)),
            State::V10(st) => Ok(DealStates::V10(V10AsActorError::context_code(
                V10DealMetaArray::load(&st.states, store),
                FVM3ExitCode::USR_ILLEGAL_STATE,
                "failed to load deal state array",
            )?)),
            State::V11(st) => Ok(DealStates::V11(V11AsActorError::context_code(
                V11DealMetaArray::load(&st.states, store),
                FVM3ExitCode::USR_ILLEGAL_STATE,
                "failed to load deal state array",
            )?)),
            State::V12(st) => Ok(DealStates::V12(V12AsActorError::context_code(
                V12DealMetaArray::load(&st.states, store),
                FVM4ExitCode::USR_ILLEGAL_STATE,
                "failed to load deal state array",
            )?)),
            State::V13(st) => Ok(DealStates::V13(V13AsActorError::context_code(
                V13DealMetaArray::load(&st.states, store),
                FVM4ExitCode::USR_ILLEGAL_STATE,
                "failed to load deal state array",
            )?)),
        }
    }

    /// Consume state to return just total funds locked
    pub fn total_locked(&self) -> TokenAmount {
        match self {
            State::V8(st) => st.total_locked(),
            State::V9(st) => st.total_locked(),
            State::V10(st) => from_token_v3_to_v2(&st.get_total_locked()),
            State::V11(st) => from_token_v3_to_v2(&st.get_total_locked()),
            State::V12(st) => from_token_v4_to_v2(&st.get_total_locked()),
            State::V13(st) => from_token_v4_to_v2(&st.get_total_locked()),
        }
    }

    pub fn verify_deals_for_activation<BS>(
        &self,
        store: &BS,
        addr: Address,
        deal_ids: Vec<u64>,
        curr_epoch: ChainEpoch,
        sector_exp: i64,
    ) -> anyhow::Result<(DealWeight, DealWeight)>
    where
        BS: Blockstore,
    {
        match self {
            State::V8(_st) => anyhow::bail!("unimplemented"),
            State::V9(_st) => anyhow::bail!("unimplemented"),
            State::V10(st) => Ok(st.verify_deals_for_activation(
                store,
                &from_address_v2_to_v3(addr),
                deal_ids,
                curr_epoch,
                sector_exp,
            )?),
            State::V11(st) => Ok(st.verify_deals_for_activation(
                store,
                &from_address_v2_to_v3(addr),
                deal_ids,
                curr_epoch,
                sector_exp,
            )?),
            State::V12(st) => Ok(st.verify_deals_for_activation(
                store,
                &from_address_v2_to_v4(addr),
                deal_ids,
                curr_epoch,
                sector_exp,
            )?),
            State::V13(st) => Ok(st.verify_deals_for_activation(
                store,
                &from_address_v2_to_v4(addr),
                deal_ids,
                curr_epoch,
                sector_exp,
            )?),
        }
    }
}

pub enum BalanceTable<'bs, BS: Blockstore> {
    V8(V8BalanceTable<'bs, BS>),
    V9(V9BalanceTable<'bs, BS>),
    V10(V10BalanceTable<'bs, BS>),
    V11(V11BalanceTable<'bs, BS>),
    V12(V12BalanceTable<&'bs BS>),
    V13(V13BalanceTable<&'bs BS>),
}

impl<'bs, BS: Blockstore> From<V8BalanceTable<'bs, BS>> for BalanceTable<'bs, BS> {
    fn from(value: V8BalanceTable<'bs, BS>) -> Self {
        Self::V8(value)
    }
}

impl<'bs, BS: Blockstore> From<V9BalanceTable<'bs, BS>> for BalanceTable<'bs, BS> {
    fn from(value: V9BalanceTable<'bs, BS>) -> Self {
        Self::V9(value)
    }
}

impl<'bs, BS: Blockstore> From<V10BalanceTable<'bs, BS>> for BalanceTable<'bs, BS> {
    fn from(value: V10BalanceTable<'bs, BS>) -> Self {
        Self::V10(value)
    }
}

impl<'bs, BS: Blockstore> From<V11BalanceTable<'bs, BS>> for BalanceTable<'bs, BS> {
    fn from(value: V11BalanceTable<'bs, BS>) -> Self {
        Self::V11(value)
    }
}

impl<'bs, BS: Blockstore> From<V12BalanceTable<&'bs BS>> for BalanceTable<'bs, BS> {
    fn from(value: V12BalanceTable<&'bs BS>) -> Self {
        Self::V12(value)
    }
}

impl<'bs, BS: Blockstore> From<V13BalanceTable<&'bs BS>> for BalanceTable<'bs, BS> {
    fn from(value: V13BalanceTable<&'bs BS>) -> Self {
        Self::V13(value)
    }
}

pub enum DealProposals<'bs, BS> {
    V9(V9DealArray<'bs, BS>),
    V10(V10DealArray<'bs, BS>),
    V11(V11DealArray<'bs, BS>),
    V12(V12DealArray<'bs, BS>),
    V13(V13DealArray<'bs, BS>),
}

impl<BS> DealProposals<'_, BS>
where
    BS: Blockstore,
{
    pub fn for_each(
        &self,
        mut f: impl FnMut(u64, Result<DealProposal, anyhow::Error>) -> anyhow::Result<(), anyhow::Error>,
    ) -> anyhow::Result<()> {
        match self {
            DealProposals::V9(deal_array) => Ok(deal_array
                .for_each(|key, deal_proposal| f(key, DealProposal::try_from(deal_proposal)))?),
            DealProposals::V10(deal_array) => Ok(deal_array
                .for_each(|key, deal_proposal| f(key, DealProposal::try_from(deal_proposal)))?),
            DealProposals::V11(deal_array) => Ok(deal_array
                .for_each(|key, deal_proposal| f(key, DealProposal::try_from(deal_proposal)))?),
            DealProposals::V12(deal_array) => Ok(deal_array
                .for_each(|key, deal_proposal| f(key, DealProposal::try_from(deal_proposal)))?),
            DealProposals::V13(deal_array) => Ok(deal_array
                .for_each(|key, deal_proposal| f(key, DealProposal::try_from(deal_proposal)))?),
        }
    }

    pub fn get(&self, key: u64) -> anyhow::Result<Option<DealProposal>> {
        match self {
            DealProposals::V9(deal_array) => deal_array.get(key)?.map(TryFrom::try_from),
            DealProposals::V10(deal_array) => deal_array.get(key)?.map(TryFrom::try_from),
            DealProposals::V11(deal_array) => deal_array.get(key)?.map(TryFrom::try_from),
            DealProposals::V12(deal_array) => deal_array.get(key)?.map(TryFrom::try_from),
            DealProposals::V13(deal_array) => deal_array.get(key)?.map(TryFrom::try_from),
        }
        .transpose()
    }
}

#[derive(Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct DealProposal {
    #[serde(rename = "PieceCID")]
    pub piece_cid: Cid,
    pub piece_size: PaddedPieceSize,
    pub verified_deal: bool,
    pub client: Address,
    pub provider: Address,
    // ! This is the field that requires unsafe unchecked utf8 deserialization
    pub label: String,
    pub start_epoch: ChainEpoch,
    pub end_epoch: ChainEpoch,
    pub storage_price_per_epoch: TokenAmount,
    pub provider_collateral: TokenAmount,
    pub client_collateral: TokenAmount,
}

impl TryFrom<&fil_actor_market_state::v9::DealProposal> for DealProposal {
    type Error = anyhow::Error;

    fn try_from(
        deal_proposal: &fil_actor_market_state::v9::DealProposal,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            piece_cid: deal_proposal.piece_cid,
            piece_size: deal_proposal.piece_size,
            verified_deal: deal_proposal.verified_deal,
            client: deal_proposal.client,
            provider: deal_proposal.provider,
            label: match &deal_proposal.label {
                fil_actor_market_state::v9::Label::String(s) => s.clone(),
                fil_actor_market_state::v9::Label::Bytes(b) => String::from_utf8(b.clone())?,
            },
            start_epoch: deal_proposal.start_epoch,
            end_epoch: deal_proposal.end_epoch,
            storage_price_per_epoch: deal_proposal.storage_price_per_epoch.clone(),
            provider_collateral: deal_proposal.provider_collateral.clone(),
            client_collateral: deal_proposal.client_collateral.clone(),
        })
    }
}

impl TryFrom<&fil_actor_market_state::v10::DealProposal> for DealProposal {
    type Error = anyhow::Error;

    fn try_from(
        deal_proposal: &fil_actor_market_state::v10::DealProposal,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            piece_cid: deal_proposal.piece_cid,
            piece_size: from_padded_piece_size_v3_to_v2(deal_proposal.piece_size),
            verified_deal: deal_proposal.verified_deal,
            client: from_address_v3_to_v2(deal_proposal.client),
            provider: from_address_v3_to_v2(deal_proposal.provider),
            label: match &deal_proposal.label {
                fil_actor_market_state::v10::Label::String(s) => s.clone(),
                fil_actor_market_state::v10::Label::Bytes(b) => String::from_utf8(b.clone())?,
            },
            start_epoch: deal_proposal.start_epoch,
            end_epoch: deal_proposal.end_epoch,
            storage_price_per_epoch: from_token_v3_to_v2(&deal_proposal.storage_price_per_epoch),
            provider_collateral: from_token_v3_to_v2(&deal_proposal.provider_collateral),
            client_collateral: from_token_v3_to_v2(&deal_proposal.client_collateral),
        })
    }
}

impl TryFrom<&fil_actor_market_state::v11::DealProposal> for DealProposal {
    type Error = anyhow::Error;

    fn try_from(
        deal_proposal: &fil_actor_market_state::v11::DealProposal,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            piece_cid: deal_proposal.piece_cid,
            piece_size: from_padded_piece_size_v3_to_v2(deal_proposal.piece_size),
            verified_deal: deal_proposal.verified_deal,
            client: from_address_v3_to_v2(deal_proposal.client),
            provider: from_address_v3_to_v2(deal_proposal.provider),
            label: match &deal_proposal.label {
                fil_actor_market_state::v11::Label::String(s) => s.clone(),
                fil_actor_market_state::v11::Label::Bytes(b) => String::from_utf8(b.clone())?,
            },
            start_epoch: deal_proposal.start_epoch,
            end_epoch: deal_proposal.end_epoch,
            storage_price_per_epoch: from_token_v3_to_v2(&deal_proposal.storage_price_per_epoch),
            provider_collateral: from_token_v3_to_v2(&deal_proposal.provider_collateral),
            client_collateral: from_token_v3_to_v2(&deal_proposal.client_collateral),
        })
    }
}

impl TryFrom<&fil_actor_market_state::v12::DealProposal> for DealProposal {
    type Error = anyhow::Error;

    fn try_from(
        deal_proposal: &fil_actor_market_state::v12::DealProposal,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            piece_cid: deal_proposal.piece_cid,
            piece_size: from_padded_piece_size_v4_to_v2(deal_proposal.piece_size),
            verified_deal: deal_proposal.verified_deal,
            client: from_address_v4_to_v2(deal_proposal.client),
            provider: from_address_v4_to_v2(deal_proposal.provider),
            label: match &deal_proposal.label {
                fil_actor_market_state::v12::Label::String(s) => s.clone(),
                fil_actor_market_state::v12::Label::Bytes(b) => String::from_utf8(b.clone())?,
            },
            start_epoch: deal_proposal.start_epoch,
            end_epoch: deal_proposal.end_epoch,
            storage_price_per_epoch: from_token_v4_to_v2(&deal_proposal.storage_price_per_epoch),
            provider_collateral: from_token_v4_to_v2(&deal_proposal.provider_collateral),
            client_collateral: from_token_v4_to_v2(&deal_proposal.client_collateral),
        })
    }
}

impl TryFrom<&fil_actor_market_state::v13::DealProposal> for DealProposal {
    type Error = anyhow::Error;

    fn try_from(
        deal_proposal: &fil_actor_market_state::v13::DealProposal,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            piece_cid: deal_proposal.piece_cid,
            piece_size: from_padded_piece_size_v4_to_v2(deal_proposal.piece_size),
            verified_deal: deal_proposal.verified_deal,
            client: from_address_v4_to_v2(deal_proposal.client),
            provider: from_address_v4_to_v2(deal_proposal.provider),
            label: match &deal_proposal.label {
                fil_actor_market_state::v13::Label::String(s) => s.clone(),
                fil_actor_market_state::v13::Label::Bytes(b) => String::from_utf8(b.clone())?,
            },
            start_epoch: deal_proposal.start_epoch,
            end_epoch: deal_proposal.end_epoch,
            storage_price_per_epoch: from_token_v4_to_v2(&deal_proposal.storage_price_per_epoch),
            provider_collateral: from_token_v4_to_v2(&deal_proposal.provider_collateral),
            client_collateral: from_token_v4_to_v2(&deal_proposal.client_collateral),
        })
    }
}

pub enum DealStates<'bs, BS> {
    V8(V9DealMetaArray<'bs, BS>),
    V9(V9DealMetaArray<'bs, BS>),
    V10(V10DealMetaArray<'bs, BS>),
    V11(V11DealMetaArray<'bs, BS>),
    V12(V12DealMetaArray<'bs, BS>),
    V13(V13DealMetaArray<'bs, BS>),
}

impl<BS> DealStates<'_, BS>
where
    BS: Blockstore,
{
    pub fn get(&self, key: u64) -> anyhow::Result<Option<DealState>> {
        match self {
            DealStates::V8(deal_array) => Ok(deal_array.get(key)?.map(|deal_state| DealState {
                sector_start_epoch: deal_state.sector_start_epoch,
                last_updated_epoch: deal_state.last_updated_epoch,
                slash_epoch: deal_state.slash_epoch,
                verified_claim: deal_state.verified_claim,
            })),
            DealStates::V9(deal_array) => Ok(deal_array.get(key)?.map(|deal_state| DealState {
                sector_start_epoch: deal_state.sector_start_epoch,
                last_updated_epoch: deal_state.last_updated_epoch,
                slash_epoch: deal_state.slash_epoch,
                verified_claim: deal_state.verified_claim,
            })),
            DealStates::V10(deal_array) => Ok(deal_array.get(key)?.map(|deal_state| DealState {
                sector_start_epoch: deal_state.sector_start_epoch,
                last_updated_epoch: deal_state.last_updated_epoch,
                slash_epoch: deal_state.slash_epoch,
                verified_claim: deal_state.verified_claim,
            })),
            DealStates::V11(deal_array) => Ok(deal_array.get(key)?.map(|deal_state| DealState {
                sector_start_epoch: deal_state.sector_start_epoch,
                last_updated_epoch: deal_state.last_updated_epoch,
                slash_epoch: deal_state.slash_epoch,
                verified_claim: deal_state.verified_claim,
            })),
            DealStates::V12(deal_array) => Ok(deal_array.get(key)?.map(|deal_state| DealState {
                sector_start_epoch: deal_state.sector_start_epoch,
                last_updated_epoch: deal_state.last_updated_epoch,
                slash_epoch: deal_state.slash_epoch,
                verified_claim: deal_state.verified_claim,
            })),
            DealStates::V13(deal_array) => Ok(deal_array.get(key)?.map(|deal_state| DealState {
                sector_start_epoch: deal_state.sector_start_epoch,
                last_updated_epoch: deal_state.last_updated_epoch,
                slash_epoch: deal_state.slash_epoch,
                verified_claim: 0,
            })),
        }
    }
}

#[derive(Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct DealState {
    pub sector_start_epoch: ChainEpoch, // -1 if not yet included in proven sector
    pub last_updated_epoch: ChainEpoch, // -1 if deal state never updated
    pub slash_epoch: ChainEpoch,        // -1 if deal never slashed
    pub verified_claim: AllocationID, // ID of the verified registry allocation/claim for this deal's data (0 if none).
}

impl DealState {
    /// Empty deal state
    pub const fn empty() -> Self {
        Self {
            sector_start_epoch: -1,
            last_updated_epoch: -1,
            slash_epoch: -1,
            verified_claim: 0,
        }
    }
}

impl<BS> BalanceTable<'_, BS>
where
    BS: Blockstore,
{
    pub fn get(&self, key: &Address) -> anyhow::Result<TokenAmount> {
        Ok(match self {
            Self::V8(t) => t.get(key)?,
            Self::V9(t) => t.get(key)?,
            Self::V10(t) => from_token_v3_to_v2(&t.get(&from_address_v2_to_v3(*key))?),
            Self::V11(t) => from_token_v3_to_v2(&t.get(&from_address_v2_to_v3(*key))?),
            Self::V12(t) => from_token_v4_to_v2(&t.get(&from_address_v2_to_v4(*key))?),
            Self::V13(t) => from_token_v4_to_v2(&t.get(&from_address_v2_to_v4(*key))?),
        })
    }
}