utils

package module
v0.0.0-...-1945114 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 6, 2025 License: MIT Imports: 9 Imported by: 2

README

Massa Units Conversion

This package provides utilities for converting between Massa and nanoMassa units in the Massa blockchain.

Overview

In the Massa blockchain:

  • 1 Massa = 1,000,000,000 nanoMassa (10^9)
  • nanoMassa is the smallest unit used in blockchain operations
  • Massa is the human-readable denomination

This package uses Go's math/big package for arbitrary precision arithmetic to ensure no loss of precision when working with large amounts.

Installation

import "github.com/nafsilabs/massa-go/utils"

Core Functions

FromMAS

Convert Massa (float64) to nanoMassa (big.Int):

amount := utils.FromMAS(1.5)
// Returns: 1500000000 nanoMassa
ToMAS

Convert nanoMassa (big.Int) to Massa (float64):

nanoMassa := big.NewInt(2_500_000_000)
massa := utils.ToMAS(nanoMassa)
// Returns: 2.5 Massa
FromNanoMAS

Convert nanoMassa (uint64) to big.Int:

amount := utils.FromNanoMAS(1_000_000_000)
// Returns: big.Int representing 1000000000
ToNanoMAS

Convert big.Int to nanoMassa (uint64):

bigInt := big.NewInt(500_000_000)
nano := utils.ToNanoMAS(bigInt)
// Returns: 500000000 (uint64)
ParseMassa

Parse Massa amount (float64) directly to uint64 nanoMassa:

nano := utils.ParseMassa(3.75)
// Returns: 3750000000 (uint64)

Usage Examples

Basic Conversion
package main

import (
    "fmt"
    "github.com/nafsilabs/massa-go/utils"
)

func main() {
    // Convert 1.5 Massa to nanoMassa
    nanoMassa := utils.FromMAS(1.5)
    fmt.Printf("1.5 Massa = %s nanoMassa\n", nanoMassa.String())
    
    // Convert back to Massa
    massa := utils.ToMAS(nanoMassa)
    fmt.Printf("%s nanoMassa = %f Massa\n", nanoMassa.String(), massa)
}
Transaction Calculation
package main

import (
    "fmt"
    "math/big"
    "github.com/nafsilabs/massa-go/utils"
)

func main() {
    // Sender has 100 Massa
    balance := utils.FromMAS(100.0)
    
    // Transfer 25.5 Massa
    transfer := utils.FromMAS(25.5)
    
    // Fee is 0.01 Massa
    fee := utils.FromMAS(0.01)
    
    // Calculate remaining balance
    remaining := new(big.Int).Sub(balance, transfer)
    remaining.Sub(remaining, fee)
    
    fmt.Printf("Remaining balance: %.2f Massa\n", utils.ToMAS(remaining))
    // Output: Remaining balance: 74.49 Massa
}
Working with Protocol Operations
package main

import (
    "github.com/nafsilabs/massa-go/client"
    "github.com/nafsilabs/massa-go/utils"
)

func main() {
    // Create transaction with 10 Massa
    amount := utils.FromMAS(10.0)
    
    // Convert to uint64 for protocol operations
    amountNano := utils.ToNanoMAS(amount)
    
    // Use in transaction
    tx := client.NewTransactionOp(
        "recipient_address",
        amountNano,
        0, // expiry period
    )
}

Constants

const (
    DecimalScale      = 9                      // 9 decimal places
    NanoMassaPerMassa = 1_000_000_000         // 10^9 nanoMassa per Massa
)

Precision Considerations

  • FromMAS/ToMAS: Use for user-facing amounts, handles floating point with appropriate precision
  • FromNanoMAS/ToNanoMAS: Use for protocol operations, provides uint64 ↔ big.Int conversion
  • ParseMassa: Convenience function for quick conversions to uint64
Floating Point Precision

Due to floating point limitations, very small amounts may experience rounding:

// 1 nanoMassa
small := utils.FromMAS(0.000000001)
fmt.Println(small.String()) // "1"

// Round trip maintains precision for reasonable amounts
original := 10.123456789
converted := utils.FromMAS(original)
back := utils.ToMAS(converted)
// back == 10.123456789 (within floating point precision)

Testing

Run the test suite:

cd utils
go test -v

See the example:

cd examples/massa_units
go run main.go

Comparison with Other Languages

Dart Implementation

This Go implementation mirrors the Dart massa_units.dart package:

  • fromMASFromMAS
  • toMASToMAS
  • Uses big.Int instead of Dart's BigInt
  • Same conversion factor: 10^9
JavaScript/TypeScript

For JavaScript/TypeScript implementations, consider using:

  • BigInt for integer arithmetic
  • Libraries like bignumber.js or decimal.js for decimal precision

Best Practices

  1. Always use big.Int for calculations: Prevents overflow and maintains precision
  2. Convert to float64 only for display: Use ToMAS() when showing amounts to users
  3. Use uint64 for protocol operations: Most blockchain operations expect uint64
  4. Validate user input: Always check that user-provided amounts are valid before conversion

