algokit_transact_ffi/
lib.rs

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
use algokit_transact::constants::*;
use algokit_transact::msgpack::{
    decode_base64_msgpack_to_json as internal_decode_base64_msgpack_to_json,
    decode_msgpack_to_json as internal_decode_msgpack_to_json,
    encode_json_to_base64_msgpack as internal_encode_json_to_base64_msgpack,
    encode_json_to_msgpack as internal_encode_json_to_msgpack,
    AlgoKitMsgPackError as InternalMsgPackError, ModelType as InternalModelType,
};
use algokit_transact::{AlgorandMsgpack, Byte32, EstimateTransactionSize, TransactionId, Transactions};
use ffi_macros::{ffi_enum, ffi_func, ffi_record};
use serde::{Deserialize, Serialize};
use serde_bytes::ByteBuf;

// thiserror is used to easily create errors than can be propagated to the language bindings
// UniFFI will create classes for errors (i.e. `MsgPackError.EncodingError` in Python)
#[derive(Debug, thiserror::Error)]
#[cfg_attr(feature = "ffi_uniffi", derive(uniffi::Error))]
pub enum AlgoKitTransactError {
    #[error("EncodingError: {0}")]
    EncodingError(String),
    #[error("DecodingError: {0}")]
    DecodingError(String),
    #[error("{0}")]
    InputError(String),
    #[error("MsgPackError: {0}")]
    MsgPackError(String),
}

// For now, in WASM we just throw the string, hence the error
// type being included in the error string above
// Perhaps in the future we could use a class like in UniFFI
#[cfg(feature = "ffi_wasm")]
impl From<AlgoKitTransactError> for JsValue {
    fn from(e: AlgoKitTransactError) -> Self {
        JsValue::from(e.to_string())
    }
}

// Convert errors from the Rust crate into the FFI-specific errors
impl From<algokit_transact::AlgoKitTransactError> for AlgoKitTransactError {
    fn from(e: algokit_transact::AlgoKitTransactError) -> Self {
        match e {
            algokit_transact::AlgoKitTransactError::DecodingError(_) => {
                AlgoKitTransactError::DecodingError(e.to_string())
            }
            algokit_transact::AlgoKitTransactError::EncodingError(_) => {
                AlgoKitTransactError::EncodingError(e.to_string())
            }
            algokit_transact::AlgoKitTransactError::MsgpackDecodingError(_) => {
                AlgoKitTransactError::DecodingError(e.to_string())
            }
            algokit_transact::AlgoKitTransactError::MsgpackEncodingError(_) => {
                AlgoKitTransactError::EncodingError(e.to_string())
            }
            algokit_transact::AlgoKitTransactError::UnknownTransactionType(_) => {
                AlgoKitTransactError::DecodingError(e.to_string())
            }
            algokit_transact::AlgoKitTransactError::InputError(e) => {
                AlgoKitTransactError::InputError(e.to_string())
            }
            algokit_transact::AlgoKitTransactError::InvalidAddress(_) => {
                AlgoKitTransactError::DecodingError(e.to_string())
            }
        }
    }
}

// Convert msgpack errors to FFI errors
impl From<InternalMsgPackError> for AlgoKitTransactError {
    fn from(e: InternalMsgPackError) -> Self {
        match e {
            InternalMsgPackError::SerializationError(e) => {
                AlgoKitTransactError::MsgPackError(e.to_string())
            }
            InternalMsgPackError::MsgpackEncodingError(e) => {
                AlgoKitTransactError::MsgPackError(e.to_string())
            }
            InternalMsgPackError::MsgpackDecodingError(e) => {
                AlgoKitTransactError::MsgPackError(e.to_string())
            }
            InternalMsgPackError::Base64DecodingError(e) => {
                AlgoKitTransactError::MsgPackError(e.to_string())
            }
            InternalMsgPackError::MsgpackWriteError(s) => AlgoKitTransactError::MsgPackError(s),
            InternalMsgPackError::UnknownModelError(s) => AlgoKitTransactError::MsgPackError(s),
            InternalMsgPackError::IoError(s) => AlgoKitTransactError::MsgPackError(s),
            InternalMsgPackError::ValueWriteError(s) => AlgoKitTransactError::MsgPackError(s),
        }
    }
}

