@xyo-network/payment-plugin 5.3.2 → 5.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/neutral/Discount/Diviner.d.ts +44 -0
  2. package/dist/neutral/Discount/Diviner.d.ts.map +1 -0
  3. package/dist/neutral/Discount/index.d.ts +3 -0
  4. package/dist/neutral/Discount/index.d.ts.map +1 -0
  5. package/dist/neutral/Discount/lib/applyCoupons.d.ts +4 -0
  6. package/dist/neutral/Discount/lib/applyCoupons.d.ts.map +1 -0
  7. package/dist/neutral/Discount/lib/findUnfulfilledConditions.d.ts +20 -0
  8. package/dist/neutral/Discount/lib/findUnfulfilledConditions.d.ts.map +1 -0
  9. package/dist/neutral/Discount/lib/index.d.ts +3 -0
  10. package/dist/neutral/Discount/lib/index.d.ts.map +1 -0
  11. package/dist/neutral/Invoice/getInvoiceForEscrow.d.ts +10 -0
  12. package/dist/neutral/Invoice/getInvoiceForEscrow.d.ts.map +1 -0
  13. package/dist/neutral/Invoice/index.d.ts +2 -0
  14. package/dist/neutral/Invoice/index.d.ts.map +1 -0
  15. package/dist/neutral/Subtotal/Diviner.d.ts +19 -0
  16. package/dist/neutral/Subtotal/Diviner.d.ts.map +1 -0
  17. package/dist/neutral/Subtotal/index.d.ts +2 -0
  18. package/dist/neutral/Subtotal/index.d.ts.map +1 -0
  19. package/dist/neutral/Subtotal/lib/appraisalValidators.d.ts +3 -0
  20. package/dist/neutral/Subtotal/lib/appraisalValidators.d.ts.map +1 -0
  21. package/dist/neutral/Subtotal/lib/durationValidators.d.ts +9 -0
  22. package/dist/neutral/Subtotal/lib/durationValidators.d.ts.map +1 -0
  23. package/dist/neutral/Subtotal/lib/index.d.ts +3 -0
  24. package/dist/neutral/Subtotal/lib/index.d.ts.map +1 -0
  25. package/dist/neutral/Subtotal/lib/termsValidators.d.ts +4 -0
  26. package/dist/neutral/Subtotal/lib/termsValidators.d.ts.map +1 -0
  27. package/dist/neutral/Total/Diviner.d.ts +18 -0
  28. package/dist/neutral/Total/Diviner.d.ts.map +1 -0
  29. package/dist/neutral/Total/index.d.ts +2 -0
  30. package/dist/neutral/Total/index.d.ts.map +1 -0
  31. package/dist/neutral/index.d.ts +5 -0
  32. package/dist/neutral/index.d.ts.map +1 -0
  33. package/dist/neutral/index.mjs +439 -0
  34. package/dist/neutral/index.mjs.map +1 -0
  35. package/package.json +17 -8
  36. package/src/Discount/Diviner.ts +0 -205
  37. package/src/Discount/index.ts +0 -2
  38. package/src/Discount/lib/applyCoupons.ts +0 -95
  39. package/src/Discount/lib/findUnfulfilledConditions.ts +0 -72
  40. package/src/Discount/lib/index.ts +0 -2
  41. package/src/Invoice/getInvoiceForEscrow.ts +0 -40
  42. package/src/Invoice/index.ts +0 -1
  43. package/src/Subtotal/Diviner.ts +0 -65
  44. package/src/Subtotal/index.ts +0 -1
  45. package/src/Subtotal/lib/appraisalValidators.ts +0 -40
  46. package/src/Subtotal/lib/durationValidators.ts +0 -17
  47. package/src/Subtotal/lib/index.ts +0 -2
  48. package/src/Subtotal/lib/termsValidators.ts +0 -17
  49. package/src/Total/Diviner.ts +0 -67
  50. package/src/Total/index.ts +0 -1
  51. package/src/index.ts +0 -4
