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
use chia_bls::PublicKey;
use chia_protocol::{Bytes32, Coin, CoinSpend};
use chia_puzzles::{
    nft::{
        NftOwnershipLayerArgs, NftOwnershipLayerSolution, NftRoyaltyTransferPuzzleArgs,
        NftStateLayerArgs, NftStateLayerSolution,
    },
    singleton::SingletonArgs,
    LineageProof, Proof,
};
use chia_sdk_types::{
    conditions::{AssertPuzzleAnnouncement, NewNftOwner},
    puzzles::NftInfo,
};
use clvm_traits::{clvm_list, ToClvm};
use clvm_utils::CurriedProgram;
use clvmr::{
    sha2::{Digest, Sha256},
    NodePtr,
};

use crate::{
    puzzles::{spend_singleton, StandardSpend},
    spend_builder::{InnerSpend, P2Spend, SpendConditions},
    SpendContext, SpendError,
};

#[derive(Debug, Clone, Copy)]
pub struct NoNftOutput;

#[derive(Debug, Clone, Copy)]
pub enum NftOutput {
    SamePuzzleHash,
    NewPuzzleHash { puzzle_hash: Bytes32 },
}

#[derive(Debug, Clone)]
#[must_use]
pub struct StandardNftSpend<T> {
    standard_spend: StandardSpend,
    output: T,
    new_owner: Option<NewNftOwner>,
}

impl Default for StandardNftSpend<NoNftOutput> {
    fn default() -> Self {
        Self {
            output: NoNftOutput,
            standard_spend: StandardSpend::new(),
            new_owner: None,
        }
    }
}

impl StandardNftSpend<NoNftOutput> {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn update(self) -> StandardNftSpend<NftOutput> {
        StandardNftSpend {
            standard_spend: self.standard_spend,
            output: NftOutput::SamePuzzleHash,
            new_owner: self.new_owner,
        }
    }

    pub fn transfer(self, puzzle_hash: Bytes32) -> StandardNftSpend<NftOutput> {
        StandardNftSpend {
            standard_spend: self.standard_spend,
            output: NftOutput::NewPuzzleHash { puzzle_hash },
            new_owner: self.new_owner,
        }
    }
}

impl<T> StandardNftSpend<T> {
    pub fn new_owner(mut self, did_id: Bytes32, did_inner_puzzle_hash: Bytes32) -> Self {
        self.new_owner = Some(NewNftOwner {
            new_owner: Some(did_id),
            trade_prices_list: Vec::new(),
            new_did_p2_puzzle_hash: Some(did_inner_puzzle_hash),
        });
        self
    }

    pub fn reset_owner(mut self) -> Self {
        self.new_owner = Some(NewNftOwner {
            new_owner: None,
            trade_prices_list: Vec::new(),
            new_did_p2_puzzle_hash: None,
        });
        self
    }

    pub fn chain(mut self, chained: SpendConditions) -> Self {
        self.standard_spend = self.standard_spend.chain(chained);
        self
    }
}

impl<T> P2Spend for StandardNftSpend<T> {
    fn raw_condition(mut self, condition: NodePtr) -> Self {
        self.standard_spend = self.standard_spend.raw_condition(condition);
        self
    }
}