#[cfg(feature = "ffi_uniffi")]
use uniffi::{self};

#[cfg(feature = "ffi_uniffi")]
uniffi::setup_scaffolding!();

#[cfg(feature = "ffi_wasm")]
use js_sys::Uint8Array;
#[cfg(feature = "ffi_wasm")]
use tsify_next::Tsify;
#[cfg(feature = "ffi_wasm")]
use wasm_bindgen::prelude::*;

// We need to use ByteBuf directly in the structs to get Uint8Array in TSify
// custom_type! and this impl is used to convert the ByteBuf to a Vec<u8> for the UniFFI bindings
#[cfg(feature = "ffi_uniffi")]
impl UniffiCustomTypeConverter for ByteBuf {
    type Builtin = Vec<u8>;

    fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
        Ok(ByteBuf::from(val))
    }

    fn from_custom(obj: Self) -> Self::Builtin {
        obj.to_vec()
    }
}

#[cfg(feature = "ffi_uniffi")]
uniffi::custom_type!(ByteBuf, Vec<u8>);

// This becomes an enum in UniFFI language bindings and a
// string literal union in TS
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
#[cfg_attr(feature = "ffi_wasm", derive(Tsify))]
#[cfg_attr(feature = "ffi_wasm", tsify(into_wasm_abi, from_wasm_abi))]
#[cfg_attr(feature = "ffi_uniffi", derive(uniffi::Enum))]
pub enum TransactionType {
    Payment,
    AssetTransfer,
    AssetFreeze,
    AssetConfig,
    KeyRegistration,
    ApplicationCall,
}

#[ffi_record]
pub struct Address {
    address: String,
    pub_key: ByteBuf,
}

impl From<algokit_transact::Address> for Address {
    fn from(value: algokit_transact::Address) -> Self {
        return Self {
            address: value.to_string(),
            pub_key: value.pub_key.to_vec().into(),
        };
    }
}

impl TryFrom<Address> for algokit_transact::Address {
    type Error = AlgoKitTransactError;

    fn try_from(value: Address) -> Result<Self, Self::Error> {
        let pub_key: [u8; ALGORAND_PUBLIC_KEY_BYTE_LENGTH] =
            value.pub_key.to_vec().try_into().map_err(|_| {
                AlgoKitTransactError::EncodingError(
                    format!(
                        "public key should be {} bytes",
                        ALGORAND_PUBLIC_KEY_BYTE_LENGTH
                    )
                    .to_string(),
                )
            })?;

        Ok(algokit_transact::Address::from_pubkey(&pub_key))
    }
}

#[ffi_record]
pub struct FeeParams {
    fee_per_byte: u64,
    min_fee: u64,
    extra_fee: Option<u64>,
    max_fee: Option<u64>,
}

#[ffi_record]
pub struct PaymentTransactionFields {
    receiver: Address,

    amount: u64,

    close_remainder_to: Option<Address>,
}

#[ffi_record]
pub struct AssetTransferTransactionFields {
    asset_id: u64,

    amount: u64,

    receiver: Address,

    asset_sender: Option<Address>,

    close_remainder_to: Option<Address>,
}

#[ffi_record]
pub struct Transaction {
    /// The type of transaction
    transaction_type: TransactionType,

    /// The sender of the transaction
    sender: Address,

    /// Optional transaction fee in microALGO.
    ///
    /// If not set, the fee will be interpreted as 0 by the network.
    fee: Option<u64>,

    first_valid: u64,

    last_valid: u64,

    genesis_hash: Option<ByteBuf>,

    genesis_id: Option<String>,

    note: Option<ByteBuf>,

    rekey_to: Option<Address>,

    lease: Option<ByteBuf>,

    group: Option<ByteBuf>,

    payment: Option<PaymentTransactionFields>,

    asset_transfer: Option<AssetTransferTransactionFields>,
}

impl TryFrom<Transaction> for algokit_transact::Transaction {
    type Error = AlgoKitTransactError;

