17 units decimals

Overview

ERC-1155 uses integer balances, but carbon credits need decimal precision (e.g., 0.25 tons, 12,437.62 tons). This document explains how to handle decimals using fixed-point units.

The Challenge

ERC-1155 Limitation:

  • Balances are uint256 (integers only)

  • No native decimal support

Carbon Credit Requirements:

  • Retail: 0.01, 0.25, 1.0 tons

  • Enterprise: 12,437.62 tons (exact decimals)

  • No rounding losses

Solution: Fixed-Point Units

Concept

Define a UNIT constant that represents 1 ton CO₂. All on-chain values are stored as multiples of UNIT.

Definition:

Conversion:


UNIT Selection

Precision: 6 decimal places (0.000001 tons)

Advantages:

  • ✅ Sufficient precision for carbon credits

  • ✅ Lower gas costs (smaller numbers)

  • ✅ Easier to read in explorers

  • ✅ Standard for many DeFi protocols

Example:


Option 2: UNIT = 1e18 (Maximum Precision)

Precision: 18 decimal places (0.000000000000000001 tons)

Advantages:

  • ✅ Maximum precision

  • ✅ Compatible with ERC-20 standard (wei-like)

  • ✅ Future-proof for any precision needs

Disadvantages:

  • ❌ Higher gas costs

  • ❌ Harder to read in explorers

  • ❌ Overkill for carbon credits

Example:

Recommendation: Use UNIT = 1e6 for carbon credits (sufficient precision, better gas efficiency).


Implementation

Contract Definition


Conversion Functions

To On-Chain (Tons → Units)

JavaScript/TypeScript:

Note: Handle decimal input carefully. For exact decimals:


From On-Chain (Units → Tons)

JavaScript/TypeScript:


UI Display

Display Balance:

Input to On-Chain:


Example: Complete Flow

Project Setup

Credit Issuance

Retail Purchase

Enterprise Purchase

Retirement


Precision Considerations

Rounding

Always Round Down (for safety):

Display Rounding:

Maximum Values

With UNIT = 1e6:

  • Maximum tons: 2^256 / 1e6 ≈ 1.15e71 tons (practically unlimited)

  • Minimum precision: 0.000001 tons

With UNIT = 1e18:

  • Maximum tons: 2^256 / 1e18 ≈ 1.15e59 tons (practically unlimited)

  • Minimum precision: 0.000000000000000001 tons


Common Patterns

Check Balance

UI Display:

Validate Purchase Amount

Calculate Total Price


Best Practices

1

Consistent UNIT Usage

  • Define UNIT as a constant

  • Use UNIT in all conversions

  • Document UNIT value clearly

2

Input Validation

  • Validate user input before conversion

  • Check for overflow

  • Handle decimal precision correctly

3

Display Formatting

  • Always convert units to tons for display

  • Use appropriate decimal places (2-6 for carbon credits)

  • Show units in tooltips (optional)

4

Error Handling

  • Handle conversion errors gracefully

  • Validate amounts before on-chain calls

  • Provide clear error messages

Last updated