MCPcopy
hub / github.com/Savjee/SavjeeCoin / addTransaction

Method addTransaction

src/blockchain.js:201–244  ·  view source on GitHub ↗

* Add a new transaction to the list of pending transactions (to be added * next time the mining process starts). This verifies that the given * transaction is properly signed. * * @param {Transaction} transaction

(transaction)

Source from the content-addressed store, hash-verified

199 * @param {Transaction} transaction
200 */
201 addTransaction(transaction) {
202 if (!transaction.fromAddress || !transaction.toAddress) {
203 throw new Error('Transaction must include from and to address');
204 }
205
206 // Verify the transactiion
207 if (!transaction.isValid()) {
208 throw new Error('Cannot add invalid transaction to chain');
209 }
210
211 if (transaction.amount <= 0) {
212 throw new Error('Transaction amount should be higher than 0');
213 }
214
215 // Making sure that the amount sent is not greater than existing balance
216 const walletBalance = this.getBalanceOfAddress(transaction.fromAddress);
217 if (walletBalance < transaction.amount) {
218 throw new Error('Not enough balance');
219 }
220
221 // Get all other pending transactions for the "from" wallet
222 const pendingTxForWallet = this.pendingTransactions.filter(
223 tx => tx.fromAddress === transaction.fromAddress
224 );
225
226 // If the wallet has more pending transactions, calculate the total amount
227 // of spend coins so far. If this exceeds the balance, we refuse to add this
228 // transaction.
229 if (pendingTxForWallet.length > 0) {
230 const totalPendingAmount = pendingTxForWallet
231 .map(tx => tx.amount)
232 .reduce((prev, curr) => prev + curr);
233
234 const totalAmount = totalPendingAmount + transaction.amount;
235 if (totalAmount > walletBalance) {
236 throw new Error(
237 'Pending transactions for this wallet is higher than its balance.'
238 );
239 }
240 }
241
242 this.pendingTransactions.push(transaction);
243 debug('transaction added: %s', transaction);
244 }
245
246 /**
247 * Returns the balance of a given wallet address.

Callers 3

createBlockchainWithTxFunction · 0.95
main.jsFile · 0.80
blockchain.test.jsFile · 0.80

Calls 2

getBalanceOfAddressMethod · 0.95
isValidMethod · 0.80

Tested by

no test coverage detected