    fn try_from(tx: Transaction) -> Result<Self, AlgoKitTransactError> {
        // Ensure there is never more than 1 transaction type specific field set
        if [tx.payment.is_some(), tx.asset_transfer.is_some()]
            .iter()
            .filter(|&&x| x)
            .count()
            > 1
        {
            return Err(Self::Error::DecodingError(
                "Multiple transaction type specific fields set".to_string(),
            ));
        }

        match tx.transaction_type {
            TransactionType::Payment => Ok(algokit_transact::Transaction::Payment(tx.try_into()?)),
            TransactionType::AssetTransfer => {
                Ok(algokit_transact::Transaction::AssetTransfer(tx.try_into()?))
            }
            _ => {
                return Err(Self::Error::DecodingError(
                    "Transaction type is not implemented".to_string(),
                ));
            }
        }
    }
}

impl TryFrom<Transaction> for algokit_transact::TransactionHeader {
    type Error = AlgoKitTransactError;

    fn try_from(tx: Transaction) -> Result<Self, AlgoKitTransactError> {
        Ok(Self {
            sender: tx.sender.try_into()?,
            fee: tx.fee,
            first_valid: tx.first_valid,
            last_valid: tx.last_valid,
            genesis_id: tx.genesis_id,
            genesis_hash: tx.genesis_hash.map(bytebuf_to_byte32).transpose()?,
            note: tx.note.map(ByteBuf::into_vec),
            rekey_to: tx.rekey_to.map(TryInto::try_into).transpose()?,
            lease: tx.lease.map(bytebuf_to_byte32).transpose()?,
            group: tx.group.map(bytebuf_to_byte32).transpose()?,
        })
    }
}

impl From<algokit_transact::PaymentTransactionFields> for PaymentTransactionFields {
    fn from(tx: algokit_transact::PaymentTransactionFields) -> Self {
        Self {
            receiver: tx.receiver.into(),
            amount: tx.amount,
            close_remainder_to: tx.close_remainder_to.map(Into::into),
        }
    }
}

impl TryFrom<Transaction> for algokit_transact::PaymentTransactionFields {
    type Error = AlgoKitTransactError;

    fn try_from(tx: Transaction) -> Result<Self, Self::Error> {
        if tx.transaction_type != TransactionType::Payment || tx.payment.is_none() {
            return Err(Self::Error::DecodingError(
                "Payment data missing".to_string(),
            ));
        }

        let data = tx.clone().payment.unwrap();
        let header: algokit_transact::TransactionHeader = tx.try_into()?;

        Ok(Self {
            header,
            amount: data.amount,
            receiver: data.receiver.try_into()?,
            close_remainder_to: data.close_remainder_to.map(TryInto::try_into).transpose()?,
        })
    }
}

impl From<algokit_transact::AssetTransferTransactionFields> for AssetTransferTransactionFields {
    fn from(tx: algokit_transact::AssetTransferTransactionFields) -> Self {
        Self {
            asset_id: tx.asset_id,
            amount: tx.amount,
            receiver: tx.receiver.into(),
            asset_sender: tx.asset_sender.map(Into::into),
            close_remainder_to: tx.close_remainder_to.map(Into::into),
        }
    }
}

impl TryFrom<Transaction> for algokit_transact::AssetTransferTransactionFields {
    type Error = AlgoKitTransactError;

    fn try_from(tx: Transaction) -> Result<Self, Self::Error> {
        if tx.transaction_type != TransactionType::AssetTransfer || tx.asset_transfer.is_none() {
            return Err(Self::Error::DecodingError(
                "Asset Transfer data missing".to_string(),
            ));
        }

        let data = tx.clone().asset_transfer.unwrap();
        let header: algokit_transact::TransactionHeader = tx.try_into()?;

        Ok(Self {
            header,
            asset_id: data.asset_id,
            amount: data.amount,
            receiver: data.receiver.try_into()?,
            asset_sender: data.asset_sender.map(TryInto::try_into).transpose()?,
            close_remainder_to: data.close_remainder_to.map(TryInto::try_into).transpose()?,
        })
    }
}

impl TryFrom<algokit_transact::Transaction> for Transaction {
    type Error = AlgoKitTransactError;

    fn try_from(tx: algokit_transact::Transaction) -> Result<Self, AlgoKitTransactError> {
        match tx {
            algokit_transact::Transaction::Payment(payment) => {
                let payment_fields = payment.clone().into();
                build_transaction(
                    payment.header,
                    TransactionType::Payment,
                    Some(payment_fields),
                    None,
                )
            }
            algokit_transact::Transaction::AssetTransfer(asset_transfer) => {
                let asset_transfer_fields = asset_transfer.clone().into();
                build_transaction(
                    asset_transfer.header,
                    TransactionType::AssetTransfer,
                    None,
                    Some(asset_transfer_fields),
                )
            }
        }
    }
}

