alephium-web3 2.0.7

A Rust library to interact with the Alephium platform
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
// Copyright 2018 - 2022 The Alephium Authors
// This file is part of the alephium project.

use crate::api::types::Token;
use crate::error::{Error, Result};
use crate::signer::PrivateKey;
use serde::{Deserialize, Serialize};

/// Transaction ID (32 bytes)
pub type TxId = String;

/// Output reference
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OutputRef {
    pub hint: i32,
    #[serde(rename = "key")]
    pub tx_hash: String,
}

/// Asset input
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetInput {
    #[serde(rename = "outputRef")]
    pub output_ref: OutputRef,
    #[serde(rename = "unlockScript")]
    pub unlock_script: String,
}

/// Asset output
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetOutput {
    #[serde(rename = "address")]
    pub address: String,
    #[serde(rename = "attoAlphAmount")]
    pub atto_alph_amount: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tokens: Option<Vec<Token>>,
    #[serde(rename = "lockTime", skip_serializing_if = "Option::is_none")]
    pub lock_time: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl AssetOutput {
    /// Create a new asset output
    pub fn new(address: String, atto_alph_amount: String) -> Self {
        Self {
            address,
            atto_alph_amount,
            tokens: None,
            lock_time: None,
            message: None,
        }
    }

    /// Create output with tokens
    pub fn with_tokens(mut self, tokens: Vec<Token>) -> Self {
        self.tokens = Some(tokens);
        self
    }

    /// Create output with lock time
    pub fn with_lock_time(mut self, lock_time: u64) -> Self {
        self.lock_time = Some(lock_time);
        self
    }

    /// Create output with message
    pub fn with_message(mut self, message: String) -> Self {
        self.message = Some(message);
        self
    }
}

/// Contract output
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContractOutput {
    #[serde(rename = "address")]
    pub address: String,
    #[serde(rename = "attoAlphAmount")]
    pub atto_alph_amount: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tokens: Option<Vec<Token>>,
}

/// Output type (either asset or contract)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum Output {
    #[serde(rename = "AssetOutput")]
    Asset(AssetOutput),
    #[serde(rename = "ContractOutput")]
    Contract(ContractOutput),
}

/// Unsigned transaction
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UnsignedTransaction {
    #[serde(rename = "txId")]
    pub tx_id: TxId,
    pub version: u8,
    #[serde(rename = "networkId")]
    pub network_id: u8,
    #[serde(rename = "gasAmount")]
    pub gas_amount: u32,
    #[serde(rename = "gasPrice")]
    pub gas_price: String,
    pub inputs: Vec<AssetInput>,
    #[serde(rename = "fixedOutputs")]
    pub fixed_outputs: Vec<AssetOutput>,
    #[serde(rename = "scriptOpt", skip_serializing_if = "Option::is_none")]
    pub script_opt: Option<String>,
}

impl UnsignedTransaction {
    /// Get the transaction ID
    pub fn id(&self) -> &str {
        &self.tx_id
    }

    /// Get the number of inputs
    pub fn input_count(&self) -> usize {
        self.inputs.len()
    }

    /// Get the number of outputs
    pub fn output_count(&self) -> usize {
        self.fixed_outputs.len()
    }

    /// Calculate total ALPH amount in outputs
    pub fn total_output_amount(&self) -> Result<u128> {
        let mut total = 0u128;
        for output in &self.fixed_outputs {
            let amount: u128 = output
                .atto_alph_amount
                .parse()
                .map_err(|e| Error::InvalidValue(format!("Invalid amount: {}", e)))?;
            total = total
                .checked_add(amount)
                .ok_or_else(|| Error::InvalidValue("Amount overflow".to_string()))?;
        }
        Ok(total)
    }
}

/// Signed transaction
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Transaction {
    pub unsigned: UnsignedTransaction,
    #[serde(rename = "scriptExecutionOk")]
    pub script_execution_ok: bool,
    #[serde(rename = "contractInputs")]
    pub contract_inputs: Vec<OutputRef>,
    #[serde(rename = "generatedOutputs")]
    pub generated_outputs: Vec<Output>,
    #[serde(rename = "inputSignatures")]
    pub input_signatures: Vec<String>,
    #[serde(rename = "scriptSignatures")]
    pub script_signatures: Vec<String>,
}