impl StandardNftSpend<NftOutput> {
    pub fn finish<M>(
        mut self,
        ctx: &mut SpendContext<'_>,
        synthetic_key: PublicKey,
        mut nft_info: NftInfo<M>,
    ) -> Result<(SpendConditions, NftInfo<M>), SpendError>
    where
        M: ToClvm<NodePtr>,
    {
        let mut parent = SpendConditions::default();

        let p2_puzzle_hash = match self.output {
            NftOutput::SamePuzzleHash => nft_info.p2_puzzle_hash,
            NftOutput::NewPuzzleHash { puzzle_hash } => puzzle_hash,
        };

        if let Some(new_owner) = &self.new_owner {
            self.standard_spend = self.standard_spend.raw_condition(ctx.alloc(new_owner)?);

            let new_nft_owner_args = ctx.alloc(&clvm_list!(
                new_owner.new_owner,
                new_owner.trade_prices_list.clone(),
                new_owner.new_did_p2_puzzle_hash
            ))?;

            let mut announcement_id = Sha256::new();
            announcement_id.update(nft_info.coin.puzzle_hash);
            announcement_id.update([0xad, 0x4c]);
            announcement_id.update(ctx.tree_hash(new_nft_owner_args));

            parent = parent.raw_condition(ctx.alloc(&AssertPuzzleAnnouncement {
                announcement_id: Bytes32::new(announcement_id.finalize().into()),
            })?);
        }

        let inner_spend = self
            .standard_spend
            .create_hinted_coin(ctx, p2_puzzle_hash, nft_info.coin.amount, p2_puzzle_hash)?
            .inner_spend(ctx, synthetic_key)?;

        let nft_spend = raw_nft_spend(ctx, &nft_info, inner_spend)?;
        ctx.spend(nft_spend);

        nft_info.current_owner = self
            .new_owner
            .map_or(nft_info.current_owner, |value| value.new_owner);

        let metadata_ptr = ctx.alloc(&nft_info.metadata)?;

        let transfer_program = NftRoyaltyTransferPuzzleArgs::curry_tree_hash(
            nft_info.launcher_id,
            nft_info.royalty_puzzle_hash,
            nft_info.royalty_percentage,
        );

        let ownership_layer = NftOwnershipLayerArgs::curry_tree_hash(
            nft_info.current_owner,
            transfer_program,
            p2_puzzle_hash.into(),
        );

        let state_layer =
            NftStateLayerArgs::curry_tree_hash(ctx.tree_hash(metadata_ptr), ownership_layer);

        let singleton_puzzle_hash =
            SingletonArgs::curry_tree_hash(nft_info.launcher_id, state_layer);

        nft_info.proof = Proof::Lineage(LineageProof {
            parent_parent_coin_id: nft_info.coin.parent_coin_info,
            parent_inner_puzzle_hash: nft_info.nft_inner_puzzle_hash,
            parent_amount: nft_info.coin.amount,
        });

        nft_info.coin = Coin::new(
            nft_info.coin.coin_id(),
            singleton_puzzle_hash.into(),
            nft_info.coin.amount,
        );

        nft_info.nft_inner_puzzle_hash = state_layer.into();

        Ok((parent, nft_info))
    }
}

pub fn raw_nft_spend<M>(
    ctx: &mut SpendContext<'_>,
    nft_info: &NftInfo<M>,
    inner_spend: InnerSpend,
) -> Result<CoinSpend, SpendError>
where
    M: ToClvm<NodePtr>,
{
    let transfer_program_puzzle = ctx.nft_royalty_transfer()?;

    let transfer_program = CurriedProgram {
        program: transfer_program_puzzle,
        args: NftRoyaltyTransferPuzzleArgs::new(
            nft_info.launcher_id,
            nft_info.royalty_puzzle_hash,
            nft_info.royalty_percentage,
        ),
    };

    let ownership_layer_spend =
        spend_nft_ownership_layer(ctx, nft_info.current_owner, transfer_program, inner_spend)?;

    let state_layer_spend = spend_nft_state_layer(ctx, &nft_info.metadata, ownership_layer_spend)?;

    spend_singleton(
        ctx,
        nft_info.coin,
        nft_info.launcher_id,
        nft_info.proof,
        state_layer_spend,
    )
}

pub fn spend_nft_state_layer<M>(
    ctx: &mut SpendContext<'_>,
    metadata: M,
    inner_spend: InnerSpend,
) -> Result<InnerSpend, SpendError>
where
    M: ToClvm<NodePtr>,
{
    let nft_state_layer = ctx.nft_state_layer()?;

    let puzzle = ctx.alloc(&CurriedProgram {
        program: nft_state_layer,
        args: NftStateLayerArgs::new(metadata, inner_spend.puzzle()),
    })?;

    let solution = ctx.alloc(&NftStateLayerSolution {
        inner_solution: inner_spend.solution(),
    })?;

    Ok(InnerSpend::new(puzzle, solution))
}