#[ffi_record]
pub struct SignedTransaction {
    /// The transaction that has been signed.
    pub transaction: Transaction,

    /// Optional Ed25519 signature authorizing the transaction.
    pub signature: Option<ByteBuf>,

    /// Optional auth address applicable if the transaction sender is a rekeyed account.
    pub auth_address: Option<Address>,
}

impl From<algokit_transact::SignedTransaction> for SignedTransaction {
    fn from(signed_tx: algokit_transact::SignedTransaction) -> Self {
        Self {
            transaction: signed_tx.transaction.try_into().unwrap(),
            signature: signed_tx.signature.map(|sig| sig.to_vec().into()),
            auth_address: signed_tx.auth_address.map(Into::into),
        }
    }
}

impl TryFrom<SignedTransaction> for algokit_transact::SignedTransaction {
    type Error = AlgoKitTransactError;

    fn try_from(signed_tx: SignedTransaction) -> Result<Self, Self::Error> {
        let signature = signed_tx
            .signature
            .map(|sig| {
                sig.to_vec().try_into().map_err(|_| {
                    AlgoKitTransactError::EncodingError(format!(
                        "signature should be {} bytes",
                        ALGORAND_SIGNATURE_BYTE_LENGTH
                    ))
                })
            })
            .transpose()?;

        Ok(Self {
            transaction: signed_tx.transaction.try_into()?,
            signature,
            auth_address: signed_tx.auth_address.map(TryInto::try_into).transpose()?,
        })
    }
}

fn bytebuf_to_byte32(buf: ByteBuf) -> Result<Byte32, AlgoKitTransactError> {
    let vec = buf.to_vec();
    vec.try_into().map_err(|_| {
        AlgoKitTransactError::DecodingError(
            "Expected 32 bytes but got a different length".to_string(),
        )
    })
}

fn byte32_to_bytebuf(b32: Byte32) -> ByteBuf {
    ByteBuf::from(b32.to_vec())
}

fn build_transaction(
    header: algokit_transact::TransactionHeader,
    transaction_type: TransactionType,
    payment: Option<PaymentTransactionFields>,
    asset_transfer: Option<AssetTransferTransactionFields>,
) -> Result<Transaction, AlgoKitTransactError> {
    Ok(Transaction {
        transaction_type,
        sender: header.sender.into(),
        fee: header.fee,
        first_valid: header.first_valid,
        last_valid: header.last_valid,
        genesis_id: header.genesis_id,
        genesis_hash: header.genesis_hash.map(byte32_to_bytebuf),
        note: header.note.map(Into::into),
        rekey_to: header.rekey_to.map(Into::into),
        lease: header.lease.map(byte32_to_bytebuf),
        group: header.group.map(byte32_to_bytebuf),
        payment,
        asset_transfer,
    })
}

// Each function need to be explicitly renamed for WASM
// and exported for UniFFI

/// Get the transaction type from the encoded transaction.
/// This is particularly useful when decoding a transaction that has an unknown type
#[ffi_func]
pub fn get_encoded_transaction_type(bytes: &[u8]) -> Result<TransactionType, AlgoKitTransactError> {
    let decoded = algokit_transact::Transaction::decode(bytes)?;

    match decoded {
        algokit_transact::Transaction::Payment(_) => Ok(TransactionType::Payment),
        algokit_transact::Transaction::AssetTransfer(_) => Ok(TransactionType::AssetTransfer),
    }
}

#[ffi_func]
/// Encode the transaction with the domain separation (e.g. "TX") prefix
pub fn encode_transaction(tx: Transaction) -> Result<Vec<u8>, AlgoKitTransactError> {
    let ctx: algokit_transact::Transaction = tx.try_into()?;
    Ok(ctx.encode()?)
}

