github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/session/pingpong/price_calculator.go (about)

     1  /*
     2   * Copyright (C) 2020 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package pingpong
    19  
    20  import (
    21  	"math/big"
    22  	"time"
    23  
    24  	"github.com/rs/zerolog/log"
    25  
    26  	"github.com/mysteriumnetwork/node/datasize"
    27  	"github.com/mysteriumnetwork/node/market"
    28  )
    29  
    30  // CalculatePaymentAmount calculates the required payment amount.
    31  func CalculatePaymentAmount(timePassed time.Duration, bytesTransferred DataTransferred, price market.Price) *big.Int {
    32  	if price.PricePerGiB.Cmp(big.NewInt(0)) == 0 && price.PricePerHour.Cmp(big.NewInt(0)) == 0 {
    33  		return big.NewInt(0)
    34  	}
    35  
    36  	timeComponent := big.NewFloat(0)
    37  	if price.PricePerHour.Cmp(big.NewInt(0)) > 0 {
    38  		timeQuote := timePassed.Seconds() / time.Hour.Seconds()
    39  		timeComponent = new(big.Float).Mul(new(big.Float).SetInt(price.PricePerHour), big.NewFloat(timeQuote))
    40  	}
    41  
    42  	dataComponent := big.NewFloat(0)
    43  	if price.PricePerGiB.Cmp(big.NewInt(0)) > 0 {
    44  		dataQuote := float64(bytesTransferred.sum()) / float64(datasize.GiB.Bytes())
    45  		dataComponent = new(big.Float).Mul(new(big.Float).SetInt(price.PricePerGiB), big.NewFloat(dataQuote))
    46  	}
    47  
    48  	tc, _ := timeComponent.Int(nil)
    49  	bc, _ := dataComponent.Int(nil)
    50  
    51  	total := new(big.Int).Add(tc, bc)
    52  	log.Debug().Msgf("Calculated price %v. Time component: %v, data component: %v. Transferred: %v, duration: %v. Price %v",
    53  		total, timeComponent, dataComponent, bytesTransferred.sum(), timePassed.Seconds(), price.String())
    54  	return total
    55  }