impl Transaction {
    /// Get the transaction ID
    pub fn id(&self) -> &str {
        self.unsigned.id()
    }

    /// Check if transaction execution was successful
    pub fn is_successful(&self) -> bool {
        self.script_execution_ok
    }

    /// Get total number of signatures
    pub fn signature_count(&self) -> usize {
        self.input_signatures.len() + self.script_signatures.len()
    }
}

/// Transaction builder for creating unsigned transactions
#[derive(Debug, Clone)]
pub struct TransactionBuilder {
    version: u8,
    network_id: u8,
    gas_amount: u32,
    gas_price: String,
    inputs: Vec<AssetInput>,
    outputs: Vec<AssetOutput>,
    script: Option<String>,
}

impl TransactionBuilder {
    /// Create a new transaction builder
    pub fn new(network_id: u8) -> Self {
        Self {
            version: 0,
            network_id,
            gas_amount: 20_000, // default gas
            gas_price: "100000000000".to_string(), // 100 Gwei
            inputs: Vec::new(),
            outputs: Vec::new(),
            script: None,
        }
    }

    /// Set the version
    pub fn version(mut self, version: u8) -> Self {
        self.version = version;
        self
    }

    /// Set gas amount
    pub fn gas_amount(mut self, gas_amount: u32) -> Self {
        self.gas_amount = gas_amount;
        self
    }

    /// Set gas price
    pub fn gas_price(mut self, gas_price: impl Into<String>) -> Self {
        self.gas_price = gas_price.into();
        self
    }

    /// Add an input
    pub fn add_input(mut self, input: AssetInput) -> Self {
        self.inputs.push(input);
        self
    }

    /// Add multiple inputs
    pub fn add_inputs(mut self, inputs: Vec<AssetInput>) -> Self {
        self.inputs.extend(inputs);
        self
    }

    /// Add an output
    pub fn add_output(mut self, output: AssetOutput) -> Self {
        self.outputs.push(output);
        self
    }

    /// Add multiple outputs
    pub fn add_outputs(mut self, outputs: Vec<AssetOutput>) -> Self {
        self.outputs.extend(outputs);
        self
    }

    /// Set script
    pub fn script(mut self, script: String) -> Self {
        self.script = Some(script);
        self
    }

    /// Build the unsigned transaction
    pub fn build(self) -> Result<UnsignedTransaction> {
        if self.inputs.is_empty() {
            return Err(Error::InvalidTransaction("No inputs provided".to_string()));
        }

        if self.outputs.is_empty() {
            return Err(Error::InvalidTransaction("No outputs provided".to_string()));
        }

        // Generate transaction ID (simplified - in real implementation this would hash the tx data)
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(format!("{:?}", self));
        let tx_id = hex::encode(hasher.finalize());

        Ok(UnsignedTransaction {
            tx_id,
            version: self.version,
            network_id: self.network_id,
            gas_amount: self.gas_amount,
            gas_price: self.gas_price,
            inputs: self.inputs,
            fixed_outputs: self.outputs,
            script_opt: self.script,
        })
    }
}

/// Transaction signer
pub struct TransactionSigner;

impl TransactionSigner {
    /// Sign an unsigned transaction with a private key
    pub fn sign(unsigned_tx: &UnsignedTransaction, private_key: &PrivateKey) -> Result<Transaction> {
        // Serialize the transaction for signing
        let tx_bytes = serde_json::to_vec(unsigned_tx)
            .map_err(|e| Error::SerializationError(e))?;

        // Sign the transaction
        let signature = private_key.sign(&tx_bytes)?;
        
        // Convert signature to hex string
        let signature_hex = hex::encode(signature.bytes());

        Ok(Transaction {
            unsigned: unsigned_tx.clone(),
            script_execution_ok: true,
            contract_inputs: Vec::new(),
            generated_outputs: Vec::new(),
            input_signatures: vec![signature_hex],
            script_signatures: Vec::new(),
        })
    }