/// Encode transactions to MsgPack with the domain separation (e.g. "TX") prefix.
///
/// # Parameters
/// * `txs` - A collection of transactions to encode
///
/// # Returns
/// A collection of MsgPack encoded bytes or an error if encoding fails.
#[cfg(feature = "ffi_wasm")]
#[ffi_func]
/// Encode transactions with the domain separation (e.g. "TX") prefix
pub fn encode_transactions(txs: Vec<Transaction>) -> Result<Vec<Uint8Array>, AlgoKitTransactError> {
    txs.into_iter()
        .map(|tx| encode_transaction(tx).map(|bytes| bytes.as_slice().into()))
        .collect()
}

/// Encode transactions to MsgPack with the domain separation (e.g. "TX") prefix.
///
/// # Parameters
/// * `txs` - A collection of transactions to encode
///
/// # Returns
/// A collection of MsgPack encoded bytes or an error if encoding fails.
#[cfg(not(feature = "ffi_wasm"))]
#[ffi_func]
pub fn encode_transactions(txs: Vec<Transaction>) -> Result<Vec<Vec<u8>>, AlgoKitTransactError> {
    txs.into_iter().map(encode_transaction).collect()
}

#[ffi_func]
/// Encode the transaction without the domain separation (e.g. "TX") prefix
/// This is useful for encoding the transaction for signing with tools that automatically add "TX" prefix to the transaction bytes.
pub fn encode_transaction_raw(tx: Transaction) -> Result<Vec<u8>, AlgoKitTransactError> {
    let ctx: algokit_transact::Transaction = tx.try_into()?;
    Ok(ctx.encode_raw()?)
}

/// Decodes MsgPack bytes into a transaction.
///
/// # Parameters
/// * `encoded_tx` - MsgPack encoded bytes representing a transaction.
///
/// # Returns
/// A decoded transaction or an error if decoding fails.
#[ffi_func]
pub fn decode_transaction(encoded_tx: &[u8]) -> Result<Transaction, AlgoKitTransactError> {
    let ctx: algokit_transact::Transaction = algokit_transact::Transaction::decode(encoded_tx)?;
    Ok(ctx.try_into()?)
}

/// Decodes a collection of MsgPack bytes into a transaction collection.
///
/// # Parameters
/// * `encoded_txs` - A collection of MsgPack encoded bytes, each representing a transaction.
///
/// # Returns
/// A collection of decoded transactions or an error if decoding fails.
#[cfg(feature = "ffi_wasm")]
#[ffi_func]
pub fn decode_transactions(
    encoded_txs: Vec<Uint8Array>,
) -> Result<Vec<Transaction>, AlgoKitTransactError> {
    encoded_txs
        .iter()
        .map(|bytes| decode_transaction(bytes.to_vec().as_slice()))
        .collect()
}

/// Decodes a collection of MsgPack bytes into a transaction collection.
///
/// # Parameters
/// * `encoded_txs` - A collection of MsgPack encoded bytes, each representing a transaction.
///
/// # Returns
/// A collection of decoded transactions or an error if decoding fails.
#[cfg(not(feature = "ffi_wasm"))]
#[ffi_func]
pub fn decode_transactions(
    encoded_txs: Vec<Vec<u8>>,
) -> Result<Vec<Transaction>, AlgoKitTransactError> {
    encoded_txs
        .iter()
        .map(|tx| decode_transaction(tx))
        .collect()
}

/// Return the size of the transaction in bytes as if it was already signed and encoded.
/// This is useful for estimating the fee for the transaction.
#[ffi_func]
pub fn estimate_transaction_size(transaction: Transaction) -> Result<u64, AlgoKitTransactError> {
    let core_tx: algokit_transact::Transaction = transaction.try_into()?;
    return core_tx
        .estimate_size()
        .map_err(|e| {
            AlgoKitTransactError::EncodingError(format!(
                "Failed to estimate transaction size: {}",
                e
            ))
        })?
        .try_into()
        .map_err(|_| {
            AlgoKitTransactError::EncodingError("Failed to convert size to u64".to_string())
        });
}

#[ffi_func]
pub fn address_from_pub_key(pub_key: &[u8]) -> Result<Address, AlgoKitTransactError> {
    Ok(
        algokit_transact::Address::from_pubkey(pub_key.try_into().map_err(|_| {
            AlgoKitTransactError::EncodingError(
                format!(
                    "public key should be {} bytes",
                    ALGORAND_PUBLIC_KEY_BYTE_LENGTH
                )
                .to_string(),
            )
        })?)
        .into(),
    )
}

