@defuse-protocol/nearintents-mpp-sdk 0.1.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -51,7 +51,7 @@ export function charge(parameters: charge.Parameters) {
51
51
  // Distribution-channel attribution: every 1Click swap minted by this
52
52
  // payment method carries the "mpp" referral (mirrors the x402 gateway).
53
53
  referral = 'mpp',
54
- refundTo,
54
+ refundTo: refundToOption,
55
55
  slippageTolerance = 100,
56
56
  } = parameters
57
57
 
@@ -70,14 +70,31 @@ export function charge(parameters: charge.Parameters) {
70
70
  const originNetwork = Types.chainOf(originAsset)
71
71
  const destinationNetwork = Types.chainOf(destinationAsset)
72
72
 
73
+ if (typeof refundToOption === 'string' && !refundToOption.trim())
74
+ throw new Error('nearintents-mpp-sdk: refundTo must not be empty.')
75
+
73
76
  const expiresWindowMs = (parameters.expiresWindow ?? 300) * 1000
74
77
  const quoteDeadlineBufferMs = (parameters.quoteDeadlineBuffer ?? 900) * 1000
75
78
  const pollIntervalMs = parameters.pollInterval ?? 2000
76
79
 
77
- const store = Store.from(
78
- (parameters.store ?? Store.memory()) as Store.AtomicStore<charge.StoreItemMap>,
79
- { keyPrefix: parameters.storeKeyPrefix ?? '' },
80
- )
80
+ assertPositiveFinite('expiresWindow', expiresWindowMs)
81
+ assertPositiveFinite('quoteDeadlineBuffer', quoteDeadlineBufferMs)
82
+ assertNonNegativeFinite('pollInterval', pollIntervalMs)
83
+ if (oneClick.requestTimeoutMs !== undefined)
84
+ assertPositiveFinite('oneClick.requestTimeoutMs', oneClick.requestTimeoutMs)
85
+ if (parameters.settlementTimeout !== undefined)
86
+ assertPositiveFinite('settlementTimeout', parameters.settlementTimeout)
87
+ if (!Number.isInteger(slippageTolerance) || slippageTolerance < 0 || slippageTolerance > 10_000)
88
+ throw new Error('nearintents-mpp-sdk: slippageTolerance must be an integer from 0 to 10000.')
89
+
90
+ const backingStore = parameters.store ?? Store.memory()
91
+ if (typeof backingStore.update !== 'function')
92
+ throw new Error(
93
+ 'nearintents-mpp-sdk: charge() requires an atomic store with update() for replay protection.',
94
+ )
95
+ const store = Store.from(backingStore as Store.AtomicStore<charge.StoreItemMap>, {
96
+ keyPrefix: parameters.storeKeyPrefix ?? '',
97
+ })
81
98
 
82
99
  // Token list is fetched lazily and re-fetched once on an unresolved asset
83
100
  // (the list evolves); a persistent miss is a merchant-config error.
@@ -106,9 +123,10 @@ export function charge(parameters: charge.Parameters) {
106
123
 
107
124
  const depositKey = (address: string) => `nearintents-mpp-sdk:deposit:${address}` as const
108
125
  const quoteKey = (identity: string) => `nearintents-mpp-sdk:quote:${identity}` as const
109
- const hashKey = (hash: string) => `nearintents-mpp-sdk:hash:${hash.toLowerCase()}` as const
126
+ const hashKey = (network: string, hash: string) =>
127
+ `nearintents-mpp-sdk:hash:${network}:${OneClick.canonicalTxHash(hash, network)}` as const
110
128
 
111
- function identityOf(amountOut: string): string {
129
+ function identityOf(amountOut: string, refundTo: string): string {
112
130
  return [
113
131
  originAsset,
114
132
  destinationAsset,
@@ -120,14 +138,31 @@ export function charge(parameters: charge.Parameters) {
120
138
  ].join('|')
121
139
  }
122
140
 
141
+ async function resolveRefundTo(
142
+ capturedRequest: Method.CapturedRequest | undefined,
143
+ ): Promise<string> {
144
+ const value =
145
+ typeof refundToOption === 'function'
146
+ ? await refundToOption({ capturedRequest, originNetwork })
147
+ : refundToOption
148
+ if (!value?.trim())
149
+ throw new Error(
150
+ 'nearintents-mpp-sdk: refundTo resolver returned no address; the server must know the payer refund address before minting an executable quote.',
151
+ )
152
+ return value
153
+ }
154
+
123
155
  /**
124
156
  * Returns the route's active canonical request, minting a fresh 1Click
125
157
  * quote when there is none — or when the cached one is stale (early
126
158
  * refresh: a quote is stale once `now + expiresWindow > quote deadline`,
127
159
  * so the challenge `expires` always precedes the active quote's deadline).
128
160
  */
129
- async function resolveActiveRequest(amountOut: string): Promise<Types.ChargeRequest> {
130
- const identity = identityOf(amountOut)
161
+ async function resolveActiveRequest(
162
+ amountOut: string,
163
+ refundTo: string,
164
+ ): Promise<Types.ChargeRequest> {
165
+ const identity = identityOf(amountOut, refundTo)
131
166
 
132
167
  const pointer = await store.get(quoteKey(identity))
133
168
  if (pointer && pointer.identity === identity) {
@@ -221,6 +256,11 @@ export function charge(parameters: charge.Parameters) {
221
256
  if (!current) return { op: 'noop', result: undefined }
222
257
  return { op: 'set', value: { ...current, state: 'settled' }, result: undefined }
223
258
  })
259
+ await dropQuotePointer(depositAddress, identity)
260
+ }
261
+
262
+ /** Drops the cache pointer only, so the next 402 mints fresh while the deposit stays presentable. */
263
+ async function dropQuotePointer(depositAddress: string, identity: string): Promise<void> {
224
264
  await store.update(quoteKey(identity), (current) => {
225
265
  if (current?.depositAddress !== depositAddress) return { op: 'noop', result: undefined }
226
266
  return { op: 'delete', result: undefined }
@@ -229,10 +269,11 @@ export function charge(parameters: charge.Parameters) {
229
269
 
230
270
  /** Atomically claims `hash` as in-flight. Expired leases are reclaimable. */
231
271
  async function claimHash(
272
+ network: string,
232
273
  hash: string,
233
274
  leaseUntil: number,
234
275
  ): Promise<'claimed' | 'inflight' | 'consumed'> {
235
- return store.update(hashKey(hash), (current) => {
276
+ return store.update(hashKey(network, hash), (current) => {
236
277
  if (current?.state === 'consumed') return { op: 'noop', result: 'consumed' }
237
278
  if (current?.state === 'inflight' && current.leaseUntil > Date.now())
238
279
  return { op: 'noop', result: 'inflight' }
@@ -259,7 +300,7 @@ export function charge(parameters: charge.Parameters) {
259
300
  minAmountIn: '0',
260
301
  depositMemo: null,
261
302
  slippageTolerance,
262
- refundTo,
303
+ refundTo: typeof refundToOption === 'string' ? refundToOption : 'payer-supplied',
263
304
  settlementBackend: Types.settlementBackend,
264
305
  credentialTypes: [...Types.credentialTypes],
265
306
  },
@@ -270,10 +311,16 @@ export function charge(parameters: charge.Parameters) {
270
311
  // binding mismatch → 402 with a fresh challenge (the client-recovery flow).
271
312
  stableBinding(request) {
272
313
  const { amount, currency, methodDetails, recipient } = request
273
- return { amount, currency, originNetwork: methodDetails.originNetwork, recipient }
314
+ return {
315
+ amount,
316
+ currency,
317
+ originNetwork: methodDetails.originNetwork,
318
+ recipient,
319
+ refundTo: methodDetails.refundTo,
320
+ }
274
321
  },
275
322
 
276
- async request({ credential, request }) {
323
+ async request({ capturedRequest, credential, request }) {
277
324
  const amountOut =
278
325
  (request.methodDetails as Partial<Types.MethodDetails> | undefined)?.amountOut ??
279
326
  defaultAmountOut
@@ -294,7 +341,7 @@ export function charge(parameters: charge.Parameters) {
294
341
  if (
295
342
  deposit &&
296
343
  deposit.state === 'active' &&
297
- deposit.identity === identityOf(amountOut) &&
344
+ deposit.identity === identityOf(amountOut, deposit.request.methodDetails.refundTo) &&
298
345
  Date.parse(deposit.deadline) > Date.now()
299
346
  )
300
347
  return deposit.request
@@ -304,7 +351,7 @@ export function charge(parameters: charge.Parameters) {
304
351
  // carrying this fresh challenge — the spec's client-recovery flow.
305
352
  }
306
353
 
307
- return resolveActiveRequest(amountOut)
354
+ return resolveActiveRequest(amountOut, await resolveRefundTo(capturedRequest))
308
355
  },
309
356
 
310
357
  async verify({ credential, request }) {
@@ -344,7 +391,7 @@ export function charge(parameters: charge.Parameters) {
344
391
  // atomically; consume permanently only on a terminal settlement state.
345
392
  // The lease covers the settlement budget so a crashed settlement never
346
393
  // strands a legitimate retry.
347
- const claim = await claimHash(hash, Date.now() + settlementTimeoutMs + 60_000)
394
+ const claim = await claimHash(originNetwork, hash, Date.now() + settlementTimeoutMs + 60_000)
348
395
  if (claim === 'consumed')
349
396
  throw new Errors.VerificationFailedError({
350
397
  reason: 'transaction hash has already been used',
@@ -380,15 +427,23 @@ export function charge(parameters: charge.Parameters) {
380
427
  emit({ type: 'settlement.status', depositAddress: recipient, status: observed }),
381
428
  })
382
429
 
383
- // Any terminal state spends the quote and its deposit address —
384
- // including SUCCESS whose observed deposits don't match the presented
385
- // hash (below). Retiring here, before that match check, is deliberate:
386
- // once the backend reaches SUCCESS the deposit is delivered, so the
387
- // quote MUST leave rotation regardless of which credential presented
388
- // it. Deferring the retire until after a match check would strand a
389
- // backend-settled deposit as "active" in the store, and a later
390
- // cache hit could hand a fresh payer an already-spent deposit address.
391
- await retireDeposit(recipient, deposit.identity)
430
+ // Deposit confirmation applies to every terminal outcome. Do not
431
+ // retire the quote or consume an unrelated hash: the real payer must
432
+ // still be able to present the observed transaction after a bad-hash
433
+ // race. Hex hashes are canonicalized by matchesOriginTx; base58 and
434
+ // other formats remain case-sensitive. The backend has still reached
435
+ // a terminal state for this deposit address, so drop the cache
436
+ // pointer: a later challenge must not hand a new payer this address.
437
+ if (!OneClick.matchesOriginTx(status, hash, originNetwork)) {
438
+ await dropQuotePointer(recipient, deposit.identity)
439
+ throw new Errors.VerificationFailedError({
440
+ reason:
441
+ 'the presented transaction hash is not among the deposits observed for this address',
442
+ })
443
+ }
444
+
445
+ // Observability: report the terminal state (retirement is handled per
446
+ // outcome below, not here — a bad-hash race must not spend the quote).
392
447
  emit({
393
448
  type: 'settlement.terminal',
394
449
  depositAddress: recipient,
@@ -400,14 +455,6 @@ export function charge(parameters: charge.Parameters) {
400
455
  })
401
456
 
402
457
  if (status.status === 'SUCCESS') {
403
- // Deposit confirmation: the presented hash must be among the
404
- // origin-chain transactions the backend observed for this address.
405
- if (!OneClick.matchesOriginTx(status, hash))
406
- throw new Errors.VerificationFailedError({
407
- reason:
408
- 'the presented transaction hash is not among the deposits observed for this address',
409
- })
410
- hashOutcome = 'consume'
411
458
  const reference =
412
459
  OneClick.destinationTxHash(status) ?? status.swapDetails?.nearTxHashes?.[0]
413
460
  // The merchant has been paid at this point; a missing reference is
@@ -430,12 +477,18 @@ export function charge(parameters: charge.Parameters) {
430
477
  originTxHash: hash,
431
478
  reference,
432
479
  })
480
+ // Retire only after the receipt is complete. If the backend reports
481
+ // SUCCESS before its settlement reference is indexed, the same
482
+ // credential can be retried instead of being stranded.
483
+ await retireDeposit(recipient, deposit.identity)
484
+ hashOutcome = 'consume'
433
485
  return receipt
434
486
  }
435
487
 
436
488
  // Non-success terminal (FAILED/REFUNDED/INCOMPLETE_DEPOSIT): the
437
489
  // deposit is refunded to refundTo and the hash can never deliver —
438
490
  // consume it. The client recovers with a fresh challenge.
491
+ await retireDeposit(recipient, deposit.identity)
439
492
  hashOutcome = 'consume'
440
493
  throw (
441
494
  OneClick.terminalError(status) ??
@@ -465,13 +518,24 @@ export function charge(parameters: charge.Parameters) {
465
518
  }
466
519
  throw error
467
520
  } finally {
468
- if (hashOutcome === 'consume') await store.put(hashKey(hash), { state: 'consumed' })
469
- else await store.delete(hashKey(hash))
521
+ const key = hashKey(originNetwork, hash)
522
+ if (hashOutcome === 'consume') await store.put(key, { state: 'consumed' })
523
+ else await store.delete(key)
470
524
  }
471
525
  },
472
526
  })
473
527
  }
474
528
 
529
+ function assertPositiveFinite(name: string, value: number): void {
530
+ if (!Number.isFinite(value) || value <= 0)
531
+ throw new Error(`nearintents-mpp-sdk: ${name} must be a positive finite number.`)
532
+ }
533
+
534
+ function assertNonNegativeFinite(name: string, value: number): void {
535
+ if (!Number.isFinite(value) || value < 0)
536
+ throw new Error(`nearintents-mpp-sdk: ${name} must be a non-negative finite number.`)
537
+ }
538
+
475
539
  export declare namespace charge {
476
540
  /**
477
541
  * Structured settlement-progress events for merchant observability (wire
@@ -545,11 +609,19 @@ export declare namespace charge {
545
609
  /** Merchant address on the destination chain. */
546
610
  destinationRecipient: string
547
611
  /**
548
- * Merchant-configured refund address on the origin chain. The server
549
- * cannot know the payer pre-payment; clients recover refunds off-band
550
- * (document this in the merchant's terms).
612
+ * Origin-chain refund address, either fixed or resolved before each wet
613
+ * quote. Prefer a resolver backed by authenticated payer context (or a
614
+ * validated HTTP header) so failed swaps return funds directly to the
615
+ * payer. A resolved address is quote-bound and echoed in the challenge.
551
616
  */
552
- refundTo: string
617
+ refundTo:
618
+ | string
619
+ | ((parameters: {
620
+ /** Captured transport request. HTTP integrations can read a payer hint from headers. */
621
+ capturedRequest?: Method.CapturedRequest | undefined
622
+ /** CAIP-2 origin network whose address format the resolver must return. */
623
+ originNetwork: string
624
+ }) => string | Promise<string>)
553
625
  /**
554
626
  * Default price: exact amount the merchant receives, in base units of
555
627
  * `destinationAsset` (EXACT_OUTPUT). Overridable per route via