mirror of
https://github.com/IT4Change/gradido.git
synced 2026-02-06 09:56:05 +00:00
move decay into shared
This commit is contained in:
parent
70e9fb1542
commit
fbd38d2e5a
@ -1,14 +1,6 @@
|
|||||||
import { Decimal } from 'decimal.js-light'
|
import { Decimal } from 'decimal.js-light'
|
||||||
import { Field, Int, ObjectType } from 'type-graphql'
|
import { Field, Int, ObjectType } from 'type-graphql'
|
||||||
|
import { Decay as DecayInterface } from 'shared'
|
||||||
interface DecayInterface {
|
|
||||||
balance: Decimal
|
|
||||||
decay: Decimal
|
|
||||||
roundedDecay: Decimal
|
|
||||||
start: Date | null
|
|
||||||
end: Date | null
|
|
||||||
duration: number | null
|
|
||||||
}
|
|
||||||
|
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
export class Decay {
|
export class Decay {
|
||||||
|
|||||||
@ -9,7 +9,7 @@ import { RIGHTS } from '@/auth/RIGHTS'
|
|||||||
import { BalanceLoggingView } from '@/logging/BalanceLogging.view'
|
import { BalanceLoggingView } from '@/logging/BalanceLogging.view'
|
||||||
import { DecayLoggingView } from '@/logging/DecayLogging.view'
|
import { DecayLoggingView } from '@/logging/DecayLogging.view'
|
||||||
import { Context, getUser } from '@/server/context'
|
import { Context, getUser } from '@/server/context'
|
||||||
import { calculateDecay } from '@/util/decay'
|
import { calculateDecay } from 'shared'
|
||||||
|
|
||||||
import { getLogger } from 'log4js'
|
import { getLogger } from 'log4js'
|
||||||
import { LOG4JS_RESOLVER_CATEGORY_NAME } from '.'
|
import { LOG4JS_RESOLVER_CATEGORY_NAME } from '.'
|
||||||
|
|||||||
@ -19,7 +19,6 @@ import { ContributionType } from '@enum/ContributionType'
|
|||||||
import { TransactionTypeId } from '@enum/TransactionTypeId'
|
import { TransactionTypeId } from '@enum/TransactionTypeId'
|
||||||
import { AdminUpdateContribution } from '@model/AdminUpdateContribution'
|
import { AdminUpdateContribution } from '@model/AdminUpdateContribution'
|
||||||
import { Contribution, ContributionListResult } from '@model/Contribution'
|
import { Contribution, ContributionListResult } from '@model/Contribution'
|
||||||
import { Decay } from '@model/Decay'
|
|
||||||
import { OpenCreation } from '@model/OpenCreation'
|
import { OpenCreation } from '@model/OpenCreation'
|
||||||
import { UnconfirmedContribution } from '@model/UnconfirmedContribution'
|
import { UnconfirmedContribution } from '@model/UnconfirmedContribution'
|
||||||
|
|
||||||
@ -44,7 +43,7 @@ import { UpdateUnconfirmedContributionContext } from '@/interactions/updateUncon
|
|||||||
import { LogError } from '@/server/LogError'
|
import { LogError } from '@/server/LogError'
|
||||||
import { Context, getClientTimezoneOffset, getUser } from '@/server/context'
|
import { Context, getClientTimezoneOffset, getUser } from '@/server/context'
|
||||||
import { TRANSACTIONS_LOCK } from '@/util/TRANSACTIONS_LOCK'
|
import { TRANSACTIONS_LOCK } from '@/util/TRANSACTIONS_LOCK'
|
||||||
import { calculateDecay } from '@/util/decay'
|
import { calculateDecay, Decay } from 'shared'
|
||||||
import { fullName } from '@/util/utilities'
|
import { fullName } from '@/util/utilities'
|
||||||
|
|
||||||
import { LOG4JS_RESOLVER_CATEGORY_NAME } from '@/graphql/resolver'
|
import { LOG4JS_RESOLVER_CATEGORY_NAME } from '@/graphql/resolver'
|
||||||
|
|||||||
@ -5,7 +5,7 @@ import { Authorized, FieldResolver, Query, Resolver } from 'type-graphql'
|
|||||||
import { CommunityStatistics, DynamicStatisticsFields } from '@model/CommunityStatistics'
|
import { CommunityStatistics, DynamicStatisticsFields } from '@model/CommunityStatistics'
|
||||||
|
|
||||||
import { RIGHTS } from '@/auth/RIGHTS'
|
import { RIGHTS } from '@/auth/RIGHTS'
|
||||||
import { calculateDecay } from '@/util/decay'
|
import { calculateDecay } from 'shared'
|
||||||
|
|
||||||
const db = AppDatabase.getInstance()
|
const db = AppDatabase.getInstance()
|
||||||
|
|
||||||
|
|||||||
@ -39,7 +39,7 @@ import { LogError } from '@/server/LogError'
|
|||||||
import { Context, getClientTimezoneOffset, getUser } from '@/server/context'
|
import { Context, getClientTimezoneOffset, getUser } from '@/server/context'
|
||||||
import { TRANSACTIONS_LOCK } from '@/util/TRANSACTIONS_LOCK'
|
import { TRANSACTIONS_LOCK } from '@/util/TRANSACTIONS_LOCK'
|
||||||
import { TRANSACTION_LINK_LOCK } from '@/util/TRANSACTION_LINK_LOCK'
|
import { TRANSACTION_LINK_LOCK } from '@/util/TRANSACTION_LINK_LOCK'
|
||||||
import { calculateDecay } from '@/util/decay'
|
import { calculateDecay } from 'shared'
|
||||||
import { fullName } from '@/util/utilities'
|
import { fullName } from '@/util/utilities'
|
||||||
import { calculateBalance } from '@/util/validate'
|
import { calculateBalance } from '@/util/validate'
|
||||||
|
|
||||||
|
|||||||
@ -1,9 +1,10 @@
|
|||||||
import { AbstractLoggingView } from 'database'
|
import { AbstractLoggingView } from 'database'
|
||||||
|
|
||||||
import { Decay } from '@/graphql/model/Decay'
|
import { Decay } from '@/graphql/model/Decay'
|
||||||
|
import type { Decay as DecayType } from 'shared'
|
||||||
|
|
||||||
export class DecayLoggingView extends AbstractLoggingView {
|
export class DecayLoggingView extends AbstractLoggingView {
|
||||||
public constructor(private self: Decay) {
|
public constructor(private self: Decay | DecayType) {
|
||||||
super()
|
super()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -4,7 +4,7 @@ import { Decay } from '@model/Decay'
|
|||||||
|
|
||||||
import { getLastTransaction } from '@/graphql/resolver/util/getLastTransaction'
|
import { getLastTransaction } from '@/graphql/resolver/util/getLastTransaction'
|
||||||
|
|
||||||
import { calculateDecay } from './decay'
|
import { calculateDecay } from 'shared'
|
||||||
|
|
||||||
export async function calculateSenderBalance(
|
export async function calculateSenderBalance(
|
||||||
userId: number,
|
userId: number,
|
||||||
@ -16,7 +16,7 @@ export async function calculateSenderBalance(
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
const decay = calculateDecay(lastTransaction.balance, lastTransaction.balanceDate, time)
|
const decay = new Decay(calculateDecay(lastTransaction.balance, lastTransaction.balanceDate, time))
|
||||||
|
|
||||||
const balance = decay.balance.add(amount.toString())
|
const balance = decay.balance.add(amount.toString())
|
||||||
return { balance, lastTransactionId: lastTransaction.id, decay }
|
return { balance, lastTransactionId: lastTransaction.id, decay }
|
||||||
|
|||||||
@ -1,71 +0,0 @@
|
|||||||
import { Decimal } from 'decimal.js-light'
|
|
||||||
|
|
||||||
import { Decay } from '@model/Decay'
|
|
||||||
|
|
||||||
import { LogError } from '@/server/LogError'
|
|
||||||
import { DECAY_START_TIME } from 'config-schema'
|
|
||||||
|
|
||||||
Decimal.set({
|
|
||||||
precision: 25,
|
|
||||||
rounding: Decimal.ROUND_HALF_UP,
|
|
||||||
})
|
|
||||||
|
|
||||||
// TODO: externalize all those definitions and functions into an external decay library
|
|
||||||
|
|
||||||
function decayFormula(value: Decimal, seconds: number): Decimal {
|
|
||||||
// TODO why do we need to convert this here to a stting to work properly?
|
|
||||||
return value.mul(
|
|
||||||
new Decimal('0.99999997803504048973201202316767079413460520837376').pow(seconds).toString(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function calculateDecay(
|
|
||||||
amount: Decimal,
|
|
||||||
from: Date,
|
|
||||||
to: Date,
|
|
||||||
startBlock: Date = DECAY_START_TIME,
|
|
||||||
): Decay {
|
|
||||||
const fromMs = from.getTime()
|
|
||||||
const toMs = to.getTime()
|
|
||||||
const startBlockMs = startBlock.getTime()
|
|
||||||
|
|
||||||
if (toMs < fromMs) {
|
|
||||||
throw new LogError('calculateDecay: to < from, reverse decay calculation is invalid')
|
|
||||||
}
|
|
||||||
|
|
||||||
// Initialize with no decay
|
|
||||||
const decay: Decay = {
|
|
||||||
balance: amount,
|
|
||||||
decay: new Decimal(0),
|
|
||||||
roundedDecay: new Decimal(0),
|
|
||||||
start: null,
|
|
||||||
end: null,
|
|
||||||
duration: null,
|
|
||||||
}
|
|
||||||
|
|
||||||
// decay started after end date; no decay
|
|
||||||
if (startBlockMs > toMs) {
|
|
||||||
return decay
|
|
||||||
}
|
|
||||||
// decay started before start date; decay for full duration
|
|
||||||
if (startBlockMs < fromMs) {
|
|
||||||
decay.start = from
|
|
||||||
decay.duration = (toMs - fromMs) / 1000
|
|
||||||
}
|
|
||||||
// decay started between start and end date; decay from decay start till end date
|
|
||||||
else {
|
|
||||||
decay.start = startBlock
|
|
||||||
decay.duration = (toMs - startBlockMs) / 1000
|
|
||||||
}
|
|
||||||
|
|
||||||
decay.end = to
|
|
||||||
decay.balance = decayFormula(amount, decay.duration)
|
|
||||||
decay.decay = decay.balance.minus(amount)
|
|
||||||
decay.roundedDecay = amount
|
|
||||||
.toDecimalPlaces(2, Decimal.ROUND_DOWN)
|
|
||||||
.minus(decay.balance.toDecimalPlaces(2, Decimal.ROUND_DOWN).toString())
|
|
||||||
.mul(-1)
|
|
||||||
return decay
|
|
||||||
}
|
|
||||||
|
|
||||||
export { decayFormula, calculateDecay }
|
|
||||||
@ -7,7 +7,7 @@ import { Decay } from '@model/Decay'
|
|||||||
import { getLastTransaction } from '@/graphql/resolver/util/getLastTransaction'
|
import { getLastTransaction } from '@/graphql/resolver/util/getLastTransaction'
|
||||||
import { transactionLinkSummary } from '@/graphql/resolver/util/transactionLinkSummary'
|
import { transactionLinkSummary } from '@/graphql/resolver/util/transactionLinkSummary'
|
||||||
|
|
||||||
import { calculateDecay } from './decay'
|
import { calculateDecay } from 'shared'
|
||||||
|
|
||||||
function isStringBoolean(value: string): boolean {
|
function isStringBoolean(value: string): boolean {
|
||||||
const lowerValue = value.toLowerCase()
|
const lowerValue = value.toLowerCase()
|
||||||
@ -36,7 +36,7 @@ async function calculateBalance(
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
const decay = calculateDecay(lastTransaction.balance, lastTransaction.balanceDate, time)
|
const decay = new Decay(calculateDecay(lastTransaction.balance, lastTransaction.balanceDate, time))
|
||||||
|
|
||||||
const balance = decay.balance.add(amount.toString())
|
const balance = decay.balance.add(amount.toString())
|
||||||
const { sumHoldAvailableAmount } = await transactionLinkSummary(userId, time)
|
const { sumHoldAvailableAmount } = await transactionLinkSummary(userId, time)
|
||||||
|
|||||||
@ -6,7 +6,7 @@ import { TransactionTypeId } from '@enum/TransactionTypeId'
|
|||||||
import { Transaction } from '@model/Transaction'
|
import { Transaction } from '@model/Transaction'
|
||||||
import { User } from '@model/User'
|
import { User } from '@model/User'
|
||||||
|
|
||||||
import { calculateDecay } from './decay'
|
import { calculateDecay } from 'shared'
|
||||||
|
|
||||||
const defaultModelFunctions = {
|
const defaultModelFunctions = {
|
||||||
hasId: function (): boolean {
|
hasId: function (): boolean {
|
||||||
|
|||||||
1
bun.lock
1
bun.lock
@ -420,6 +420,7 @@
|
|||||||
"name": "shared",
|
"name": "shared",
|
||||||
"version": "2.6.0",
|
"version": "2.6.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"decimal.js-light": "^2.5.1",
|
||||||
"esbuild": "^0.25.2",
|
"esbuild": "^0.25.2",
|
||||||
"log4js": "^6.9.1",
|
"log4js": "^6.9.1",
|
||||||
"zod": "^3.25.61",
|
"zod": "^3.25.61",
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
import {
|
import {
|
||||||
DECAY_START_TIME,
|
|
||||||
GRAPHIQL,
|
GRAPHIQL,
|
||||||
LOG4JS_CONFIG_PLACEHOLDER,
|
LOG4JS_CONFIG_PLACEHOLDER,
|
||||||
LOG_FILES_BASE_PATH,
|
LOG_FILES_BASE_PATH,
|
||||||
@ -10,7 +9,6 @@ import {
|
|||||||
import Joi from 'joi'
|
import Joi from 'joi'
|
||||||
|
|
||||||
export const schema = Joi.object({
|
export const schema = Joi.object({
|
||||||
DECAY_START_TIME,
|
|
||||||
GRAPHIQL,
|
GRAPHIQL,
|
||||||
LOG4JS_CONFIG_PLACEHOLDER,
|
LOG4JS_CONFIG_PLACEHOLDER,
|
||||||
LOG_FILES_BASE_PATH,
|
LOG_FILES_BASE_PATH,
|
||||||
|
|||||||
@ -1,14 +1,6 @@
|
|||||||
import { Decimal } from 'decimal.js-light'
|
import { Decimal } from 'decimal.js-light'
|
||||||
import { Field, Int, ObjectType } from 'type-graphql'
|
import { Field, Int, ObjectType } from 'type-graphql'
|
||||||
|
import { Decay as DecayInterface} from 'shared'
|
||||||
interface DecayInterface {
|
|
||||||
balance: Decimal
|
|
||||||
decay: Decimal
|
|
||||||
roundedDecay: Decimal
|
|
||||||
start: Date | null
|
|
||||||
end: Date | null
|
|
||||||
duration: number | null
|
|
||||||
}
|
|
||||||
|
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
export class Decay {
|
export class Decay {
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import { calculateDecay } from '@/graphql/util/decay'
|
import { calculateDecay } from 'shared'
|
||||||
import { getLastTransaction } from '@/graphql/util/getLastTransaction'
|
import { getLastTransaction } from '@/graphql/util/getLastTransaction'
|
||||||
import { Decimal } from 'decimal.js-light'
|
import { Decimal } from 'decimal.js-light'
|
||||||
import { Decay } from '../model/Decay'
|
import { Decay } from '../model/Decay'
|
||||||
@ -13,7 +13,7 @@ export async function calculateRecipientBalance(
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
const decay = calculateDecay(lastTransaction.balance, lastTransaction.balanceDate, time)
|
const decay = new Decay(calculateDecay(lastTransaction.balance, lastTransaction.balanceDate, time))
|
||||||
|
|
||||||
const balance = decay.balance.add(amount.toString())
|
const balance = decay.balance.add(amount.toString())
|
||||||
|
|
||||||
|
|||||||
@ -1,42 +0,0 @@
|
|||||||
import { Decimal } from 'decimal.js-light'
|
|
||||||
|
|
||||||
import { calculateDecay, decayFormula } from './decay'
|
|
||||||
|
|
||||||
describe('utils/decay', () => {
|
|
||||||
describe('decayFormula', () => {
|
|
||||||
it('has base 0.99999997802044727', () => {
|
|
||||||
const amount = new Decimal(1.0)
|
|
||||||
const seconds = 1
|
|
||||||
// TODO: toString() was required, we could not compare two decimals
|
|
||||||
expect(decayFormula(amount, seconds).toString()).toBe('0.999999978035040489732012')
|
|
||||||
})
|
|
||||||
it('has correct backward calculation', () => {
|
|
||||||
const amount = new Decimal(1.0)
|
|
||||||
const seconds = -1
|
|
||||||
expect(decayFormula(amount, seconds).toString()).toBe('1.000000021964959992727444')
|
|
||||||
})
|
|
||||||
// we get pretty close, but not exact here, skipping
|
|
||||||
|
|
||||||
it.skip('has correct forward calculation', () => {
|
|
||||||
const amount = new Decimal(1.0).div(
|
|
||||||
new Decimal('0.99999997803504048973201202316767079413460520837376'),
|
|
||||||
)
|
|
||||||
const seconds = 1
|
|
||||||
expect(decayFormula(amount, seconds).toString()).toBe('1.0')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
it('has base 0.99999997802044727', () => {
|
|
||||||
const now = new Date()
|
|
||||||
now.setSeconds(1)
|
|
||||||
const oneSecondAgo = new Date(now.getTime())
|
|
||||||
oneSecondAgo.setSeconds(0)
|
|
||||||
expect(calculateDecay(new Decimal(1.0), oneSecondAgo, now).balance.toString()).toBe(
|
|
||||||
'0.999999978035040489732012',
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('returns input amount when from and to is the same', () => {
|
|
||||||
const now = new Date()
|
|
||||||
expect(calculateDecay(new Decimal(100.0), now, now).balance.toString()).toBe('100')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@ -31,6 +31,7 @@
|
|||||||
"uuid": "^8.3.2"
|
"uuid": "^8.3.2"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"decimal.js-light": "^2.5.1",
|
||||||
"esbuild": "^0.25.2",
|
"esbuild": "^0.25.2",
|
||||||
"log4js": "^6.9.1",
|
"log4js": "^6.9.1",
|
||||||
"zod": "^3.25.61"
|
"zod": "^3.25.61"
|
||||||
|
|||||||
2
shared/src/const/index.ts
Normal file
2
shared/src/const/index.ts
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
export const DECAY_START_TIME = new Date('2021-05-13T17:46:31Z')
|
||||||
|
export const LOG4JS_BASE_CATEGORY_NAME = 'shared'
|
||||||
@ -1,2 +1,3 @@
|
|||||||
export * from './schema'
|
export * from './schema'
|
||||||
export * from './enum'
|
export * from './enum'
|
||||||
|
export * from './logic'
|
||||||
|
|||||||
@ -1,34 +1,47 @@
|
|||||||
import { Decimal } from 'decimal.js-light'
|
import { Decimal } from 'decimal.js-light'
|
||||||
|
|
||||||
import { LogError } from '@/server/LogError'
|
import { getLogger } from 'log4js'
|
||||||
import { DECAY_START_TIME } from 'config-schema'
|
import { LOG4JS_LOGIC_CATEGORY } from '.'
|
||||||
import { Decay } from '../api/1_0/model/Decay'
|
import { DECAY_START_TIME } from '../const'
|
||||||
|
|
||||||
|
const logger = getLogger(`${LOG4JS_LOGIC_CATEGORY}.DecayLogic`)
|
||||||
|
|
||||||
Decimal.set({
|
Decimal.set({
|
||||||
precision: 25,
|
precision: 25,
|
||||||
rounding: Decimal.ROUND_HALF_UP,
|
rounding: Decimal.ROUND_HALF_UP,
|
||||||
})
|
})
|
||||||
|
|
||||||
// TODO: externalize all those definitions and functions into an external decay library
|
export interface Decay {
|
||||||
function decayFormula(value: Decimal, seconds: number): Decimal {
|
balance: Decimal
|
||||||
|
decay: Decimal
|
||||||
|
roundedDecay: Decimal
|
||||||
|
start: Date | null
|
||||||
|
end: Date | null
|
||||||
|
duration: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decayFormula(value: Decimal, seconds: number): Decimal {
|
||||||
// TODO why do we need to convert this here to a string to work properly?
|
// TODO why do we need to convert this here to a string to work properly?
|
||||||
|
// chatgpt: We convert to string here to avoid precision loss:
|
||||||
|
// .pow(seconds) can internally round the result, especially for large values of `seconds`.
|
||||||
|
// Using .toString() ensures full precision is preserved in the multiplication.
|
||||||
return value.mul(
|
return value.mul(
|
||||||
new Decimal('0.99999997803504048973201202316767079413460520837376').pow(seconds).toString(),
|
new Decimal('0.99999997803504048973201202316767079413460520837376').pow(seconds).toString(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function calculateDecay(
|
export function calculateDecay(
|
||||||
amount: Decimal,
|
amount: Decimal,
|
||||||
from: Date,
|
from: Date,
|
||||||
to: Date,
|
to: Date
|
||||||
startBlock: Date = DECAY_START_TIME,
|
|
||||||
): Decay {
|
): Decay {
|
||||||
const fromMs = from.getTime()
|
const fromMs = from.getTime()
|
||||||
const toMs = to.getTime()
|
const toMs = to.getTime()
|
||||||
const startBlockMs = startBlock.getTime()
|
const startBlockMs = DECAY_START_TIME.getTime()
|
||||||
|
|
||||||
if (toMs < fromMs) {
|
if (toMs < fromMs) {
|
||||||
throw new LogError('calculateDecay: to < from, reverse decay calculation is invalid')
|
logger.error('calculateDecay: to < from, reverse decay calculation is invalid', from, to)
|
||||||
|
throw new Error('calculateDecay: to < from, reverse decay calculation is invalid')
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize with no decay
|
// Initialize with no decay
|
||||||
@ -52,7 +65,7 @@ function calculateDecay(
|
|||||||
}
|
}
|
||||||
// decay started between start and end date; decay from decay start till end date
|
// decay started between start and end date; decay from decay start till end date
|
||||||
else {
|
else {
|
||||||
decay.start = startBlock
|
decay.start = DECAY_START_TIME
|
||||||
decay.duration = (toMs - startBlockMs) / 1000
|
decay.duration = (toMs - startBlockMs) / 1000
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -65,5 +78,3 @@ function calculateDecay(
|
|||||||
.mul(-1)
|
.mul(-1)
|
||||||
return decay
|
return decay
|
||||||
}
|
}
|
||||||
|
|
||||||
export { decayFormula, calculateDecay }
|
|
||||||
4
shared/src/logic/index.ts
Normal file
4
shared/src/logic/index.ts
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
import { LOG4JS_BASE_CATEGORY_NAME } from '../const'
|
||||||
|
|
||||||
|
export const LOG4JS_LOGIC_CATEGORY = `${LOG4JS_BASE_CATEGORY_NAME}.logic`
|
||||||
|
export { calculateDecay, Decay } from './decay'
|
||||||
Loading…
x
Reference in New Issue
Block a user