@@ -1,205 +0,0 @@
1
- import {
2
- Address, assertEx, exists, filterAs, Hash,
3
- } from '@xylabs/sdk-js'
4
- import { ArchivistInstance, asArchivistInstance } from '@xyo-network/archivist-model'
5
- import { AbstractDiviner } from '@xyo-network/diviner-abstract'
6
- import { BoundWitnessDivinerQueryPayload, BoundWitnessDivinerQuerySchema } from '@xyo-network/diviner-boundwitness-model'
7
- import {
8
- HashLeaseEstimate,
9
- isHashLeaseEstimate,
10
- } from '@xyo-network/diviner-hash-lease'
11
- import {
12
- asDivinerInstance, DivinerInstance, DivinerModuleEventData,
13
- } from '@xyo-network/diviner-model'
14
- import { creatableModule } from '@xyo-network/module-model'
15
- import { Payload } from '@xyo-network/payload-model'
16
- import {
17
- asCondition,
18
- asCoupon,
19
- Condition,
20
- Coupon,
21
- Discount,
22
- EscrowTerms, isCondition, isCoupon,
23
- isEscrowTerms, NO_DISCOUNT, PaymentDiscountDivinerConfigSchema, PaymentDiscountDivinerParams,
24
- } from '@xyo-network/payment-payload-plugins'
25
- import { PayloadBuilder } from '@xyo-network/sdk-js'
26
-
27
- import { applyCoupons, areConditionsFulfilled } from './lib/index.ts'
28
-
29
- const DEFAULT_BOUND_WITNESS_DIVINER_QUERY_PROPS: Readonly<BoundWitnessDivinerQueryPayload> = {
30
- limit: 1,
31
- order: 'desc',
32
- schema: BoundWitnessDivinerQuerySchema,
33
- }
34
-
35
- export type PaymentDiscountDivinerInputType = EscrowTerms | Coupon | HashLeaseEstimate | Payload
36
-
37
- @creatableModule()
38
- export class PaymentDiscountDiviner<
39
- TParams extends PaymentDiscountDivinerParams = PaymentDiscountDivinerParams,
40
- TIn extends PaymentDiscountDivinerInputType = PaymentDiscountDivinerInputType,
41
- TOut extends Discount = Discount,
42
- TEventData extends DivinerModuleEventData<DivinerInstance<TParams, TIn, TOut>, TIn, TOut> = DivinerModuleEventData<
43
- DivinerInstance<TParams, TIn, TOut>,
44
- TIn,
45
- TOut
46
- >,
47
- > extends AbstractDiviner<TParams, TIn, TOut, TEventData> {
48
- static override readonly configSchemas = [PaymentDiscountDivinerConfigSchema]
49
- static override readonly defaultConfigSchema = PaymentDiscountDivinerConfigSchema
50
-
51
- protected get couponAuthorities(): Address[] {
52
- return [...(this.config.couponAuthorities ?? []), ...(this.params.couponAuthorities ?? [])]
53
- }
54
-
55
- protected async divineHandler(payloads: TIn[] = []): Promise<TOut[]> {
56
- const $sources: Hash[] = []
57
-
58
- // Parse terms
59
- const terms = payloads.find(isEscrowTerms) as EscrowTerms | undefined
60
- if (!terms) return [{ ...NO_DISCOUNT, $sources }] as TOut[]
61
- $sources.push(await PayloadBuilder.hash(terms))
62
-
63
- // Parse appraisals
64
- const termsAppraisals = terms?.appraisals
65
- // If the escrow terms do not have appraisals, return no discount
66
- if (!termsAppraisals || termsAppraisals.length === 0) return [{ ...NO_DISCOUNT, $sources }] as TOut[]
67
- const hashMap = await PayloadBuilder.toAllHashMap(payloads) as Record<Hash, Payload>
68
- const appraisals = this.getEscrowAppraisals(terms, hashMap)
69
- // Add the appraisals that were found to the sources
70
- $sources.push(...termsAppraisals)
71
- // If not all appraisals are found, return no discount
72
- if (appraisals.length !== termsAppraisals.length) return [{ ...NO_DISCOUNT, $sources }] as TOut[]
73
-
74
- // Parse coupons
75
- const [coupons, conditions] = await this.getEscrowDiscounts(terms, hashMap)
76
- // Add the coupons that were found to the sources
77
- // TODO: Should we throw if not all coupons are found?
78
- const couponHashes = await PayloadBuilder.hashes(coupons)
79
- $sources.push(...couponHashes)
80
-
81
- const currentCoupons = coupons.filter(this.isCouponCurrent)
82
- const conditionsMetCoupons = (
83
- await Promise.all(currentCoupons.map(async coupon => await areConditionsFulfilled(coupon, conditions, payloads) ? coupon : undefined))).filter(exists)
84
-
85
- const validCoupons = await this.filterToSigned(conditionsMetCoupons)
86
- // TODO: Should we throw if not all coupons are valid?
87
- if (validCoupons.length === 0) return [{ ...NO_DISCOUNT, $sources }] as TOut[]
88
-
89
- // TODO: Call paymentSubtotalDiviner to get the subtotal to centralize the logic
90
- const discount = applyCoupons(appraisals, validCoupons)
91
- return [{ ...discount, $sources }] as TOut[]
92
- }
93
-
94
- /**
95
- * Filters the supplied list of coupons to only those that are signed by
96
- * addresses specified in the couponAuthorities
97
- * @param coupons The list of coupons to filter
98
- * @returns The filtered list of coupons that are signed by the couponAuthorities
99
- */
100
- protected async filterToSigned(coupons: Coupon[]): Promise<Coupon[]> {
101
- const signed: Coupon[] = []
102
- const dataHashMap = await PayloadBuilder.toDataHashMap(coupons)
103
- const boundWitnessDiviner = await this.getDiscountsBoundWitnessDiviner()
104
- const hashes = Object.keys(dataHashMap)
105
- const addresses = this.couponAuthorities
106
- // TODO: Keep an in memory cache of the hashes queried and their results
107
- // to avoid querying the same hash multiple times
108
- await Promise.all(hashes.map((h) => {
109
- const hash = h as Hash
110
- return Promise.all(addresses.map(async (address) => {
111
- const query: BoundWitnessDivinerQueryPayload = {
112
- ...DEFAULT_BOUND_WITNESS_DIVINER_QUERY_PROPS, addresses: [address], payload_hashes: [hash],
113
- }
114
- const result = await boundWitnessDiviner.divine([query])
115
- if (result.length > 0) signed.push(dataHashMap[hash])
116
- }))
117
- }))
118
- return signed
119
- }
120
-
121
- protected async getDiscountsArchivist(): Promise<ArchivistInstance> {
122
- const name = assertEx(this.config.archivist, () => 'Missing archivist in config')
123
- const mod = assertEx(await this.resolve(name), () => `Error resolving archivist: ${name}`)
124
- return assertEx(asArchivistInstance(mod), () => `Resolved module ${mod.address} not a valid Archivist`)
125
- }
126
-
127
- protected async getDiscountsBoundWitnessDiviner(): Promise<DivinerInstance> {
128
- const name = assertEx(this.config.boundWitnessDiviner, () => 'Missing boundWitnessDiviner in config')
129
- const mod = assertEx(await this.resolve(name), () => `Error resolving boundWitnessDiviner: ${name}`)
130
- return assertEx(asDivinerInstance(mod), () => `Resolved module ${mod.address} not a valid Diviner`)
131
- }
132
-
133
- /**
134
- * Finds the appraisals specified by the escrow terms from the supplied payloads
135
- * @param terms The escrow terms
136
- * @param payloads The payloads to search for the appraisals
137
- * @returns The appraisals found in the payloads
138
- */
139
- protected getEscrowAppraisals(terms: EscrowTerms, hashMap: Record<Hash, Payload>): HashLeaseEstimate[] {
140
- const hashes = terms?.appraisals ?? []
141
- if (hashes.length === 0) return []
142
- return hashes.map(hash => hashMap[hash]).filter(exists).filter(isHashLeaseEstimate)
143
- }
144
-
145
- /**
146
- * Finds the discounts specified by the escrow terms from the supplied payloads
147
- * @param terms The escrow terms
148
- * @param hashMap The payloads to search for the discounts
149
- * @returns A tuple containing all the escrow coupons and conditions referenced in those coupons
150
- * that were found in the either the supplied payloads or the archivist
151
- */
152
- protected async getEscrowDiscounts(terms: EscrowTerms, hashMap: Record<Hash, Payload>): Promise<[Coupon[], Condition[]]> {
153
- // Parse discounts
154
- const discountsHashes = terms.discounts ?? []
155
- if (discountsHashes.length === 0) return [[], []]
156
-
157
- // Use the supplied payloads to find the discounts
158
- const discounts: Coupon[] = discountsHashes.map(hash => hashMap[hash]).filter(exists).filter(isCoupon)
159
- const missingDiscounts = discountsHashes.filter(hash => !hashMap[hash])
160
- // If not all discounts are found
161
- if (missingDiscounts.length > 0) {
162
- // Find any remaining from discounts archivist
163
- const discountsArchivist = await this.getDiscountsArchivist()
164
- const payloads = await discountsArchivist.get(missingDiscounts)
165
- discounts.push(...filterAs(payloads, asCoupon))
166
- }
167
- // If not all discounts are found
168
- if (discounts.length !== discountsHashes.length) {
169
- const termsHash = await PayloadBuilder.hash(terms)
170
- const foundHashes = await PayloadBuilder.hashes(discounts)
171
- // Log individual discounts that were not found
172
- for (const hash of discountsHashes) {
173
- if (!foundHashes.includes(hash)) console.warn(`Discount ${hash} not found for terms ${termsHash}`)
174
- }
175
- }
176
-
177
- const conditionsHashes: Hash[] = discounts.flatMap(discount => discount.conditions ?? [])
178
- const conditions: Condition[] = conditionsHashes.map(hash => hashMap[hash]).filter(exists).filter(isCondition)
179
- const missingConditions = conditionsHashes.filter(hash => !hashMap[hash])
180
-
181
- // If not all conditions are found
182
- if (missingConditions.length > 0) {
183
- // Find any remaining from discounts archivist
184
- const discountsArchivist = await this.getDiscountsArchivist()
185
- const payloads = await discountsArchivist.get(missingConditions)
186
- conditions.push(...filterAs(payloads, asCondition))
187
- }
188
- // If not all conditions are found
189
- if (conditions.length !== conditionsHashes.length) {
190
- const termsHash = await PayloadBuilder.hash(terms)
191
- const foundHashes = await PayloadBuilder.hashes(conditions)
192
- // Log individual conditions that were not found
193
- for (const hash of discountsHashes) {
194
- if (!foundHashes.includes(hash)) console.warn(`Coupon condition ${hash} not found for terms ${termsHash}`)
195
- }
196
- }
197
-
198
- return [discounts, conditions]
199
- }
200
-
201
- protected isCouponCurrent(coupon: Coupon): boolean {
202
- const now = Date.now()
203
- return coupon.exp > now && coupon.nbf < now
204
- }
205
- }
@@ -1,2 +0,0 @@
1
- export * from './Diviner.ts'
2
- export * from './lib/index.ts'
@@ -1,95 +0,0 @@
1
- import { assertEx, exists } from '@xylabs/sdk-js'
2
- import type { HashLeaseEstimate } from '@xyo-network/diviner-hash-lease'
3
- import type {
4
- AmountFields,
5
- Coupon, Discount, FixedAmountCoupon,
6
- FixedPercentageCoupon,
7
- FixedPriceCoupon,
8
- } from '@xyo-network/payment-payload-plugins'
9
- import {
10
- DiscountSchema,
11
- isFixedAmountCoupon, isFixedPercentageCoupon,
12
- isFixedPriceCoupon,
13
- isStackable,
14
- } from '@xyo-network/payment-payload-plugins'
15
-
16
- export const applyCoupons = (appraisals: HashLeaseEstimate[], coupons: Coupon[]): Discount => {
17
- // Ensure all appraisals and coupons are in USD
18
- const allAppraisalsAreUSD = appraisals.every(appraisal => appraisal.currency === 'USD')
19
- assertEx(allAppraisalsAreUSD, () => 'All appraisals must be in USD')
20
- const allCouponsAreUSD = coupons.map(coupon => (coupon as Partial<AmountFields>)?.currency).filter(exists).every(currency => currency === 'USD')
21
- assertEx(allCouponsAreUSD, () => 'All coupons must be in USD')
22
- const total = appraisals.reduce((acc, appraisal) => acc + appraisal.price, 0)
23
-
24
- // Calculated non-stackable discount coupons
25
- const singularFixedDiscount = Math.max(...coupons
26
- .filter(coupon => isFixedAmountCoupon(coupon) && !isStackable(coupon))
27
- .map(coupon => (coupon as FixedAmountCoupon).amount), 0)
28
- const singularPercentageDiscount = (Math.max(...coupons
29
- .filter(coupon => isFixedPercentageCoupon(coupon) && !isStackable(coupon))
30
- .map(coupon => (coupon as FixedPercentageCoupon).percentage), 0)) * total
31
- const singularFixedPriceDiscount = calculateSingularFixedPriceDiscount(total, appraisals, coupons, false)
32
-
33
- // Calculate stackable discount coupons
34
- // First calculate the total discount from fixed amount coupons
35
- const stackedFixedDiscount = coupons
36
- .filter(coupon => isFixedAmountCoupon(coupon) && isStackable(coupon))
37
- .reduce((acc, coupon) => acc + (coupon as FixedAmountCoupon).amount, 0)
38
- // Then calculate the total discount from percentage coupons and apply
39
- // the percentage discount to the remaining total after fixed discounts
40
- const stackedPercentageDiscount = coupons
41
- .filter(coupon => isFixedPercentageCoupon(coupon) && isStackable(coupon))
42
- .reduce((acc, coupon) => acc + (coupon as FixedPercentageCoupon).percentage, 0) * (total - stackedFixedDiscount)
43
- // Then calculate the total discount from fixed price coupons
44
- const stackedFixedPriceDiscount = calculateSingularFixedPriceDiscount(total, appraisals, coupons, true)
45
-
46
- // Sum all stackable discounts
47
- const stackedDiscount = stackedFixedDiscount + stackedPercentageDiscount + stackedFixedPriceDiscount
48
-
49
- // Find the best coupon(s) to apply
50
- const maxDiscount = Math.max(
51
- singularFixedDiscount,
52
- singularFixedPriceDiscount,
53
- singularPercentageDiscount,
54
- stackedDiscount,
55
- 0,
56
- )
57
-
58
- // Ensure discount is not more than the total
59
- const amount = Math.min(maxDiscount, total)
60
-
61
- // Return single discount payload
62
- return {
63
- amount, schema: DiscountSchema, currency: 'USD',
64
- }
65
- }
66
-
67
- const calculateSingularFixedPriceDiscount = (total: number, appraisals: HashLeaseEstimate[], coupons: Coupon[], stackable = false): number => {
68
- // Find all singular fixed price discounts
69
- const singularFixedPriceDiscounts = coupons
70
- .filter(isFixedPriceCoupon)
71
- .filter(coupon => stackable ? isStackable(coupon) : !isStackable(coupon))
72
- .map(coupon => (coupon as FixedPriceCoupon).amount)
73
- // Ensure all fixed price discounts are positive
74
- .filter(amount => amount > 0)
75
-
76
- // If there are no singular fixed price discounts, return no discount
77
- if (singularFixedPriceDiscounts.length === 0) return 0
78
-
79
- // Find the maximum discount (the lowest fixed price)
80
- const lowestFixedPrice = Math.min(...singularFixedPriceDiscounts)
81
-
82
- // Apply the fixed price to all appraisals to get the reduced prices
83
- const reducedPrices = appraisals.map(appraisal =>
84
- // If the appraisal price is less than the fixed price
85
- Math.min(appraisal.price, lowestFixedPrice))
86
-
87
- // Calculate the reduced total using the reduced prices
88
- const reducedTotal = reducedPrices.reduce((acc, price) => acc + price, 0)
89
-
90
- // Calculate the discount
91
- const discount = total - reducedTotal
92
-
93
- // Return the discount or 0 if the discount would have resulted in a negative value
94
- return Math.max(discount, 0)
95
- }
@@ -1,72 +0,0 @@
1
- import type { Hash } from '@xylabs/sdk-js'
2
- import type { Payload } from '@xyo-network/payload-model'
3
- import type { Condition, Coupon } from '@xyo-network/payment-payload-plugins'
4
- import { isCondition } from '@xyo-network/payment-payload-plugins'
5
- import type { SchemaPayload } from '@xyo-network/schema-payload-plugin'
6
- import { isSchemaPayload } from '@xyo-network/schema-payload-plugin'
7
- import { PayloadBuilder } from '@xyo-network/sdk-js'
8
- import type { ValidateFunction } from 'ajv'
9
- import { Ajv } from 'ajv'
10
-
11
- // TODO: Use our schema cache
12
- const ajv = new Ajv({ strict: false }) // Create the Ajv instance once
13
- const schemaCache = new Map() // Cache to store compiled validators
14
-
15
- /**
16
- * Validates the conditions of a coupon against the provided payloads
17
- * @param coupon The coupon to check
18
- * @param conditions The conditions associated with the coupon
19
- * @param payloads The associated payloads (containing the conditions and data to validate the conditions against)
20
- * @returns True if all conditions are fulfilled, false otherwise
21
- */
22
- export const areConditionsFulfilled = async (coupon: Coupon, conditions: Condition[] = [], payloads: Payload[] = []): Promise<boolean> =>
23
- (await findUnfulfilledConditions(coupon, conditions, payloads)).length === 0
24
-
25
- /**
26
- * Validates the conditions of a coupon against the provided payloads
27
- * @param coupon The coupon to check
28
- * @param conditions The conditions associated with the coupon
29
- * @param payloads The associated payloads (containing the conditions and data to validate the conditions against)
30
- * @returns The unfulfilled condition hashes
31
- */
32
- export const findUnfulfilledConditions = async (coupon: Coupon, conditions: Condition[] = [], payloads: Payload[] = []): Promise<Hash[]> => {
33
- const unfulfilledConditions: Hash[] = []
34
- // If there are no conditions, then they are fulfilled
35
- if (!coupon.conditions || coupon.conditions.length === 0) return unfulfilledConditions
36
- const hashMap = await PayloadBuilder.toAllHashMap([...conditions, ...payloads])
37
- // Find all the conditions
38
- const foundConditions = coupon.conditions.map(hash => hashMap[hash]).filter(isCondition)
39
- // Not all conditions were found
40
- if (foundConditions.length !== coupon.conditions.length) {
41
- const missing = coupon.conditions.filter(hash => !hashMap[hash])
42
- unfulfilledConditions.push(...missing)
43
- return unfulfilledConditions
44
- }
45
-
46
- // Test each condition
47
- for (const hash of coupon.conditions) {
48
- let validator: ValidateFunction
49
-
50
- // Check if the schema is already cached
51
- if (schemaCache.has(hash)) {
52
- validator = schemaCache.get(hash)
53
- } else {
54
- const payload = hashMap[hash]
55
- const definition = isSchemaPayload(payload) ? (payload as SchemaPayload).definition : undefined
56
- if (definition) {
57
- // Compile and cache the validator
58
- validator = ajv.compile(definition)
59
- schemaCache.set(hash, validator)
60
-
61
- // Validate the payload
62
- } else {
63
- unfulfilledConditions.push(hash)
64
- continue
65
- }
66
- }
67
- if (!validator(payloads)) unfulfilledConditions.push(hash)
68
- }
69
-
70
- // All conditions passed
71
- return unfulfilledConditions
72
- }
@@ -1,2 +0,0 @@
1
- export * from './applyCoupons.ts'
2
- export * from './findUnfulfilledConditions.ts'
@@ -1,40 +0,0 @@
1
- import type { Hash } from '@xylabs/sdk-js'
2
- import type { DivinerInstance } from '@xyo-network/diviner-model'
3
- import type { Payload } from '@xyo-network/payload-model'
4
- import type {
5
- Discount, EscrowTerms, Invoice, Payment,
6
- Subtotal, Total,
7
- } from '@xyo-network/payment-payload-plugins'
8
- import {
9
- isDiscount, isSubtotal, isTotal, PaymentSchema,
10
- } from '@xyo-network/payment-payload-plugins'
11
- import { PayloadBuilder } from '@xyo-network/sdk-js'
12
-
13
- /**
14
- * Validates the escrow terms to ensure they are valid for a purchase
15
- * @returns A payment if the terms are valid for a purchase, undefined otherwise
16
- */
17
- export const getInvoiceForEscrow = async (
18
- terms: EscrowTerms,
19
- dataHashMap: Record<Hash, Payload>,
20
- paymentTotalDiviner: DivinerInstance,
21
- ): Promise<Invoice | undefined> => {
22
- const payloads = Object.values(dataHashMap)
23
- const results = await paymentTotalDiviner.divine([terms, ...payloads])
24
- const subtotal = results.find(isSubtotal) as Subtotal | undefined
25
- const discount = results.find(isDiscount) as Discount | undefined
26
- const total = results.find(isTotal) as Total | undefined
27
- if (!subtotal || !total) return undefined
28
- const { amount, currency } = total
29
- if (currency !== 'USD') return undefined
30
- const $sources = await getSources(terms, subtotal, total, discount)
31
- const payment: Payment = {
32
- amount, currency, schema: PaymentSchema, $sources,
33
- }
34
- return discount ? [subtotal, total, payment, discount] : [subtotal, total, payment]
35
- }
36
-
37
- const getSources = async (terms: EscrowTerms, subtotal: Subtotal, total: Total, discount?: Discount): Promise<Hash[]> => {
38
- const sources = discount ? [terms, subtotal, total, discount] : [terms, subtotal, total]
39
- return await Promise.all(sources.map(p => PayloadBuilder.dataHash(p)))
40
- }
@@ -1 +0,0 @@
1
- export * from './getInvoiceForEscrow.ts'
@@ -1,65 +0,0 @@
1
- import { AbstractDiviner } from '@xyo-network/diviner-abstract'
2
- import { HashLeaseEstimate, isHashLeaseEstimate } from '@xyo-network/diviner-hash-lease'
3
- import { DivinerInstance, DivinerModuleEventData } from '@xyo-network/diviner-model'
4
- import { creatableModule } from '@xyo-network/module-model'
5
- import { Payload } from '@xyo-network/payload-model'
6
- import {
7
- EscrowTerms, isEscrowTerms, PaymentSubtotalDivinerConfigSchema, PaymentSubtotalDivinerParams, Subtotal, SubtotalSchema,
8
- } from '@xyo-network/payment-payload-plugins'
9
- import { PayloadBuilder } from '@xyo-network/sdk-js'
10
-
11
- import {
12
- appraisalValidators, termsValidators, ValidEscrowTerms,
13
- } from './lib/index.ts'
14
-
15
- const currency = 'USD'
16
-
17
- /**
18
- * Escrow terms that contain all the valid fields for calculating a subtotal
19
- */
20
- export type PaymentSubtotalDivinerInputType = EscrowTerms | HashLeaseEstimate | Payload
21
-
22
- @creatableModule()
23
- export class PaymentSubtotalDiviner<
24
- TParams extends PaymentSubtotalDivinerParams = PaymentSubtotalDivinerParams,
25
- TIn extends PaymentSubtotalDivinerInputType = PaymentSubtotalDivinerInputType,
26
- TOut extends Subtotal = Subtotal,
27
- TEventData extends DivinerModuleEventData<DivinerInstance<TParams, TIn, TOut>, TIn, TOut> = DivinerModuleEventData<
28
- DivinerInstance<TParams, TIn, TOut>,
29
- TIn,
30
- TOut
31
- >,
32
- > extends AbstractDiviner<TParams, TIn, TOut, TEventData> {
33
- static override readonly configSchemas = [PaymentSubtotalDivinerConfigSchema]
34
- static override readonly defaultConfigSchema = PaymentSubtotalDivinerConfigSchema
35
-
36
- protected async divineHandler(payloads: TIn[] = []): Promise<TOut[]> {
37
- // Find the escrow terms
38
- const terms = payloads.find(isEscrowTerms) as EscrowTerms | undefined
39
- if (!terms) return []
40
-
41
- // Run all terms validations
42
- if (!termsValidators.every(validator => validator(terms))) return []
43
- const validTerms = terms as ValidEscrowTerms
44
-
45
- // Retrieve all appraisals from terms
46
- const hashMap = await PayloadBuilder.toAllHashMap(payloads)
47
- const appraisals = validTerms.appraisals.map(appraisal => hashMap[appraisal]).filter(isHashLeaseEstimate) as unknown as HashLeaseEstimate[]
48
-
49
- // Ensure all appraisals are present
50
- if (appraisals.length !== validTerms.appraisals.length) return []
51
-
52
- // Run all appraisal validations
53
- if (!appraisalValidators.every(validator => validator(appraisals))) return []
54
- const amount = calculateSubtotal(appraisals)
55
- const $sources = [await PayloadBuilder.dataHash(validTerms), ...validTerms.appraisals]
56
- return [{
57
- amount, currency, schema: SubtotalSchema, $sources,
58
- }] as TOut[]
59
- }
60
- }
61
-
62
- // TODO: Add support for other currencies
63
- const calculateSubtotal = (appraisals: HashLeaseEstimate[]): number => {
64
- return appraisals.reduce((sum, appraisal) => sum + appraisal.price, 0)
65
- }
@@ -1 +0,0 @@
1
- export * from './Diviner.ts'
@@ -1,40 +0,0 @@
1
- import type { HashLeaseEstimate } from '@xyo-network/diviner-hash-lease'
2
- import { isIso4217CurrencyCode } from '@xyo-network/payment-payload-plugins'
3
-
4
- import { validateDuration } from './durationValidators.ts'
5
-
6
- const validateAppraisalAmount = (appraisals: HashLeaseEstimate[]): boolean => {
7
- // Ensure all appraisals are numeric
8
- if (appraisals.some(appraisal => typeof appraisal.price !== 'number')) return false
9
- // Ensure all appraisals are positive numbers
10
- return !(appraisals.some(appraisal => appraisal.price < 0))
11
- }
12
-
13
- const validateAppraisalCurrency = (appraisals: HashLeaseEstimate[]): boolean => {
14
- // Only supporting USD for now, the remaining checks are for future-proofing.
15
- if (!appraisals.every(appraisal => appraisal.currency == 'USD')) return false
16
-
17
- // Check every object in the array to ensure they all are in a supported currency.
18
- return (appraisals.every(appraisal => isIso4217CurrencyCode(appraisal.currency)))
19
- }
20
-
21
- const validateAppraisalConsistentCurrency = (appraisals: HashLeaseEstimate[]): boolean => {
22
- // Check if the array is empty or contains only one element, no need to compare.
23
- if (appraisals.length <= 1) return true
24
-
25
- // Get the currency of the first element to compare with others.
26
- const { currency } = appraisals[0]
27
- if (!currency) return false
28
-
29
- // Check every object in the array to ensure they all have the same currency.
30
- return (appraisals.every(item => item.currency === currency))
31
- }
32
-
33
- const validateAppraisalWindow = (appraisals: HashLeaseEstimate[]): boolean => appraisals.every(validateDuration)
34
-
35
- export const appraisalValidators = [
36
- validateAppraisalAmount,
37
- validateAppraisalCurrency,
38
- validateAppraisalConsistentCurrency,
39
- validateAppraisalWindow,
40
- ]
@@ -1,17 +0,0 @@
1
- import type { DurationFields } from '@xyo-network/xns-record-payload-plugins'
2
-
3
- const FIVE_MINUTES = 1000 * 60 * 5
4
-
5
- /**
6
- * Validates that the current time is within the duration window, within a configurable a buffer
7
- * @param value The duration value
8
- * @param windowMs The window in milliseconds to allow for a buffer
9
- * @returns True if the duration is valid, false otherwise
10
- */
11
- export const validateDuration = (value: Partial<DurationFields>, windowMs = FIVE_MINUTES): boolean => {
12
- const now = Date.now()
13
- if (!value.nbf || value.nbf > now) return false
14
- // If already expired (include for a 5 minute buffer to allow for a reasonable
15
- // minimum amount of time for the transaction to be processed)
16
- return !(!value.exp || value.exp - now < windowMs)
17
- }
@@ -1,2 +0,0 @@
1
- export * from './appraisalValidators.ts'
2
- export * from './termsValidators.ts'
@@ -1,17 +0,0 @@
1
- import type { Hash } from '@xylabs/sdk-js'
2
- import type { EscrowTerms } from '@xyo-network/payment-payload-plugins'
3
-
4
- import { validateDuration } from './durationValidators.ts'
5
-
6
- export type ValidEscrowTerms = Required<EscrowTerms>
7
-
8
- const validateTermsAppraisals = (terms: EscrowTerms): terms is Required<EscrowTerms & { appraisals: Hash[] }> => {
9
- if (!terms.appraisals) return false
10
- return terms.appraisals.length > 0
11
- }
12
- const validateTermsWindow = (terms: EscrowTerms): boolean => validateDuration(terms)
13
-
14
- export const termsValidators = [
15
- validateTermsAppraisals,
16
- validateTermsWindow,
17
- ]
@@ -1,67 +0,0 @@
1
- import { assertEx, Hash } from '@xylabs/sdk-js'
2
- import { AbstractDiviner } from '@xyo-network/diviner-abstract'
3
- import {
4
- asDivinerInstance, DivinerInstance, DivinerModuleEventData,
5
- } from '@xyo-network/diviner-model'
6
- import { creatableModule } from '@xyo-network/module-model'
7
- import {
8
- Discount,
9
- isDiscount,
10
- isSubtotal,
11
- PaymentTotalDivinerConfigSchema, PaymentTotalDivinerParams, Subtotal, Total, TotalSchema,
12
- } from '@xyo-network/payment-payload-plugins'
13
- import { PayloadBuilder } from '@xyo-network/sdk-js'
14
-
15
- import { PaymentDiscountDiviner, PaymentDiscountDivinerInputType } from '../Discount/index.ts'
16
- import { PaymentSubtotalDiviner, PaymentSubtotalDivinerInputType } from '../Subtotal/index.ts'
17
-
18
- type InputType = PaymentDiscountDivinerInputType | PaymentSubtotalDivinerInputType
19
- type OutputType = Subtotal | Discount | Total
20
-
21
- @creatableModule()
22
- export class PaymentTotalDiviner<
23
- TParams extends PaymentTotalDivinerParams = PaymentTotalDivinerParams,
24
- TIn extends InputType = InputType,
25
- TOut extends OutputType = OutputType,
26
- TEventData extends DivinerModuleEventData<DivinerInstance<TParams, TIn, TOut>, TIn, TOut> = DivinerModuleEventData<
27
- DivinerInstance<TParams, TIn, TOut>,
28
- TIn,
29
- TOut
30
- >,
31
- > extends AbstractDiviner<TParams, TIn, TOut, TEventData> {
32
- static override readonly configSchemas = [PaymentTotalDivinerConfigSchema]
33
- static override readonly defaultConfigSchema: PaymentTotalDivinerConfigSchema = PaymentTotalDivinerConfigSchema
34
-
35
- protected async divineHandler(payloads: TIn[] = []): Promise<TOut[]> {
36
- const subtotalDiviner = await this.getPaymentSubtotalDiviner()
37
- const subtotalResult = await subtotalDiviner.divine(payloads)
38
- const subtotal = subtotalResult.find(isSubtotal)
39
- if (!subtotal) return []
40
- const discountDiviner = await this.getPaymentDiscountsDiviner()
41
- const discountResult = await discountDiviner.divine(payloads)
42
- const discount = discountResult.find(isDiscount)
43
- if (!discount) return []
44
- const { currency: subtotalCurrency } = subtotal
45
- const { currency: discountCurrency } = discount
46
- assertEx(subtotalCurrency === discountCurrency, () => `Subtotal currency ${subtotalCurrency} does not match discount currency ${discountCurrency}`)
47
- const amount = Math.max(0, subtotal.amount - discount.amount)
48
- const currency = subtotalCurrency
49
- const $sources = [await PayloadBuilder.dataHash(subtotal), await PayloadBuilder.dataHash(discount)] as Hash[]
50
- const total: Total = {
51
- amount, currency, $sources, schema: TotalSchema,
52
- }
53
- return [subtotal, discount, total] as TOut[]
54
- }
55
-
56
- protected async getPaymentDiscountsDiviner(): Promise<PaymentDiscountDiviner> {
57
- const name = assertEx(this.config.paymentDiscountDiviner, () => 'Missing paymentDiscountDiviner in config')
58
- const mod = assertEx(await this.resolve(name), () => `Error resolving paymentDiscountDiviner: ${name}`)
59
- return assertEx(asDivinerInstance(mod), () => `Resolved module ${mod.address} not a valid Diviner`) as PaymentDiscountDiviner
60
- }
61
-
62
- protected async getPaymentSubtotalDiviner(): Promise<PaymentSubtotalDiviner> {
63
- const name = assertEx(this.config.paymentSubtotalDiviner, () => 'Missing paymentSubtotalDiviner in config')
64
- const mod = assertEx(await this.resolve(name), () => `Error resolving paymentSubtotalDiviner: ${name}`)
65
- return assertEx(asDivinerInstance(mod), () => `Resolved module ${mod.address} not a valid Diviner`) as PaymentSubtotalDiviner
66
- }
67
- }
@@ -1 +0,0 @@
1
- export * from './Diviner.ts'
package/src/index.ts DELETED
@@ -1,4 +0,0 @@
1
- export * from './Discount/index.ts'
2
- export * from './Invoice/index.ts'
3
- export * from './Subtotal/index.ts'
4
- export * from './Total/index.ts'