Common Patterns

Validating Sufficient Balance
balance := utils.FromMAS(100.0)
required := utils.FromMAS(150.0)

if balance.Cmp(required) < 0 {
    return errors.New("insufficient balance")
}
Calculating Total with Fee
amount := utils.FromMAS(10.0)
fee := utils.FromMAS(0.01)

total := new(big.Int).Add(amount, fee)
fmt.Printf("Total: %.2f Massa\n", utils.ToMAS(total))
Splitting Amounts
total := utils.FromMAS(100.0)
parts := 3

perPart := new(big.Int).Div(total, big.NewInt(int64(parts)))
fmt.Printf("Each part: %.2f Massa\n", utils.ToMAS(perPart))

See Also

Documentation

Index

Constants

View Source
const (
	BytesPerUint64 = 8
	BytesPerUint32 = 4
)
View Source
const (
	// DecimalScale is the number of decimal places in Massa (9 for nanoMassa)
	DecimalScale = 9

	// DecimalFactor represents the maximum scale factor
	DecimalFactor = math.MaxFloat64

	// NanoMassaPerMassa is the number of nanoMassa in 1 Massa (10^9)
	NanoMassaPerMassa = 1_000_000_000
)

Constants for Massa unit conversions

View Source
const MasDecimals = 9

Variables

This section is empty.

Functions

func BytesToI32

func BytesToI32(byteArray []byte) (int32, error)

func BytesToU64

func BytesToU64(byteArray []byte) (uint64, error)

func BytesToU256

func BytesToU256(bytes []byte) (*big.Int, error)

BytesToU256 decodes the given bytes, representing a 256-bit unsigned integer in big-endian format, into a big.Int. It constructs a new big.Int with the bytes interpreted in little-endian order. The function returns the resulting big.Int representing the 256-bit integer.

func DecodeBase64

func DecodeBase64(encoded string) ([]byte, error)

Helper method to decode base64 to bytes

func DoubleToMassaInt

func DoubleToMassaInt(amount float64) *big.Int

DoubleToMassaInt converts a float64 Massa amount to nanoMassa as *big.Int This multiplies the amount by 10^9 to convert from Massa to nanoMassa

func EncodeBase64

func EncodeBase64(data []byte) string

Helper method to encode bytes to base64

func FormatMassa

func FormatMassa(amount float64, decimals int) string

FormatMassa formats a Massa amount (float64) as a string with specified decimal places

func FromMAS

func FromMAS(amount float64) *big.Int

FromMAS converts Massa (as float64) to nanoMassa (as *big.Int) Example: FromMAS(1.5) returns 1500000000 nanoMassa

func FromNanoMAS

func FromNanoMAS(nanoMassa uint64) *big.Int

FromNanoMAS converts nanoMassa (as uint64) to *big.Int This is useful when working with uint64 amounts

func I32ToBytes

func I32ToBytes(nb int) (bytes []byte)

Encode int32 to byte array.

func MassaIntToDouble

func MassaIntToDouble(amount *big.Int) float64

MassaIntToDouble converts nanoMassa (*big.Int) to Massa as float64 This is an alias for ToMAS for consistency with naming conventions

func NanoToMas

func NanoToMas(nanoMasAmount uint64) (string, error)

func ParseMassa

func ParseMassa(amount float64) uint64

ParseMassa parses a float64 amount and returns nanoMassa as uint64

func ReverseBytes

func ReverseBytes(bytes []byte) []byte

ReverseBytes creates and returns a new byte slice with reversed order.

func StringArrayToArrayOfByteArray

func StringArrayToArrayOfByteArray(stringArray []string) [][]byte

this function encodes a string array to an array of byte arrays.

func ToBytes

func ToBytes(str string) []byte

func ToBytesWithPrefixLength

func ToBytesWithPrefixLength(str string) []byte

func ToMAS

func ToMAS(amount *big.Int) float64

ToMAS converts nanoMassa (as *big.Int) to Massa (as float64) Example: ToMAS(1500000000) returns 1.5 Massa

func ToNanoMAS

func ToNanoMAS(amount *big.Int) uint64

ToNanoMAS converts *big.Int to nanoMassa (as uint64) Returns 0 if amount is nil or exceeds uint64 range

func ToString

func ToString(entry []byte) string

func ToStringArray

func ToStringArray(entry []byte) []string

func U32ToBytes

func U32ToBytes(nb int) (bytes []byte)

Encode uint32 to byte array.

func U64ToBytes

func U64ToBytes(nb uint64) (bytes []byte)

Encode uint64 to byte array.

Types

type NetworkType

type NetworkType int64
const (
	MAINNET   NetworkType = 77658377
	BUILDNET  NetworkType = 77658366
	SECURENET NetworkType = 77658383
	LABNET    NetworkType = 77658376
	SANDBOX   NetworkType = 77
)

func (NetworkType) Serialize

func (nt NetworkType) Serialize() []byte

Serialize serializes the NetworkType into an 8-byte big-endian byte slice.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL