Skip to content

Support additional fees for payment requests #53

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

Merged
merged 20 commits into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
1fd44da
Update request stores to include fee metadata
jeffyanta Feb 7, 2024
fbf221a
Add basis points to payment request fee model
jeffyanta Feb 9, 2024
dc97b34
Ensure consistent fee ordering from DB store
jeffyanta Feb 12, 2024
98f411d
Pull in v1.10.0 protobuf APIs
jeffyanta Feb 12, 2024
8fb7e2a
Support additional fee takers in SubmitIntent
jeffyanta Feb 12, 2024
ddc1d22
Add edge case tests for SubmitIntent when using additional fee takers
jeffyanta Feb 12, 2024
5752c59
Ensure additional third party fees are subtracted from RECEIVED chat …
jeffyanta Feb 12, 2024
beefc58
Support additional fee takers in messaging service
jeffyanta Feb 12, 2024
c4fd23f
Add happy path tests for additional fees in messaging service
jeffyanta Feb 13, 2024
011fd01
Add edge case tests for additional fees in messaging service
jeffyanta Feb 13, 2024
ab99a02
Improve error messaging to distinguish between fee taker and payment …
jeffyanta Feb 13, 2024
e1421c8
Update merchant chats to consider fees to Code accounts
jeffyanta Feb 13, 2024
b41e144
Be more strict about wasteful fees
jeffyanta Feb 13, 2024
ed87d4e
Max fee basis points is now configurable
jeffyanta Feb 13, 2024
b415bb4
Add tests for new fee edge cases in messaging service
jeffyanta Feb 13, 2024
6248bfe
Update scheduler test to ensure multiple fees are handled
jeffyanta Feb 13, 2024
bf24c9c
Add local simulation test to ensure we catch invalid fee structures d…
jeffyanta Feb 13, 2024
494170d
Add client-side assertions on fee server parameter expectations
jeffyanta Feb 13, 2024
403f832
Add a test for getMicroPaymentReceiveExchangeDataByOwner
jeffyanta Feb 13, 2024
3309ce4
Fix micropayment check in getMicroPaymentReceiveExchangeDataByOwner
jeffyanta Feb 13, 2024
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
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ require (
firebase.google.com/go/v4 v4.8.0
github.com/aws/aws-sdk-go-v2 v0.17.0
github.com/bits-and-blooms/bloom/v3 v3.1.0
github.com/code-payments/code-protobuf-api v1.9.0
github.com/code-payments/code-protobuf-api v1.10.0
github.com/emirpasic/gods v1.12.0
github.com/envoyproxy/protoc-gen-validate v0.1.0
github.com/golang-jwt/jwt/v5 v5.0.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWH
github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I=
github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ=
github.com/code-payments/code-protobuf-api v1.9.0 h1:V8v/yAlZnVtcqh1LZ+zBIYC+Z04kOcCr8GRvwka69C0=
github.com/code-payments/code-protobuf-api v1.9.0/go.mod h1:pHQm75vydD6Cm2qHAzlimW6drysm489Z4tVxC2zHSsU=
github.com/code-payments/code-protobuf-api v1.10.0 h1:0I/lCHUtuQdbSKj02miQZlwSEdEUqVtTR0LxPTxA15w=
github.com/code-payments/code-protobuf-api v1.10.0/go.mod h1:pHQm75vydD6Cm2qHAzlimW6drysm489Z4tVxC2zHSsU=
github.com/containerd/continuity v0.0.0-20190827140505-75bee3e2ccb6 h1:NmTXa/uVnDyp0TY5MKi197+3HWcnYWfnHGyaFthlnGw=
github.com/containerd/continuity v0.0.0-20190827140505-75bee3e2ccb6/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y=
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
Expand Down
59 changes: 43 additions & 16 deletions pkg/code/async/sequencer/scheduler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,17 @@ func TestContextualScheduler_NoPrivacyWithdraw(t *testing.T) {
}
}

