@totemsdk/omnia-lsp-provider 0.0.0-stage → 0.2.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.
@@ -0,0 +1,56 @@
1
+ import type { OmniaLspAsset, OmniaLspDirection, OmniaLspManifest } from '@totemsdk/omnia-lsp';
2
+ export interface OmniaLspOpenRequest {
3
+ providerId: string;
4
+ consumerAddress: string;
5
+ /** Consumer Omnia party id (identity id or channel party id). */
6
+ consumerPartyId: string;
7
+ /** Consumer channel key digest (32-byte hex). */
8
+ consumerPublicKeyDigest: string;
9
+ consumerSettlementAddress?: string;
10
+ consumerTransportPubkey?: string;
11
+ tokenId: string;
12
+ /** Consumer side of the initial channel balance, decimal units. */
13
+ localAmount: string;
14
+ /** Provider side of the initial channel balance, decimal units. */
15
+ remoteAmount: string;
16
+ direction: OmniaLspDirection;
17
+ lease?: boolean;
18
+ jit?: boolean;
19
+ /** Reject when the total open fee exceeds this decimal amount. */
20
+ maxOpenFee?: string;
21
+ /**
22
+ * Legacy ceiling for the percentage component. Also bounds a flat fee by
23
+ * converting it to the equivalent basis points on the fee basis (OMN-072).
24
+ */
25
+ maxOpenFeeBps?: number;
26
+ }
27
+ export interface OmniaLspOpenDecision {
28
+ allowed: boolean;
29
+ errors: string[];
30
+ asset?: OmniaLspAsset;
31
+ }
32
+ export interface OmniaLspProviderPolicy {
33
+ /** Reject hosted-custody manifests. Default true for a non-custodial LSP. */
34
+ requireNonCustodial?: boolean;
35
+ /** Minimum provider-bond score accepted by this provider. Informational only. */
36
+ minProviderScore?: number;
37
+ /**
38
+ * Spendable provider funds for the requested asset, decimal units. When set,
39
+ * the provider-side contribution must fit inside it (OMN-067).
40
+ */
41
+ availableProviderFunds?: string;
42
+ }
43
+ declare function hasCapacity(asset: OmniaLspAsset, direction: OmniaLspDirection, amount: bigint): boolean;
44
+ /**
45
+ * Evaluate an open request against a provider manifest.
46
+ *
47
+ * This is the provider's admission policy. It does not reserve capacity; the
48
+ * provider MUST do that through the quote ledger (OMN-068).
49
+ *
50
+ * Both sides of the channel are validated independently (OMN-067): the
51
+ * consumer's `localAmount` and the provider's own `remoteAmount`, because the
52
+ * provider is the party that funds the latter. `now` is the provider's trusted
53
+ * clock — never the requester's (OMN-069).
54
+ */
55
+ export declare function evaluateOpenRequest(manifest: OmniaLspManifest, request: OmniaLspOpenRequest, policy?: OmniaLspProviderPolicy, now?: number): OmniaLspOpenDecision;
56
+ export { hasCapacity };
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.evaluateOpenRequest = evaluateOpenRequest;
4
+ exports.hasCapacity = hasCapacity;
5
+ const omnia_lsp_1 = require("@totemsdk/omnia-lsp");
6
+ function hasCapacity(asset, direction, amount) {
7
+ if (direction === 'send')
8
+ return parseUnitsAtLeast(asset.outboundCapacity, amount);
9
+ if (direction === 'receive')
10
+ return parseUnitsAtLeast(asset.inboundCapacity, amount);
11
+ return parseUnitsAtLeast(asset.inboundCapacity, amount) && parseUnitsAtLeast(asset.outboundCapacity, amount);
12
+ }
13
+ /** True when `capacity` (decimal) is at least `amount` (units). */
14
+ function parseUnitsAtLeast(capacity, amount) {
15
+ const parsed = (0, omnia_lsp_1.parseDecimalUnits)(capacity, { allowZero: true });
16
+ return parsed.ok && parsed.units >= amount;
17
+ }
18
+ /** The capacity side the provider itself draws on for a direction. */
19
+ function providerCapacitySide(direction) {
20
+ return direction === 'send' ? 'outbound' : direction === 'receive' ? 'inbound' : 'both';
21
+ }
22
+ /** The capacity side the consumer's contribution lands on. */
23
+ function consumerCapacitySide(direction) {
24
+ return direction === 'send' ? 'inbound' : direction === 'receive' ? 'outbound' : 'both';
25
+ }
26
+ function withinCapacity(asset, side, amount) {
27
+ if (side === 'both') {
28
+ return parseUnitsAtLeast(asset.inboundCapacity, amount) && parseUnitsAtLeast(asset.outboundCapacity, amount);
29
+ }
30
+ return parseUnitsAtLeast(side === 'inbound' ? asset.inboundCapacity : asset.outboundCapacity, amount);
31
+ }
32
+ /**
33
+ * Evaluate an open request against a provider manifest.
34
+ *
35
+ * This is the provider's admission policy. It does not reserve capacity; the
36
+ * provider MUST do that through the quote ledger (OMN-068).
37
+ *
38
+ * Both sides of the channel are validated independently (OMN-067): the
39
+ * consumer's `localAmount` and the provider's own `remoteAmount`, because the
40
+ * provider is the party that funds the latter. `now` is the provider's trusted
41
+ * clock — never the requester's (OMN-069).
42
+ */
43
+ function evaluateOpenRequest(manifest, request, policy = {}, now = Date.now()) {
44
+ const errors = [];
45
+ if (request.providerId !== manifest.providerId) {
46
+ errors.push('request.providerId does not match the manifest');
47
+ }
48
+ if (manifest.expiresAt <= now) {
49
+ errors.push('manifest is expired');
50
+ }
51
+ if (policy.requireNonCustodial !== false && (manifest.custody.mode === 'hosted' || manifest.custody.canMoveFunds)) {
52
+ errors.push('hosted custody is not accepted by this provider policy');
53
+ }
54
+ const asset = manifest.assets.find((entry) => entry.tokenId === request.tokenId);
55
+ if (!asset) {
56
+ errors.push('asset is not offered by the provider');
57
+ }
58
+ else {
59
+ const local = (0, omnia_lsp_1.parseDecimalUnits)(request.localAmount);
60
+ const remote = (0, omnia_lsp_1.parseDecimalUnits)(request.remoteAmount);
61
+ const minChannel = (0, omnia_lsp_1.parseDecimalUnits)(asset.minChannel, { allowZero: true });
62
+ const maxChannel = (0, omnia_lsp_1.parseDecimalUnits)(asset.maxChannel, { allowZero: true });
63
+ if (!local.ok)
64
+ errors.push(`localAmount: ${local.error}`);
65
+ if (!remote.ok)
66
+ errors.push(`remoteAmount: ${remote.error}`);
67
+ if (!minChannel.ok)
68
+ errors.push(`manifest asset minChannel: ${minChannel.error}`);
69
+ if (!maxChannel.ok)
70
+ errors.push(`manifest asset maxChannel: ${maxChannel.error}`);
71
+ if (local.ok && minChannel.ok && maxChannel.ok) {
72
+ if (local.units < minChannel.units)
73
+ errors.push('localAmount is below the provider minimum');
74
+ if (local.units > maxChannel.units)
75
+ errors.push('localAmount is above the provider maximum');
76
+ }
77
+ if (remote.ok && minChannel.ok && maxChannel.ok) {
78
+ // OMN-067: the provider's own contribution is a channel limit too.
79
+ if (remote.units < minChannel.units)
80
+ errors.push('remoteAmount is below the provider minimum');
81
+ if (remote.units > maxChannel.units)
82
+ errors.push('remoteAmount is above the provider maximum');
83
+ }
84
+ if (local.ok && !withinCapacity(asset, consumerCapacitySide(request.direction), local.units)) {
85
+ errors.push('insufficient capacity for the consumer contribution in the requested direction');
86
+ }
87
+ if (remote.ok && !withinCapacity(asset, providerCapacitySide(request.direction), remote.units)) {
88
+ errors.push('insufficient capacity for the provider contribution in the requested direction');
89
+ }
90
+ if (remote.ok && policy.availableProviderFunds !== undefined) {
91
+ const available = (0, omnia_lsp_1.parseDecimalUnits)(policy.availableProviderFunds, { allowZero: true });
92
+ if (!available.ok) {
93
+ errors.push(`availableProviderFunds: ${available.error}`);
94
+ }
95
+ else if (remote.units > available.units) {
96
+ errors.push('provider-side amount exceeds the provider available funds');
97
+ }
98
+ }
99
+ if (local.ok && remote.ok) {
100
+ const fees = (0, omnia_lsp_1.computeOpenFees)(manifest, request, omnia_lsp_1.DEFAULT_FEE_BASIS);
101
+ if (!fees.ok) {
102
+ errors.push(`fee schedule: ${fees.error}`);
103
+ }
104
+ else {
105
+ const schedule = fees.schedule;
106
+ if (request.maxOpenFee !== undefined) {
107
+ const ceiling = (0, omnia_lsp_1.parseDecimalUnits)(request.maxOpenFee, { allowZero: true });
108
+ if (!ceiling.ok) {
109
+ errors.push(`maxOpenFee: ${ceiling.error}`);
110
+ }
111
+ else if (schedule.totalFeeUnits > ceiling.units) {
112
+ errors.push('provider total open fee exceeds the request maximum');
113
+ }
114
+ }
115
+ if (request.maxOpenFeeBps !== undefined) {
116
+ // A flat fee is bounded by converting the ceiling onto the fee basis,
117
+ // so a manifest with openFlat can no longer bypass the check (OMN-072).
118
+ const basis = (0, omnia_lsp_1.parseDecimalUnits)(schedule.basisAmount, { allowZero: true });
119
+ const bpsCeiling = basis.ok ? (0, omnia_lsp_1.applyBpsUnits)(basis.units, request.maxOpenFeeBps) : 0n;
120
+ if (schedule.openFeeUnits > bpsCeiling) {
121
+ errors.push('provider open fee exceeds the request maximum rate');
122
+ }
123
+ }
124
+ }
125
+ }
126
+ }
127
+ if (request.lease === true && manifest.terms.lease !== true) {
128
+ errors.push('lease is not offered by the provider');
129
+ }
130
+ if (request.jit === true && manifest.terms.jit !== true) {
131
+ errors.push('JIT is not offered by the provider');
132
+ }
133
+ return { allowed: errors.length === 0, errors, ...(asset ? { asset } : {}) };
134
+ }
@@ -0,0 +1,108 @@
1
+ import { type OmniaLspManifest, type OmniaLspOpenQuote, type OpenQuoteSigningPayload } from '@totemsdk/omnia-lsp';
2
+ import { type OmniaLspOpenDecision, type OmniaLspOpenRequest, type OmniaLspProviderPolicy } from './policy.js';
3
+ import { type UnsignedOmniaLspOpenQuote } from './quote.js';
4
+ import { type OmniaLspQuoteLedger } from './ledger.js';
5
+ /**
6
+ * Optional funding inputs for a provider-hosted open.
7
+ *
8
+ * A provider that already selected its funding coin can pass the coin id plus
9
+ * the node proof material. A provider that wants the host to select a coin can
10
+ * omit all of these; `omnia-host` then selects a sendable coin and builds the
11
+ * funding witness from its own wallet/node.
12
+ */
13
+ export interface OmniaLspHostFunding {
14
+ /** Address to select the provider funding coin from (simple wallet address). */
15
+ fundingAddress?: string;
16
+ fundingCoinId?: string;
17
+ fundingPubkey?: string;
18
+ fundingScript?: string;
19
+ fundingCoinProofsHex?: string | string[];
20
+ /** Provider-wallet-built witness. The consumer/dApp witness is still forbidden. */
21
+ fundingWitnessHex?: string;
22
+ /**
23
+ * Channel contest delay. Omit for the host/program default (normally 256).
24
+ * Test/dev hosts may pass a shorter value when OMNIA_ALLOW_SHORT_CONTEST_DELAY=1.
25
+ */
26
+ contestDelayBlocks?: number;
27
+ }
28
+ export interface OmniaLspHostOpenInput extends OmniaLspHostFunding {
29
+ quote: OmniaLspOpenQuote;
30
+ }
31
+ export interface OmniaLspHostOpenResult {
32
+ success: boolean;
33
+ channelId?: string;
34
+ fundingTxId?: string;
35
+ error?: string;
36
+ errorCode?: string;
37
+ }
38
+ export interface OmniaLspHostCloseResult {
39
+ success: boolean;
40
+ error?: string;
41
+ errorCode?: string;
42
+ }
43
+ /**
44
+ * Host port implemented by the provider runtime (for example an `omnia-host`
45
+ * wrapper). The LSP package owns policy and quotes; the host owns channel
46
+ * construction, signing and broadcast.
47
+ */
48
+ export interface OmniaLspProviderHost {
49
+ openChannel(input: OmniaLspHostOpenInput): Promise<OmniaLspHostOpenResult>;
50
+ closeChannel?(channelId: string): Promise<OmniaLspHostCloseResult>;
51
+ }
52
+ /** The authenticated caller's identity, supplied by the API layer. */
53
+ export interface OmniaLspConsumerIdentity {
54
+ address?: string;
55
+ partyId?: string;
56
+ publicKeyDigest?: string;
57
+ }
58
+ export interface OmniaLspProviderConfig {
59
+ manifest: OmniaLspManifest;
60
+ host: OmniaLspProviderHost;
61
+ policy?: OmniaLspProviderPolicy;
62
+ /** Provider identity signer for quotes. Required for quote issuance. */
63
+ signQuote: (quote: UnsignedOmniaLspOpenQuote, payload: OpenQuoteSigningPayload) => Promise<string> | string;
64
+ /**
65
+ * Verify a provider quote signature over `domain|termsHash` (OMN-066).
66
+ * Required to redeem a quote with `openQuote`; when absent, redemption fails
67
+ * closed rather than trusting an unverified quote.
68
+ */
69
+ verifyQuoteSignature?: (input: OpenQuoteSigningPayload & {
70
+ signature: string;
71
+ quote: OmniaLspOpenQuote;
72
+ }) => boolean | Promise<boolean>;
73
+ /**
74
+ * Durable reservation ledger (OMN-068). Defaults to an in-process ledger,
75
+ * which enforces concurrency limits but does not survive a restart.
76
+ */
77
+ quoteLedger?: OmniaLspQuoteLedger;
78
+ /**
79
+ * Require `openQuote` to be given the authenticated consumer so the quote can
80
+ * be bound to it. Default true — pass false only for a caller that has
81
+ * already authenticated the quote's consumer outside this facade.
82
+ */
83
+ requireConsumerBinding?: boolean;
84
+ /** Default quote TTL. Default 60s. */
85
+ quoteTtlMs?: number;
86
+ /** Clock injection for deterministic tests. The provider clock is authoritative. */
87
+ now?: () => number;
88
+ }
89
+ export interface OmniaLspOpenQuoteOptions {
90
+ /** Identity of the already-authenticated caller redeeming this quote. */
91
+ consumer?: OmniaLspConsumerIdentity;
92
+ }
93
+ export interface OmniaLspProvider {
94
+ manifest(): OmniaLspManifest;
95
+ evaluate(request: OmniaLspOpenRequest): OmniaLspOpenDecision;
96
+ quote(request: OmniaLspOpenRequest): Promise<OmniaLspOpenQuote>;
97
+ open(request: OmniaLspOpenRequest, funding?: OmniaLspHostFunding | string): Promise<OmniaLspHostOpenResult>;
98
+ openQuote(quote: OmniaLspOpenQuote, funding?: OmniaLspHostFunding | string, options?: OmniaLspOpenQuoteOptions): Promise<OmniaLspHostOpenResult>;
99
+ close(channelId: string): Promise<OmniaLspHostCloseResult>;
100
+ }
101
+ /**
102
+ * Reference provider facade.
103
+ *
104
+ * It does not hold keys, open channels or broadcast. It applies policy, issues
105
+ * signed quotes, reserves provider capacity and delegates the channel operation
106
+ * to the injected host.
107
+ */
108
+ export declare function createOmniaLspProvider(config: OmniaLspProviderConfig): OmniaLspProvider;
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createOmniaLspProvider = createOmniaLspProvider;
4
+ const omnia_lsp_1 = require("@totemsdk/omnia-lsp");
5
+ const policy_js_1 = require("./policy.js");
6
+ const quote_js_1 = require("./quote.js");
7
+ const ledger_js_1 = require("./ledger.js");
8
+ function assertAllowed(decision) {
9
+ if (!decision.allowed) {
10
+ throw new Error(`Open request rejected: ${decision.errors.join('; ')}`);
11
+ }
12
+ }
13
+ function reject(error, errorCode) {
14
+ return { success: false, error, errorCode };
15
+ }
16
+ function fundingInput(funding) {
17
+ return typeof funding === 'string' ? { fundingCoinId: funding } : funding ?? {};
18
+ }
19
+ /**
20
+ * Reference provider facade.
21
+ *
22
+ * It does not hold keys, open channels or broadcast. It applies policy, issues
23
+ * signed quotes, reserves provider capacity and delegates the channel operation
24
+ * to the injected host.
25
+ */
26
+ function createOmniaLspProvider(config) {
27
+ const now = config.now ?? Date.now;
28
+ const ledger = config.quoteLedger ?? (0, ledger_js_1.createMemoryQuoteLedger)();
29
+ let quoteCounter = 0;
30
+ /**
31
+ * Re-apply admission to a quote that is being redeemed (OMN-066). The quote
32
+ * does not carry `direction` or the lease flag, so this uses the conservative
33
+ * `both` direction and derives lease from the quoted lease fee.
34
+ */
35
+ function quoteAsRequest(quote) {
36
+ return {
37
+ providerId: quote.providerId,
38
+ consumerAddress: quote.consumerAddress,
39
+ consumerPartyId: quote.consumerPartyId,
40
+ consumerPublicKeyDigest: quote.consumerPublicKeyDigest,
41
+ ...(quote.consumerSettlementAddress !== undefined
42
+ ? { consumerSettlementAddress: quote.consumerSettlementAddress }
43
+ : {}),
44
+ ...(quote.consumerTransportPubkey !== undefined
45
+ ? { consumerTransportPubkey: quote.consumerTransportPubkey }
46
+ : {}),
47
+ tokenId: quote.tokenId,
48
+ localAmount: quote.localAmount,
49
+ remoteAmount: quote.remoteAmount,
50
+ direction: 'both',
51
+ ...(quote.leaseFee !== undefined ? { lease: true } : {}),
52
+ };
53
+ }
54
+ async function quote(request) {
55
+ const issuedAt = now();
56
+ const decision = (0, policy_js_1.evaluateOpenRequest)(config.manifest, request, config.policy, issuedAt);
57
+ assertAllowed(decision);
58
+ const unsigned = (0, quote_js_1.createUnsignedOpenQuote)({
59
+ manifest: config.manifest,
60
+ request,
61
+ now: issuedAt,
62
+ ttlMs: config.quoteTtlMs,
63
+ quoteId: `quote-${issuedAt.toString(36)}-${(++quoteCounter).toString(36)}`,
64
+ });
65
+ const signed = await (0, quote_js_1.signOpenQuote)(unsigned, config.signQuote);
66
+ const remote = (0, omnia_lsp_1.parseDecimalUnits)(signed.remoteAmount);
67
+ if (!remote.ok)
68
+ throw new Error(`cannot reserve provider capacity: ${remote.error}`);
69
+ // Outstanding reservations count against the same capacity the manifest
70
+ // advertises, so concurrent quotes cannot collectively exceed it (OMN-068).
71
+ if (decision.asset) {
72
+ const outstanding = await ledger.outstanding(signed.tokenId, config.manifest.providerId, issuedAt);
73
+ if (!(0, policy_js_1.hasCapacity)(decision.asset, request.direction, outstanding + remote.units)) {
74
+ throw new Error('Open request rejected: provider capacity is exhausted by outstanding quotes');
75
+ }
76
+ }
77
+ await ledger.reserve({
78
+ quoteId: signed.quoteId,
79
+ providerId: config.manifest.providerId,
80
+ tokenId: signed.tokenId,
81
+ amount: signed.remoteAmount,
82
+ amountUnits: remote.units,
83
+ expiresAt: signed.expiresAt,
84
+ state: 'reserved',
85
+ updatedAt: issuedAt,
86
+ });
87
+ return signed;
88
+ }
89
+ async function redeem(quote, funding) {
90
+ const consumed = await ledger.consume(quote.quoteId, now());
91
+ if (consumed === 'unknown') {
92
+ return reject(`Quote ${quote.quoteId} was not issued by this provider`, 'QUOTE_NOT_ISSUED');
93
+ }
94
+ if (consumed === 'expired') {
95
+ return reject('Quote expired', 'QUOTE_EXPIRED');
96
+ }
97
+ if (consumed === 'already-consumed') {
98
+ return reject(`Quote ${quote.quoteId} has already been used`, 'QUOTE_ALREADY_CONSUMED');
99
+ }
100
+ const result = await config.host.openChannel({
101
+ quote,
102
+ ...fundingInput(funding),
103
+ });
104
+ if (result?.success !== true) {
105
+ // Nothing was funded, so the capacity goes back rather than being burned.
106
+ await ledger.release(quote.quoteId, now());
107
+ }
108
+ return result;
109
+ }
110
+ return {
111
+ manifest() {
112
+ return config.manifest;
113
+ },
114
+ evaluate(request) {
115
+ return (0, policy_js_1.evaluateOpenRequest)(config.manifest, request, config.policy, now());
116
+ },
117
+ quote,
118
+ async open(request, funding) {
119
+ const issued = await quote(request);
120
+ return redeem(issued, funding);
121
+ },
122
+ async openQuote(quote, funding, options) {
123
+ const currentTime = now();
124
+ if (quote.expiresAt <= currentTime) {
125
+ return reject('Quote expired', 'QUOTE_EXPIRED');
126
+ }
127
+ if (quote.providerId !== config.manifest.providerId) {
128
+ return reject('Quote provider mismatch', 'QUOTE_PROVIDER_MISMATCH');
129
+ }
130
+ // Bind the quote to the authenticated caller before anything else can act
131
+ // on it. Without this the LSP authorization boundary is missing (OMN-066).
132
+ const consumer = options?.consumer;
133
+ const consumerBound = Boolean(consumer && (consumer.address || consumer.partyId || consumer.publicKeyDigest));
134
+ if (!consumerBound && config.requireConsumerBinding !== false) {
135
+ return reject('openQuote requires the authenticated consumer identity', 'QUOTE_CONSUMER_UNBOUND');
136
+ }
137
+ const verified = await (0, omnia_lsp_1.verifyOpenQuote)(quote, config.manifest, {
138
+ now: currentTime,
139
+ ...(config.verifyQuoteSignature
140
+ ? { verifySignature: config.verifyQuoteSignature }
141
+ : {}),
142
+ ...(consumer?.partyId !== undefined
143
+ ? { expectedConsumerPartyId: consumer.partyId }
144
+ : {}),
145
+ ...(consumer?.publicKeyDigest !== undefined
146
+ ? { expectedConsumerPublicKeyDigest: consumer.publicKeyDigest }
147
+ : {}),
148
+ ...(consumer?.address !== undefined
149
+ ? { expectedConsumerAddress: consumer.address }
150
+ : {}),
151
+ });
152
+ if (!verified.ok) {
153
+ return reject(`Quote rejected: ${verified.errors.join('; ')}`, 'QUOTE_INVALID');
154
+ }
155
+ // Re-apply the current policy: the manifest, custody mode and capacity may
156
+ // have changed since the quote was issued.
157
+ const policyDecision = (0, policy_js_1.evaluateOpenRequest)(config.manifest, quoteAsRequest(quote), config.policy, currentTime);
158
+ if (!policyDecision.allowed) {
159
+ return reject(`Quote no longer satisfies provider policy: ${policyDecision.errors.join('; ')}`, 'QUOTE_POLICY_REJECTED');
160
+ }
161
+ return redeem(quote, funding);
162
+ },
163
+ async close(channelId) {
164
+ if (!config.host.closeChannel) {
165
+ return reject('Host does not implement closeChannel', 'UNSUPPORTED');
166
+ }
167
+ return config.host.closeChannel(channelId);
168
+ },
169
+ };
170
+ }
@@ -0,0 +1,30 @@
1
+ import type { OmniaLspFeeBasis, OmniaLspManifest, OmniaLspOpenQuote, OpenQuoteSigningPayload } from '@totemsdk/omnia-lsp';
2
+ import type { OmniaLspOpenRequest } from './policy.js';
3
+ export type UnsignedOmniaLspOpenQuote = Omit<OmniaLspOpenQuote, 'signature'>;
4
+ export interface CreateQuoteOptions {
5
+ manifest: OmniaLspManifest;
6
+ request: OmniaLspOpenRequest;
7
+ now?: number;
8
+ ttlMs?: number;
9
+ quoteId?: string;
10
+ /** Fee basis for percentage fees. Defaults to the total channel value. */
11
+ feeBasis?: OmniaLspFeeBasis;
12
+ }
13
+ /**
14
+ * Build the provider's unsigned open quote. The provider host signs it before
15
+ * returning it to the consumer; a quote without a signature is not authoritative.
16
+ *
17
+ * The quoted fees come from the shared schedule (OMN-072) and the terms object
18
+ * is built by `buildOpenTerms`, which is the same function the verifier uses to
19
+ * recompute the hash.
20
+ */
21
+ export declare function createUnsignedOpenQuote(options: CreateQuoteOptions): UnsignedOmniaLspOpenQuote;
22
+ /**
23
+ * Sign an unsigned quote with a provider identity signer. The signer is injected
24
+ * so the package stays runtime-neutral and never holds a private key.
25
+ *
26
+ * The second argument is the exact payload to sign (`domain|termsHash`). A
27
+ * one-argument signer keeps working; a signer that ignores the payload must sign
28
+ * this same string to produce quotes that `verifyOpenQuote` accepts.
29
+ */
30
+ export declare function signOpenQuote(quote: UnsignedOmniaLspOpenQuote, sign: (quote: UnsignedOmniaLspOpenQuote, payload: OpenQuoteSigningPayload) => Promise<string> | string): Promise<OmniaLspOpenQuote>;
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createUnsignedOpenQuote = createUnsignedOpenQuote;
4
+ exports.signOpenQuote = signOpenQuote;
5
+ const omnia_lsp_1 = require("@totemsdk/omnia-lsp");
6
+ /**
7
+ * Build the provider's unsigned open quote. The provider host signs it before
8
+ * returning it to the consumer; a quote without a signature is not authoritative.
9
+ *
10
+ * The quoted fees come from the shared schedule (OMN-072) and the terms object
11
+ * is built by `buildOpenTerms`, which is the same function the verifier uses to
12
+ * recompute the hash.
13
+ */
14
+ function createUnsignedOpenQuote(options) {
15
+ const { manifest, request } = options;
16
+ const now = options.now ?? Date.now();
17
+ const ttlMs = options.ttlMs ?? 60000;
18
+ const expiresAt = now + ttlMs;
19
+ const basis = options.feeBasis ?? omnia_lsp_1.DEFAULT_FEE_BASIS;
20
+ const fees = (0, omnia_lsp_1.computeOpenFees)(manifest, request, basis);
21
+ if (!fees.ok) {
22
+ throw new Error(`cannot quote open request: ${fees.error}`);
23
+ }
24
+ const schedule = fees.schedule;
25
+ const terms = (0, omnia_lsp_1.buildOpenTerms)({
26
+ manifest,
27
+ consumerAddress: request.consumerAddress,
28
+ consumerPartyId: request.consumerPartyId,
29
+ consumerPublicKeyDigest: request.consumerPublicKeyDigest,
30
+ ...(request.consumerSettlementAddress !== undefined
31
+ ? { consumerSettlementAddress: request.consumerSettlementAddress }
32
+ : {}),
33
+ ...(request.consumerTransportPubkey !== undefined
34
+ ? { consumerTransportPubkey: request.consumerTransportPubkey }
35
+ : {}),
36
+ tokenId: request.tokenId,
37
+ localAmount: request.localAmount,
38
+ remoteAmount: request.remoteAmount,
39
+ openFee: schedule.openFee,
40
+ ...(schedule.leaseFee !== undefined ? { leaseFee: schedule.leaseFee } : {}),
41
+ feeBasis: schedule.basis,
42
+ expiresAt,
43
+ });
44
+ const termsHash = (0, omnia_lsp_1.openTermsHash)(terms);
45
+ return {
46
+ version: 'omnia-lsp/open-quote/v1',
47
+ quoteId: options.quoteId ?? `quote-${termsHash.slice(2, 18)}-${now.toString(36)}`,
48
+ providerId: manifest.providerId,
49
+ consumerAddress: request.consumerAddress,
50
+ consumerPartyId: request.consumerPartyId,
51
+ consumerPublicKeyDigest: request.consumerPublicKeyDigest,
52
+ ...(request.consumerSettlementAddress
53
+ ? { consumerSettlementAddress: request.consumerSettlementAddress }
54
+ : {}),
55
+ ...(request.consumerTransportPubkey
56
+ ? { consumerTransportPubkey: request.consumerTransportPubkey }
57
+ : {}),
58
+ tokenId: request.tokenId,
59
+ localAmount: request.localAmount,
60
+ remoteAmount: request.remoteAmount,
61
+ openFee: schedule.openFee,
62
+ ...(schedule.leaseFee !== undefined ? { leaseFee: schedule.leaseFee } : {}),
63
+ feeBasis: schedule.basis,
64
+ providerPartyId: manifest.channel.partyId,
65
+ providerPublicKeyDigest: manifest.channel.publicKeyDigest,
66
+ providerSettlementAddress: manifest.channel.settlementAddress,
67
+ termsHash,
68
+ expiresAt,
69
+ };
70
+ }
71
+ /**
72
+ * Sign an unsigned quote with a provider identity signer. The signer is injected
73
+ * so the package stays runtime-neutral and never holds a private key.
74
+ *
75
+ * The second argument is the exact payload to sign (`domain|termsHash`). A
76
+ * one-argument signer keeps working; a signer that ignores the payload must sign
77
+ * this same string to produce quotes that `verifyOpenQuote` accepts.
78
+ */
79
+ function signOpenQuote(quote, sign) {
80
+ const payload = (0, omnia_lsp_1.openQuoteSigningPayload)(quote);
81
+ return Promise.resolve(sign(quote, payload)).then((signature) => ({ ...quote, signature }));
82
+ }
package/dist/host.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { OmniaLspProviderHost } from './provider.js';
2
+ export type OmniaHostHandler = (params: unknown) => Promise<unknown> | unknown;
3
+ export interface OmniaHostMethodMap {
4
+ get(name: string): OmniaHostHandler | undefined;
5
+ }
6
+ export interface CreateOmniaHostProviderHostOptions {
7
+ /** `createHostMethods(context)` map (or any Map-like handler registry). */
8
+ methods: OmniaHostMethodMap | Map<string, OmniaHostHandler>;
9
+ openMethod?: string;
10
+ closeMethod?: string;
11
+ /** Optional operation id prefix. Default: omnia-lsp. */
12
+ operationIdPrefix?: string;
13
+ }
14
+ /**
15
+ * Adapt an `omnia-host` method registry (`createHostMethods(context)`) to the
16
+ * LSP provider host port.
17
+ *
18
+ * The quote is written from the consumer's perspective: `localAmount` is the
19
+ * consumer side and `remoteAmount` is the provider side. The host is the provider,
20
+ * so those sides are swapped when calling `totem_omniaOpenChannel`.
21
+ */
22
+ export declare function createOmniaHostProviderHost(options: CreateOmniaHostProviderHostOptions): OmniaLspProviderHost;