    /// Sign with multiple private keys (for multi-sig)
    pub fn sign_with_keys(
        unsigned_tx: &UnsignedTransaction,
        private_keys: &[PrivateKey],
    ) -> Result<Transaction> {
        let tx_bytes = serde_json::to_vec(unsigned_tx)
            .map_err(|e| Error::SerializationError(e))?;

        let mut signatures = Vec::new();
        for private_key in private_keys {
            let signature = private_key.sign(&tx_bytes)?;
            signatures.push(hex::encode(signature.bytes()));
        }

        Ok(Transaction {
            unsigned: unsigned_tx.clone(),
            script_execution_ok: true,
            contract_inputs: Vec::new(),
            generated_outputs: Vec::new(),
            input_signatures: signatures,
            script_signatures: Vec::new(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::signer::KeyType;

    #[test]
    fn test_asset_output_builder() {
        let output = AssetOutput::new(
            "1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
            "1000000000000000000".to_string(),
        )
        .with_lock_time(1234567890)
        .with_message("test message".to_string());

        assert_eq!(output.lock_time, Some(1234567890));
        assert_eq!(output.message, Some("test message".to_string()));
    }

    #[test]
    fn test_transaction_builder() {
        let input = AssetInput {
            output_ref: OutputRef {
                hint: 0,
                tx_hash: "0".repeat(64),
            },
            unlock_script: "".to_string(),
        };

        let output = AssetOutput::new(
            "1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
            "1000000000000000000".to_string(),
        );

        let unsigned_tx = TransactionBuilder::new(0)
            .gas_amount(20000)
            .add_input(input)
            .add_output(output)
            .build()
            .unwrap();

        assert_eq!(unsigned_tx.network_id, 0);
        assert_eq!(unsigned_tx.gas_amount, 20000);
        assert_eq!(unsigned_tx.input_count(), 1);
        assert_eq!(unsigned_tx.output_count(), 1);
    }

    #[test]
    fn test_transaction_builder_no_inputs() {
        let output = AssetOutput::new(
            "1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
            "1000000000000000000".to_string(),
        );

        let result = TransactionBuilder::new(0).add_output(output).build();

        assert!(result.is_err());
    }

    #[test]
    fn test_transaction_signing() {
        let private_key = PrivateKey::generate(KeyType::Secp256k1).unwrap();

        let input = AssetInput {
            output_ref: OutputRef {
                hint: 0,
                tx_hash: "0".repeat(64),
            },
            unlock_script: "".to_string(),
        };

        let output = AssetOutput::new(
            "1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
            "1000000000000000000".to_string(),
        );

        let unsigned_tx = TransactionBuilder::new(0)
            .add_input(input)
            .add_output(output)
            .build()
            .unwrap();

        let signed_tx = TransactionSigner::sign(&unsigned_tx, &private_key).unwrap();

        assert_eq!(signed_tx.id(), unsigned_tx.id());
        assert_eq!(signed_tx.input_signatures.len(), 1);
        assert!(signed_tx.is_successful());
    }

    #[test]
    fn test_multi_sig_transaction() {
        let key1 = PrivateKey::generate(KeyType::Secp256k1).unwrap();
        let key2 = PrivateKey::generate(KeyType::Ed25519).unwrap();

        let input = AssetInput {
            output_ref: OutputRef {
                hint: 0,
                tx_hash: "0".repeat(64),
            },
            unlock_script: "".to_string(),
        };

        let output = AssetOutput::new(
            "1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
            "1000000000000000000".to_string(),
        );

        let unsigned_tx = TransactionBuilder::new(0)
            .add_input(input)
            .add_output(output)
            .build()
            .unwrap();

        let signed_tx = TransactionSigner::sign_with_keys(&unsigned_tx, &[key1, key2]).unwrap();

        assert_eq!(signed_tx.signature_count(), 2);
    }

    #[test]
    fn test_total_output_amount() {
        let input = AssetInput {
            output_ref: OutputRef {
                hint: 0,
                tx_hash: "0".repeat(64),
            },
            unlock_script: "".to_string(),
        };

        let output1 = AssetOutput::new("addr1".to_string(), "1000000000000000000".to_string());
        let output2 = AssetOutput::new("addr2".to_string(), "2000000000000000000".to_string());

        let unsigned_tx = TransactionBuilder::new(0)
            .add_input(input)
            .add_outputs(vec![output1, output2])
            .build()
            .unwrap();

        let total = unsigned_tx.total_output_amount().unwrap();
        assert_eq!(total, 3000000000000000000u128);
    }
}