Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(x/ecocredit): Retire ORM #826

Merged
merged 9 commits into from
Mar 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions x/ecocredit/server/core/retire.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package core

import (
"context"
sdk "github.com/cosmos/cosmos-sdk/types"
ecocreditv1 "github.com/regen-network/regen-ledger/api/regen/ecocredit/v1"
"github.com/regen-network/regen-ledger/types"
"github.com/regen-network/regen-ledger/types/math"
v1 "github.com/regen-network/regen-ledger/x/ecocredit/v1"
)

// Retire credits to the specified location.
// WARNING: retiring credits is permanent. Retired credits cannot be un-retired.
func (k Keeper) Retire(ctx context.Context, req *v1.MsgRetire) (*v1.MsgRetireResponse, error) {
sdkCtx := types.UnwrapSDKContext(ctx)
holder, _ := sdk.AccAddressFromBech32(req.Holder)

for _, credit := range req.Credits {
batch, err := k.stateStore.BatchInfoStore().GetByBatchDenom(ctx, credit.BatchDenom)
if err != nil {
return nil, err
}
creditType, err := k.getCreditTypeFromBatchDenom(ctx, batch.BatchDenom)
if err != nil {
return nil, err
}
userBalance, err := k.stateStore.BatchBalanceStore().Get(ctx, holder, batch.Id)
if err != nil {
return nil, err
}

decs, err := getNonNegativeFixedDecs(creditType.Precision, credit.Amount, userBalance.Tradable)
if err != nil {
return nil, err
}
amtToRetire, userTradableBalance := decs[0], decs[1]

userTradableBalance, err = math.SafeSubBalance(userTradableBalance, amtToRetire)
if err != nil {
return nil, err
}
userRetiredBalance, err := math.NewNonNegativeFixedDecFromString(userBalance.Retired, creditType.Precision)
if err != nil {
return nil, err
}
userRetiredBalance, err = userRetiredBalance.Add(amtToRetire)
if err != nil {
return nil, err
}
batchSupply, err := k.stateStore.BatchSupplyStore().Get(ctx, batch.Id)
if err != nil {
return nil, err
}
decs, err = getNonNegativeFixedDecs(creditType.Precision, batchSupply.RetiredAmount, batchSupply.TradableAmount)
if err != nil {
return nil, err
}
supplyRetired, supplyTradable := decs[0], decs[1]
supplyRetired, err = supplyRetired.Add(amtToRetire)
if err != nil {
return nil, err
}
supplyTradable, err = math.SafeSubBalance(supplyTradable, amtToRetire)
if err != nil {
return nil, err
}

if err = k.stateStore.BatchBalanceStore().Update(ctx, &ecocreditv1.BatchBalance{
Address: holder,
BatchId: batch.Id,
Tradable: userTradableBalance.String(),
Retired: userRetiredBalance.String(),
}); err != nil {
return nil, err
}
err = k.stateStore.BatchSupplyStore().Update(ctx, &ecocreditv1.BatchSupply{
BatchId: batch.Id,
TradableAmount: supplyTradable.String(),
RetiredAmount: supplyRetired.String(),
CancelledAmount: batchSupply.CancelledAmount,
})
if err = sdkCtx.EventManager().EmitTypedEvent(&v1.EventRetire{
Retirer: req.Holder,
BatchDenom: credit.BatchDenom,
Amount: credit.Amount,
Location: req.Location,
}); err != nil {
return nil, err
}
sdkCtx.GasMeter().ConsumeGas(gasCostPerIteration, "retire ecocredits")
}
return &v1.MsgRetireResponse{}, nil
}
91 changes: 91 additions & 0 deletions x/ecocredit/server/core/retire_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package core

import (
"github.com/cosmos/cosmos-sdk/orm/types/ormerrors"
"github.com/cosmos/cosmos-sdk/types/errors"
"github.com/golang/mock/gomock"
"github.com/regen-network/regen-ledger/x/ecocredit"
v1 "github.com/regen-network/regen-ledger/x/ecocredit/v1"
"gotest.tools/v3/assert"
"testing"
)