#[ffi_func]
pub fn address_from_string(address: &str) -> Result<Address, AlgoKitTransactError> {
    address
        .parse::<algokit_transact::Address>()
        .map(Into::into)
        .map_err(|e| AlgoKitTransactError::EncodingError(e.to_string()))
}

/// Get the raw 32-byte transaction ID for a transaction.
#[ffi_func]
pub fn get_transaction_id_raw(tx: Transaction) -> Result<Vec<u8>, AlgoKitTransactError> {
    let tx_internal: algokit_transact::Transaction = tx.try_into()?;
    let id_raw = tx_internal.id_raw()?;
    Ok(id_raw.to_vec())
}

/// Get the base32 transaction ID string for a transaction.
#[ffi_func]
pub fn get_transaction_id(tx: Transaction) -> Result<String, AlgoKitTransactError> {
    let tx_internal: algokit_transact::Transaction = tx.try_into()?;
    Ok(tx_internal.id()?)
}

/// Groups a collection of transactions by calculating and assigning the group to each transaction.
#[ffi_func]
pub fn group_transactions(txs: Vec<Transaction>) -> Result<Vec<Transaction>, AlgoKitTransactError> {
    let txs_internal: Vec<algokit_transact::Transaction> = txs
        .into_iter()
        .map(|tx| tx.try_into())
        .collect::<Result<Vec<_>, _>>()?;

    let grouped_txs: Vec<Transaction> = txs_internal
        .assign_group()?
        .into_iter()
        .map(|tx| tx.try_into())
        .collect::<Result<Vec<_>, _>>()?;

    Ok(grouped_txs)
}

/// Enum containing all constants used in this crate.
#[ffi_enum]
pub enum AlgorandConstant {
    /// Length of hash digests (32)
    HashLength,

    /// Length of the checksum used in Algorand addresses (4)
    ChecksumLength,

    /// Length of a base32-encoded Algorand address (58)
    AddressLength,

    /// Length of an Algorand public key in bytes (32)
    PublicKeyLength,

    /// Length of an Algorand secret key in bytes (32)
    SecretKeyLength,

    /// Length of an Algorand signature in bytes (64)
    SignatureLength,

    /// Increment in the encoded byte size when a signature is attached to a transaction (75)
    SignatureEncodingIncrLength,

    // The maximum number of transactions in a group (16)
    MaxTxGroupSize,
}

impl AlgorandConstant {
    /// Get the numeric value of the constant
    pub fn value(&self) -> u64 {
        match self {
            AlgorandConstant::HashLength => HASH_BYTES_LENGTH as u64,
            AlgorandConstant::ChecksumLength => ALGORAND_CHECKSUM_BYTE_LENGTH as u64,
            AlgorandConstant::AddressLength => ALGORAND_ADDRESS_LENGTH as u64,
            AlgorandConstant::PublicKeyLength => ALGORAND_PUBLIC_KEY_BYTE_LENGTH as u64,
            AlgorandConstant::SecretKeyLength => ALGORAND_SECRET_KEY_BYTE_LENGTH as u64,
            AlgorandConstant::SignatureLength => ALGORAND_SIGNATURE_BYTE_LENGTH as u64,
            AlgorandConstant::SignatureEncodingIncrLength => {
                ALGORAND_SIGNATURE_ENCODING_INCR as u64
            }
            AlgorandConstant::MaxTxGroupSize => MAX_TX_GROUP_SIZE as u64,
        }
    }
}

#[ffi_func]
pub fn get_algorand_constant(constant: AlgorandConstant) -> u64 {
    constant.value()
}

impl TryFrom<FeeParams> for algokit_transact::FeeParams {
    type Error = AlgoKitTransactError;

    fn try_from(value: FeeParams) -> Result<Self, Self::Error> {
        Ok(Self {
            fee_per_byte: value.fee_per_byte,
            min_fee: value.min_fee,
            extra_fee: value.extra_fee,
            max_fee: value.max_fee,
        })
    }
}

#[ffi_func]
pub fn assign_fee(
    txn: Transaction,
    fee_params: FeeParams,
) -> Result<Transaction, AlgoKitTransactError> {
    let txn_internal: algokit_transact::Transaction = txn.try_into()?;
    let fee_params_internal: algokit_transact::FeeParams = fee_params.try_into()?;

    let updated_txn = txn_internal.assign_fee(fee_params_internal)?;

    Ok(updated_txn.try_into()?)
}

