@atcn/subledger 1.3.0
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.
- package/LICENSE +202 -0
- package/README.md +22 -0
- package/dist/allocation.d.ts +29 -0
- package/dist/allocation.js +69 -0
- package/dist/bridge.d.ts +104 -0
- package/dist/bridge.js +161 -0
- package/dist/documents.d.ts +1877 -0
- package/dist/documents.js +310 -0
- package/dist/exceptions.d.ts +46 -0
- package/dist/exceptions.js +52 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +10 -0
- package/dist/matching.d.ts +12 -0
- package/dist/matching.js +15 -0
- package/dist/projection.d.ts +99 -0
- package/dist/projection.js +218 -0
- package/dist/response.d.ts +24 -0
- package/dist/response.js +34 -0
- package/dist/rollup.d.ts +78 -0
- package/dist/rollup.js +176 -0
- package/dist/types.d.ts +280 -0
- package/dist/types.js +188 -0
- package/dist/verify.d.ts +30 -0
- package/dist/verify.js +372 -0
- package/package.json +40 -0
- package/test-vectors/vectors.json +108 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# @atcn/subledger
|
|
2
|
+
|
|
3
|
+
The ATCN Agent Work Subledger. It records a task's delegations, delivery claims and financial events. Charges are matched to work through stable references, and an event is attributed only when exactly one task or delegation matches. The package also covers:
|
|
4
|
+
|
|
5
|
+
- exceptions for unmatched, ambiguous, duplicate, over-budget and other conditions;
|
|
6
|
+
- roll-up totals;
|
|
7
|
+
- signed task closures and provider receipts;
|
|
8
|
+
- `verifySubledgerDocument`, the offline verifier for those documents.
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm install @atcn/subledger
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { verifySubledgerDocument } from "@atcn/subledger";
|
|
16
|
+
|
|
17
|
+
const report = verifySubledgerDocument(closure, { trustedKeys, obligationPackages });
|
|
18
|
+
if (report.unsupported_schema_version) console.log("upgrade the verifier");
|
|
19
|
+
console.log(report.valid);
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Supported subledger schema versions are `1.2` and `1.3`; see [COMPATIBILITY.md](../schema/COMPATIBILITY.md). Part of [ATCN](../../README.md). Apache-2.0.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { AllocationLine, AllocationTarget } from "./types.js";
|
|
2
|
+
export declare const ROUNDING_METHOD = "largest_remainder";
|
|
3
|
+
export interface Rounding {
|
|
4
|
+
method: typeof ROUNDING_METHOD | "none";
|
|
5
|
+
/** Minor units added to lines after flooring, by line index. Empty when the split was exact. */
|
|
6
|
+
remainder_units: {
|
|
7
|
+
line_index: number;
|
|
8
|
+
units: number;
|
|
9
|
+
}[];
|
|
10
|
+
}
|
|
11
|
+
export interface AllocationResult {
|
|
12
|
+
lines: AllocationLine[];
|
|
13
|
+
rounding: Rounding;
|
|
14
|
+
}
|
|
15
|
+
export declare const UNALLOCATED: AllocationTarget;
|
|
16
|
+
/**
|
|
17
|
+
* Splits an amount by basis-point weights. Each line gets floor(amount * weight / total weight);
|
|
18
|
+
* leftover units go to the largest fractional remainders, ties to the earlier line. Deterministic.
|
|
19
|
+
*/
|
|
20
|
+
export declare function splitByWeights(amountMinor: number, splits: {
|
|
21
|
+
target: AllocationTarget;
|
|
22
|
+
weight_bps: number;
|
|
23
|
+
}[]): AllocationResult;
|
|
24
|
+
/**
|
|
25
|
+
* Validates manual allocation lines against the source amount (acceptance 4).
|
|
26
|
+
* Over-allocation is rejected; any shortfall becomes an explicit unallocated line, so lines always sum to the source.
|
|
27
|
+
*/
|
|
28
|
+
export declare function completeManualAllocation(sourceAmountMinor: number, lines: AllocationLine[]): AllocationResult;
|
|
29
|
+
export declare function allocationSum(lines: AllocationLine[]): number;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
export const ROUNDING_METHOD = "largest_remainder";
|
|
2
|
+
export const UNALLOCATED = { type: "unallocated", id: null };
|
|
3
|
+
/**
|
|
4
|
+
* Splits an amount by basis-point weights. Each line gets floor(amount * weight / total weight);
|
|
5
|
+
* leftover units go to the largest fractional remainders, ties to the earlier line. Deterministic.
|
|
6
|
+
*/
|
|
7
|
+
export function splitByWeights(amountMinor, splits) {
|
|
8
|
+
const totalWeight = splits.reduce((sum, s) => sum + s.weight_bps, 0);
|
|
9
|
+
if (totalWeight !== 10_000)
|
|
10
|
+
throw new Error(`split weights must sum to 10000 bps, got ${totalWeight}`);
|
|
11
|
+
const amount = BigInt(amountMinor);
|
|
12
|
+
const shares = splits.map((s, index) => {
|
|
13
|
+
const exact = amount * BigInt(s.weight_bps);
|
|
14
|
+
return { index, floor: exact / 10000n, remainder: exact % 10000n };
|
|
15
|
+
});
|
|
16
|
+
let leftover = amount - shares.reduce((sum, s) => sum + s.floor, 0n);
|
|
17
|
+
const byRemainder = [...shares].sort((a, b) => (b.remainder === a.remainder ? a.index - b.index : b.remainder > a.remainder ? 1 : -1));
|
|
18
|
+
const extra = new Map();
|
|
19
|
+
for (const share of byRemainder) {
|
|
20
|
+
if (leftover === 0n)
|
|
21
|
+
break;
|
|
22
|
+
extra.set(share.index, 1);
|
|
23
|
+
leftover -= 1n;
|
|
24
|
+
}
|
|
25
|
+
const lines = splits.map((s, index) => ({ target: s.target, amount_minor: Number(shares[index].floor) + (extra.get(index) ?? 0) }));
|
|
26
|
+
const remainder_units = [...extra.entries()].map(([line_index, units]) => ({ line_index, units })).sort((a, b) => a.line_index - b.line_index);
|
|
27
|
+
return { lines, rounding: { method: ROUNDING_METHOD, remainder_units } };
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Validates manual allocation lines against the source amount (acceptance 4).
|
|
31
|
+
* Over-allocation is rejected; any shortfall becomes an explicit unallocated line, so lines always sum to the source.
|
|
32
|
+
*/
|
|
33
|
+
export function completeManualAllocation(sourceAmountMinor, lines) {
|
|
34
|
+
const sum = lines.reduce((total, line) => total + line.amount_minor, 0);
|
|
35
|
+
if (lines.some((line) => line.amount_minor < 0 || !Number.isSafeInteger(line.amount_minor)))
|
|
36
|
+
throw new Error("allocation amounts must be non-negative integers");
|
|
37
|
+
if (sum > sourceAmountMinor)
|
|
38
|
+
throw new Error(`allocation lines sum to ${sum}, more than the source amount ${sourceAmountMinor}`);
|
|
39
|
+
const merged = mergeUnallocated(lines);
|
|
40
|
+
const unallocatedIndex = merged.findIndex((line) => line.target.type === "unallocated");
|
|
41
|
+
const shortfall = sourceAmountMinor - sum;
|
|
42
|
+
if (shortfall > 0) {
|
|
43
|
+
if (unallocatedIndex >= 0)
|
|
44
|
+
merged[unallocatedIndex] = { ...merged[unallocatedIndex], amount_minor: merged[unallocatedIndex].amount_minor + shortfall };
|
|
45
|
+
else
|
|
46
|
+
merged.push({ target: UNALLOCATED, amount_minor: shortfall });
|
|
47
|
+
}
|
|
48
|
+
return { lines: merged, rounding: { method: "none", remainder_units: [] } };
|
|
49
|
+
}
|
|
50
|
+
function mergeUnallocated(lines) {
|
|
51
|
+
const result = [];
|
|
52
|
+
let unallocated = 0;
|
|
53
|
+
let sawUnallocated = false;
|
|
54
|
+
for (const line of lines) {
|
|
55
|
+
if (line.target.type === "unallocated") {
|
|
56
|
+
unallocated += line.amount_minor;
|
|
57
|
+
sawUnallocated = true;
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
result.push({ target: { type: line.target.type, id: line.target.id }, amount_minor: line.amount_minor });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (sawUnallocated)
|
|
64
|
+
result.push({ target: UNALLOCATED, amount_minor: unallocated });
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
export function allocationSum(lines) {
|
|
68
|
+
return lines.reduce((total, line) => total + line.amount_minor, 0);
|
|
69
|
+
}
|
package/dist/bridge.d.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { type ObligationTerms, type PostingBatch, type RecordedEvent, type SettlementEvent } from "@atcn/schema";
|
|
2
|
+
import type { ClaimAsserter, DeliveryEventType, EvidenceRef, FinancialEventInput, FinancialEventRecord } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Bridge from the clearing network's journal to the buyer's subledger. A delegation backed by an obligation
|
|
5
|
+
* receives one financial event per journal fact; the API records them and the offline verifier recomputes them
|
|
6
|
+
* from the obligation's closure package with this same code.
|
|
7
|
+
*/
|
|
8
|
+
/** Source of financial events recorded from the clearing network's journal. */
|
|
9
|
+
export declare const CLEARING_SOURCE: "atcn-clearing";
|
|
10
|
+
export type ClearingFactType = "charge" | "fee" | "payment_reported" | "refund" | "reversal";
|
|
11
|
+
export interface ClearingFact {
|
|
12
|
+
/** The financial event's source_event_id: "<batch_id>:<kind>". */
|
|
13
|
+
key: string;
|
|
14
|
+
type: ClearingFactType;
|
|
15
|
+
amount_minor: number;
|
|
16
|
+
currency: string;
|
|
17
|
+
/** Reversals only: the key of the fact being undone. */
|
|
18
|
+
reverses_key: string | null;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Financial facts of one journal batch, from the payer's side:
|
|
22
|
+
* - clearing: a charge (the payee's share, including child cost and margin) and a platform fee;
|
|
23
|
+
* - settlement: a payment report; refund: a refund;
|
|
24
|
+
* - a reversal of a clearing batch, or a return of a settlement: reversals of the undone batch's facts.
|
|
25
|
+
* Contingent, reserve, and dispute-freeze batches are estimates or holds, not costs, and produce nothing.
|
|
26
|
+
*/
|
|
27
|
+
export declare function clearingFacts(batch: PostingBatch, undone: PostingBatch | null): ClearingFact[];
|
|
28
|
+
/**
|
|
29
|
+
* What backs a settlement report, by the adapter that reported it. ATCN receives every report from the operator,
|
|
30
|
+
* so none is confirmed by the payment provider to ATCN itself: a manual report is the operator's statement, and a
|
|
31
|
+
* Stripe report was checked against Stripe's webhook signature by the operator's own connector before relaying.
|
|
32
|
+
*/
|
|
33
|
+
export declare const SETTLEMENT_REPORT_BASIS: Record<SettlementEvent["provider"], string>;
|
|
34
|
+
/**
|
|
35
|
+
* Evidence for the financial events of a batch posted from a settlement report (settlement, refund, return): the
|
|
36
|
+
* report's ID and digest, labeled with its basis. Null for batches not posted from a settlement report.
|
|
37
|
+
*/
|
|
38
|
+
export declare function settlementEvidence(batch: PostingBatch, settlementEvents: SettlementEvent[]): EvidenceRef | null;
|
|
39
|
+
/**
|
|
40
|
+
* The batch whose facts a reversal or return undoes: the reversed batch, or the settlement batch of the
|
|
41
|
+
* returned instruction. Null for every other batch and when the undone batch is not among the given batches.
|
|
42
|
+
*/
|
|
43
|
+
export declare function undoneBatch(batch: PostingBatch, batches: PostingBatch[], settlementEvents: SettlementEvent[]): PostingBatch | null;
|
|
44
|
+
export declare const CLEARING_FACT_STATUS: Record<ClearingFactType, FinancialEventRecord["normalized_status"]>;
|
|
45
|
+
export interface ClearingFactContext {
|
|
46
|
+
batch: PostingBatch;
|
|
47
|
+
settlementEvents: SettlementEvent[];
|
|
48
|
+
obligationId: string;
|
|
49
|
+
delegationId: string;
|
|
50
|
+
providerId: string | null;
|
|
51
|
+
/** Reversals only: the recorded financial event of the fact being undone. */
|
|
52
|
+
reversesEventId: string | null;
|
|
53
|
+
}
|
|
54
|
+
/** The financial event recorded on the delegation for one clearing fact. Its source key makes retries deduplicate. */
|
|
55
|
+
export declare function clearingFactEvent(fact: ClearingFact, ctx: ClearingFactContext): FinancialEventInput;
|
|
56
|
+
/** Delivery claim recorded for a decision's outcome event. Insufficient evidence and disputed outcomes record none. */
|
|
57
|
+
export declare const CLAIM_BY_OUTCOME_EVENT: Record<string, DeliveryEventType>;
|
|
58
|
+
/** A claim recorded from a network event cites that signed event, which is in the obligation's closure package. */
|
|
59
|
+
export declare function networkEventEvidence(event: RecordedEvent): EvidenceRef[];
|
|
60
|
+
export interface DecisionEventData {
|
|
61
|
+
decision_id: string;
|
|
62
|
+
outcome: string;
|
|
63
|
+
accepted_amount_minor: number;
|
|
64
|
+
policy_version: string;
|
|
65
|
+
decision_maker: {
|
|
66
|
+
type: "automated" | "human";
|
|
67
|
+
id: string;
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Who stands behind a clearing decision, and the claim's note. A policy decision means the evidence the provider
|
|
72
|
+
* submitted met the agreed policy; ATCN parses that evidence but does not re-run checks against the delivered work.
|
|
73
|
+
*/
|
|
74
|
+
export declare function decisionClaim(data: DecisionEventData, policyId: string): {
|
|
75
|
+
asserted_by: ClaimAsserter;
|
|
76
|
+
note: string;
|
|
77
|
+
};
|
|
78
|
+
export interface LinkedObligation {
|
|
79
|
+
obligation_id: string;
|
|
80
|
+
terms: ObligationTerms;
|
|
81
|
+
terms_digest: string;
|
|
82
|
+
}
|
|
83
|
+
/** Delegation fields of an obligation offered for a subledger task, taken from its signed terms. */
|
|
84
|
+
export declare function obligationDelegationFields(ob: LinkedObligation): {
|
|
85
|
+
provider_own_id: string | null;
|
|
86
|
+
provider_job_ref: string;
|
|
87
|
+
shared_description: string;
|
|
88
|
+
currency: string;
|
|
89
|
+
quoted_max_minor: number;
|
|
90
|
+
quote_basis: string;
|
|
91
|
+
quote_valid_until: string;
|
|
92
|
+
terms_digest: string;
|
|
93
|
+
expected_delivery: string;
|
|
94
|
+
downstream_visibility: "unknown" | "none";
|
|
95
|
+
};
|
|
96
|
+
type AcceptedTerms = {
|
|
97
|
+
quoted_max_minor: number | null;
|
|
98
|
+
accepted_amount_minor: number | null;
|
|
99
|
+
terms_digest: string | null;
|
|
100
|
+
expected_delivery: string | null;
|
|
101
|
+
};
|
|
102
|
+
/** Accepted terms that differ from what the delegation records; recorded as a terms_update claim when non-empty. */
|
|
103
|
+
export declare function acceptedTermsChanges(delegation: AcceptedTerms, ob: LinkedObligation): Partial<AcceptedTerms>;
|
|
104
|
+
export {};
|
package/dist/bridge.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { agreedAmount } from "@atcn/core";
|
|
2
|
+
import { digestOf } from "@atcn/schema";
|
|
3
|
+
/**
|
|
4
|
+
* Bridge from the clearing network's journal to the buyer's subledger. A delegation backed by an obligation
|
|
5
|
+
* receives one financial event per journal fact; the API records them and the offline verifier recomputes them
|
|
6
|
+
* from the obligation's closure package with this same code.
|
|
7
|
+
*/
|
|
8
|
+
/** Source of financial events recorded from the clearing network's journal. */
|
|
9
|
+
export const CLEARING_SOURCE = "atcn-clearing";
|
|
10
|
+
const PAYEE_ROLES = ["payee_share", "child_cost", "parent_margin"];
|
|
11
|
+
function credited(lines, match) {
|
|
12
|
+
return lines.filter(match).reduce((sum, line) => sum + line.credit_minor, 0);
|
|
13
|
+
}
|
|
14
|
+
function fact(batch, kind, type, amount) {
|
|
15
|
+
return amount > 0 ? [{ key: `${batch.batch_id}:${kind}`, type, amount_minor: amount, currency: batch.lines[0].currency, reverses_key: null }] : [];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Financial facts of one journal batch, from the payer's side:
|
|
19
|
+
* - clearing: a charge (the payee's share, including child cost and margin) and a platform fee;
|
|
20
|
+
* - settlement: a payment report; refund: a refund;
|
|
21
|
+
* - a reversal of a clearing batch, or a return of a settlement: reversals of the undone batch's facts.
|
|
22
|
+
* Contingent, reserve, and dispute-freeze batches are estimates or holds, not costs, and produce nothing.
|
|
23
|
+
*/
|
|
24
|
+
export function clearingFacts(batch, undone) {
|
|
25
|
+
switch (batch.entry_type) {
|
|
26
|
+
case "clearing":
|
|
27
|
+
return [
|
|
28
|
+
...fact(batch, "charge", "charge", credited(batch.lines, (l) => l.account_type === "payable" && PAYEE_ROLES.includes(l.allocation_role))),
|
|
29
|
+
...fact(batch, "fee", "fee", credited(batch.lines, (l) => l.account_type === "platform_fee")),
|
|
30
|
+
];
|
|
31
|
+
case "settlement":
|
|
32
|
+
return fact(batch, "payment", "payment_reported", credited(batch.lines, (l) => l.account_type === "settlement_reported"));
|
|
33
|
+
case "refund":
|
|
34
|
+
return fact(batch, "refund", "refund", credited(batch.lines, (l) => l.account_type === "refund"));
|
|
35
|
+
case "reversal":
|
|
36
|
+
case "return": {
|
|
37
|
+
if (!undone)
|
|
38
|
+
return [];
|
|
39
|
+
return clearingFacts(undone, null).map((f) => ({
|
|
40
|
+
key: `${batch.batch_id}:${f.key.slice(f.key.indexOf(":") + 1)}`,
|
|
41
|
+
type: "reversal",
|
|
42
|
+
amount_minor: f.amount_minor,
|
|
43
|
+
currency: f.currency,
|
|
44
|
+
reverses_key: f.key,
|
|
45
|
+
}));
|
|
46
|
+
}
|
|
47
|
+
default:
|
|
48
|
+
return [];
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* What backs a settlement report, by the adapter that reported it. ATCN receives every report from the operator,
|
|
53
|
+
* so none is confirmed by the payment provider to ATCN itself: a manual report is the operator's statement, and a
|
|
54
|
+
* Stripe report was checked against Stripe's webhook signature by the operator's own connector before relaying.
|
|
55
|
+
*/
|
|
56
|
+
export const SETTLEMENT_REPORT_BASIS = {
|
|
57
|
+
manual: "settlement_reported_by_operator",
|
|
58
|
+
stripe: "settlement_relayed_from_stripe_by_operator_connector",
|
|
59
|
+
sandbox: "settlement_simulated_in_sandbox",
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Evidence for the financial events of a batch posted from a settlement report (settlement, refund, return): the
|
|
63
|
+
* report's ID and digest, labeled with its basis. Null for batches not posted from a settlement report.
|
|
64
|
+
*/
|
|
65
|
+
export function settlementEvidence(batch, settlementEvents) {
|
|
66
|
+
const event = settlementEvents.find((e) => e.settlement_event_id === batch.settlement_event_id);
|
|
67
|
+
if (!event)
|
|
68
|
+
return null;
|
|
69
|
+
return { uri: `urn:atcn:settlement-event:${event.settlement_event_id}`, digest: digestOf(event), evidence_type: SETTLEMENT_REPORT_BASIS[event.provider] };
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The batch whose facts a reversal or return undoes: the reversed batch, or the settlement batch of the
|
|
73
|
+
* returned instruction. Null for every other batch and when the undone batch is not among the given batches.
|
|
74
|
+
*/
|
|
75
|
+
export function undoneBatch(batch, batches, settlementEvents) {
|
|
76
|
+
if (batch.entry_type === "reversal")
|
|
77
|
+
return batches.find((b) => b.batch_id === batch.reverses_batch_id) ?? null;
|
|
78
|
+
if (batch.entry_type !== "return")
|
|
79
|
+
return null;
|
|
80
|
+
const instructionId = settlementEvents.find((e) => e.settlement_event_id === batch.settlement_event_id)?.instruction_id;
|
|
81
|
+
if (!instructionId)
|
|
82
|
+
return null;
|
|
83
|
+
const settled = new Set(settlementEvents.filter((e) => e.instruction_id === instructionId && e.normalized_status === "settled").map((e) => e.settlement_event_id));
|
|
84
|
+
return batches.find((b) => b.entry_type === "settlement" && b.settlement_event_id !== null && settled.has(b.settlement_event_id)) ?? null;
|
|
85
|
+
}
|
|
86
|
+
export const CLEARING_FACT_STATUS = {
|
|
87
|
+
charge: "issued",
|
|
88
|
+
fee: "issued",
|
|
89
|
+
payment_reported: "reported_paid",
|
|
90
|
+
refund: "refunded",
|
|
91
|
+
reversal: "reversed",
|
|
92
|
+
};
|
|
93
|
+
/** The financial event recorded on the delegation for one clearing fact. Its source key makes retries deduplicate. */
|
|
94
|
+
export function clearingFactEvent(fact, ctx) {
|
|
95
|
+
const settlement = ctx.settlementEvents.find((e) => e.settlement_event_id === ctx.batch.settlement_event_id) ?? null;
|
|
96
|
+
return {
|
|
97
|
+
type: fact.type,
|
|
98
|
+
source: CLEARING_SOURCE,
|
|
99
|
+
source_event_id: fact.key,
|
|
100
|
+
provider_id: ctx.providerId,
|
|
101
|
+
provider_reference: settlement?.provider_reference ?? ctx.obligationId,
|
|
102
|
+
amount_minor: fact.amount_minor,
|
|
103
|
+
currency: fact.currency,
|
|
104
|
+
event_date: ctx.batch.posted_at,
|
|
105
|
+
provider_status: settlement?.provider_status ?? null,
|
|
106
|
+
normalized_status: CLEARING_FACT_STATUS[fact.type],
|
|
107
|
+
evidence: settlementEvidence(ctx.batch, ctx.settlementEvents),
|
|
108
|
+
reverses_event_id: ctx.reversesEventId,
|
|
109
|
+
reason: fact.type === "reversal" ? `clearing-network ${ctx.batch.entry_type} batch ${ctx.batch.batch_id}` : null,
|
|
110
|
+
match: { delegation_id: ctx.delegationId },
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/** Delivery claim recorded for a decision's outcome event. Insufficient evidence and disputed outcomes record none. */
|
|
114
|
+
export const CLAIM_BY_OUTCOME_EVENT = {
|
|
115
|
+
"completion.accepted": "completion",
|
|
116
|
+
"completion.partially_accepted": "partial_completion",
|
|
117
|
+
"completion.rejected": "provider_failure",
|
|
118
|
+
};
|
|
119
|
+
/** A claim recorded from a network event cites that signed event, which is in the obligation's closure package. */
|
|
120
|
+
export function networkEventEvidence(event) {
|
|
121
|
+
return [{ uri: `urn:atcn:event:${event.payload.event_id}`, digest: event.payload_hash, evidence_type: "atcn_signed_event" }];
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Who stands behind a clearing decision, and the claim's note. A policy decision means the evidence the provider
|
|
125
|
+
* submitted met the agreed policy; ATCN parses that evidence but does not re-run checks against the delivered work.
|
|
126
|
+
*/
|
|
127
|
+
export function decisionClaim(data, policyId) {
|
|
128
|
+
const result = `${data.outcome}, accepted ${data.accepted_amount_minor} (${data.decision_id})`;
|
|
129
|
+
if (data.decision_maker.type === "human")
|
|
130
|
+
return { asserted_by: "dispute_reviewer", note: `decided by dispute reviewer ${data.decision_maker.id}: ${result}` };
|
|
131
|
+
return {
|
|
132
|
+
asserted_by: "clearing_policy",
|
|
133
|
+
note: `decided by policy ${policyId}@${data.policy_version} from the provider's submitted evidence: ${result}. ATCN did not re-run checks against the delivered work.`,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
const isoMs = (value) => new Date(value).toISOString();
|
|
137
|
+
/** Delegation fields of an obligation offered for a subledger task, taken from its signed terms. */
|
|
138
|
+
export function obligationDelegationFields(ob) {
|
|
139
|
+
return {
|
|
140
|
+
provider_own_id: ob.terms.counterparty_agent_id,
|
|
141
|
+
provider_job_ref: ob.obligation_id,
|
|
142
|
+
shared_description: ob.terms.scope.description.slice(0, 1000),
|
|
143
|
+
currency: ob.terms.currency,
|
|
144
|
+
quoted_max_minor: ob.terms.max_amount_minor,
|
|
145
|
+
quote_basis: `ATCN obligation terms version ${ob.terms.terms_version}`,
|
|
146
|
+
quote_valid_until: isoMs(ob.terms.offer_expires_at),
|
|
147
|
+
terms_digest: ob.terms_digest,
|
|
148
|
+
expected_delivery: isoMs(ob.terms.deadline),
|
|
149
|
+
downstream_visibility: ob.terms.allow_subdelegation ? "unknown" : "none",
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/** Accepted terms that differ from what the delegation records; recorded as a terms_update claim when non-empty. */
|
|
153
|
+
export function acceptedTermsChanges(delegation, ob) {
|
|
154
|
+
const accepted = {
|
|
155
|
+
quoted_max_minor: ob.terms.max_amount_minor,
|
|
156
|
+
accepted_amount_minor: agreedAmount(ob.terms),
|
|
157
|
+
terms_digest: ob.terms_digest,
|
|
158
|
+
expected_delivery: isoMs(ob.terms.deadline),
|
|
159
|
+
};
|
|
160
|
+
return Object.fromEntries(Object.entries(accepted).filter(([key, value]) => delegation[key] !== value));
|
|
161
|
+
}
|