@totemsdk/omnia-lsp-provider 0.1.0 → 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.
package/dist/policy.js CHANGED
@@ -1,29 +1,43 @@
1
- const DECIMAL_SCALE = 18n;
2
- const DECIMAL_FACTOR = 10n ** DECIMAL_SCALE;
3
- function decimalKey(value) {
4
- const [whole = '0', fraction = ''] = value.split('.');
5
- return (BigInt(whole) * DECIMAL_FACTOR +
6
- BigInt(fraction.padEnd(Number(DECIMAL_SCALE), '0').slice(0, Number(DECIMAL_SCALE))));
7
- }
8
- function gte(a, b) {
9
- return decimalKey(a) >= decimalKey(b);
10
- }
1
+ import { applyBpsUnits, computeOpenFees, DEFAULT_FEE_BASIS, parseDecimalUnits, } from '@totemsdk/omnia-lsp';
11
2
  function hasCapacity(asset, direction, amount) {
12
3
  if (direction === 'send')
13
- return gte(asset.outboundCapacity, amount);
4
+ return parseUnitsAtLeast(asset.outboundCapacity, amount);
14
5
  if (direction === 'receive')
15
- return gte(asset.inboundCapacity, amount);
16
- return gte(asset.inboundCapacity, amount) && gte(asset.outboundCapacity, amount);
6
+ return parseUnitsAtLeast(asset.inboundCapacity, amount);
7
+ return parseUnitsAtLeast(asset.inboundCapacity, amount) && parseUnitsAtLeast(asset.outboundCapacity, amount);
8
+ }
9
+ /** True when `capacity` (decimal) is at least `amount` (units). */
10
+ function parseUnitsAtLeast(capacity, amount) {
11
+ const parsed = parseDecimalUnits(capacity, { allowZero: true });
12
+ return parsed.ok && parsed.units >= amount;
13
+ }
14
+ /** The capacity side the provider itself draws on for a direction. */
15
+ function providerCapacitySide(direction) {
16
+ return direction === 'send' ? 'outbound' : direction === 'receive' ? 'inbound' : 'both';
17
+ }
18
+ /** The capacity side the consumer's contribution lands on. */
19
+ function consumerCapacitySide(direction) {
20
+ return direction === 'send' ? 'inbound' : direction === 'receive' ? 'outbound' : 'both';
21
+ }
22
+ function withinCapacity(asset, side, amount) {
23
+ if (side === 'both') {
24
+ return parseUnitsAtLeast(asset.inboundCapacity, amount) && parseUnitsAtLeast(asset.outboundCapacity, amount);
25
+ }
26
+ return parseUnitsAtLeast(side === 'inbound' ? asset.inboundCapacity : asset.outboundCapacity, amount);
17
27
  }
18
28
  /**
19
29
  * Evaluate an open request against a provider manifest.
20
30
  *
21
31
  * This is the provider's admission policy. It does not reserve capacity; the
22
- * provider MUST re-check capacity and channel state before co-signing.
32
+ * provider MUST do that through the quote ledger (OMN-068).
33
+ *
34
+ * Both sides of the channel are validated independently (OMN-067): the
35
+ * consumer's `localAmount` and the provider's own `remoteAmount`, because the
36
+ * provider is the party that funds the latter. `now` is the provider's trusted
37
+ * clock — never the requester's (OMN-069).
23
38
  */