/// Decodes a signed transaction.
///
/// # Parameters
/// * `bytes` - The MsgPack encoded signed transaction bytes
///
/// # Returns
/// The decoded SignedTransaction or an error if decoding fails.
#[ffi_func]
pub fn decode_signed_transaction(bytes: &[u8]) -> Result<SignedTransaction, AlgoKitTransactError> {
    let signed_tx = algokit_transact::SignedTransaction::decode(bytes)?;
    Ok(signed_tx.into())
}

/// Decodes a collection of MsgPack bytes into a signed transaction collection.
///
/// # Parameters
/// * `encoded_signed_txs` - A collection of MsgPack encoded bytes, each representing a signed transaction.
///
/// # Returns
/// A collection of decoded signed transactions or an error if decoding fails.
#[cfg(feature = "ffi_wasm")]
#[ffi_func]
pub fn decode_signed_transactions(
    encoded_signed_txs: Vec<Uint8Array>,
) -> Result<Vec<SignedTransaction>, AlgoKitTransactError> {
    encoded_signed_txs
        .iter()
        .map(|bytes| decode_signed_transaction(bytes.to_vec().as_slice()))
        .collect()
}

/// Decodes a collection of MsgPack bytes into a signed transaction collection.
///
/// # Parameters
/// * `encoded_signed_txs` - A collection of MsgPack encoded bytes, each representing a signed transaction.
///
/// # Returns
/// A collection of decoded signed transactions or an error if decoding fails.
#[cfg(not(feature = "ffi_wasm"))]
#[ffi_func]
pub fn decode_signed_transactions(
    encoded_signed_txs: Vec<Vec<u8>>,
) -> Result<Vec<SignedTransaction>, AlgoKitTransactError> {
    encoded_signed_txs
        .iter()
        .map(|tx| decode_signed_transaction(tx))
        .collect()
}

/// Encode a signed transaction to MsgPack for sending on the network.
///
/// This method performs canonical encoding. No domain separation prefix is applicable.
///
/// # Parameters
/// * `signed_tx` - The signed transaction to encode
///
/// # Returns
/// The MsgPack encoded bytes or an error if encoding fails.
#[ffi_func]
pub fn encode_signed_transaction(
    signed_tx: SignedTransaction,
) -> Result<Vec<u8>, AlgoKitTransactError> {
    let signed_tx_internal: algokit_transact::SignedTransaction = signed_tx.try_into()?;
    Ok(signed_tx_internal.encode()?)
}

/// Encode signed transactions to MsgPack for sending on the network.
///
/// This method performs canonical encoding. No domain separation prefix is applicable.
///
/// # Parameters
/// * `signed_txs` - A collection of signed transactions to encode
///
/// # Returns
/// A collection of MsgPack encoded bytes or an error if encoding fails.
#[cfg(feature = "ffi_wasm")]
#[ffi_func]
pub fn encode_signed_transactions(
    signed_txs: Vec<SignedTransaction>,
) -> Result<Vec<Uint8Array>, AlgoKitTransactError> {
    signed_txs
        .into_iter()
        .map(|tx| encode_signed_transaction(tx).map(|bytes| bytes.as_slice().into()))
        .collect()
}

