Skip to content

Commit

Permalink
adding new CalculateFee method
Browse files Browse the repository at this point in the history
  • Loading branch information
Mark committed May 5, 2021
1 parent d2651db commit 4bb9384
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
13 changes: 13 additions & 0 deletions tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,19 @@ func (tx *Tx) ChangeToOutput(index uint, f []*Fee) error {
return nil
}

// CalculateFee will return the amount of fees the current transaction will
// require.
func (tx *Tx) CalculateFee(f []*Fee) (uint64, error) {
total := tx.GetTotalInputSatoshis() - tx.GetTotalOutputSatoshis()
sats, _, err := tx.change(nil, f, false)
if err != nil {
return 0, err
}
return total - sats, nil
}

// change will return the amount of satoshis to add to an input after fees are removed.
// True will be returned if change has been added.
func (tx *Tx) change(s *bscript.Script, f []*Fee, newOutput bool) (uint64, bool, error) {
inputAmount := tx.GetTotalInputSatoshis()
outputAmount := tx.GetTotalOutputSatoshis()
Expand Down
47 changes: 47 additions & 0 deletions tx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -851,3 +851,50 @@ func TestTx_ChangeToOutput(t *testing.T) {
})
}
}

func TestTx_CalculateChange(t *testing.T) {
tests := map[string]struct {
tx *bt.Tx
fees []*bt.Fee
expFees uint64
err error
}{
"Transaction with one input one output should return 96": {
tx: func() *bt.Tx {
tx := bt.NewTx()
assert.NoError(t, tx.From(
"07912972e42095fe58daaf09161c5a5da57be47c2054dc2aaa52b30fefa1940b",
0,
"76a914af2590a45ae401651fdbdf59a76ad43d1862534088ac",
1000))
assert.NoError(t, tx.PayTo("mxAoAyZFXX6LZBWhoam3vjm6xt9NxPQ15f", 500))
return tx
}(),
fees: bt.DefaultFees(),
expFees: 96,
}, "Transaction with one input 4 outputs should return 147": {
tx: func() *bt.Tx {
tx := bt.NewTx()
assert.NoError(t, tx.From(
"07912972e42095fe58daaf09161c5a5da57be47c2054dc2aaa52b30fefa1940b",
0,
"76a914af2590a45ae401651fdbdf59a76ad43d1862534088ac",
2500))
assert.NoError(t, tx.PayTo("mxAoAyZFXX6LZBWhoam3vjm6xt9NxPQ15f", 500))
assert.NoError(t, tx.PayTo("mxAoAyZFXX6LZBWhoam3vjm6xt9NxPQ15f", 500))
assert.NoError(t, tx.PayTo("mxAoAyZFXX6LZBWhoam3vjm6xt9NxPQ15f", 500))
assert.NoError(t, tx.PayTo("mxAoAyZFXX6LZBWhoam3vjm6xt9NxPQ15f", 500))
return tx
}(),
fees: bt.DefaultFees(),
expFees: 147,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
fee, err := test.tx.CalculateFee(test.fees)
assert.Equal(t, test.err, err)
assert.Equal(t, test.expFees, fee)
})
}
}

0 comments on commit 4bb9384

Please sign in to comment.