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
use account::Account; use memo::Memo; use operation::Operation; use transaction::{Transaction, Fee}; use time_bounds::{TimeBounds, UnixTimestamp}; use error::Result; const BASE_FEE: u32 = 100; pub struct TransactionBuilder<'a> { source: &'a mut Account, base_fee: Fee, memo: Memo, lower_time_bound: Option<UnixTimestamp>, upper_time_bound: Option<UnixTimestamp>, operations: Vec<Operation>, } impl<'a> TransactionBuilder<'a> { pub fn new(source: &'a mut Account) -> TransactionBuilder<'a> { TransactionBuilder { source: source, base_fee: BASE_FEE, memo: Memo::None, lower_time_bound: None, upper_time_bound: None, operations: Vec::new(), } } pub fn add_operation(mut self, op: Operation) -> TransactionBuilder<'a> { self.operations.push(op); self } pub fn with_memo(mut self, memo: Memo) -> TransactionBuilder<'a> { self.memo = memo; self } pub fn with_fee(mut self, fee: Fee) -> TransactionBuilder<'a> { self.base_fee = fee; self } pub fn with_lower_time_bound(mut self, t: UnixTimestamp) -> TransactionBuilder<'a> { self.lower_time_bound = Some(t); self } pub fn with_upper_time_bound(mut self, t: UnixTimestamp) -> TransactionBuilder<'a> { self.upper_time_bound = Some(t); self } pub fn build(self) -> Result<Transaction> { let seqnum = self.source.seqnum() + 1; let time_bounds = match (self.lower_time_bound, self.upper_time_bound) { (None, None) => None, (l, u) => Some(TimeBounds::new(l, u)), }; let public_key = self.source.public_key().clone(); let fee = self.base_fee * (self.operations.len() as u32); let tx = Transaction::new(public_key, fee, self.memo, seqnum, time_bounds, self.operations); self.source.inc_seqnum(); Ok(tx) } } #[cfg(test)] mod tests { use TransactionBuilder; use account::Account; #[test] fn increment_account_seqnum_on_build() { let mut account = Account::from_account_id("GBBM6BKZPEHWYO3E3YKREDPQXMS4VK35YLNU7NFBRI26RAN7GI5POFBB", 100) .unwrap(); let _tx = TransactionBuilder::new(&mut account).build(); assert_eq!(account.seqnum(), 101); } }