/// Encode signed transactions to MsgPack for sending on the network.
///
/// This method performs canonical encoding. No domain separation prefix is applicable.
///
/// # Parameters
/// * `signed_txs` - A collection of signed transactions to encode
///
/// # Returns
/// A collection of MsgPack encoded bytes or an error if encoding fails.
#[cfg(not(feature = "ffi_wasm"))]
#[ffi_func]
pub fn encode_signed_transactions(
    signed_txs: Vec<SignedTransaction>,
) -> Result<Vec<Vec<u8>>, AlgoKitTransactError> {
    signed_txs
        .into_iter()
        .map(encode_signed_transaction)
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use algokit_transact::test_utils::{TestDataMother, TransactionMother};
    use pretty_assertions::assert_eq;

    #[test]
    fn test_get_encoded_transaction_type() {
        let txn: Transaction = TransactionMother::simple_payment()
            .build()
            .unwrap()
            .try_into()
            .unwrap();

        // Encode the transaction
        let encoded = encode_transaction(txn).unwrap();

        // Test the get_encoded_transaction_type function
        let tx_type = get_encoded_transaction_type(&encoded).unwrap();
        assert_eq!(tx_type, TransactionType::Payment);
    }

    #[test]
    fn test_transaction_id_ffi() {
        let data = TestDataMother::simple_payment();
        let tx_ffi: Transaction = data.transaction.try_into().unwrap();

        let actual_id = get_transaction_id(tx_ffi.clone()).unwrap();
        let actual_id_raw = get_transaction_id_raw(tx_ffi.clone()).unwrap();

        assert_eq!(actual_id, data.id);
        assert_eq!(actual_id_raw, data.id_raw);
    }

    #[test]
    fn test_group_transactions_ffi() {
        let expected_group = [
            202, 79, 82, 7, 197, 237, 213, 55, 117, 226, 131, 74, 221, 85, 86, 215, 64, 133, 212,
            7, 58, 234, 248, 162, 222, 53, 161, 29, 141, 101, 133, 49,
        ];
        let tx1 = TestDataMother::simple_payment()
            .transaction
            .try_into()
            .unwrap();
        let tx2 = TestDataMother::opt_in_asset_transfer()
            .transaction
            .try_into()
            .unwrap();
        let txs = vec![tx1, tx2];

        let grouped_txs = group_transactions(txs.clone()).unwrap();

        assert_eq!(grouped_txs.len(), txs.len());
        for grouped_tx in grouped_txs.into_iter() {
            assert_eq!(grouped_tx.group.unwrap(), &expected_group);
        }
    }
}

// ========== MessagePack FFI Functions ==========

#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
#[cfg_attr(feature = "ffi_wasm", derive(tsify_next::Tsify))]
#[cfg_attr(feature = "ffi_wasm", tsify(into_wasm_abi, from_wasm_abi))]
#[cfg_attr(feature = "ffi_uniffi", derive(uniffi::Enum))]
pub enum ModelType {
    SimulateRequest,
    SimulateTransaction200Response,
}

impl From<ModelType> for InternalModelType {
    fn from(model_type: ModelType) -> Self {
        match model_type {
            ModelType::SimulateRequest => InternalModelType::SimulateRequest,
            ModelType::SimulateTransaction200Response => {
                InternalModelType::SimulateTransaction200Response
            }
        }
    }
}

impl From<InternalModelType> for ModelType {
    fn from(model_type: InternalModelType) -> Self {
        match model_type {
            InternalModelType::SimulateRequest => ModelType::SimulateRequest,
            InternalModelType::SimulateTransaction200Response => {
                ModelType::SimulateTransaction200Response
            }
        }
    }
}

#[ffi_func]
pub fn encode_json_to_msgpack(
    model_type: ModelType,
    json_str: &str,
) -> Result<Vec<u8>, AlgoKitTransactError> {
    let internal_type: InternalModelType = model_type.into();
    Ok(internal_encode_json_to_msgpack(internal_type, json_str)?)
}

#[ffi_func]
pub fn decode_msgpack_to_json(
    model_type: ModelType,
    msgpack_bytes: &[u8],
) -> Result<String, AlgoKitTransactError> {
    let internal_type: InternalModelType = model_type.into();
    Ok(internal_decode_msgpack_to_json(
        internal_type,
        msgpack_bytes,
    )?)
}

#[ffi_func]
pub fn encode_json_to_base64_msgpack(
    model_type: ModelType,
    json_str: &str,
) -> Result<String, AlgoKitTransactError> {
    let internal_type: InternalModelType = model_type.into();
    Ok(internal_encode_json_to_base64_msgpack(
        internal_type,
        json_str,
    )?)
}

#[ffi_func]
pub fn decode_base64_msgpack_to_json(
    model_type: ModelType,
    base64_str: &str,
) -> Result<String, AlgoKitTransactError> {
    let internal_type: InternalModelType = model_type.into();
    Ok(internal_decode_base64_msgpack_to_json(
        internal_type,
        base64_str,
    )?)
}

#[ffi_func]
pub fn supported_models() -> Vec<ModelType> {
    algokit_transact::msgpack::supported_models()
        .into_iter()
        .map(Into::into)
        .collect()
}