Skip to content

Commit

Permalink
feat: replace Lovelace with shopspring/decimal.Decimal
Browse files Browse the repository at this point in the history
Droping Lovelace makes math ops on values easier and strictly to follow
github.com/shopspring/decimal api.

BREAKING CHANGE: drop Lovelace data type

Signed-off-by: Marko Kungla <marko.kungla@gmail.com>
  • Loading branch information
mkungla committed Oct 3, 2022
1 parent d1bb64c commit 40bbe41
Show file tree
Hide file tree
Showing 13 changed files with 97 additions and 163 deletions.
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ import (
- [Usage](#usage)
- [Basic usage](#basic-usage)
- [Concurrency using goroutines](#concurrency-using-goroutines)
- [Lovelace (math on ada, assets and tokens).](#lovelace-math-on-ada-assets-and-tokens)
- [Lovelace / Coin (math on ada, assets and tokens).](#lovelace--coin-math-on-ada-assets-and-tokens)
- [Contributing](#contributing)
- [Code of Conduct](#code-of-conduct)
- [Got a Question or Problem?](#got-a-question-or-problem)
Expand Down Expand Up @@ -167,9 +167,10 @@ func main() {
}
```

## Lovelace (math on ada, assets and tokens).
## Lovelace / Coin (math on ada, assets and tokens).

Library uses for most cases to represent lovelace using [`Lovelace`](https://pkg.go.dev/github.com/cardano-community/koios-go-client#Lovelace) data type.
Library uses [`decimal.Decimal`](https://pkg.go.dev/badge/github.com/shopspring/decimal) data type to represent lovelace and coin values.
Which provides arbitrary-precision fixed-point decimal numbers in go.

**For decimal package API see**

Expand Down
40 changes: 21 additions & 19 deletions account.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,37 +18,39 @@ package koios

import (
"context"

"github.com/shopspring/decimal"
)

type (
// AccountInfo data returned by `/account_info`.
AccountInfo struct {
Status string `json:"status"`
DelegatedPool PoolID `json:"delegated_pool"`
TotalBalance Lovelace `json:"total_balance"`
UTxO Lovelace `json:"utxo"`
Rewards Lovelace `json:"rewards"`
Withdrawals Lovelace `json:"withdrawals"`
RewardsAvailable Lovelace `json:"rewards_available"`
Reserves Lovelace `json:"reserves"`
Treasury Lovelace `json:"treasury"`
Status string `json:"status"`
DelegatedPool PoolID `json:"delegated_pool"`
TotalBalance decimal.Decimal `json:"total_balance"`
UTxO decimal.Decimal `json:"utxo"`
Rewards decimal.Decimal `json:"rewards"`
Withdrawals decimal.Decimal `json:"withdrawals"`
RewardsAvailable decimal.Decimal `json:"rewards_available"`
Reserves decimal.Decimal `json:"reserves"`
Treasury decimal.Decimal `json:"treasury"`
}

// AccountRewards data returned by `/account_rewards`.
AccountRewards struct {
PoolID PoolID `json:"pool_id"`
EarnedEpoch EpochNo `json:"earned_epoch"`
SpendableEpoch EpochNo `json:"spendable_epoch"`
Amount Lovelace `json:"amount"`
Type string `json:"type"`
PoolID PoolID `json:"pool_id"`
EarnedEpoch EpochNo `json:"earned_epoch"`
SpendableEpoch EpochNo `json:"spendable_epoch"`
Amount decimal.Decimal `json:"amount"`
Type string `json:"type"`
}

// AccountHistoryEntry history entry list item.
AccountHistoryEntry struct {
StakeAddress StakeAddress `json:"stake_address"`
PoolID PoolID `json:"pool_id"`
Epoch EpochNo `json:"epoch_no"`
ActiveStake Lovelace `json:"active_stake"`
StakeAddress StakeAddress `json:"stake_address"`
PoolID PoolID `json:"pool_id"`
Epoch EpochNo `json:"epoch_no"`
ActiveStake decimal.Decimal `json:"active_stake"`
}

// AccountAsset asset list item when requesting account info.
Expand All @@ -60,7 +62,7 @@ type (
PolicyID PolicyID `json:"asset_policy"`

// Quantity of assets
Quantity Lovelace `json:"quantity"`
Quantity decimal.Decimal `json:"quantity"`
}

// AccountAction data entry for `/account_updates`.
Expand Down
6 changes: 3 additions & 3 deletions account_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,12 @@ func (s *accountTestSuite) TestAccountInfoEndpoint() {
)
if s.NoError(err) {
s.Equal("pool12fclephansjkz0qn339w7mu9jwef2ty439as08avaw7fuyk56j6", res.Data.DelegatedPool.String())
s.True(res.Data.Reserves.Decimal.Equal(koios.ZeroLovelace.Decimal))
s.True(res.Data.Reserves.Equal(koios.ZeroLovelace))
s.True(res.Data.Rewards.IsPositive())
s.True(res.Data.RewardsAvailable.IsPositive())
s.Equal("registered", res.Data.Status)
s.True(res.Data.TotalBalance.IsPositive())
s.True(res.Data.Treasury.Equal(koios.ZeroLovelace.Decimal))
s.True(res.Data.Treasury.Equal(koios.ZeroLovelace))
s.True(res.Data.UTxO.IsPositive())
s.True(res.Data.Withdrawals.IsPositive())
}
Expand Down Expand Up @@ -183,7 +183,7 @@ func (s *accountTestSuite) TestAccountAssetsEndpoint() {
if s.NoError(err) && s.Greater(len(res.Data), 0) {
s.Equal("DONTSPAM", res.Data[0].Name)
s.Equal("d3501d9531fcc25e3ca4b6429318c2cc374dbdbcf5e99c1c1e5da1ff", res.Data[0].PolicyID.String())
s.True(res.Data[0].Quantity.Decimal.Equal(decimal.New(9900000, 0)))
s.True(res.Data[0].Quantity.Equal(decimal.New(9900000, 0)))
}
}

Expand Down
6 changes: 4 additions & 2 deletions address.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"context"
"encoding/json"
"io"

"github.com/shopspring/decimal"
)

type (
Expand All @@ -38,7 +40,7 @@ type (
TxIndex uint32 `json:"tx_index"`

// Balance on the selected input transaction.
Value Lovelace `json:"value"`
Value decimal.Decimal `json:"value"`

// An array of assets contained on UTxO.
AssetList []Asset `json:"asset_list"`
Expand All @@ -47,7 +49,7 @@ type (
// AddressInfo esponse for `/address_info`.
AddressInfo struct {
// Balance ADA Lovelace balance of address
Balance Lovelace `json:"balance"`
Balance decimal.Decimal `json:"balance"`

// StakeAddress associated with address
StakeAddress StakeAddress `json:"stake_address,omitempty"`
Expand Down
14 changes: 8 additions & 6 deletions asset.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ package koios

import (
"context"

"github.com/shopspring/decimal"
)

// introduces breaking change since v1.3.0
Expand All @@ -35,7 +37,7 @@ type (
// Input: asset balance on the selected input transaction.
// Output: sum of assets for output UTxO.
// Mint: sum of minted assets (negative on burn).
Quantity Lovelace `json:"quantity"`
Quantity decimal.Decimal `json:"quantity"`
}

// TokenRegistryMetadata metadata registered on the Cardano Token Registry.
Expand Down Expand Up @@ -90,7 +92,7 @@ type (
PolicyID PolicyID `json:"policy_id,omitempty"`

// TotalSupply of Asset
TotalSupply Lovelace `json:"total_supply"`
TotalSupply decimal.Decimal `json:"total_supply"`

// CreationTime of Asset
CreationTime Time `json:"creation_time"`
Expand Down Expand Up @@ -134,8 +136,8 @@ type (

// AssetHolder payment addresses holding the given token (including balance).
AssetHolder struct {
PaymentAddress Address `json:"payment_address"`
Quantity Lovelace `json:"quantity"`
PaymentAddress Address `json:"payment_address"`
Quantity decimal.Decimal `json:"quantity"`
}

// AssetAddressListResponse represents response from `/asset_address_list` endpoint.
Expand Down Expand Up @@ -176,8 +178,8 @@ type (

// AssetMintTX holds specific mint tx hash and amount.
AssetMintTX struct {
TxHash TxHash `json:"tx_hash"`
Quantity Lovelace `json:"quantity"`
TxHash TxHash `json:"tx_hash"`
Quantity decimal.Decimal `json:"quantity"`
}

// AssetHistory holds given asset mint/burn tx's.
Expand Down
20 changes: 10 additions & 10 deletions epoch.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ type (
// EpochInfo defines model for epoch_info.
EpochInfo struct {
// Rewards accumulated as of given epoch (in lovelaces)
ActiveStake Lovelace `json:"active_stake"`
ActiveStake decimal.Decimal `json:"active_stake"`

// Number of blocks created in epoch
BlkCount int64 `json:"blk_count"`
Expand All @@ -38,7 +38,7 @@ type (
Epoch EpochNo `json:"epoch_no"`

// Total fees incurred by transactions in epoch
Fees Lovelace `json:"fees"`
Fees decimal.Decimal `json:"fees"`

// Timestamp for first block created in epoch
FirstBlockTime Time `json:"first_block_time"`
Expand All @@ -47,7 +47,7 @@ type (
LastBlockTime Time `json:"last_block_time"`

// Total output value across all transactions in epoch
OutSum Lovelace `json:"out_sum"`
OutSum decimal.Decimal `json:"out_sum"`

// Number of transactions submitted in epoch
TxCount int64 `json:"tx_count"`
Expand All @@ -71,7 +71,7 @@ type (
BlockHash BlockHash `json:"block_hash"`

// The cost per UTxO word
CoinsPerUtxoSize Lovelace `json:"coins_per_utxo_size"`
CoinsPerUtxoWord decimal.Decimal `json:"coins_per_utxo_word"`

// The percentage of the tx fee which must be provided as collateral
// when including non-native scripts
Expand All @@ -94,7 +94,7 @@ type (
Influence float64 `json:"influence"`

// The amount (in lovelace) required for a deposit to register a stake address
KeyDeposit Lovelace `json:"key_deposit"`
KeyDeposit decimal.Decimal `json:"key_deposit"`

// The maximum block header size (in bytes)
MaxBhSize int `json:"max_bh_size"`
Expand Down Expand Up @@ -134,10 +134,10 @@ type (
MinFeeB decimal.Decimal `json:"min_fee_b"`

// The minimum pool cost
MinPoolCost Lovelace `json:"min_pool_cost"`
MinPoolCost decimal.Decimal `json:"min_pool_cost"`

// The minimum value of a UTxO entry
MinUtxoValue Lovelace `json:"min_utxo_value"`
MinUtxoValue decimal.Decimal `json:"min_utxo_value"`

// The monetary expansion rate
MonetaryExpandRate float64 `json:"monetary_expand_rate"`
Expand All @@ -149,13 +149,13 @@ type (
OptimalPoolCount int `json:"optimal_pool_count"`

// The amount (in lovelace) required for a deposit to register a stake pool
PoolDeposit Lovelace `json:"pool_deposit"`
PoolDeposit decimal.Decimal `json:"pool_deposit"`

// The per word cost of script memory usage
PriceMem Lovelace `json:"price_mem"`
PriceMem decimal.Decimal `json:"price_mem"`

// The cost of script execution step usage
PriceStep Lovelace `json:"price_step"`
PriceStep decimal.Decimal `json:"price_step"`

// The protocol major version
ProtocolMajor int `json:"protocol_major"`
Expand Down
16 changes: 4 additions & 12 deletions koios.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,10 @@ var (
ErrUnexpectedResponseField = errors.New("unexpected response field")
ErrUTxOInputAlreadyUsed = errors.New("UTxO already used")

ZeroLovelace = NewLovelace(0, 1) //nolint: gochecknoglobals
// ZeroLovelace is alias decimal.Zero
ZeroLovelace = decimal.Zero.Copy() //1nolint: gochecknoglobals
// ZeroCoin is alias decimal.Zero
ZeroCoin = decimal.Zero.Copy() //nolint: gochecknoglobals
)

// introduces breaking change since v1.3.0
Expand Down Expand Up @@ -109,17 +112,6 @@ type (
time.Time
}

// Lovelace defines type for ADA lovelaces. This library uses forked snapshot
// of github.com/shopspring/decimal package to provide. JSON and XML
// serialization/deserialization and make it ease to work with calculations
// and deciimal precisions of ADA lovelace and native assets.
//
// For API of decimal package see
// https://pkg.go.dev/github.com/shopspring/decimal
Lovelace struct {
decimal.Decimal
}

// PaymentAddr info.
PaymentAddr struct {
// Bech32 is Cardano payment/base address (bech32 encoded)
Expand Down
71 changes: 0 additions & 71 deletions lovelace.go

This file was deleted.

Loading

0 comments on commit 40bbe41

Please sign in to comment.