@fintekkers/ledger-models 1.1.32 → 1.1.33

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.
@@ -0,0 +1,25 @@
1
+ import { TransactionProto } from '../../../fintekkers/models/transaction/transaction_pb';
2
+ import { FieldViolationProto } from '../../../fintekkers/requests/util/errors/field_violation_pb';
3
+ /**
4
+ * Transaction input rules: JS counterpart of Java's TransactionRules
5
+ * (docs/adr/typed-input-errors.md). Pure: proto in, violations out.
6
+ *
7
+ * The security rules run on an inline security, with field paths prefixed
8
+ * `security.`. Child structure (LM-438) is checked at every level of
9
+ * child_transactions: at most one cash child, and no two children with the
10
+ * same UUID. Each violation is on `child_transactions[i]` (nested:
11
+ * `child_transactions[1].child_transactions[0]`) and its object_id is the
12
+ * UUID of the transaction that owns the list. A child with no UUID, or an
13
+ * empty one, is never a duplicate. A child whose security is a link is not
14
+ * counted as cash: hydrate it first. The Transaction wrapper does not call
15
+ * these rules, so stored rows that break them still load; writers call
16
+ * `validate` / `requireValid` before sending.
17
+ */
18
+ export declare const SECURITY_PREFIX = "security.";
19
+ export declare const CHILD_TRANSACTIONS = "child_transactions";
20
+ export declare const SECOND_CASH_CHILD = "second cash child";
21
+ export declare const DUPLICATE_CHILD_ID = "duplicate child id";
22
+ /** Returns every field-level violation on this transaction, or an empty array when it is valid. */
23
+ export declare function validate(proto: TransactionProto): FieldViolationProto[];
24
+ /** Throws ModelValidationError carrying every violation if `validate` finds any. */
25
+ export declare function requireValid(proto: TransactionProto): void;
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.requireValid = exports.validate = exports.DUPLICATE_CHILD_ID = exports.SECOND_CASH_CHILD = exports.CHILD_TRANSACTIONS = exports.SECURITY_PREFIX = void 0;
4
+ const product_type_pb_1 = require("../../../fintekkers/models/security/product_type_pb");
5
+ const errors_1 = require("../errors");
6
+ const security_rules_1 = require("../security/security_rules");
7
+ const uuid_1 = require("../utils/uuid");
8
+ /**
9
+ * Transaction input rules: JS counterpart of Java's TransactionRules
10
+ * (docs/adr/typed-input-errors.md). Pure: proto in, violations out.
11
+ *
12
+ * The security rules run on an inline security, with field paths prefixed
13
+ * `security.`. Child structure (LM-438) is checked at every level of
14
+ * child_transactions: at most one cash child, and no two children with the
15
+ * same UUID. Each violation is on `child_transactions[i]` (nested:
16
+ * `child_transactions[1].child_transactions[0]`) and its object_id is the
17
+ * UUID of the transaction that owns the list. A child with no UUID, or an
18
+ * empty one, is never a duplicate. A child whose security is a link is not
19
+ * counted as cash: hydrate it first. The Transaction wrapper does not call
20
+ * these rules, so stored rows that break them still load; writers call
21
+ * `validate` / `requireValid` before sending.
22
+ */
23
+ exports.SECURITY_PREFIX = 'security.';
24
+ exports.CHILD_TRANSACTIONS = 'child_transactions';
25
+ exports.SECOND_CASH_CHILD = 'second cash child';
26
+ exports.DUPLICATE_CHILD_ID = 'duplicate child id';
27
+ /** Returns every field-level violation on this transaction, or an empty array when it is valid. */
28
+ function validate(proto) {
29
+ const out = [];
30
+ const security = proto.getSecurity();
31
+ if (security) {
32
+ for (const v of (0, security_rules_1.validate)(security)) {
33
+ const prefixed = v.cloneMessage();
34
+ prefixed.setField(exports.SECURITY_PREFIX + v.getField());
35
+ out.push(prefixed);
36
+ }
37
+ }
38
+ addChildViolations(proto, '', out);
39
+ return out;
40
+ }
41
+ exports.validate = validate;
42
+ /** Throws ModelValidationError carrying every violation if `validate` finds any. */
43
+ function requireValid(proto) {
44
+ const violations = validate(proto);
45
+ if (violations.length > 0)
46
+ throw new errors_1.ModelValidationError(violations);
47
+ }
48
+ exports.requireValid = requireValid;
49
+ function addChildViolations(parent, prefix, out) {
50
+ const parentId = idOf(parent);
51
+ let seenCash = false;
52
+ let firstCashId;
53
+ const seenIds = new Set();
54
+ parent.getChildtransactionsList().forEach((child, i) => {
55
+ const field = `${prefix}${exports.CHILD_TRANSACTIONS}[${i}]`;
56
+ const childId = idOf(child);
57
+ if (isCash(child)) {
58
+ if (seenCash) {
59
+ out.push((0, errors_1.violation)(field, parentId, `${exports.SECOND_CASH_CHILD}: transaction ${display(parentId)} already has cash child `
60
+ + `${display(firstCashId)}; ${display(childId)} is a second one`));
61
+ }
62
+ else {
63
+ seenCash = true;
64
+ firstCashId = childId;
65
+ }
66
+ }
67
+ if (childId) {
68
+ const key = childId.toString();
69
+ if (seenIds.has(key)) {
70
+ out.push((0, errors_1.violation)(field, parentId, `${exports.DUPLICATE_CHILD_ID}: transaction ${display(parentId)} already has a child with id ${key}`));
71
+ }
72
+ seenIds.add(key);
73
+ }
74
+ addChildViolations(child, `${field}.`, out);
75
+ });
76
+ }
77
+ /** Same test as Java Security.isCash() on an inline security; a link is not cash. */
78
+ function isCash(child) {
79
+ const security = child.getSecurity();
80
+ if (!security || security.getIsLink())
81
+ return false;
82
+ return security.getProductType() === product_type_pb_1.ProductTypeProto.CURRENCY || security.hasCashDetails();
83
+ }
84
+ /** The transaction's UUID, or undefined when it has none or it is not 16 bytes. */
85
+ function idOf(proto) {
86
+ var _a;
87
+ const raw = (_a = proto.getUuid()) === null || _a === void 0 ? void 0 : _a.getRawUuid_asU8();
88
+ return raw && raw.length === 16 ? uuid_1.UUID.fromU8Array(raw) : undefined;
89
+ }
90
+ function display(id) {
91
+ return id ? id.toString() : 'null';
92
+ }
93
+ //# sourceMappingURL=transaction_rules.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transaction_rules.js","sourceRoot":"","sources":["transaction_rules.ts"],"names":[],"mappings":";;;AAAA,yFAAuF;AAGvF,sCAA4D;AAC5D,+DAA0E;AAC1E,wCAAqC;AAErC;;;;;;;;;;;;;;GAcG;AAEU,QAAA,eAAe,GAAG,WAAW,CAAC;AAC9B,QAAA,kBAAkB,GAAG,oBAAoB,CAAC;AAC1C,QAAA,iBAAiB,GAAG,mBAAmB,CAAC;AACxC,QAAA,kBAAkB,GAAG,oBAAoB,CAAC;AAEvD,mGAAmG;AACnG,SAAgB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G,IAAI,GAAG,CAAC,MAAM,KAAK,EAAE,CAAC,CAAC,CAAC,WAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACxE,CAAC;AAED,SAAS,OAAO,CAAC,EAAoB;IACjC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC;AACvC,CAAC"}
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ // LM-438: transaction child-structure rules. The same fixture
3
+ // (test-fixtures/transaction-children/cases.json) runs in Java, Python and Rust.
4
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
+ if (k2 === undefined) k2 = k;
6
+ var desc = Object.getOwnPropertyDescriptor(m, k);
7
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
+ desc = { enumerable: true, get: function() { return m[k]; } };
9
+ }
10
+ Object.defineProperty(o, k2, desc);
11
+ }) : (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ o[k2] = m[k];
14
+ }));
15
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
17
+ }) : function(o, v) {
18
+ o["default"] = v;
19
+ });
20
+ var __importStar = (this && this.__importStar) || function (mod) {
21
+ if (mod && mod.__esModule) return mod;
22
+ var result = {};
23
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
24
+ __setModuleDefault(result, mod);
25
+ return result;
26
+ };
27
+ Object.defineProperty(exports, "__esModule", { value: true });
28
+ const fs = __importStar(require("fs"));
29
+ const path = __importStar(require("path"));
30
+ const product_type_pb_1 = require("../../../fintekkers/models/security/product_type_pb");
31
+ const security_pb_1 = require("../../../fintekkers/models/security/security_pb");
32
+ const transaction_pb_1 = require("../../../fintekkers/models/transaction/transaction_pb");
33
+ const transaction_type_pb_1 = require("../../../fintekkers/models/transaction/transaction_type_pb");
34
+ const uuid_pb_1 = require("../../../fintekkers/models/util/uuid_pb");
35
+ const errors_1 = require("../errors");
36
+ const uuid_1 = require("../utils/uuid");
37
+ const transaction_rules_1 = require("./transaction_rules");
38
+ const FIXTURE = path.resolve(__dirname, '../../../../../test-fixtures/transaction-children/cases.json');
39
+ const CASES = JSON.parse(fs.readFileSync(FIXTURE, 'utf-8')).cases;
40
+ const byName = (name) => CASES.find(c => c.name === name);
41
+ function uuid(s) {
42
+ return s === '' ? new uuid_pb_1.UUIDProto().setRawUuid(new Uint8Array()) : new uuid_1.UUID(uuid_1.UUID.fromString(s)).toUUIDProto();
43
+ }
44
+ function security(s) {
45
+ const p = new security_pb_1.SecurityProto().setUuid(uuid(s.uuid));
46
+ if (s.link)
47
+ return p.setIsLink(true);
48
+ if (s.product_type)
49
+ p.setProductType(product_type_pb_1.ProductTypeProto[s.product_type]);
50
+ if (s.cash_details)
51
+ p.setCashDetails(new security_pb_1.CashDetailsProto());
52
+ return p;
53
+ }
54
+ function node(n) {
55
+ var _a;
56
+ const p = new transaction_pb_1.TransactionProto()
57
+ .setTransactionType(transaction_type_pb_1.TransactionTypeProto[n.transaction_type])
58
+ .setSecurity(security(n.security));
59
+ if (n.uuid !== undefined)
60
+ p.setUuid(uuid(n.uuid));
61
+ for (const c of (_a = n.children) !== null && _a !== void 0 ? _a : [])
62
+ p.addChildtransactions(node(c));
63
+ return p;
64
+ }
65
+ describe('transaction_rules.validate', () => {
66
+ test('fixture has the six cases', () => {
67
+ expect(CASES.map(c => c.name).sort()).toEqual([
68
+ 'children_without_uuid', 'duplicate_child_ids', 'maturation_with_two_cash',
69
+ 'two_cash_children', 'valid_buy', 'valid_sell',
70
+ ]);
71
+ });
72
+ test.each(CASES.map(c => c.name))('%s matches the shared fixture', name => {
73
+ const c = byName(name);
74
+ const actual = (0, transaction_rules_1.validate)(node(c.transaction));
75
+ expect(actual.map(v => v.getField())).toEqual(c.violations.map(v => v.field));
76
+ c.violations.forEach((want, i) => {
77
+ var _a;
78
+ const got = actual[i];
79
+ expect((_a = uuid_1.UUID.fromUUIDProto(got.getObjectId())) === null || _a === void 0 ? void 0 : _a.toString()).toBe(want.object_id);
80
+ for (const id of want.message_ids)
81
+ expect(got.getMessage()).toContain(id);
82
+ });
83
+ });
84
+ test('children_without_uuid has an unset and an empty-raw_uuid child', () => {
85
+ const children = node(byName('children_without_uuid').transaction).getChildtransactionsList();
86
+ expect(children[0].hasUuid()).toBe(false);
87
+ expect(children[2].hasUuid()).toBe(true);
88
+ expect(children[2].getUuid().getRawUuid_asU8().length).toBe(0);
89
+ });
90
+ test('requireValid throws ModelValidationError on two cash children', () => {
91
+ const p = node(byName('two_cash_children').transaction);
92
+ expect(() => (0, transaction_rules_1.requireValid)(p)).toThrow(errors_1.ModelValidationError);
93
+ try {
94
+ (0, transaction_rules_1.requireValid)(p);
95
+ }
96
+ catch (e) {
97
+ expect(e.field).toBe('child_transactions[1]');
98
+ expect(e.violations[0].getMessage().startsWith(transaction_rules_1.SECOND_CASH_CHILD)).toBe(true);
99
+ }
100
+ });
101
+ });
102
+ //# sourceMappingURL=transaction_rules.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transaction_rules.test.js","sourceRoot":"","sources":["transaction_rules.test.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,iFAAiF;;;;;;;;;;;;;;;;;;;;;;;;;AAEjF,uCAAyB;AACzB,2CAA6B;AAC7B,yFAAuF;AACvF,iFAAkG;AAClG,0FAAyF;AACzF,oGAAkG;AAClG,qEAAoE;AACpE,sCAAiD;AACjD,wCAAqC;AACrC,2DAAgF;AAOhF,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,8DAA8D,CAAC,CAAC;AACxG,MAAM,KAAK,GAAW,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC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AC,CAAC,UAAU,EAAE,CAAC,UAAU,CAAC,qCAAiB,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;SAC3G;IACL,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"}
@@ -0,0 +1,81 @@
1
+ // LM-438: transaction child-structure rules. The same fixture
2
+ // (test-fixtures/transaction-children/cases.json) runs in Java, Python and Rust.
3
+
4
+ import * as fs from 'fs';
5
+ import * as path from 'path';
6
+ import { ProductTypeProto } from '../../../fintekkers/models/security/product_type_pb';
7
+ import { CashDetailsProto, SecurityProto } from '../../../fintekkers/models/security/security_pb';
8
+ import { TransactionProto } from '../../../fintekkers/models/transaction/transaction_pb';
9
+ import { TransactionTypeProto } from '../../../fintekkers/models/transaction/transaction_type_pb';
10
+ import { UUIDProto } from '../../../fintekkers/models/util/uuid_pb';
11
+ import { ModelValidationError } from '../errors';
12
+ import { UUID } from '../utils/uuid';
13
+ import { requireValid, SECOND_CASH_CHILD, validate } from './transaction_rules';
14
+
15
+ interface SecuritySpec { uuid: string; link?: boolean; product_type?: string; cash_details?: boolean }
16
+ interface Node { uuid?: string; transaction_type: string; security: SecuritySpec; children?: Node[] }
17
+ interface Violation { field: string; object_id: string; message_ids: string[] }
18
+ interface Case { name: string; transaction: Node; violations: Violation[] }
19
+
20
+ const FIXTURE = path.resolve(__dirname, '../../../../../test-fixtures/transaction-children/cases.json');
21
+ const CASES: Case[] = JSON.parse(fs.readFileSync(FIXTURE, 'utf-8')).cases;
22
+ const byName = (name: string): Case => CASES.find(c => c.name === name)!;
23
+
24
+ function uuid(s: string): UUIDProto {
25
+ return s === '' ? new UUIDProto().setRawUuid(new Uint8Array()) : new UUID(UUID.fromString(s)).toUUIDProto();
26
+ }
27
+
28
+ function security(s: SecuritySpec): SecurityProto {
29
+ const p = new SecurityProto().setUuid(uuid(s.uuid));
30
+ if (s.link) return p.setIsLink(true);
31
+ if (s.product_type) p.setProductType(ProductTypeProto[s.product_type as keyof typeof ProductTypeProto]);
32
+ if (s.cash_details) p.setCashDetails(new CashDetailsProto());
33
+ return p;
34
+ }
35
+
36
+ function node(n: Node): TransactionProto {
37
+ const p = new TransactionProto()
38
+ .setTransactionType(TransactionTypeProto[n.transaction_type as keyof typeof TransactionTypeProto])
39
+ .setSecurity(security(n.security));
40
+ if (n.uuid !== undefined) p.setUuid(uuid(n.uuid));
41
+ for (const c of n.children ?? []) p.addChildtransactions(node(c));
42
+ return p;
43
+ }
44
+
45
+ describe('transaction_rules.validate', () => {
46
+ test('fixture has the six cases', () => {
47
+ expect(CASES.map(c => c.name).sort()).toEqual([
48
+ 'children_without_uuid', 'duplicate_child_ids', 'maturation_with_two_cash',
49
+ 'two_cash_children', 'valid_buy', 'valid_sell',
50
+ ]);
51
+ });
52
+
53
+ test.each(CASES.map(c => c.name))('%s matches the shared fixture', name => {
54
+ const c = byName(name);
55
+ const actual = validate(node(c.transaction));
56
+ expect(actual.map(v => v.getField())).toEqual(c.violations.map(v => v.field));
57
+ c.violations.forEach((want, i) => {
58
+ const got = actual[i];
59
+ expect(UUID.fromUUIDProto(got.getObjectId())?.toString()).toBe(want.object_id);
60
+ for (const id of want.message_ids) expect(got.getMessage()).toContain(id);
61
+ });
62
+ });
63
+
64
+ test('children_without_uuid has an unset and an empty-raw_uuid child', () => {
65
+ const children = node(byName('children_without_uuid').transaction).getChildtransactionsList();
66
+ expect(children[0].hasUuid()).toBe(false);
67
+ expect(children[2].hasUuid()).toBe(true);
68
+ expect(children[2].getUuid()!.getRawUuid_asU8().length).toBe(0);
69
+ });
70
+
71
+ test('requireValid throws ModelValidationError on two cash children', () => {
72
+ const p = node(byName('two_cash_children').transaction);
73
+ expect(() => requireValid(p)).toThrow(ModelValidationError);
74
+ try {
75
+ requireValid(p);
76
+ } catch (e) {
77
+ expect((e as ModelValidationError).field).toBe('child_transactions[1]');
78
+ expect((e as ModelValidationError).violations[0].getMessage().startsWith(SECOND_CASH_CHILD)).toBe(true);
79
+ }
80
+ });
81
+ });
@@ -0,0 +1,95 @@
1
+ import { ProductTypeProto } from '../../../fintekkers/models/security/product_type_pb';
2
+ import { TransactionProto } from '../../../fintekkers/models/transaction/transaction_pb';
3
+ import { FieldViolationProto } from '../../../fintekkers/requests/util/errors/field_violation_pb';
4
+ import { ModelValidationError, violation } from '../errors';
5
+ import { validate as validateSecurity } from '../security/security_rules';
6
+ import { UUID } from '../utils/uuid';
7
+
8
+ /**
9
+ * Transaction input rules: JS counterpart of Java's TransactionRules
10
+ * (docs/adr/typed-input-errors.md). Pure: proto in, violations out.
11
+ *
12
+ * The security rules run on an inline security, with field paths prefixed
13
+ * `security.`. Child structure (LM-438) is checked at every level of
14
+ * child_transactions: at most one cash child, and no two children with the
15
+ * same UUID. Each violation is on `child_transactions[i]` (nested:
16
+ * `child_transactions[1].child_transactions[0]`) and its object_id is the
17
+ * UUID of the transaction that owns the list. A child with no UUID, or an
18
+ * empty one, is never a duplicate. A child whose security is a link is not
19
+ * counted as cash: hydrate it first. The Transaction wrapper does not call
20
+ * these rules, so stored rows that break them still load; writers call
21
+ * `validate` / `requireValid` before sending.
22
+ */
23
+
24
+ export const SECURITY_PREFIX = 'security.';
25
+ export const CHILD_TRANSACTIONS = 'child_transactions';
26
+ export const SECOND_CASH_CHILD = 'second cash child';
27
+ export const DUPLICATE_CHILD_ID = 'duplicate child id';
28
+
29
+ /** Returns every field-level violation on this transaction, or an empty array when it is valid. */
30
+ export function validate(proto: TransactionProto): FieldViolationProto[] {
31
+ const out: FieldViolationProto[] = [];
32
+ const security = proto.getSecurity();
33
+ if (security) {
34
+ for (const v of validateSecurity(security)) {
35
+ const prefixed = v.cloneMessage();
36
+ prefixed.setField(SECURITY_PREFIX + v.getField());
37
+ out.push(prefixed);
38
+ }
39
+ }
40
+ addChildViolations(proto, '', out);
41
+ return out;
42
+ }
43
+
44
+ /** Throws ModelValidationError carrying every violation if `validate` finds any. */
45
+ export function requireValid(proto: TransactionProto): void {
46
+ const violations = validate(proto);
47
+ if (violations.length > 0) throw new ModelValidationError(violations);
48
+ }
49
+
50
+ function addChildViolations(parent: TransactionProto, prefix: string, out: FieldViolationProto[]): void {
51
+ const parentId = idOf(parent);
52
+ let seenCash = false;
53
+ let firstCashId: UUID | undefined;
54
+ const seenIds = new Set<string>();
55
+ parent.getChildtransactionsList().forEach((child, i) => {
56
+ const field = `${prefix}${CHILD_TRANSACTIONS}[${i}]`;
57
+ const childId = idOf(child);
58
+ if (isCash(child)) {
59
+ if (seenCash) {
60
+ out.push(violation(field, parentId,
61
+ `${SECOND_CASH_CHILD}: transaction ${display(parentId)} already has cash child `
62
+ + `${display(firstCashId)}; ${display(childId)} is a second one`));
63
+ } else {
64
+ seenCash = true;
65
+ firstCashId = childId;
66
+ }
67
+ }
68
+ if (childId) {
69
+ const key = childId.toString();
70
+ if (seenIds.has(key)) {
71
+ out.push(violation(field, parentId,
72
+ `${DUPLICATE_CHILD_ID}: transaction ${display(parentId)} already has a child with id ${key}`));
73
+ }
74
+ seenIds.add(key);
75
+ }
76
+ addChildViolations(child, `${field}.`, out);
77
+ });
78
+ }
79
+
80
+ /** Same test as Java Security.isCash() on an inline security; a link is not cash. */
81
+ function isCash(child: TransactionProto): boolean {
82
+ const security = child.getSecurity();
83
+ if (!security || security.getIsLink()) return false;
84
+ return security.getProductType() === ProductTypeProto.CURRENCY || security.hasCashDetails();
85
+ }
86
+
87
+ /** The transaction's UUID, or undefined when it has none or it is not 16 bytes. */
88
+ function idOf(proto: TransactionProto): UUID | undefined {
89
+ const raw = proto.getUuid()?.getRawUuid_asU8();
90
+ return raw && raw.length === 16 ? UUID.fromU8Array(raw) : undefined;
91
+ }
92
+
93
+ function display(id: UUID | undefined): string {
94
+ return id ? id.toString() : 'null';
95
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@fintekkers/ledger-models",
3
3
  "todo": "Replace the version with build script version number",
4
- "version": "1.1.32",
4
+ "version": "1.1.33",
5
5
  "description": "ledger model protos ",
6
6
  "authors": [
7
7
  "David Doherty",