forceSimulateFeePayment := func(env *schedulerTestEnv, transfer *fulfillment.Record, fulfillmentRecords []*fulfillment.Record) {
forceSimulateOneFeePayments := func(env *schedulerTestEnv, transfer *fulfillment.Record, fulfillmentRecords []*fulfillment.Record) {
for _, fulfillmentRecord := range fulfillmentRecords {
if fulfillmentRecord.FulfillmentType == fulfillment.NoPrivacyTransferWithAuthority && fulfillmentRecord.Source == transfer.Source {
fulfillmentRecord.State = fulfillment.StateConfirmed
env.data.UpdateFulfillment(env.ctx, fulfillmentRecord)
break
}
}
}

forceSimulateAllFeePayments := func(env *schedulerTestEnv, transfer *fulfillment.Record, fulfillmentRecords []*fulfillment.Record) {
for _, fulfillmentRecord := range fulfillmentRecords {
if fulfillmentRecord.FulfillmentType == fulfillment.NoPrivacyTransferWithAuthority && fulfillmentRecord.Source == transfer.Source {
fulfillmentRecord.State = fulfillment.StateConfirmed
Expand All @@ -632,7 +642,7 @@ func TestContextualScheduler_NoPrivacyWithdraw(t *testing.T) {
simulation: func(env *schedulerTestEnv, transfer *fulfillment.Record, fulfillmentRecords []*fulfillment.Record) {
simulateOpeningSourceAccount(env, transfer, fulfillmentRecords)
simulateOpeningDestinationAccount(env, transfer, fulfillmentRecords)
forceSimulateFeePayment(env, transfer, fulfillmentRecords)
forceSimulateAllFeePayments(env, transfer, fulfillmentRecords)
},
expected: false,
},
Expand All @@ -642,7 +652,7 @@ func TestContextualScheduler_NoPrivacyWithdraw(t *testing.T) {
simulateOpeningSourceAccount(env, transfer, fulfillmentRecords)
simulateOpeningDestinationAccount(env, transfer, fulfillmentRecords)
simulateOneTreasuryPayment(env, transfer, fulfillmentRecords)
forceSimulateFeePayment(env, transfer, fulfillmentRecords)
forceSimulateAllFeePayments(env, transfer, fulfillmentRecords)
},
expected: false,
},
Expand All @@ -651,21 +661,21 @@ func TestContextualScheduler_NoPrivacyWithdraw(t *testing.T) {
simulation: func(env *schedulerTestEnv, transfer *fulfillment.Record, fulfillmentRecords []*fulfillment.Record) {
simulateOpeningSourceAccount(env, transfer, fulfillmentRecords)
simulateAllTreasuryPayments(env, transfer, fulfillmentRecords)
forceSimulateFeePayment(env, transfer, fulfillmentRecords)
forceSimulateAllFeePayments(env, transfer, fulfillmentRecords)
},
expected: false,
},
{
// Source user account not opened
simulation: func(env *schedulerTestEnv, transfer *fulfillment.Record, fulfillmentRecords []*fulfillment.Record) {
forceSimulateAllTreasuryPayments(env, transfer, fulfillmentRecords)
forceSimulateFeePayment(env, transfer, fulfillmentRecords)
forceSimulateAllFeePayments(env, transfer, fulfillmentRecords)
simulateOpeningDestinationAccount(env, transfer, fulfillmentRecords)
},
expected: false,
},
{
// Fee payment not confirmed
// All fee payments not confirmed
simulation: func(env *schedulerTestEnv, transfer *fulfillment.Record, fulfillmentRecords []*fulfillment.Record) {
simulateOpeningSourceAccount(env, transfer, fulfillmentRecords)
simulateOpeningDestinationAccount(env, transfer, fulfillmentRecords)
Expand All @@ -674,11 +684,21 @@ func TestContextualScheduler_NoPrivacyWithdraw(t *testing.T) {
expected: false,
},
{
// Subset of fee payments not confirmed
simulation: func(env *schedulerTestEnv, transfer *fulfillment.Record, fulfillmentRecords []*fulfillment.Record) {
simulateOpeningSourceAccount(env, transfer, fulfillmentRecords)
simulateOpeningDestinationAccount(env, transfer, fulfillmentRecords)
simulateAllTreasuryPayments(env, transfer, fulfillmentRecords)
forceSimulateFeePayment(env, transfer, fulfillmentRecords)
forceSimulateOneFeePayments(env, transfer, fulfillmentRecords)
},
expected: false,
},
{
simulation: func(env *schedulerTestEnv, transfer *fulfillment.Record, fulfillmentRecords []*fulfillment.Record) {
simulateOpeningSourceAccount(env, transfer, fulfillmentRecords)
simulateOpeningDestinationAccount(env, transfer, fulfillmentRecords)
simulateAllTreasuryPayments(env, transfer, fulfillmentRecords)
forceSimulateAllFeePayments(env, transfer, fulfillmentRecords)
},
expected: true,
},
Expand Down Expand Up @@ -2306,14 +2326,21 @@ func (e *schedulerTestEnv) setupSchedulerTest(t *testing.T, intentRecords []*int
bucketActionRecords = append(bucketActionRecords, bucketReorganization)
}

var feePaymentAction *action.Record
var feePaymentActions []*action.Record
if intentRecord.SendPrivatePaymentMetadata.IsMicroPayment {
feePaymentAction = &action.Record{
ActionType: action.NoPrivacyTransfer,

Source: fmt.Sprintf("%s-outgoing-%d", intentRecord.InitiatorOwnerAccount, currentOutgoingByUser[intentRecord.InitiatorOwnerAccount]),
Destination: &codeFeeCollector,
Quantity: &feeAmount,
feePaymentActions = []*action.Record{
{
ActionType: action.NoPrivacyTransfer,
Source: fmt.Sprintf("%s-outgoing-%d", intentRecord.InitiatorOwnerAccount, currentOutgoingByUser[intentRecord.InitiatorOwnerAccount]),
Destination: &codeFeeCollector,
Quantity: &feeAmount,
},
{
ActionType: action.NoPrivacyTransfer,
Source: fmt.Sprintf("%s-outgoing-%d", intentRecord.InitiatorOwnerAccount, currentOutgoingByUser[intentRecord.InitiatorOwnerAccount]),
Destination: pointer.String(testutil.NewRandomAccount(t).PublicKey().ToBase58()),
Quantity: &feeAmount,
},
}
}

Expand Down Expand Up @@ -2343,8 +2370,8 @@ func (e *schedulerTestEnv) setupSchedulerTest(t *testing.T, intentRecords []*int
newActionRecords,
bucketActionRecords...,
)
if feePaymentAction != nil {
newActionRecords = append(newActionRecords, feePaymentAction)
if feePaymentActions != nil {
newActionRecords = append(newActionRecords, feePaymentActions...)
}
newActionRecords = append(
newActionRecords,
Expand Down
11 changes: 7 additions & 4 deletions pkg/code/chat/message_merchant.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ func SendMerchantExchangeMessage(ctx context.Context, data code_data.Provider, i
if !ok {
return nil, nil
}
exchangeDataMinusFees := getExchangeDataMinusFees(exchangeData, intentRecord, actionRecords)

type verbAndExchangeData struct {
verb chatpb.ExchangeDataContent_Verb
Expand All @@ -74,10 +73,14 @@ func SendMerchantExchangeMessage(ctx context.Context, data code_data.Provider, i
verb: chatpb.ExchangeDataContent_SPENT,
exchangeData: exchangeData,
}
if len(intentRecord.SendPrivatePaymentMetadata.DestinationOwnerAccount) > 0 {
verbAndExchangeDataByMessageReceiver[intentRecord.SendPrivatePaymentMetadata.DestinationOwnerAccount] = &verbAndExchangeData{
receiveByOwner, err := getMicroPaymentReceiveExchangeDataByOwner(ctx, data, exchangeData, intentRecord, actionRecords)
if err != nil {
return nil, err
}
for owner, exchangeData := range receiveByOwner {
verbAndExchangeDataByMessageReceiver[owner] = &verbAndExchangeData{
verb: chatpb.ExchangeDataContent_RECEIVED,
exchangeData: exchangeDataMinusFees,
exchangeData: exchangeData,
}
}
} else if intentRecord.SendPrivatePaymentMetadata.IsWithdrawal {
Expand Down
91 changes: 76 additions & 15 deletions pkg/code/chat/util.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
package chat

import (
"context"
"time"

"github.com/mr-tron/base58/base58"
"github.com/pkg/errors"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"

chatpb "github.com/code-payments/code-protobuf-api/generated/go/chat/v1"
transactionpb "github.com/code-payments/code-protobuf-api/generated/go/transaction/v2"

code_data "github.com/code-payments/code-server/pkg/code/data"
"github.com/code-payments/code-server/pkg/code/data/account"
"github.com/code-payments/code-server/pkg/code/data/action"
"github.com/code-payments/code-server/pkg/code/data/intent"
currency_lib "github.com/code-payments/code-server/pkg/currency"
Expand Down Expand Up @@ -96,17 +98,18 @@ func getExchangeDataFromIntent(intentRecord *intent.Record) (*transactionpb.Exch
return nil, false
}

func getExchangeDataMinusFees(exchangeData *transactionpb.ExchangeData, intentRecord *intent.Record, actionRecords []*action.Record) *transactionpb.ExchangeData {
cloned := proto.Clone(exchangeData).(*transactionpb.ExchangeData)

if intentRecord.IntentType != intent.SendPrivatePayment {
return cloned
}

if !intentRecord.SendPrivatePaymentMetadata.IsMicroPayment {
return cloned
func getMicroPaymentReceiveExchangeDataByOwner(
ctx context.Context,
data code_data.Provider,
exchangeData *transactionpb.ExchangeData,
intentRecord *intent.Record,
actionRecords []*action.Record,
) (map[string]*transactionpb.ExchangeData, error) {
if intentRecord.IntentType != intent.SendPrivatePayment || !intentRecord.SendPrivatePaymentMetadata.IsMicroPayment {
return nil, errors.New("intent is not a micro payment")
}

// Find the action record where the final payment is made
var thirdPartyPaymentAction *action.Record
for _, actionRecord := range actionRecords {
if actionRecord.ActionType != action.NoPrivacyWithdraw {
Expand All @@ -119,12 +122,70 @@ func getExchangeDataMinusFees(exchangeData *transactionpb.ExchangeData, intentRe
}
}

// Should never happen
// Should never happen if the intent is a micropayment
if thirdPartyPaymentAction == nil {
return cloned
return nil, errors.New("payment action is missing")
}

quarksByTokenAccount := make(map[string]uint64)
quarksByTokenAccount[*thirdPartyPaymentAction.Destination] = *thirdPartyPaymentAction.Quantity

// Find and consolidate all fee payments into a quark amount by token account
var foundCodeFee bool
for _, actionRecord := range actionRecords {
if actionRecord.ActionType != action.NoPrivacyTransfer {
continue
}

if actionRecord.Source != thirdPartyPaymentAction.Source {
continue
}

// The first fee is always Code, and can be skipped
if !foundCodeFee {
foundCodeFee = true
continue
}

quarksByTokenAccount[*actionRecord.Destination] += *actionRecord.Quantity
}

// Consolidate quark amount by owner account
quarksByOwnerAccount := make(map[string]uint64)
for tokenAccount, quarks := range quarksByTokenAccount {
if tokenAccount == intentRecord.SendPrivatePaymentMetadata.DestinationTokenAccount {
if len(intentRecord.SendPrivatePaymentMetadata.DestinationOwnerAccount) > 0 {
quarksByOwnerAccount[intentRecord.SendPrivatePaymentMetadata.DestinationOwnerAccount] += quarks
}
continue
}

accountInfoRecord, err := data.GetAccountInfoByTokenAddress(ctx, tokenAccount)
if err == nil {
quarksByOwnerAccount[accountInfoRecord.OwnerAccount] += quarks
} else if err != account.ErrAccountInfoNotFound {
return nil, err
}
}

// Map result to an exchange data
res := make(map[string]*transactionpb.ExchangeData)
for ownerAccount, quarks := range quarksByOwnerAccount {
res[ownerAccount] = getExchangeDataInOtherQuarkAmount(exchangeData, quarks)
}
return res, nil
}

cloned.Quarks = *thirdPartyPaymentAction.Quantity
cloned.NativeAmount = cloned.ExchangeRate * float64(cloned.Quarks) / float64(kin.QuarksPerKin)
return cloned
func getExchangeDataInOtherQuarkAmount(original *transactionpb.ExchangeData, quarks uint64) *transactionpb.ExchangeData {
nativeAmount := original.NativeAmount
if original.Quarks != quarks {
nativeAmount = original.ExchangeRate * float64(quarks) / float64(kin.QuarksPerKin)
}

return &transactionpb.ExchangeData{
Currency: original.Currency,
ExchangeRate: original.ExchangeRate,
NativeAmount: nativeAmount,
Quarks: quarks,
}
}
Loading