@ottochain/sdk 2.3.0 → 2.4.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.
Files changed (209) hide show
  1. package/dist/cjs/apps/contracts/index.js +15 -8
  2. package/dist/cjs/apps/contracts/state-machines/contract-agreement.js +35 -40
  3. package/dist/cjs/apps/contracts/state-machines/contract-escrow.js +80 -37
  4. package/dist/cjs/apps/contracts/state-machines/contract-universal.js +4 -4
  5. package/dist/cjs/apps/corporate/index.js +2 -2
  6. package/dist/cjs/apps/corporate/state-machines/corp-board.js +169 -59
  7. package/dist/cjs/apps/corporate/state-machines/corp-entity.js +245 -47
  8. package/dist/cjs/apps/corporate/state-machines/corp-securities.js +407 -99
  9. package/dist/cjs/apps/corporate/state-machines/corp-shareholders.js +151 -37
  10. package/dist/cjs/apps/governance/index.js +14 -14
  11. package/dist/cjs/apps/governance/state-machines/dao-multisig.js +58 -40
  12. package/dist/cjs/apps/governance/state-machines/dao-reputation.js +46 -40
  13. package/dist/cjs/apps/governance/state-machines/dao-single.js +28 -11
  14. package/dist/cjs/apps/governance/state-machines/dao-token.js +67 -41
  15. package/dist/cjs/apps/governance/state-machines/governance-simple.js +93 -61
  16. package/dist/cjs/apps/governance/state-machines/governance-universal.js +2 -2
  17. package/dist/cjs/apps/identity/constants.js +55 -14
  18. package/dist/cjs/apps/identity/index.js +27 -11
  19. package/dist/cjs/apps/identity/state-machines/identity-agent.js +3 -3
  20. package/dist/cjs/apps/identity/state-machines/identity-oracle.js +25 -22
  21. package/dist/cjs/apps/identity/state-machines/identity-registry.js +288 -0
  22. package/dist/cjs/apps/identity/state-machines/identity-universal.js +3 -3
  23. package/dist/cjs/apps/identity/state-machines/index.js +3 -1
  24. package/dist/cjs/apps/index.js +19 -8
  25. package/dist/cjs/apps/lending/assets.js +223 -0
  26. package/dist/cjs/apps/lending/credit-scoring.js +87 -0
  27. package/dist/cjs/apps/lending/eligibility.js +121 -0
  28. package/dist/cjs/apps/lending/index.js +91 -0
  29. package/dist/cjs/apps/lending/state-machines/index.js +9 -0
  30. package/dist/cjs/apps/lending/state-machines/lending-zk-loan.js +412 -0
  31. package/dist/cjs/apps/markets/index.js +21 -11
  32. package/dist/cjs/apps/markets/state-machines/market-auction.js +14 -13
  33. package/dist/cjs/apps/markets/state-machines/market-crowdfund.js +29 -24
  34. package/dist/cjs/apps/markets/state-machines/market-group-buy.js +24 -26
  35. package/dist/cjs/apps/markets/state-machines/market-prediction.js +80 -53
  36. package/dist/cjs/apps/markets/state-machines/market-universal.js +5 -5
  37. package/dist/cjs/apps/oracles/index.js +2 -2
  38. package/dist/cjs/errors.js +3 -3
  39. package/dist/cjs/generated/google/protobuf/struct.js +4 -4
  40. package/dist/cjs/generated/index.js +11 -7
  41. package/dist/cjs/generated/openapi.js +6 -0
  42. package/dist/cjs/generated/ottochain/apps/contracts/v1/contract.js +50 -50
  43. package/dist/cjs/generated/ottochain/apps/corporate/v1/corporate.js +19 -20
  44. package/dist/cjs/generated/ottochain/apps/governance/v1/governance.js +13 -13
  45. package/dist/cjs/generated/ottochain/apps/identity/v1/attestation.js +4 -4
  46. package/dist/cjs/generated/ottochain/apps/identity/v1/identity.js +124 -130
  47. package/dist/cjs/generated/ottochain/apps/markets/v1/market.js +107 -107
  48. package/dist/cjs/generated/ottochain/v1/common.js +4 -4
  49. package/dist/cjs/generated/ottochain/v1/fiber.js +4 -4
  50. package/dist/cjs/index.js +41 -7
  51. package/dist/cjs/openapi.js +2 -0
  52. package/dist/cjs/ottochain/drop-nulls.js +1 -2
  53. package/dist/cjs/ottochain/genesis-manifest.js +11 -11
  54. package/dist/cjs/ottochain/index.js +23 -13
  55. package/dist/cjs/ottochain/metagraph-client.js +65 -8
  56. package/dist/cjs/ottochain/snapshot.js +11 -12
  57. package/dist/cjs/ottochain/transaction.js +57 -14
  58. package/dist/cjs/ottochain/types.js +16 -2
  59. package/dist/cjs/privacy/index.js +14 -0
  60. package/dist/cjs/privacy/sealed-bid.js +210 -0
  61. package/dist/cjs/privacy/shield-app.js +131 -0
  62. package/dist/cjs/schema/effects.js +40 -0
  63. package/dist/cjs/schema/fiber-app.js +19 -13
  64. package/dist/cjs/schema/guard-lint.js +352 -0
  65. package/dist/cjs/schema/guards.js +246 -0
  66. package/dist/cjs/signing.js +80 -0
  67. package/dist/cjs/types.js +2 -3
  68. package/dist/cjs/validation.js +8 -8
  69. package/dist/cjs/verify.js +9 -4
  70. package/dist/cjs/zk/commit.js +53 -0
  71. package/dist/cjs/zk/guard.js +107 -0
  72. package/dist/cjs/zk/index.js +48 -0
  73. package/dist/cjs/zk/preimage.js +37 -0
  74. package/dist/cjs/zk/prover.js +87 -0
  75. package/dist/cjs/zk/registry.js +62 -0
  76. package/dist/cjs/zk/types.js +28 -0
  77. package/dist/cjs/zk/witness.js +19 -0
  78. package/dist/esm/apps/contracts/index.js +7 -3
  79. package/dist/esm/apps/contracts/state-machines/contract-agreement.js +35 -40
  80. package/dist/esm/apps/contracts/state-machines/contract-escrow.js +80 -37
  81. package/dist/esm/apps/contracts/state-machines/contract-universal.js +4 -4
  82. package/dist/esm/apps/corporate/state-machines/corp-board.js +169 -59
  83. package/dist/esm/apps/corporate/state-machines/corp-entity.js +245 -47
  84. package/dist/esm/apps/corporate/state-machines/corp-securities.js +407 -99
  85. package/dist/esm/apps/corporate/state-machines/corp-shareholders.js +151 -37
  86. package/dist/esm/apps/governance/state-machines/dao-multisig.js +58 -40
  87. package/dist/esm/apps/governance/state-machines/dao-reputation.js +46 -40
  88. package/dist/esm/apps/governance/state-machines/dao-single.js +28 -11
  89. package/dist/esm/apps/governance/state-machines/dao-token.js +67 -41
  90. package/dist/esm/apps/governance/state-machines/governance-simple.js +93 -61
  91. package/dist/esm/apps/governance/state-machines/governance-universal.js +2 -2
  92. package/dist/esm/apps/identity/constants.js +51 -12
  93. package/dist/esm/apps/identity/index.js +12 -7
  94. package/dist/esm/apps/identity/state-machines/identity-agent.js +3 -3
  95. package/dist/esm/apps/identity/state-machines/identity-oracle.js +25 -22
  96. package/dist/esm/apps/identity/state-machines/identity-registry.js +285 -0
  97. package/dist/esm/apps/identity/state-machines/identity-universal.js +3 -3
  98. package/dist/esm/apps/identity/state-machines/index.js +1 -0
  99. package/dist/esm/apps/index.js +1 -0
  100. package/dist/esm/apps/lending/assets.js +207 -0
  101. package/dist/esm/apps/lending/credit-scoring.js +81 -0
  102. package/dist/esm/apps/lending/eligibility.js +115 -0
  103. package/dist/esm/apps/lending/index.js +69 -0
  104. package/dist/esm/apps/lending/state-machines/index.js +5 -0
  105. package/dist/esm/apps/lending/state-machines/lending-zk-loan.js +409 -0
  106. package/dist/esm/apps/markets/index.js +8 -4
  107. package/dist/esm/apps/markets/state-machines/market-auction.js +14 -13
  108. package/dist/esm/apps/markets/state-machines/market-crowdfund.js +29 -24
  109. package/dist/esm/apps/markets/state-machines/market-group-buy.js +24 -26
  110. package/dist/esm/apps/markets/state-machines/market-prediction.js +80 -53
  111. package/dist/esm/apps/markets/state-machines/market-universal.js +5 -5
  112. package/dist/esm/generated/index.js +9 -5
  113. package/dist/esm/generated/openapi.js +5 -0
  114. package/dist/esm/generated/ottochain/apps/contracts/v1/contract.js +46 -46
  115. package/dist/esm/generated/ottochain/apps/identity/v1/identity.js +114 -120
  116. package/dist/esm/generated/ottochain/apps/markets/v1/market.js +100 -100
  117. package/dist/esm/index.js +21 -2
  118. package/dist/esm/openapi.js +1 -0
  119. package/dist/esm/ottochain/genesis-manifest.js +9 -9
  120. package/dist/esm/ottochain/index.js +2 -3
  121. package/dist/esm/ottochain/metagraph-client.js +65 -8
  122. package/dist/esm/ottochain/snapshot.js +4 -4
  123. package/dist/esm/ottochain/transaction.js +43 -3
  124. package/dist/esm/ottochain/types.js +15 -1
  125. package/dist/esm/privacy/index.js +6 -0
  126. package/dist/esm/privacy/sealed-bid.js +206 -0
  127. package/dist/esm/privacy/shield-app.js +127 -0
  128. package/dist/esm/schema/effects.js +35 -0
  129. package/dist/esm/schema/fiber-app.js +13 -6
  130. package/dist/esm/schema/guard-lint.js +346 -0
  131. package/dist/esm/schema/guards.js +229 -0
  132. package/dist/esm/signing.js +74 -0
  133. package/dist/esm/verify.js +8 -2
  134. package/dist/esm/zk/commit.js +44 -0
  135. package/dist/esm/zk/guard.js +99 -0
  136. package/dist/esm/zk/index.js +19 -0
  137. package/dist/esm/zk/preimage.js +30 -0
  138. package/dist/esm/zk/prover.js +82 -0
  139. package/dist/esm/zk/registry.js +55 -0
  140. package/dist/esm/zk/types.js +25 -0
  141. package/dist/esm/zk/witness.js +15 -0
  142. package/dist/types/apps/contracts/index.d.ts +69 -209
  143. package/dist/types/apps/contracts/state-machines/contract-agreement.d.ts +20 -95
  144. package/dist/types/apps/contracts/state-machines/contract-escrow.d.ts +46 -112
  145. package/dist/types/apps/corporate/index.d.ts +1040 -304
  146. package/dist/types/apps/corporate/state-machines/corp-board.d.ts +188 -52
  147. package/dist/types/apps/corporate/state-machines/corp-entity.d.ts +267 -62
  148. package/dist/types/apps/corporate/state-machines/corp-securities.d.ts +355 -131
  149. package/dist/types/apps/corporate/state-machines/corp-shareholders.d.ts +225 -53
  150. package/dist/types/apps/governance/index.d.ts +296 -398
  151. package/dist/types/apps/governance/state-machines/dao-multisig.d.ts +77 -92
  152. package/dist/types/apps/governance/state-machines/dao-reputation.d.ts +42 -66
  153. package/dist/types/apps/governance/state-machines/dao-single.d.ts +25 -47
  154. package/dist/types/apps/governance/state-machines/dao-token.d.ts +60 -49
  155. package/dist/types/apps/governance/state-machines/governance-simple.d.ts +87 -117
  156. package/dist/types/apps/governance/state-machines/governance-universal.d.ts +2 -2
  157. package/dist/types/apps/identity/constants.d.ts +32 -4
  158. package/dist/types/apps/identity/index.d.ts +378 -94
  159. package/dist/types/apps/identity/state-machines/identity-oracle.d.ts +16 -87
  160. package/dist/types/apps/identity/state-machines/identity-registry.d.ts +379 -0
  161. package/dist/types/apps/identity/state-machines/index.d.ts +1 -0
  162. package/dist/types/apps/index.d.ts +1 -0
  163. package/dist/types/apps/lending/assets.d.ts +258 -0
  164. package/dist/types/apps/lending/credit-scoring.d.ts +80 -0
  165. package/dist/types/apps/lending/eligibility.d.ts +83 -0
  166. package/dist/types/apps/lending/index.d.ts +548 -0
  167. package/dist/types/apps/lending/state-machines/index.d.ts +5 -0
  168. package/dist/types/apps/lending/state-machines/lending-zk-loan.d.ts +528 -0
  169. package/dist/types/apps/markets/index.d.ts +108 -203
  170. package/dist/types/apps/markets/state-machines/market-auction.d.ts +13 -37
  171. package/dist/types/apps/markets/state-machines/market-crowdfund.d.ts +16 -34
  172. package/dist/types/apps/markets/state-machines/market-group-buy.d.ts +17 -43
  173. package/dist/types/apps/markets/state-machines/market-prediction.d.ts +51 -72
  174. package/dist/types/apps/markets/state-machines/market-universal.d.ts +5 -5
  175. package/dist/types/generated/index.d.ts +5 -5
  176. package/dist/types/generated/openapi.d.ts +1257 -0
  177. package/dist/types/generated/ottochain/apps/contracts/v1/contract.d.ts +5 -5
  178. package/dist/types/generated/ottochain/apps/identity/v1/identity.d.ts +12 -12
  179. package/dist/types/generated/ottochain/apps/markets/v1/market.d.ts +11 -11
  180. package/dist/types/index.d.ts +6 -2
  181. package/dist/types/openapi.d.ts +22 -0
  182. package/dist/types/ottochain/genesis-manifest.d.ts +5 -5
  183. package/dist/types/ottochain/index.d.ts +5 -6
  184. package/dist/types/ottochain/metagraph-client.d.ts +49 -7
  185. package/dist/types/ottochain/snapshot.d.ts +6 -6
  186. package/dist/types/ottochain/transaction.d.ts +33 -1
  187. package/dist/types/ottochain/types.d.ts +335 -30
  188. package/dist/types/privacy/index.d.ts +6 -0
  189. package/dist/types/privacy/sealed-bid.d.ts +348 -0
  190. package/dist/types/privacy/shield-app.d.ts +48 -0
  191. package/dist/types/schema/effects.d.ts +34 -0
  192. package/dist/types/schema/fiber-app.d.ts +1 -2
  193. package/dist/types/schema/guard-lint.d.ts +111 -0
  194. package/dist/types/schema/guards.d.ts +134 -0
  195. package/dist/types/signing.d.ts +45 -0
  196. package/dist/types/validation.d.ts +22 -217
  197. package/dist/types/verify.d.ts +4 -0
  198. package/dist/types/zk/commit.d.ts +28 -0
  199. package/dist/types/zk/guard.d.ts +46 -0
  200. package/dist/types/zk/index.d.ts +19 -0
  201. package/dist/types/zk/preimage.d.ts +10 -0
  202. package/dist/types/zk/prover.d.ts +34 -0
  203. package/dist/types/zk/registry.d.ts +34 -0
  204. package/dist/types/zk/types.d.ts +33 -0
  205. package/dist/types/zk/witness.d.ts +40 -0
  206. package/package.json +27 -13
  207. package/dist/cjs/ottochain/normalize.js +0 -186
  208. package/dist/esm/ottochain/normalize.js +0 -179
  209. package/dist/types/ottochain/normalize.d.ts +0 -79
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Asset-subsystem integration for the lending family.
3
+ *
4
+ * The loan's collateral, principal/debt, and repayment are ASSETS. This module provides
5
+ * typed payload builders for the OttoChain asset operations and loan-specific helpers that
6
+ * map the zk-loan lifecycle onto typed asset morphisms.
7
+ *
8
+ * Wire shapes mirror the asset-model proposal
9
+ * (`/home/euler/repos/ottochain/docs/proposals/asset-model.md` §7 — `CreateAssetPolicy`,
10
+ * `MintAsset`, `ApplyMorphism`, `AuthorizeCompose`; §8 — Governed/ZkVerify-gated morphisms)
11
+ * and follow the SDK's existing single-key-wrapper convention (the discriminator is the outer
12
+ * key, e.g. `{ MintAsset: {...} }`), matching `src/ottochain/transaction.ts`
13
+ * (`createTransitionPayload`, `createScriptPayload`, ...). The asset op-codes are not yet a
14
+ * merged TypeScript SDK surface; these builders let the lending app construct the proposed
15
+ * wire format today and sign it with the existing `signTransaction` path.
16
+ *
17
+ * Amounts are `Long` on-chain; modeled here as `number` for SDK ergonomics (callers may pass a
18
+ * string for values beyond 2^53 — the field is serialized verbatim).
19
+ */
20
+ /** Helpers for the two-variant holder. */
21
+ export const walletHolder = (address) => ({ Wallet: { address } });
22
+ export const fiberHolder = (fiberId) => ({ Fiber: { fiberId } });
23
+ /** Pack a {@link TokenBehavior} to its 5-bit integer (T=16 S=8 C=4 E=2 G=1). */
24
+ export function behaviorBits(b) {
25
+ return ((b.transferable ? 16 : 0) |
26
+ (b.splittable ? 8 : 0) |
27
+ (b.combinable ? 4 : 0) |
28
+ (b.expirable ? 2 : 0) |
29
+ (b.governable ? 1 : 0));
30
+ }
31
+ /** Common behavior presets (asset-model.md §2). */
32
+ export const TokenBehaviors = {
33
+ /** Non-transferable, non-divisible (bits 0). */
34
+ Soulbound: { transferable: false, splittable: false, combinable: false, expirable: false, governable: false },
35
+ /** Transferable only (bits 16). */
36
+ NFT: { transferable: true, splittable: false, combinable: false, expirable: false, governable: false },
37
+ /** Transferable + splittable + combinable (bits 28 = TSC). */
38
+ Fungible: { transferable: true, splittable: true, combinable: true, expirable: false, governable: false },
39
+ /** Fungible + governable (bits 29 = TSCG) — the default for a gated debt token. */
40
+ GovernedFungible: { transferable: true, splittable: true, combinable: true, expirable: false, governable: true },
41
+ };
42
+ /** Publish an asset policy package version. asset-model.md §7. */
43
+ export function createAssetPolicyPayload(params) {
44
+ return {
45
+ CreateAssetPolicy: {
46
+ name: params.name,
47
+ version: params.version,
48
+ behavior: params.behavior,
49
+ supply: params.supply,
50
+ morphisms: params.morphisms,
51
+ stateShape: params.stateShape,
52
+ ...(params.metadata ? { metadata: params.metadata } : {}),
53
+ },
54
+ };
55
+ }
56
+ /**
57
+ * Mint an asset instance. asset-model.md §7. When the policy's `mintPolicy` is a
58
+ * `groth16_verify` guard (proof-gated mint), pass the eligibility `witness`.
59
+ */
60
+ export function createMintAssetPayload(params) {
61
+ return {
62
+ MintAsset: {
63
+ assetId: params.assetId,
64
+ policyRef: params.policyRef,
65
+ holder: params.holder,
66
+ amount: params.amount,
67
+ ...(params.expiresAt !== undefined ? { expiresAt: params.expiresAt } : {}),
68
+ ...(params.witness ? { witness: params.witness } : {}),
69
+ },
70
+ };
71
+ }
72
+ /**
73
+ * Apply a typed morphism (Transfer / Burn / Compose / ...). asset-model.md §7.
74
+ * Transfer = `{ kind: "Transfer", recipient }`; Burn (repay) = `{ kind: "Burn" }`.
75
+ */
76
+ export function createApplyMorphismPayload(params) {
77
+ return {
78
+ ApplyMorphism: {
79
+ assetId: params.assetId,
80
+ kind: params.kind,
81
+ targetSequenceNumber: params.targetSequenceNumber,
82
+ ...(params.recipient ? { recipient: params.recipient } : {}),
83
+ ...(params.otherAssets ? { otherAssets: params.otherAssets } : {}),
84
+ ...(params.compositeId ? { compositeId: params.compositeId } : {}),
85
+ ...(params.shardIds ? { shardIds: params.shardIds } : {}),
86
+ ...(params.nonce !== undefined ? { nonce: params.nonce } : {}),
87
+ ...(params.witness ? { witness: params.witness } : {}),
88
+ },
89
+ };
90
+ }
91
+ /** Commit half of a two-party compose. asset-model.md §7/§8. */
92
+ export function createAuthorizeComposePayload(params) {
93
+ return {
94
+ AuthorizeCompose: {
95
+ assetId: params.assetId,
96
+ partnerPolicy: params.partnerPolicy,
97
+ nonce: params.nonce,
98
+ expiresAt: params.expiresAt,
99
+ targetSequenceNumber: params.targetSequenceNumber,
100
+ },
101
+ };
102
+ }
103
+ // ---------------------------------------------------------------------------
104
+ // Loan-specific asset policy builders
105
+ // ---------------------------------------------------------------------------
106
+ /**
107
+ * The collateral vault policy: an NFT-like custodial holding (no fungible split) whose
108
+ * `Transfer` morphism is Governed — the loan/escrow fiber is the authorization. Locking is
109
+ * a custody Transfer into `AssetHolder.Fiber(escrow)`; release/liquidation is a Transfer out
110
+ * driven by the loan fiber's REPAID / LIQUIDATED transition (`_transferAsset`).
111
+ */
112
+ export function collateralPolicy(name = "collateral-vault-v1.asset", version = "1.0.0") {
113
+ return {
114
+ name,
115
+ version,
116
+ behavior: { transferable: true, splittable: false, combinable: false, expirable: false, governable: true },
117
+ supply: { maxSupply: null, mintPolicy: null, burnPolicy: null, decimals: 0 },
118
+ morphisms: {
119
+ Transfer: { visibility: "Governed" },
120
+ Burn: { visibility: "Disabled" },
121
+ Compose: { visibility: "Disabled" },
122
+ },
123
+ stateShape: {},
124
+ metadata: { family: "lending", role: "collateral" },
125
+ };
126
+ }
127
+ /**
128
+ * The loan-debt / principal policy: a governed fungible whose `mintPolicy` is the
129
+ * proof-gated origination guard — the principal is mintable to the borrower only when the
130
+ * eligibility proof verifies. Repayment is a `Burn` governed by `burnPolicy`.
131
+ *
132
+ * @param mintGuard the origination guard (see `buildOriginationGuard`) — a `groth16_verify`
133
+ * expression bound to the pinned public lending rule.
134
+ */
135
+ export function debtPolicy(mintGuard, name = "loan-debt-v1.asset", version = "1.0.0") {
136
+ return {
137
+ name,
138
+ version,
139
+ behavior: TokenBehaviors.GovernedFungible,
140
+ supply: {
141
+ maxSupply: null,
142
+ // Proof-gated mint: principal is minted only if the eligibility proof verifies.
143
+ mintPolicy: mintGuard,
144
+ // Repayment burns the debt; only the holder (borrower) may burn theirs. The asset context has
145
+ // no `event` key — bind to the verified `signers` (chain-derived from the op's proofs).
146
+ burnPolicy: { in: [{ var: "holder.Wallet.address" }, { var: "signers" }] },
147
+ decimals: 2,
148
+ },
149
+ morphisms: {
150
+ Transfer: { visibility: "Public" },
151
+ Burn: { visibility: "Public" },
152
+ },
153
+ stateShape: {},
154
+ metadata: { family: "lending", role: "debt" },
155
+ };
156
+ }
157
+ // ---------------------------------------------------------------------------
158
+ // Loan lifecycle → asset morphism drivers
159
+ // ---------------------------------------------------------------------------
160
+ /**
161
+ * lock_collateral: custody Transfer of the pledged collateral into the loan escrow fiber.
162
+ * (asset-model.md §10 — locking is a custody transfer to `AssetHolder.Fiber`, there is no
163
+ * `Lock` morphism.)
164
+ */
165
+ export function lockCollateralOp(args) {
166
+ return createApplyMorphismPayload({
167
+ assetId: args.collateralAssetId,
168
+ kind: "Transfer",
169
+ recipient: fiberHolder(args.escrowFiberId),
170
+ targetSequenceNumber: args.targetSequenceNumber,
171
+ });
172
+ }
173
+ /**
174
+ * originate: Mint the loan principal/debt to the borrower. The policy's `mintPolicy`
175
+ * (the origination guard) reads the eligibility `witness` ({publicValues, proof}).
176
+ */
177
+ export function mintPrincipalOp(args) {
178
+ return createMintAssetPayload({
179
+ assetId: args.debtAssetId,
180
+ policyRef: args.debtPolicyRef,
181
+ holder: walletHolder(args.borrower),
182
+ amount: args.principalAmount,
183
+ witness: args.witness,
184
+ });
185
+ }
186
+ /** repay: Burn the borrower's debt token (the principal is repaid). */
187
+ export function repayBurnOp(args) {
188
+ return createApplyMorphismPayload({
189
+ assetId: args.debtAssetId,
190
+ kind: "Burn",
191
+ targetSequenceNumber: args.targetSequenceNumber,
192
+ });
193
+ }
194
+ /**
195
+ * release / liquidate: Transfer the escrowed collateral out of the escrow fiber to a
196
+ * recipient (the borrower on REPAID, the lender on LIQUIDATED). On-chain this is emitted by
197
+ * the loan fiber's transition via `_transferAsset`; this builder produces the equivalent
198
+ * explicit `ApplyMorphism(Transfer)` for off-fiber/manual settlement.
199
+ */
200
+ export function settleCollateralOp(args) {
201
+ return createApplyMorphismPayload({
202
+ assetId: args.collateralAssetId,
203
+ kind: "Transfer",
204
+ recipient: walletHolder(args.recipient),
205
+ targetSequenceNumber: args.targetSequenceNumber,
206
+ });
207
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Credit scoring via the identity + reputation app.
3
+ *
4
+ * A zk-loan's `creditScore` is NOT a self-asserted number — it is the borrower's on-chain identity
5
+ * REPUTATION, derived from their {@link Attestation} deltas (the identity app's reputation model:
6
+ * `baseReputation + Σ delta`, floored at `minReputation`). This module is the wire between the two
7
+ * apps: it computes the reputation-backed score, pins a lending rule that BINDS the score to a
8
+ * specific borrower identity (so a borrower cannot prove eligibility against someone else's
9
+ * reputation), and assembles the PRIVATE data context the borrower proves it over.
10
+ *
11
+ * Privacy boundary: the exact `creditScore` and `collateralValue` stay private (their keccak is the
12
+ * proof's `dataHash`); the `subject` (borrower identity) and the bounds are PUBLIC (pinned in the
13
+ * rule's `logicHash`). The zk proof attests "borrower X's reputation-backed score ≥ floor and
14
+ * collateral coverage ≥ ratio" without revealing the score or the holdings.
15
+ *
16
+ * Trust model: the proof binds the score to the borrower's identity, but the borrower supplies the
17
+ * score value. When reputation attestations are PUBLIC on-chain, a verifier can independently
18
+ * recompute the score and check the proof used it; when reputation is PRIVATE (off-chain / held
19
+ * credentials) the score is genuinely hidden. To make the score AUTHORITY-attested in zero knowledge
20
+ * (the strongest form), have the SP1 rule additionally `schnorr_verify` the reputation issuer's
21
+ * signature over `(subject, score)` — see {@link reputationAuthorityClause}.
22
+ */
23
+ import { DEFAULT_REPUTATION_CONFIG, } from "../identity/index.js";
24
+ import { lendingRule } from "./eligibility.js";
25
+ /**
26
+ * Derive an agent's credit score from their identity reputation attestations:
27
+ * `baseReputation + Σ attestation.delta`, floored at `minReputation`. This IS the integration point —
28
+ * a zk-loan's creditScore is the borrower's identity reputation, not an independent number.
29
+ */
30
+ export function reputationScore(attestations, config = DEFAULT_REPUTATION_CONFIG) {
31
+ const raw = attestations.reduce((sum, a) => sum + (a.delta ?? 0), config.baseReputation);
32
+ return Math.max(config.minReputation, raw);
33
+ }
34
+ /**
35
+ * The PUBLIC reputation-credit lending rule. Extends {@link lendingRule} (collateral coverage +
36
+ * optional credit-score floor) with a SUBJECT binding `subject === borrowerId`, so the proven score
37
+ * belongs to a specific identity — a borrower cannot prove eligibility against another agent's
38
+ * reputation. `borrowerId` and all bounds are literals, so pinning the rule pins them.
39
+ */
40
+ export function reputationCreditRule(params) {
41
+ const base = lendingRule(params); // coverage, or {and:[coverage, creditScore floor]}
42
+ const subjectBound = { "===": [{ var: "subject" }, params.borrowerId] };
43
+ const clauses = "and" in base ? base.and : [base];
44
+ return { and: [...clauses, subjectBound] };
45
+ }
46
+ /**
47
+ * Assemble the PRIVATE data context the borrower feeds to the zk-jlvm prover: the `creditScore` is
48
+ * their identity {@link reputationScore}, the `subject` is their identity. Only its keccak (`dataHash`)
49
+ * becomes public.
50
+ */
51
+ export function buildCreditDataContext(args) {
52
+ return {
53
+ collateralValue: args.collateralValue,
54
+ creditScore: reputationScore(args.attestations, args.config ?? DEFAULT_REPUTATION_CONFIG),
55
+ subject: args.borrowerId,
56
+ };
57
+ }
58
+ /**
59
+ * OPTIONAL hardening — an authority-attested credit clause. ANDed into a rule, it makes the SP1 guest
60
+ * verify (in zero knowledge) the reputation issuer's Schnorr signature over the score, so the score is
61
+ * not merely borrower-supplied but ATTESTED.
62
+ *
63
+ * SECURITY: the authority's `authorityPubKey` MUST be a LITERAL pinned in the rule (it is part of the
64
+ * rule's keccak `logicHash`, so pinning it binds it) — NEVER read from the borrower's witness/private
65
+ * data, or the borrower could supply their own keypair and self-attest any score. Only the signature
66
+ * `repSig` and the signed `scoreCommit` ride on the (private) witness; the signature binds them to the
67
+ * pinned key. `scoreCommit` should commit the pinned `subject` + the proof's `dataHash` so a signature
68
+ * cannot be replayed for a different borrower/score.
69
+ *
70
+ * NOTE: producing a real signature + proof is required to exercise this end-to-end; the builder pins
71
+ * the structure so the on-chain rule and the prover agree. See the JLVM `schnorr_verify` opcode.
72
+ */
73
+ export function reputationAuthorityClause(authorityPubKey) {
74
+ return {
75
+ schnorr_verify: [
76
+ authorityPubKey, // the reputation authority's public key — PINNED literal, not witness-supplied
77
+ { var: "scoreCommit" }, // the signed message: a commitment over (subject, creditScore)
78
+ { var: "repSig" }, // the authority's signature over scoreCommit
79
+ ],
80
+ };
81
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * The eligibility-proof model for the zk-loan: pin a PUBLIC lending rule, build the
3
+ * semi-private origination guard that gates it, and construct the witness the guard reads.
4
+ *
5
+ * The borrower proves in zero-knowledge that their PRIVATE financials satisfy the PUBLIC
6
+ * lending rule — without revealing them. The rule (with its literal bounds) is canonicalized
7
+ * and keccak-hashed into a `logicHash`; the proof commits that same `exprHash`, so binding
8
+ * `exprHash == logicHash` pins exactly WHICH rule was proven. See `src/zk` and
9
+ * `/home/euler/repos/ottochain/docs/proposals/asset-model.md` §8 (ZkVerify-gated morphisms).
10
+ */
11
+ import { exprHash, KECCAK_TRUE } from "../../zk/index.js";
12
+ /**
13
+ * The PUBLIC lending rule, as a JSON-Logic predicate over the borrower's PRIVATE data context
14
+ * `{ collateralValue, creditScore }`. Evaluates to `true` iff the borrower is eligible:
15
+ *
16
+ * collateralValue * 100 >= loanAmount * collateralRatioPct (collateral coverage)
17
+ * AND creditScore >= minCreditScore (if a floor is set)
18
+ *
19
+ * Only the predicate and its literal bounds are public; the data it is evaluated over
20
+ * (`collateralValue`, `creditScore`) is the prover's private witness — its keccak is the
21
+ * proof's `dataHash`, never revealed. This is the rule the zk-jlvm guest runs; its `exprHash`
22
+ * is pinned as the loan's `lendingRuleLogicHash`.
23
+ */
24
+ export function lendingRule(params) {
25
+ const coverage = {
26
+ ">=": [
27
+ { "*": [{ var: "collateralValue" }, 100] },
28
+ params.loanAmount * params.collateralRatioPct,
29
+ ],
30
+ };
31
+ if (params.minCreditScore === undefined) {
32
+ return coverage;
33
+ }
34
+ return {
35
+ and: [
36
+ coverage,
37
+ { ">=": [{ var: "creditScore" }, params.minCreditScore] },
38
+ ],
39
+ };
40
+ }
41
+ /**
42
+ * Pin a lending rule: produce the public rule plus the three constants the loan's origination
43
+ * guard binds against. `vkey` is the verifying key of the SP1 zk-jlvm program that runs the
44
+ * rule (supplied by the lender / deployment).
45
+ */
46
+ export function pinLendingRule(params, vkey) {
47
+ const rule = lendingRule(params);
48
+ return {
49
+ rule,
50
+ logicHash: exprHash(rule),
51
+ keccakTrue: KECCAK_TRUE,
52
+ vkey,
53
+ };
54
+ }
55
+ /**
56
+ * Build the semi-private ORIGINATION guard expression.
57
+ *
58
+ * It verifies the SP1-Groth16 eligibility proof AND binds its committed public values to the
59
+ * pinned public rule. `publicValues = abi_encode(JlvmPublicValues{exprHash|dataHash|outputHash|ok})`
60
+ * is opaque to `groth16_verify`; the guard slices the `0x`-hex form with native JLVM `substr`
61
+ * (start, len) and re-`cat`s the `0x` prefix — there is no `jlvm_pv_decode` opcode. Clauses:
62
+ *
63
+ * 1. `groth16_verify(vkey, witness.publicValues, witness.proof)` — the proof is valid
64
+ * 2. `exprHash == logicHash` (word 0, hex chars [2,66)) — it proved THE pinned rule
65
+ * 3. `outputHash == keccakTrue` (word 2, hex chars [130,194)) — the rule evaluated to true
66
+ * 4. `ok == "01"` (word 3 final pair, [256,258)) — the JLVM run did not error
67
+ *
68
+ * This is the closed boolean an asset `mintPolicy` or a fiber-transition guard wraps. The
69
+ * lending state machine ANDs clause 0 (`agent == lender`) in front of it; the debt asset
70
+ * policy uses it directly as the proof-gated `mintPolicy`.
71
+ */
72
+ export function buildOriginationGuard(refs = {}) {
73
+ const vkeyVar = refs.vkeyVar ?? "state.lendingRuleVKey";
74
+ const logicHashVar = refs.logicHashVar ?? "state.lendingRuleLogicHash";
75
+ const keccakTrueVar = refs.keccakTrueVar ?? "state.keccakTrue";
76
+ return {
77
+ and: [
78
+ {
79
+ groth16_verify: [
80
+ { var: vkeyVar },
81
+ { var: "witness.publicValues" },
82
+ { var: "witness.proof" },
83
+ ],
84
+ },
85
+ {
86
+ "===": [
87
+ { cat: ["0x", { substr: [{ var: "witness.publicValues" }, 2, 64] }] },
88
+ { var: logicHashVar },
89
+ ],
90
+ },
91
+ {
92
+ "===": [
93
+ { cat: ["0x", { substr: [{ var: "witness.publicValues" }, 130, 64] }] },
94
+ { var: keccakTrueVar },
95
+ ],
96
+ },
97
+ {
98
+ "===": [{ substr: [{ var: "witness.publicValues" }, 256, 2] }, "01"],
99
+ },
100
+ ],
101
+ };
102
+ }
103
+ /**
104
+ * Construct the eligibility-proof witness the origination guard reads. The `{publicValues,
105
+ * proof}` come from the SP1 zk-jlvm prover (`--mode groth16`) run over the public rule and the
106
+ * borrower's PRIVATE data context. Both are lowercase `0x`-hex; they are exposed to the guard
107
+ * under the reserved `witness` key (on the loan `originate` event payload, or on a proof-gated
108
+ * `MintAsset`).
109
+ */
110
+ export function buildEligibilityWitness(bundle) {
111
+ return {
112
+ publicValues: bundle.publicValues,
113
+ proof: bundle.proof,
114
+ };
115
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Lending Application — privacy-preserving credit & lending on OttoChain.
3
+ *
4
+ * The lending family hosts private-finance fibers whose financial state stays private while
5
+ * eligibility is proven in zero-knowledge. The collateral, principal, and repayment are
6
+ * asset-subsystem tokens driven by the fiber lifecycle.
7
+ *
8
+ * Variants:
9
+ * - `zkLoan` — a collateralized loan whose origination is gated by a zk eligibility proof
10
+ * (collateral coverage / credit-score floor) without revealing the borrower's financials.
11
+ *
12
+ * The name `lending` (vs. `loans`) deliberately generalizes for the future credit family —
13
+ * credit lines, BNPL, bonds, escrowed credit — mirroring how `markets` hosts prediction /
14
+ * auction / crowdfund variants under one app.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import {
19
+ * getLendingDefinition,
20
+ * pinLendingRule,
21
+ * buildOriginationGuard,
22
+ * buildEligibilityWitness,
23
+ * debtPolicy,
24
+ * collateralPolicy,
25
+ * } from '@ottochain/sdk/apps/lending';
26
+ *
27
+ * const loanDef = getLendingDefinition('zkLoan');
28
+ *
29
+ * // Pin the public rule + build the proof-gated origination guard.
30
+ * const pinned = pinLendingRule({ collateralRatioPct: 150, loanAmount: 1000, minCreditScore: 680 }, vkey);
31
+ * const guard = buildOriginationGuard();
32
+ * const debt = debtPolicy(guard);
33
+ * ```
34
+ *
35
+ * @packageDocumentation
36
+ */
37
+ import { lendingZkLoanDef } from "./state-machines/index.js";
38
+ export { lendingZkLoanDef };
39
+ /** All lending state machine definitions. */
40
+ export const LENDING_DEFINITIONS = {
41
+ zkLoan: lendingZkLoanDef,
42
+ };
43
+ /**
44
+ * Get a lending state machine definition by type.
45
+ * @param type - 'zkLoan' (default: 'zkLoan')
46
+ */
47
+ export function getLendingDefinition(type = "zkLoan") {
48
+ return LENDING_DEFINITIONS[type];
49
+ }
50
+ // ---------------------------------------------------------------------------
51
+ // Eligibility-proof model (the semi-private gate)
52
+ // ---------------------------------------------------------------------------
53
+ export { lendingRule, pinLendingRule, buildOriginationGuard, buildEligibilityWitness, } from "./eligibility.js";
54
+ // ---------------------------------------------------------------------------
55
+ // Credit scoring via the identity + reputation app (the creditScore IS reputation)
56
+ // ---------------------------------------------------------------------------
57
+ export { reputationScore, reputationCreditRule, buildCreditDataContext, reputationAuthorityClause, } from "./credit-scoring.js";
58
+ // ---------------------------------------------------------------------------
59
+ // Asset-subsystem integration (collateral, debt/principal, repayment morphisms)
60
+ // ---------------------------------------------------------------------------
61
+ export {
62
+ // value types
63
+ walletHolder, fiberHolder, behaviorBits, TokenBehaviors,
64
+ // op payload builders
65
+ createAssetPolicyPayload, createMintAssetPayload, createApplyMorphismPayload, createAuthorizeComposePayload,
66
+ // loan policy builders
67
+ collateralPolicy, debtPolicy,
68
+ // lifecycle → morphism drivers
69
+ lockCollateralOp, mintPrincipalOp, repayBurnOp, settleCollateralOp, } from "./assets.js";
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Lending state machine definitions.
3
+ * Re-exports from TypeScript definition files.
4
+ */
5
+ export { lendingZkLoanDef } from './lending-zk-loan.js';