24
- export function evaluateOpenRequest(manifest, request, policy = {}) {
39
+ export function evaluateOpenRequest(manifest, request, policy = {}, now = Date.now()) {
25
40
  const errors = [];
26
- const now = request.now ?? Date.now();
27
41
  if (request.providerId !== manifest.providerId) {
28
42
  errors.push('request.providerId does not match the manifest');
29
43
  }
@@ -38,14 +52,72 @@ export function evaluateOpenRequest(manifest, request, policy = {}) {
38
52
  errors.push('asset is not offered by the provider');
39
53
  }
40
54
  else {
41
- if (!gte(request.localAmount, asset.minChannel)) {
42
- errors.push('localAmount is below the provider minimum');
55
+ const local = parseDecimalUnits(request.localAmount);
56
+ const remote = parseDecimalUnits(request.remoteAmount);
57
+ const minChannel = parseDecimalUnits(asset.minChannel, { allowZero: true });
58
+ const maxChannel = parseDecimalUnits(asset.maxChannel, { allowZero: true });
59
+ if (!local.ok)
60
+ errors.push(`localAmount: ${local.error}`);
61
+ if (!remote.ok)
62
+ errors.push(`remoteAmount: ${remote.error}`);
63
+ if (!minChannel.ok)
64
+ errors.push(`manifest asset minChannel: ${minChannel.error}`);
65
+ if (!maxChannel.ok)
66
+ errors.push(`manifest asset maxChannel: ${maxChannel.error}`);
67
+ if (local.ok && minChannel.ok && maxChannel.ok) {
68
+ if (local.units < minChannel.units)
69
+ errors.push('localAmount is below the provider minimum');
70
+ if (local.units > maxChannel.units)
71
+ errors.push('localAmount is above the provider maximum');
72
+ }
73
+ if (remote.ok && minChannel.ok && maxChannel.ok) {
74
+ // OMN-067: the provider's own contribution is a channel limit too.
75
+ if (remote.units < minChannel.units)
76
+ errors.push('remoteAmount is below the provider minimum');
77
+ if (remote.units > maxChannel.units)
78
+ errors.push('remoteAmount is above the provider maximum');
43
79
  }
44
- if (!gte(asset.maxChannel, request.localAmount)) {
45
- errors.push('localAmount is above the provider maximum');
80
+ if (local.ok && !withinCapacity(asset, consumerCapacitySide(request.direction), local.units)) {
81
+ errors.push('insufficient capacity for the consumer contribution in the requested direction');
46
82
  }
47
- if (!hasCapacity(asset, request.direction, request.localAmount)) {
48
- errors.push('insufficient capacity for the requested direction');
83
+ if (remote.ok && !withinCapacity(asset, providerCapacitySide(request.direction), remote.units)) {
84
+ errors.push('insufficient capacity for the provider contribution in the requested direction');
85
+ }
86
+ if (remote.ok && policy.availableProviderFunds !== undefined) {
87
+ const available = parseDecimalUnits(policy.availableProviderFunds, { allowZero: true });
88
+ if (!available.ok) {
89
+ errors.push(`availableProviderFunds: ${available.error}`);
90
+ }
91
+ else if (remote.units > available.units) {
92
+ errors.push('provider-side amount exceeds the provider available funds');
93
+ }
94
+ }
95
+ if (local.ok && remote.ok) {
96
+ const fees = computeOpenFees(manifest, request, DEFAULT_FEE_BASIS);
97
+ if (!fees.ok) {
98
+ errors.push(`fee schedule: ${fees.error}`);
99
+ }
100
+ else {
101
+ const schedule = fees.schedule;
102
+ if (request.maxOpenFee !== undefined) {
103
+ const ceiling = parseDecimalUnits(request.maxOpenFee, { allowZero: true });
104
+ if (!ceiling.ok) {
105
+ errors.push(`maxOpenFee: ${ceiling.error}`);
106
+ }
107
+ else if (schedule.totalFeeUnits > ceiling.units) {
108
+ errors.push('provider total open fee exceeds the request maximum');
109
+ }
110
+ }
111
+ if (request.maxOpenFeeBps !== undefined) {
112
+ // A flat fee is bounded by converting the ceiling onto the fee basis,
113
+ // so a manifest with openFlat can no longer bypass the check (OMN-072).
114
+ const basis = parseDecimalUnits(schedule.basisAmount, { allowZero: true });
115
+ const bpsCeiling = basis.ok ? applyBpsUnits(basis.units, request.maxOpenFeeBps) : 0n;
116
+ if (schedule.openFeeUnits > bpsCeiling) {
117
+ errors.push('provider open fee exceeds the request maximum rate');
118
+ }
119
+ }
120
+ }
49
121
  }
50
122
  }
51
123
  if (request.lease === true && manifest.terms.lease !== true) {
@@ -54,9 +126,6 @@ export function evaluateOpenRequest(manifest, request, policy = {}) {
54
126
  if (request.jit === true && manifest.terms.jit !== true) {
55
127
  errors.push('JIT is not offered by the provider');
56
128
  }
57
- if (request.maxOpenFeeBps !== undefined &&
58
- (manifest.fees.openBps ?? 0) > request.maxOpenFeeBps) {
59
- errors.push('provider open fee exceeds the request maximum');
60
- }
61
129
  return { allowed: errors.length === 0, errors, ...(asset ? { asset } : {}) };
62
130
  }
131
+ export { hasCapacity };
@@ -1,6 +1,7 @@
1
- import type { OmniaLspManifest, OmniaLspOpenQuote } from '@totemsdk/omnia-lsp';
1
+ import { type OmniaLspManifest, type OmniaLspOpenQuote, type OpenQuoteSigningPayload } from '@totemsdk/omnia-lsp';
2
2
  import { type OmniaLspOpenDecision, type OmniaLspOpenRequest, type OmniaLspProviderPolicy } from './policy.js';
3
3
  import { type UnsignedOmniaLspOpenQuote } from './quote.js';
4
+ import { type OmniaLspQuoteLedger } from './ledger.js';
4
5
  /**
5
6
  * Optional funding inputs for a provider-hosted open.
6
7
  *
@@ -48,29 +49,60 @@ export interface OmniaLspProviderHost {
48
49
  openChannel(input: OmniaLspHostOpenInput): Promise<OmniaLspHostOpenResult>;
49
50
  closeChannel?(channelId: string): Promise<OmniaLspHostCloseResult>;
50
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
+ }
51
58
  export interface OmniaLspProviderConfig {
52
59
  manifest: OmniaLspManifest;
53
60
  host: OmniaLspProviderHost;
54
61
  policy?: OmniaLspProviderPolicy;
55
62
  /** Provider identity signer for quotes. Required for quote issuance. */
56
- signQuote: (quote: UnsignedOmniaLspOpenQuote) => Promise<string> | string;
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;
57
84
  /** Default quote TTL. Default 60s. */
58
85
  quoteTtlMs?: number;
59
- /** Clock injection for deterministic tests. */
86
+ /** Clock injection for deterministic tests. The provider clock is authoritative. */
60
87
  now?: () => number;
61
88
  }
89
+ export interface OmniaLspOpenQuoteOptions {
90
+ /** Identity of the already-authenticated caller redeeming this quote. */
91
+ consumer?: OmniaLspConsumerIdentity;
92
+ }
62
93
  export interface OmniaLspProvider {
63
94
  manifest(): OmniaLspManifest;
64
95
  evaluate(request: OmniaLspOpenRequest): OmniaLspOpenDecision;
65
96
  quote(request: OmniaLspOpenRequest): Promise<OmniaLspOpenQuote>;
66
97
  open(request: OmniaLspOpenRequest, funding?: OmniaLspHostFunding | string): Promise<OmniaLspHostOpenResult>;
67
- openQuote(quote: OmniaLspOpenQuote, funding?: OmniaLspHostFunding | string): Promise<OmniaLspHostOpenResult>;
98
+ openQuote(quote: OmniaLspOpenQuote, funding?: OmniaLspHostFunding | string, options?: OmniaLspOpenQuoteOptions): Promise<OmniaLspHostOpenResult>;
68
99
  close(channelId: string): Promise<OmniaLspHostCloseResult>;
69
100
  }
70
101
  /**
71
102
  * Reference provider facade.
72
103
  *
73
104
  * It does not hold keys, open channels or broadcast. It applies policy, issues
74
- * signed quotes and delegates the channel operation to the injected host.
105
+ * signed quotes, reserves provider capacity and delegates the channel operation
106
+ * to the injected host.
75
107
  */
76
108
  export declare function createOmniaLspProvider(config: OmniaLspProviderConfig): OmniaLspProvider;
package/dist/provider.js CHANGED
@@ -1,59 +1,165 @@
1
- import { evaluateOpenRequest, } from './policy.js';
1
+ import { parseDecimalUnits, verifyOpenQuote, } from '@totemsdk/omnia-lsp';
2
+ import { evaluateOpenRequest, hasCapacity, } from './policy.js';
2
3
  import { createUnsignedOpenQuote, signOpenQuote, } from './quote.js';
4
+ import { createMemoryQuoteLedger } from './ledger.js';
3
5
  function assertAllowed(decision) {
4
6
  if (!decision.allowed) {
5
7
  throw new Error(`Open request rejected: ${decision.errors.join('; ')}`);
6
8
  }
7
9
  }
10
+ function reject(error, errorCode) {
11
+ return { success: false, error, errorCode };
12
+ }
13
+ function fundingInput(funding) {
14
+ return typeof funding === 'string' ? { fundingCoinId: funding } : funding ?? {};
15
+ }
8
16
  /**
9
17
  * Reference provider facade.
10
18
  *
11
19
  * It does not hold keys, open channels or broadcast. It applies policy, issues
12
- * signed quotes and delegates the channel operation to the injected host.
20
+ * signed quotes, reserves provider capacity and delegates the channel operation
21
+ * to the injected host.
13
22
  */
14
23
  export function createOmniaLspProvider(config) {
15
24
  const now = config.now ?? Date.now;
25
+ const ledger = config.quoteLedger ?? createMemoryQuoteLedger();
26
+ let quoteCounter = 0;
27
+ /**
28
+ * Re-apply admission to a quote that is being redeemed (OMN-066). The quote
29
+ * does not carry `direction` or the lease flag, so this uses the conservative
30
+ * `both` direction and derives lease from the quoted lease fee.
31
+ */
32
+ function quoteAsRequest(quote) {
33
+ return {
34
+ providerId: quote.providerId,
35
+ consumerAddress: quote.consumerAddress,
36
+ consumerPartyId: quote.consumerPartyId,
37
+ consumerPublicKeyDigest: quote.consumerPublicKeyDigest,
38
+ ...(quote.consumerSettlementAddress !== undefined
39
+ ? { consumerSettlementAddress: quote.consumerSettlementAddress }
40
+ : {}),
41
+ ...(quote.consumerTransportPubkey !== undefined
42
+ ? { consumerTransportPubkey: quote.consumerTransportPubkey }
43
+ : {}),
44
+ tokenId: quote.tokenId,
45
+ localAmount: quote.localAmount,
46
+ remoteAmount: quote.remoteAmount,
47
+ direction: 'both',
48
+ ...(quote.leaseFee !== undefined ? { lease: true } : {}),
49
+ };
50
+ }
16
51
  async function quote(request) {
17
- const decision = evaluateOpenRequest(config.manifest, request, config.policy);
52
+ const issuedAt = now();
53
+ const decision = evaluateOpenRequest(config.manifest, request, config.policy, issuedAt);
18
54
  assertAllowed(decision);
19
55
  const unsigned = createUnsignedOpenQuote({
20
56
  manifest: config.manifest,
21
57
  request,
22
- now: now(),
58
+ now: issuedAt,
23
59
  ttlMs: config.quoteTtlMs,
60
+ quoteId: `quote-${issuedAt.toString(36)}-${(++quoteCounter).toString(36)}`,
24
61
  });
25
- return signOpenQuote(unsigned, config.signQuote);
62
+ const signed = await signOpenQuote(unsigned, config.signQuote);
63
+ const remote = parseDecimalUnits(signed.remoteAmount);
64
+ if (!remote.ok)
65
+ throw new Error(`cannot reserve provider capacity: ${remote.error}`);
66
+ // Outstanding reservations count against the same capacity the manifest
67
+ // advertises, so concurrent quotes cannot collectively exceed it (OMN-068).
68
+ if (decision.asset) {
69
+ const outstanding = await ledger.outstanding(signed.tokenId, config.manifest.providerId, issuedAt);
70
+ if (!hasCapacity(decision.asset, request.direction, outstanding + remote.units)) {
71
+ throw new Error('Open request rejected: provider capacity is exhausted by outstanding quotes');
72
+ }
73
+ }
74
+ await ledger.reserve({
75
+ quoteId: signed.quoteId,
76
+ providerId: config.manifest.providerId,
77
+ tokenId: signed.tokenId,
78
+ amount: signed.remoteAmount,
79
+ amountUnits: remote.units,
80
+ expiresAt: signed.expiresAt,
81
+ state: 'reserved',
82
+ updatedAt: issuedAt,
83
+ });
84
+ return signed;
85
+ }
86
+ async function redeem(quote, funding) {
87
+ const consumed = await ledger.consume(quote.quoteId, now());
88
+ if (consumed === 'unknown') {
89
+ return reject(`Quote ${quote.quoteId} was not issued by this provider`, 'QUOTE_NOT_ISSUED');
90
+ }
91
+ if (consumed === 'expired') {
92
+ return reject('Quote expired', 'QUOTE_EXPIRED');
93
+ }
94
+ if (consumed === 'already-consumed') {
95
+ return reject(`Quote ${quote.quoteId} has already been used`, 'QUOTE_ALREADY_CONSUMED');
96
+ }
97
+ const result = await config.host.openChannel({
98
+ quote,
99
+ ...fundingInput(funding),
100
+ });
101
+ if (result?.success !== true) {
102
+ // Nothing was funded, so the capacity goes back rather than being burned.
103
+ await ledger.release(quote.quoteId, now());
104
+ }
105
+ return result;
26
106
  }
27
107
  return {
28
108
  manifest() {
29
109
  return config.manifest;
30
110
  },
31
111
  evaluate(request) {
32
- return evaluateOpenRequest(config.manifest, request, config.policy);
112
+ return evaluateOpenRequest(config.manifest, request, config.policy, now());
33
113
  },
34
114
  quote,
35
115
  async open(request, funding) {
36
116
  const issued = await quote(request);
37
- return config.host.openChannel({
38
- quote: issued,
39
- ...(typeof funding === 'string' ? { fundingCoinId: funding } : funding ?? {}),
40
- });
117
+ return redeem(issued, funding);
41
118
  },
42
- async openQuote(quote, funding) {
43
- if (quote.expiresAt <= now()) {
44
- return { success: false, error: 'Quote expired', errorCode: 'QUOTE_EXPIRED' };
119
+ async openQuote(quote, funding, options) {
120
+ const currentTime = now();
121
+ if (quote.expiresAt <= currentTime) {
122
+ return reject('Quote expired', 'QUOTE_EXPIRED');
45
123
  }
46
124
  if (quote.providerId !== config.manifest.providerId) {
47
- return { success: false, error: 'Quote provider mismatch', errorCode: 'QUOTE_PROVIDER_MISMATCH' };
125
+ return reject('Quote provider mismatch', 'QUOTE_PROVIDER_MISMATCH');
126
+ }
127
+ // Bind the quote to the authenticated caller before anything else can act
128
+ // on it. Without this the LSP authorization boundary is missing (OMN-066).
129
+ const consumer = options?.consumer;
130
+ const consumerBound = Boolean(consumer && (consumer.address || consumer.partyId || consumer.publicKeyDigest));
131
+ if (!consumerBound && config.requireConsumerBinding !== false) {
132
+ return reject('openQuote requires the authenticated consumer identity', 'QUOTE_CONSUMER_UNBOUND');
48
133
  }
49
- return config.host.openChannel({
50
- quote,
51
- ...(typeof funding === 'string' ? { fundingCoinId: funding } : funding ?? {}),
134
+ const verified = await verifyOpenQuote(quote, config.manifest, {
135
+ now: currentTime,
136
+ ...(config.verifyQuoteSignature
137
+ ? { verifySignature: config.verifyQuoteSignature }
138
+ : {}),
139
+ ...(consumer?.partyId !== undefined
140
+ ? { expectedConsumerPartyId: consumer.partyId }
141
+ : {}),
142
+ ...(consumer?.publicKeyDigest !== undefined
143
+ ? { expectedConsumerPublicKeyDigest: consumer.publicKeyDigest }
144
+ : {}),
145
+ ...(consumer?.address !== undefined
146
+ ? { expectedConsumerAddress: consumer.address }
147
+ : {}),
52
148
  });
149
+ if (!verified.ok) {
150
+ return reject(`Quote rejected: ${verified.errors.join('; ')}`, 'QUOTE_INVALID');
151
+ }
152
+ // Re-apply the current policy: the manifest, custody mode and capacity may
153
+ // have changed since the quote was issued.
154
+ const policyDecision = evaluateOpenRequest(config.manifest, quoteAsRequest(quote), config.policy, currentTime);
155
+ if (!policyDecision.allowed) {
156
+ return reject(`Quote no longer satisfies provider policy: ${policyDecision.errors.join('; ')}`, 'QUOTE_POLICY_REJECTED');
157
+ }
158
+ return redeem(quote, funding);
53
159
  },
54
160
  async close(channelId) {
55
161
  if (!config.host.closeChannel) {
56
- return { success: false, error: 'Host does not implement closeChannel', errorCode: 'UNSUPPORTED' };
162
+ return reject('Host does not implement closeChannel', 'UNSUPPORTED');
57
163
  }
58
164
  return config.host.closeChannel(channelId);
59
165
  },
package/dist/quote.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { OmniaLspManifest, OmniaLspOpenQuote } from '@totemsdk/omnia-lsp';
1
+ import type { OmniaLspFeeBasis, OmniaLspManifest, OmniaLspOpenQuote, OpenQuoteSigningPayload } from '@totemsdk/omnia-lsp';
2
2
  import type { OmniaLspOpenRequest } from './policy.js';
3
3
  export type UnsignedOmniaLspOpenQuote = Omit<OmniaLspOpenQuote, 'signature'>;
4
4
  export interface CreateQuoteOptions {
@@ -7,14 +7,24 @@ export interface CreateQuoteOptions {
7
7
  now?: number;
8
8
  ttlMs?: number;
9
9
  quoteId?: string;
10
+ /** Fee basis for percentage fees. Defaults to the total channel value. */
11
+ feeBasis?: OmniaLspFeeBasis;
10
12
  }
11
13
  /**
12
14
  * Build the provider's unsigned open quote. The provider host signs it before
13
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.
14
20
  */
15
21
  export declare function createUnsignedOpenQuote(options: CreateQuoteOptions): UnsignedOmniaLspOpenQuote;
16
22
  /**
17
23
  * Sign an unsigned quote with a provider identity signer. The signer is injected
18
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.
19
29
  */
20
- export declare function signOpenQuote(quote: UnsignedOmniaLspOpenQuote, sign: (quote: UnsignedOmniaLspOpenQuote) => Promise<string> | string): Promise<OmniaLspOpenQuote>;
30
+ export declare function signOpenQuote(quote: UnsignedOmniaLspOpenQuote, sign: (quote: UnsignedOmniaLspOpenQuote, payload: OpenQuoteSigningPayload) => Promise<string> | string): Promise<OmniaLspOpenQuote>;
package/dist/quote.js CHANGED
@@ -1,59 +1,43 @@
1
- import { hashCanonical } from '@totemsdk/core';
2
- const DECIMAL_SCALE = 18n;
3
- const DECIMAL_FACTOR = 10n ** DECIMAL_SCALE;
4
- function decimalKey(value) {
5
- const [whole = '0', fraction = ''] = value.split('.');
6
- return (BigInt(whole) * DECIMAL_FACTOR +
7
- BigInt(fraction.padEnd(Number(DECIMAL_SCALE), '0').slice(0, Number(DECIMAL_SCALE))));
8
- }
9
- function formatScaled(value) {
10
- const negative = value < 0n;
11
- const absolute = negative ? -value : value;
12
- const whole = absolute / DECIMAL_FACTOR;
13
- const fraction = absolute % DECIMAL_FACTOR;
14
- const fractionText = fraction
15
- .toString()
16
- .padStart(Number(DECIMAL_SCALE), '0')
17
- .replace(/0+$/, '');
18
- return `${negative ? '-' : ''}${whole.toString()}${fractionText ? `.${fractionText}` : ''}`;
19
- }
20
- function applyBps(amount, bps) {
21
- return formatScaled((decimalKey(amount) * BigInt(bps)) / 10000n);
22
- }
1
+ import { buildOpenTerms, computeOpenFees, DEFAULT_FEE_BASIS, openQuoteSigningPayload, openTermsHash, } from '@totemsdk/omnia-lsp';
23
2
  /**
24
3
  * Build the provider's unsigned open quote. The provider host signs it before
25
4
  * returning it to the consumer; a quote without a signature is not authoritative.
5
+ *
6
+ * The quoted fees come from the shared schedule (OMN-072) and the terms object
7
+ * is built by `buildOpenTerms`, which is the same function the verifier uses to
8
+ * recompute the hash.
26
9
  */
27
10
  export function createUnsignedOpenQuote(options) {
28
11
  const { manifest, request } = options;
29
12
  const now = options.now ?? Date.now();
30
13
  const ttlMs = options.ttlMs ?? 60000;
31
14
  const expiresAt = now + ttlMs;
32
- const openFee = manifest.fees.openFlat ??
33
- (manifest.fees.openBps ? applyBps(request.localAmount, manifest.fees.openBps) : '0');
34
- const leaseFee = request.lease === true && manifest.fees.leaseBps
35
- ? applyBps(request.localAmount, manifest.fees.leaseBps)
36
- : undefined;
37
- const terms = {
38
- version: 'omnia-lsp/open-terms/v1',
39
- providerId: manifest.providerId,
15
+ const basis = options.feeBasis ?? DEFAULT_FEE_BASIS;
16
+ const fees = computeOpenFees(manifest, request, basis);
17
+ if (!fees.ok) {
18
+ throw new Error(`cannot quote open request: ${fees.error}`);
19
+ }
20
+ const schedule = fees.schedule;
21
+ const terms = buildOpenTerms({
22
+ manifest,
40
23
  consumerAddress: request.consumerAddress,
41
24
  consumerPartyId: request.consumerPartyId,
42
25
  consumerPublicKeyDigest: request.consumerPublicKeyDigest,
43
- consumerSettlementAddress: request.consumerSettlementAddress ?? null,
44
- consumerTransportPubkey: request.consumerTransportPubkey ?? null,
26
+ ...(request.consumerSettlementAddress !== undefined
27
+ ? { consumerSettlementAddress: request.consumerSettlementAddress }
28
+ : {}),
29
+ ...(request.consumerTransportPubkey !== undefined
30
+ ? { consumerTransportPubkey: request.consumerTransportPubkey }
31
+ : {}),
45
32
  tokenId: request.tokenId,
46
33
  localAmount: request.localAmount,
47
34
  remoteAmount: request.remoteAmount,
48
- openFee,
49
- leaseFee: leaseFee ?? null,
50
- providerPartyId: manifest.channel.partyId,
51
- providerPublicKeyDigest: manifest.channel.publicKeyDigest,
52
- providerSettlementAddress: manifest.channel.settlementAddress,
35
+ openFee: schedule.openFee,
36
+ ...(schedule.leaseFee !== undefined ? { leaseFee: schedule.leaseFee } : {}),
37
+ feeBasis: schedule.basis,
53
38
  expiresAt,
54
- };
55
- const rawTermsHash = hashCanonical('omnia-lsp:open-terms:v1', terms);
56
- const termsHash = rawTermsHash.startsWith('0x') ? rawTermsHash : `0x${rawTermsHash}`;
39
+ });
40
+ const termsHash = openTermsHash(terms);
57
41
  return {
58
42
  version: 'omnia-lsp/open-quote/v1',
59
43
  quoteId: options.quoteId ?? `quote-${termsHash.slice(2, 18)}-${now.toString(36)}`,
@@ -70,8 +54,9 @@ export function createUnsignedOpenQuote(options) {
70
54
  tokenId: request.tokenId,
71
55
  localAmount: request.localAmount,
72
56
  remoteAmount: request.remoteAmount,
73
- openFee,
74
- ...(leaseFee !== undefined ? { leaseFee } : {}),
57
+ openFee: schedule.openFee,
58
+ ...(schedule.leaseFee !== undefined ? { leaseFee: schedule.leaseFee } : {}),
59
+ feeBasis: schedule.basis,
75
60
  providerPartyId: manifest.channel.partyId,
76
61
  providerPublicKeyDigest: manifest.channel.publicKeyDigest,
77
62
  providerSettlementAddress: manifest.channel.settlementAddress,
@@ -82,7 +67,12 @@ export function createUnsignedOpenQuote(options) {
82
67
  /**
83
68
  * Sign an unsigned quote with a provider identity signer. The signer is injected
84
69
  * so the package stays runtime-neutral and never holds a private key.
70
+ *
71
+ * The second argument is the exact payload to sign (`domain|termsHash`). A
72
+ * one-argument signer keeps working; a signer that ignores the payload must sign
73
+ * this same string to produce quotes that `verifyOpenQuote` accepts.
85
74
  */
86
75
  export function signOpenQuote(quote, sign) {
87
- return Promise.resolve(sign(quote)).then((signature) => ({ ...quote, signature }));
76
+ const payload = openQuoteSigningPayload(quote);
77
+ return Promise.resolve(sign(quote, payload)).then((signature) => ({ ...quote, signature }));
88
78
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totemsdk/omnia-lsp-provider",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Reference Omnia Liquidity Service Provider — policy, signed quotes and host adapter",
5
5
  "main": "dist/cjs/index.js",
6
6
  "types": "dist/cjs/index.d.ts",
@@ -24,7 +24,7 @@
24
24
  ],
25
25
  "dependencies": {
26
26
  "@totemsdk/core": "^1.6.1",
27
- "@totemsdk/omnia-lsp": "^0.1.0"
27
+ "@totemsdk/omnia-lsp": "^0.2.0"
28
28
  },
29
29
  "devDependencies": {
30
30
  "@types/node": "^20.0.0",