func TestRetire_Valid(t *testing.T) {
t.Parallel()
s := setupBase(t)
s.setupClassProjectBatch(t)

// starting balance
// tradable: 10.5
// retired: 10.5

any := gomock.Any()
s.paramsKeeper.EXPECT().GetParamSet(any, any).Do(func(_ interface{}, p *ecocredit.Params) {
p.CreditTypes = []*ecocredit.CreditType{{Name: "carbon", Abbreviation: "C", Unit: "tonne", Precision: 6}}
}).Times(1)

// starting balance -> 10.5 tradable, 10.5 retired
// retire 10.0 -> 0.5 leftover in tradable, retired becomes 20.5

_, err := s.k.Retire(s.ctx, &v1.MsgRetire{
Holder: s.addr.String(),
Credits: []*v1.MsgRetire_RetireCredits{
{BatchDenom: "C01-20200101-20210101-01", Amount: "10.0"},
},
Location: "US-NY",
})
assert.NilError(t, err)

// check both balance and supply reflect the change

bal, err := s.stateStore.BatchBalanceStore().Get(s.ctx, s.addr, 1)
assert.NilError(t, err)
assert.Equal(t, bal.Tradable, "0.5")
assert.Equal(t, bal.Retired, "20.5")

sup, err := s.stateStore.BatchSupplyStore().Get(s.ctx, 1)
assert.NilError(t, err)
assert.Equal(t, sup.TradableAmount, "0.5")
assert.Equal(t, sup.RetiredAmount, "20.5")
technicallyty marked this conversation as resolved.
Show resolved Hide resolved
}

func TestRetire_Invalid(t *testing.T) {
t.Parallel()
s := setupBase(t)
_, _, batchDenom := s.setupClassProjectBatch(t)

// invalid batch denom
_, err := s.k.Retire(s.ctx, &v1.MsgRetire{
Holder: s.addr.String(),
Credits: []*v1.MsgRetire_RetireCredits{
{BatchDenom: "A00-00000000-00000000-01", Amount: "10.35"},
},
Location: "US-NY",
})
assert.ErrorContains(t, err, ormerrors.NotFound.Error())

any := gomock.Any()
s.paramsKeeper.EXPECT().GetParamSet(any, any).Do(func(_ interface{}, p *ecocredit.Params) {
p.CreditTypes = []*ecocredit.CreditType{{Name: "carbon", Abbreviation: "C", Unit: "tonne", Precision: 6}}
}).Times(2)

// out of precision
_, err = s.k.Retire(s.ctx, &v1.MsgRetire{
Holder: s.addr.String(),
Credits: []*v1.MsgRetire_RetireCredits{
{BatchDenom: batchDenom, Amount: "10.35250982359823095"},
},
Location: "US-NY",
})
assert.ErrorContains(t, err,"exceeds maximum decimal places")

// not enough credits
_, err = s.k.Retire(s.ctx, &v1.MsgRetire{
Holder: s.addr.String(),
Credits: []*v1.MsgRetire_RetireCredits{
{BatchDenom: batchDenom, Amount: "150"},
},
Location: "US-NY",
})
assert.ErrorContains(t, err,errors.ErrInsufficientFunds.Error())
}
25 changes: 13 additions & 12 deletions x/ecocredit/server/core/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ func (k Keeper) getCreditType(ctAbbrev string, creditTypes []*ecocredit.CreditTy
return ecocredit.CreditType{}, sdkerrors.ErrInvalidType.Wrapf("%s is not a valid credit type", ctAbbrev)
}

// getCreditTypeFromBatchDenom extracts the classId from a batch denom string, then retrieves it from the params.
func (k Keeper) getCreditTypeFromBatchDenom(ctx context.Context, denom string) (ecocredit.CreditType, error) {
sdkCtx := sdk.UnwrapSDKContext(ctx)
classId := ecocredit.GetClassIdFromBatchDenom(denom)
classInfo, err := k.stateStore.ClassInfoStore().GetByName(ctx, classId)
if err != nil {
return ecocredit.CreditType{}, err
}
p := &ecocredit.Params{}
k.params.GetParamSet(sdkCtx, p)
return k.getCreditType(classInfo.CreditType, p.CreditTypes)
}

// getNonNegativeFixedDecs takes an arbitrary amount of decimal strings, and returns their corresponding fixed decimals
// in a slice.
func getNonNegativeFixedDecs(precision uint32, decimals ...string) ([]math.Dec, error) {
Expand All @@ -48,15 +61,3 @@ func getNonNegativeFixedDecs(precision uint32, decimals ...string) ([]math.Dec,
}
return decs, nil
}

func (k Keeper) getCreditTypeFromBatchDenom(ctx context.Context, denom string) (ecocredit.CreditType, error) {
sdkCtx := sdk.UnwrapSDKContext(ctx)
classId := ecocredit.GetClassIdFromBatchDenom(denom)
classInfo, err := k.stateStore.ClassInfoStore().GetByName(ctx, classId)
if err != nil {
return ecocredit.CreditType{}, err
}
p := &ecocredit.Params{}
k.params.GetParamSet(sdkCtx, p)
return k.getCreditType(classInfo.CreditType, p.CreditTypes)
}