pub fn spend_nft_ownership_layer<P>(
    ctx: &mut SpendContext<'_>,
    current_owner: Option<Bytes32>,
    transfer_program: P,
    inner_spend: InnerSpend,
) -> Result<InnerSpend, SpendError>
where
    P: ToClvm<NodePtr>,
{
    let nft_ownership_layer = ctx.nft_ownership_layer()?;

    let puzzle = ctx.alloc(&CurriedProgram {
        program: nft_ownership_layer,
        args: NftOwnershipLayerArgs::new(current_owner, transfer_program, inner_spend.puzzle()),
    })?;

    let solution = ctx.alloc(&NftOwnershipLayerSolution {
        inner_solution: inner_spend.solution(),
    })?;

    Ok(InnerSpend::new(puzzle, solution))
}

#[cfg(test)]
mod tests {
    use crate::puzzles::{
        CreateDid, IntermediateLauncher, Launcher, MintNft, OwnerDid, StandardDidSpend,
        StandardMint,
    };

    use super::*;

    use chia_puzzles::standard::StandardArgs;
    use chia_sdk_test::{test_transaction, Simulator};
    use clvmr::Allocator;

    #[tokio::test]
    async fn test_nft_lineage() -> anyhow::Result<()> {
        let sim = Simulator::new().await?;
        let peer = sim.connect().await?;

        let sk = sim.secret_key().await?;
        let pk = sk.public_key();

        let puzzle_hash = StandardArgs::curry_tree_hash(pk).into();
        let coin = sim.mint_coin(puzzle_hash, 2).await;

        let mut allocator = Allocator::new();
        let ctx = &mut SpendContext::new(&mut allocator);

        let (create_did, did_info) = Launcher::new(coin.coin_id(), 1)
            .create(ctx)?
            .create_standard_did(ctx, pk)?;

        StandardSpend::new()
            .chain(create_did)
            .finish(ctx, coin, pk)?;

        let (mint_nft, mut nft_info) = IntermediateLauncher::new(did_info.coin.coin_id(), 0, 1)
            .create(ctx)?
            .mint_standard_nft(
                ctx,
                StandardMint {
                    metadata: (),
                    royalty_puzzle_hash: puzzle_hash,
                    royalty_percentage: 300,
                    synthetic_key: pk,
                    owner_puzzle_hash: puzzle_hash,
                    owner_did: Some(OwnerDid {
                        did_id: did_info.launcher_id,
                        did_inner_puzzle_hash: did_info.did_inner_puzzle_hash,
                    }),
                },
            )?;

        let mut did_info = StandardDidSpend::new()
            .chain(mint_nft)
            .recreate()
            .finish(ctx, pk, did_info)?;

        for i in 0..5 {
            let mut spend = StandardNftSpend::new().update();

            if i % 2 == 0 {
                spend = spend.new_owner(did_info.launcher_id, did_info.did_inner_puzzle_hash);
            }

            let (nft_spend, new_nft_info) = spend.finish(ctx, pk, nft_info)?;
            nft_info = new_nft_info;

            did_info = StandardDidSpend::new()
                .chain(nft_spend)
                .recreate()
                .finish(ctx, pk, did_info)?;
        }

        test_transaction(
            &peer,
            ctx.take_spends(),
            &[sk],
            sim.config().genesis_challenge,
        )
        .await;

        let coin_state = sim
            .coin_state(did_info.coin.coin_id())
            .await
            .expect("expected did coin");
        assert_eq!(coin_state.coin, did_info.coin);

        let coin_state = sim
            .coin_state(nft_info.coin.coin_id())
            .await
            .expect("expected nft coin");
        assert_eq!(coin_state.coin, nft_info.coin);

        Ok(())
    }
}