@agoric/portfolio-api 0.1.1-dev-8cdc94d.0.8cdc94d → 0.1.1-dev-c4c46b1.0.c4c46b1

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.
@@ -20,7 +20,8 @@
20
20
  *
21
21
  * This module has no runtime dependency on Endo, so that it can be used
22
22
  * outside of a locked-down (SES) environment, e.g. by the attestor. In
23
- * particular, the values it returns are not hardened.
23
+ * particular, the values it returns are not hardened, but they share no
24
+ * state with the caller's: the converters validate a copy of their input.
24
25
  */
25
26
 
26
27
 
@@ -35,7 +36,9 @@ import {
35
36
 
36
37
 
37
38
  } from '@agoric/orchestration/src/utils/eip712-messages.js';
39
+ ;
38
40
  ;
41
+ import { sameEvmAddress } from '@agoric/orchestration/src/utils/evm-address.js';
39
42
  import {
40
43
  isEvmChain,
41
44
  isInterChainAccountRef,
@@ -45,7 +48,11 @@ import {
45
48
  getCanonicalHoldingKey,
46
49
  } from './places.js';
47
50
  ;
51
+
52
+
53
+
48
54
 
55
+
49
56
 
50
57
 
51
58
 
@@ -64,12 +71,21 @@ const ObservationOperationTypes = {
64
71
  * - syncState: the portfolio state the observations correspond to
65
72
  * - holdings: the balance of every balance-bearing place of the portfolio
66
73
  * - instruments: details of the instruments relevant to the portfolio
74
+ * - aaveClaims, compoundClaims, merklClaims, oneInchSwaps: optional claim
75
+ * evidence and swap instructions, which plan steps select by index (see
76
+ * {@link SelectableObservations}), each present only when requested. As
77
+ * there is a single `PortfolioObservations` per message, their presence
78
+ * never conflicts.
67
79
  */
68
80
  PortfolioObservations: [
69
81
  PortfolioIdParam,
70
82
  { name: 'syncState', type: 'SyncState' },
71
83
  { name: 'holdings', type: 'HoldingDetail[]' },
72
84
  { name: 'instruments', type: 'InstrumentDetail[]' },
85
+ { name: 'aaveClaims', type: 'AaveClaim[]', optional: true },
86
+ { name: 'compoundClaims', type: 'CompoundClaim[]', optional: true },
87
+ { name: 'merklClaims', type: 'MerklClaim[]', optional: true },
88
+ { name: 'oneInchSwaps', type: 'OneInchSwap[]', optional: true },
73
89
  ],
74
90
  } ;
75
91
 
@@ -106,6 +122,43 @@ const ObservationSubTypes = {
106
122
  /** in whole USD */
107
123
  { name: 'tvlUsd', type: 'uint256' },
108
124
  ],
125
+ // Every field of the selectable structs is required.
126
+ /** @see {@link AaveClaimEvidence} */
127
+ AaveClaim: [
128
+ { name: 'instrumentId', type: 'string' },
129
+ { name: 'tokenId', type: 'address' },
130
+ { name: 'expectedAmount', type: 'uint256' },
131
+ ],
132
+ /** @see {@link CompoundClaimEvidence} */
133
+ CompoundClaim: [
134
+ { name: 'instrumentId', type: 'string' },
135
+ { name: 'tokenId', type: 'address' },
136
+ { name: 'expectedAmount', type: 'uint256' },
137
+ ],
138
+ /** @see {@link MerklClaimEvidence} */
139
+ MerklClaim: [
140
+ { name: 'accountPlace', type: 'string' },
141
+ { name: 'distributor', type: 'address' },
142
+ { name: 'tokenId', type: 'address' },
143
+ { name: 'cumulativeAmount', type: 'uint256' },
144
+ { name: 'claimedAmount', type: 'uint256' },
145
+ { name: 'proof', type: 'bytes32[]' },
146
+ ],
147
+ /** @see {@link OneInchSwapInstructions} */
148
+ OneInchSwap: [
149
+ { name: 'accountPlace', type: 'string' },
150
+ { name: 'tokenIn', type: 'address' },
151
+ { name: 'tokenOut', type: 'address' },
152
+ { name: 'amountIn', type: 'uint256' },
153
+ { name: 'quotedAmountOut', type: 'uint256' },
154
+ { name: 'minAmountOut', type: 'uint256' },
155
+ { name: 'slippageBps', type: 'uint16' },
156
+ { name: 'expiresAt', type: 'uint64' },
157
+ { name: 'flags', type: 'uint256' },
158
+ { name: 'executor', type: 'address' },
159
+ { name: 'srcReceiver', type: 'address' },
160
+ { name: 'data', type: 'bytes' },
161
+ ],
109
162
  } ;
110
163
 
111
164
  /**
@@ -207,6 +260,10 @@ const typedHoldingFromEIP712 = ({
207
260
  : { valueUusd }),
208
261
  }) ;
209
262
 
263
+ /** A canonical (lowercase) EVM address. */
264
+ const LOWERCASE_EVM_ADDRESS_REGEX = /^0x[0-9a-f]{40}$/;
265
+ const ZERO_EVM_ADDRESS = `0x${'0'.repeat(40)}`;
266
+
210
267
  const assertUint256 = (value , field ) => {
211
268
  if (typeof value !== 'bigint' || value < 0n || value >= 2n ** 256n) {
212
269
  throw RangeError(`invalid uint256 ${field}: ${String(value)}`);
@@ -245,15 +302,22 @@ const assertTypedHoldings
245
302
  }
246
303
  const isNative =
247
304
  typeof kind === 'string' && kind.startsWith('$') && kind.length > 1;
305
+ // A claimable reward may be attributed to an instrument, or only
306
+ // to the account entitled to claim it (e.g. Merkl rewards).
307
+ const isClaimableReward = kind === 'claimable-reward';
248
308
  const isInstrument =
249
- kind === 'shares' || kind === 'principal' || kind === 'claimable-reward';
309
+ isClaimableReward || kind === 'shares' || kind === 'principal';
250
310
  const isAccountHolding =
251
- isNative || kind === 'token' || kind === 'claimed-reward';
311
+ isClaimableReward ||
312
+ isNative ||
313
+ kind === 'token' ||
314
+ kind === 'claimed-reward';
252
315
  if (!isAccountHolding && !isInstrument) {
253
316
  throw TypeError(`invalid holding kind ${JSON.stringify(kind)}`);
254
317
  }
255
318
  if (
256
- isInstrument ? !isInstrumentId(place) : !isInterChainAccountRef(place)
319
+ !(isInstrument && isInstrumentId(place)) &&
320
+ !(isAccountHolding && isInterChainAccountRef(place))
257
321
  ) {
258
322
  throw TypeError(
259
323
  `holding kind ${kind} is incompatible with place ${place}`,
@@ -266,7 +330,7 @@ const assertTypedHoldings
266
330
  if (
267
331
  typeof tokenId !== 'string' ||
268
332
  /\s/.test(tokenId) ||
269
- (!isNative && isEvmPlace && !/^0x[0-9a-f]{40}$/.test(tokenId))
333
+ (!isNative && isEvmPlace && !LOWERCASE_EVM_ADDRESS_REGEX.test(tokenId))
270
334
  ) {
271
335
  throw TypeError(`invalid holding token identifier ${String(tokenId)}`);
272
336
  }
@@ -322,6 +386,207 @@ const balancesFromTypedHoldings = (
322
386
  return Object.fromEntries(balances);
323
387
  };
324
388
 
389
+ /**
390
+ * A deep copy of plain data (arrays, records and primitives), so that what is
391
+ * validated cannot then be changed through references the caller retains.
392
+ * Rejects anything else (e.g. a `Uint8Array`), which the converters' types
393
+ * never declare.
394
+ */
395
+ const copyPlainData = (value ) => {
396
+ if (Array.isArray(value)) return value.map(copyPlainData) ;
397
+ if (typeof value === 'function') {
398
+ throw TypeError('expected plain data, got a function');
399
+ }
400
+ if (value !== null && typeof value === 'object') {
401
+ const proto = Object.getPrototypeOf(value);
402
+ if (proto !== Object.prototype && proto !== null) {
403
+ throw TypeError(
404
+ `expected plain data, got ${Object.prototype.toString.call(value)}`,
405
+ );
406
+ }
407
+ return Object.fromEntries(
408
+ Object.entries(value).map(([k, v]) => [k, copyPlainData(v)]),
409
+ ) ;
410
+ }
411
+ return value;
412
+ };
413
+
414
+ /**
415
+ * Signed selectable observations, before {@link pickSelectableObservations}
416
+ * narrows them. The EIP-712 layer checks primitive types and ranges (and, when
417
+ * decoding, rejects missing or unknown fields); only application constraints
418
+ * are checked here.
419
+ */
420
+ ;
421
+
422
+
423
+
424
+ ;
425
+
426
+
427
+ /**
428
+ * Addresses in selectable observations are EIP-712 `address` values, whose
429
+ * hashing ignores case (unlike holding token identifiers, which are strings),
430
+ * so they may be lowercase or EIP-55 checksummed. Like the EIP-712 layer, this
431
+ * does not verify checksums, which signing does. Compare them with
432
+ * {@link sameEvmAddress}, or lowercase them for keys.
433
+ */
434
+ const assertNonZeroAddress = (
435
+ value ,
436
+ label ,
437
+ field ,
438
+ ) => {
439
+ if (value === ZERO_EVM_ADDRESS) {
440
+ throw TypeError(`[${label}] invalid ${field} address ${value}`);
441
+ }
442
+ };
443
+
444
+ const assertEvmAccountPlace
445
+
446
+
447
+ = (place, label) => {
448
+ if (!isInterChainAccountRef(place) || !isEvmChain(maybeChainOf(place))) {
449
+ throw TypeError(
450
+ `[${label}] invalid account place ${JSON.stringify(place)}`,
451
+ );
452
+ }
453
+ };
454
+
455
+ /**
456
+ * Validate instrument-attributed claims, whose instrument must be of the
457
+ * claim's protocol, on an EVM chain.
458
+ */
459
+ const assertInstrumentClaims
460
+
461
+
462
+
463
+ = (
464
+ claims,
465
+ key,
466
+ protocol,
467
+ ) => {
468
+ const identities = new Set ();
469
+ claims.forEach(({ instrumentId, tokenId }, i) => {
470
+ const label = `${key}[${i}]`;
471
+ if (
472
+ !isInstrumentId(instrumentId) ||
473
+ !instrumentId.startsWith(`${protocol}_`) ||
474
+ !isEvmChain(maybeChainOf(instrumentId))
475
+ ) {
476
+ throw TypeError(
477
+ `[${label}] invalid ${protocol} instrument ${JSON.stringify(instrumentId)}`,
478
+ );
479
+ }
480
+ assertNonZeroAddress(tokenId, label, 'token');
481
+ const identity = JSON.stringify([instrumentId, tokenId.toLowerCase()]);
482
+ if (identities.has(identity)) {
483
+ throw TypeError(`[${label}] duplicate ${identity}`);
484
+ }
485
+ identities.add(identity);
486
+ });
487
+ };
488
+
489
+ /**
490
+ * The estimated incremental payout of a Merkl claim: its cumulative
491
+ * entitlement less what was observed to be claimed already. Not guaranteed,
492
+ * since the distributor uses its own claimed state at execution time.
493
+ *
494
+ * @param claim
495
+ * @throws {RangeError} if more was claimed than the cumulative entitlement
496
+ */
497
+ export const getMerklClaimExpectedAmount = ({
498
+ cumulativeAmount,
499
+ claimedAmount,
500
+ } ) => {
501
+ if (claimedAmount > cumulativeAmount) {
502
+ throw RangeError(
503
+ `claimedAmount ${claimedAmount} exceeds cumulativeAmount ${cumulativeAmount}`,
504
+ );
505
+ }
506
+ return cumulativeAmount - claimedAmount;
507
+ };
508
+
509
+ const assertMerklClaims
510
+
511
+ = claims => {
512
+ const identities = new Set ();
513
+ claims.forEach((claim, i) => {
514
+ const label = `merklClaims[${i}]`;
515
+ const { accountPlace, distributor, tokenId } = claim;
516
+ assertEvmAccountPlace(accountPlace, label);
517
+ assertNonZeroAddress(distributor, label, 'distributor');
518
+ assertNonZeroAddress(tokenId, label, 'token');
519
+ try {
520
+ getMerklClaimExpectedAmount(claim);
521
+ } catch (err) {
522
+ throw RangeError(`[${label}] ${(err ).message}`);
523
+ }
524
+ const identity = JSON.stringify([
525
+ accountPlace,
526
+ distributor.toLowerCase(),
527
+ tokenId.toLowerCase(),
528
+ ]);
529
+ if (identities.has(identity)) {
530
+ throw TypeError(`[${label}] duplicate ${identity}`);
531
+ }
532
+ identities.add(identity);
533
+ });
534
+ };
535
+
536
+ /**
537
+ * Validate the structure of swap instructions. Whether they are acceptable
538
+ * (their tokens, slippage, flags or expiry) is for its consumer to decide.
539
+ */
540
+ const assertOneInchSwaps
541
+
542
+ = swaps => {
543
+ swaps.forEach((swap, i) => {
544
+ const label = `oneInchSwaps[${i}]`;
545
+ const { accountPlace, tokenIn, tokenOut, amountIn, slippageBps } = swap;
546
+ assertEvmAccountPlace(accountPlace, label);
547
+ // The route's executor and srcReceiver may be the zero address,
548
+ // but tokens may not be.
549
+ assertNonZeroAddress(tokenIn, label, 'tokenIn');
550
+ assertNonZeroAddress(tokenOut, label, 'tokenOut');
551
+ if (sameEvmAddress(tokenIn, tokenOut)) {
552
+ throw TypeError(`[${label}] tokenIn and tokenOut must differ`);
553
+ }
554
+ if (amountIn === 0n) {
555
+ throw RangeError(`[${label}] amountIn must be positive`);
556
+ }
557
+ if (swap.minAmountOut > swap.quotedAmountOut) {
558
+ throw RangeError(`[${label}] minAmountOut exceeds quotedAmountOut`);
559
+ }
560
+ if (slippageBps > 10_000) {
561
+ throw RangeError(`[${label}] invalid slippageBps: ${slippageBps}`);
562
+ }
563
+ });
564
+ };
565
+
566
+ /**
567
+ * Pick the arrays present in `source`, validated. An absent array remains
568
+ * absent, distinct from an empty one.
569
+ */
570
+ const pickSelectableObservations = ({
571
+ aaveClaims,
572
+ compoundClaims,
573
+ merklClaims,
574
+ oneInchSwaps,
575
+ } ) => {
576
+ if (aaveClaims) assertInstrumentClaims(aaveClaims, 'aaveClaims', 'Aave');
577
+ if (compoundClaims) {
578
+ assertInstrumentClaims(compoundClaims, 'compoundClaims', 'Compound');
579
+ }
580
+ if (merklClaims) assertMerklClaims(merklClaims);
581
+ if (oneInchSwaps) assertOneInchSwaps(oneInchSwaps);
582
+ return {
583
+ ...(aaveClaims && { aaveClaims }),
584
+ ...(compoundClaims && { compoundClaims }),
585
+ ...(merklClaims && { merklClaims }),
586
+ ...(oneInchSwaps && { oneInchSwaps }),
587
+ };
588
+ };
589
+
325
590
  /**
326
591
  * Author either legacy balances or typed holdings using the shared schema.
327
592
  * Typed holdings always carry `valueUusd`, with {@link VALUE_UUSD_UNKNOWN}
@@ -329,11 +594,14 @@ const balancesFromTypedHoldings = (
329
594
  * repeat what their `balanceUsdc` values derive (as decoding returns), so no
330
595
  * balance is silently dropped.
331
596
  */
332
- export const portfolioObservationsToEIP712 = ({
333
- portfolioId,
334
- syncState,
335
- observations: { balances, holdings, instrumentTvls },
336
- } ) => {
597
+ export const portfolioObservationsToEIP712 = (
598
+ content ,
599
+ ) => {
600
+ const {
601
+ portfolioId,
602
+ syncState,
603
+ observations: { balances, holdings, instrumentTvls, ...rest },
604
+ } = copyPlainData(content);
337
605
  for (const [field, value] of Object.entries({
338
606
  portfolio: portfolioId,
339
607
  ...syncState,
@@ -380,12 +648,17 @@ export const portfolioObservationsToEIP712 = ({
380
648
  return [{ instrumentId, tvlUsd: tvl.tvlUsd }];
381
649
  },
382
650
  );
651
+ const selectable = pickSelectableObservations(rest);
383
652
  return {
384
653
  portfolio: portfolioId,
385
- syncState: { ...syncState },
654
+ syncState,
386
655
  holdings:
387
656
  holdings === undefined ? legacy : holdings.map(typedHoldingToEIP712),
388
657
  instruments,
658
+ ...(selectable
659
+
660
+
661
+ ),
389
662
  };
390
663
  };
391
664
 
@@ -397,12 +670,11 @@ export const portfolioObservationsToEIP712 = ({
397
670
  * A typed holding's {@link VALUE_UUSD_UNKNOWN} valuation decodes to an absent
398
671
  * `valueUusd`.
399
672
  */
400
- export const portfolioObservationsFromEIP712 = ({
401
- portfolio,
402
- syncState,
403
- holdings,
404
- instruments,
405
- } ) => {
673
+ export const portfolioObservationsFromEIP712 = (
674
+ message ,
675
+ ) => {
676
+ const { portfolio, syncState, holdings, instruments, ...rest } =
677
+ copyPlainData(message);
406
678
  const legacyBalances = {};
407
679
  const rawHoldings = [];
408
680
  for (const holding of holdings) {
@@ -446,6 +718,8 @@ export const portfolioObservationsFromEIP712 = ({
446
718
  assertUint256(tvlUsd, 'tvlUsd');
447
719
  instrumentTvls[instrumentId] = { tvlUsd };
448
720
  }
721
+ // Other fields (e.g. the standalone envelope) are the handler's concern.
722
+ const selectable = pickSelectableObservations(rest);
449
723
  return {
450
724
  portfolioId: toSafeNumber(portfolio, 'portfolio'),
451
725
  syncState: {
@@ -456,6 +730,7 @@ export const portfolioObservationsFromEIP712 = ({
456
730
  balances,
457
731
  ...(rawHoldings.length ? { holdings: rawHoldings } : {}),
458
732
  instrumentTvls,
733
+ ...selectable,
459
734
  },
460
735
  };
461
736
  };
@@ -62,6 +62,37 @@ export type UserFacingPortfolioPermissions = Omit<PortfolioPermissions, 'rebalan
62
62
  };
63
63
  /** Convert user-facing permissions to the intentionally narrower EIP-712 form. */
64
64
  export declare const portfolioPermissionsToEIP712: (permissions: UserFacingPortfolioPermissions) => PortfolioPermissionsEIP712;
65
+ /**
66
+ * The authority actually conferred by a {@link PortfolioPermissions} record,
67
+ * after inheritance. Unlike the stored (or signed) permission keys, every
68
+ * authority is resolved to a boolean, and none is ever absent.
69
+ */
70
+ export type EffectivePortfolioPermissions = {
71
+ allocation: boolean;
72
+ rebalance: boolean;
73
+ claimRewards: boolean;
74
+ };
75
+ /**
76
+ * Resolve the effective authority of stored permissions, using **stepwise**
77
+ * inheritance down the chain `allocation` → `rebalance` → `claimRewards`:
78
+ *
79
+ * - `allocation` is granted by `true` or by a constraint object (even `{}`),
80
+ * and denied when absent or `false`.
81
+ * - an absent `rebalance` inherits the effective `allocation`.
82
+ * - an absent `claimRewards` inherits the effective `rebalance`.
83
+ *
84
+ * An explicit `false` therefore blocks inheritance by lower permissions: with
85
+ * `{ allocation: true, rebalance: false }`, `claimRewards` is denied. An
86
+ * explicit `true` is an independent grant, regardless of higher permissions.
87
+ *
88
+ * This is the single source of truth for every consumer (contract, YDS,
89
+ * MCP, planner), including the planner's own auto-feature opt-out. Callers
90
+ * are expected to have validated `permissions` against
91
+ * {@link PortfolioPermissionsShape} when they come from an untrusted source.
92
+ *
93
+ * @param permissions
94
+ */
95
+ export declare const getEffectivePortfolioPermissions: (permissions: PortfolioPermissions) => EffectivePortfolioPermissions;
65
96
  /**
66
97
  * Extensible app-level shape for portfolio permissions.
67
98
  *
@@ -1 +1 @@
1
- {"version":3,"file":"portfolio-permissions.d.ts","sourceRoot":"","sources":["portfolio-permissions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,KAAK,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAEhE,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,OAAO,KAAK,EACV,2BAA2B,EAC3B,0BAA0B,EAC3B,MAAM,iCAAiC,CAAC;AAEzC;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,GAAG,8BAA8B,CAAC;IACtD,0EAA0E;IAC1E,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,0EAA0E;IAC1E,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,8BAA8B,GAAG;IAC3C;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,uBAAuB,GAAG,oBAAoB,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC;AAI7E;;;;;GAKG;AACH,eAAO,MAAM,mCAAmC,EAAE,YAAY,CAAC,8BAA8B,CAS1F,CAA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IACpB,SAAS,EAAE,OAAO,CAAC;IACnB,YAAY,EAAE,OAAO,CAAC;CACvB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,gCAAgC,GAC3C,aAAa,oBAAoB,KAChC,6BAUF,CAAC;AAGF;;;;;GAKG;AACH,eAAO,MAAM,4BAA4B,EAAE,YAAY,CAAC,uBAAuB,CAC9C,CAAC;AAElC,kEAAkE;AAClE,MAAM,MAAM,qBAAqB,GAAG;IAClC,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,0BAA0B,EAAE,YAAY,CAAC,qBAAqB,CACG,CAAC;AAE/E,eAAO,MAAM,gCAAgC,EAAE,YAAY,CAAC,2BAA2B,CACT,CAAC;AAE/E,uEAAuE;AACvE,MAAM,MAAM,wBAAwB,GAAG,qBAAqB,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC;AAE/E,mEAAmE;AACnE,eAAO,MAAM,6BAA6B,EAAE,YAAY,CAAC,wBAAwB,CAChD,CAAC"}
@@ -157,6 +157,52 @@ export const portfolioPermissionsToEIP712 = (
157
157
  });
158
158
  };
159
159
 
160
+ /**
161
+ * The authority actually conferred by a {@link PortfolioPermissions} record,
162
+ * after inheritance. Unlike the stored (or signed) permission keys, every
163
+ * authority is resolved to a boolean, and none is ever absent.
164
+ */
165
+ ;
166
+
167
+
168
+
169
+
170
+
171
+ /**
172
+ * Resolve the effective authority of stored permissions, using **stepwise**
173
+ * inheritance down the chain `allocation` → `rebalance` → `claimRewards`:
174
+ *
175
+ * - `allocation` is granted by `true` or by a constraint object (even `{}`),
176
+ * and denied when absent or `false`.
177
+ * - an absent `rebalance` inherits the effective `allocation`.
178
+ * - an absent `claimRewards` inherits the effective `rebalance`.
179
+ *
180
+ * An explicit `false` therefore blocks inheritance by lower permissions: with
181
+ * `{ allocation: true, rebalance: false }`, `claimRewards` is denied. An
182
+ * explicit `true` is an independent grant, regardless of higher permissions.
183
+ *
184
+ * This is the single source of truth for every consumer (contract, YDS,
185
+ * MCP, planner), including the planner's own auto-feature opt-out. Callers
186
+ * are expected to have validated `permissions` against
187
+ * {@link PortfolioPermissionsShape} when they come from an untrusted source.
188
+ *
189
+ * @param permissions
190
+ */
191
+ export const getEffectivePortfolioPermissions = (
192
+ permissions ,
193
+ ) => {
194
+ const { allocation, rebalance, claimRewards } = permissions;
195
+ const effectiveAllocation = allocation !== undefined && allocation !== false;
196
+ const effectiveRebalance = rebalance ?? effectiveAllocation;
197
+ const effectiveClaimRewards = claimRewards ?? effectiveRebalance;
198
+ return harden({
199
+ allocation: effectiveAllocation,
200
+ rebalance: effectiveRebalance,
201
+ claimRewards: effectiveClaimRewards,
202
+ });
203
+ };
204
+ harden(getEffectivePortfolioPermissions);
205
+
160
206
  /**
161
207
  * Extensible app-level shape for portfolio permissions.
162
208
  *
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @file Policy shared by the portfolio contract and the observation service
3
+ * (YDS) for swapping claimed rewards.
4
+ *
5
+ * This module has no runtime dependency on Endo, so that it can be used
6
+ * outside of a locked-down (SES) environment.
7
+ */
8
+ /**
9
+ * The maximum slippage tolerated by reward swap instructions, in basis
10
+ * points (2%). YDS quotes with this slippage unless the requester asks for a
11
+ * stricter one, and the contract rejects swap instructions whose
12
+ * `slippageBps` exceeds it, or whose `minAmountOut` is below what it implies.
13
+ */
14
+ export declare const MAX_REWARD_SWAP_SLIPPAGE_BPS = 200;
15
+ /**
16
+ * The least minimum output acceptable for a swap quoted to output
17
+ * `quotedAmountOut` with a tolerance of `slippageBps`, rounding up so that
18
+ * the tolerance is never exceeded:
19
+ * `ceil(quotedAmountOut * (10000 - slippageBps) / 10000)`.
20
+ *
21
+ * Both amounts are in raw units of the swap's output token.
22
+ *
23
+ * @param quotedAmountOut
24
+ * @param slippageBps an integer from 0 to 10000
25
+ */
26
+ export declare const getMinAmountOutForSlippage: (quotedAmountOut: bigint, slippageBps: number) => bigint;
27
+ //# sourceMappingURL=reward-swaps.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reward-swaps.d.ts","sourceRoot":"","sources":["reward-swaps.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH;;;;;GAKG;AACH,eAAO,MAAM,4BAA4B,MAAM,CAAC;AAEhD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,0BAA0B,GACrC,iBAAiB,MAAM,EACvB,aAAa,MAAM,KAClB,MAaF,CAAC"}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @file Policy shared by the portfolio contract and the observation service
3
+ * (YDS) for swapping claimed rewards.
4
+ *
5
+ * This module has no runtime dependency on Endo, so that it can be used
6
+ * outside of a locked-down (SES) environment.
7
+ */
8
+
9
+ const BPS_DENOMINATOR = 10_000n;
10
+
11
+ /**
12
+ * The maximum slippage tolerated by reward swap instructions, in basis
13
+ * points (2%). YDS quotes with this slippage unless the requester asks for a
14
+ * stricter one, and the contract rejects swap instructions whose
15
+ * `slippageBps` exceeds it, or whose `minAmountOut` is below what it implies.
16
+ */
17
+ export const MAX_REWARD_SWAP_SLIPPAGE_BPS = 200;
18
+
19
+ /**
20
+ * The least minimum output acceptable for a swap quoted to output
21
+ * `quotedAmountOut` with a tolerance of `slippageBps`, rounding up so that
22
+ * the tolerance is never exceeded:
23
+ * `ceil(quotedAmountOut * (10000 - slippageBps) / 10000)`.
24
+ *
25
+ * Both amounts are in raw units of the swap's output token.
26
+ *
27
+ * @param quotedAmountOut
28
+ * @param slippageBps an integer from 0 to 10000
29
+ */
30
+ export const getMinAmountOutForSlippage = (
31
+ quotedAmountOut ,
32
+ slippageBps ,
33
+ ) => {
34
+ if (typeof quotedAmountOut !== 'bigint' || quotedAmountOut < 0n) {
35
+ throw RangeError(`invalid quotedAmountOut: ${String(quotedAmountOut)}`);
36
+ }
37
+ if (
38
+ !Number.isSafeInteger(slippageBps) ||
39
+ slippageBps < 0 ||
40
+ slippageBps > Number(BPS_DENOMINATOR)
41
+ ) {
42
+ throw RangeError(`invalid slippageBps: ${String(slippageBps)}`);
43
+ }
44
+ const numerator = quotedAmountOut * (BPS_DENOMINATOR - BigInt(slippageBps));
45
+ return (numerator + BPS_DENOMINATOR - 1n) / BPS_DENOMINATOR;
46
+ };
47
+ Object.freeze(getMinAmountOutForSlippage);
@@ -1,6 +1,6 @@
1
1
  import { type CastedPattern } from '@endo/patterns';
2
2
  import type { ChainTokenMetadata, TokenMetadata } from './places.js';
3
- import type { PortfolioAgentKey, PortfolioDelegatedClaimRewardsParams, PortfolioDelegatedRebalanceParams, PortfolioSyncState, WithdrawParams, HoldingKind, HoldingDetail, PlanObservations } from './types.js';
3
+ import type { PortfolioAgentKey, PortfolioDelegatedClaimRewardsParams, PortfolioDelegatedRebalanceParams, PortfolioSyncState, WithdrawParams, HoldingKind, HoldingDetail, PlanObservations, AaveClaimEvidence, CompoundClaimEvidence, MerklClaimEvidence, OneInchSwapInstructions, ClaimRewardsSelector, SwapProvider, RewardClaimProtocol, SwapSelector } from './types.js';
4
4
  export { isBeefyInstrumentId, isDepositFromChainRef, isERC4626InstrumentId, isERC4626MorphoInstrumentId, isInstrumentId, isInterChainAccountRef, isLocalChainAccountRef, isPortfolioBalancePlaceRef, isWithdrawToChainRef, makeTokenIdKey, } from './places.js';
5
5
  export type { ChainTokenMetadata, ChainTokenMetadataEntry, TokenIdKey, TokenMetadata, } from './places.js';
6
6
  export declare const TokenUsageShape: import("@endo/patterns").MatcherOf<"or", ["swapFrom", "swapTo"]>;
@@ -27,6 +27,14 @@ export declare const HoldingDetailV2Shape: import("@endo/patterns").MatcherOf<"s
27
27
  }, {}]>;
28
28
  /** Structural shape; the observation decoder also checks places and addresses. */
29
29
  export declare const HoldingDetailShape: CastedPattern<HoldingDetail>;
30
+ export declare const AaveClaimEvidenceShape: CastedPattern<AaveClaimEvidence>;
31
+ export declare const CompoundClaimEvidenceShape: CastedPattern<CompoundClaimEvidence>;
32
+ export declare const MerklClaimEvidenceShape: CastedPattern<MerklClaimEvidence>;
33
+ export declare const OneInchSwapInstructionsShape: CastedPattern<OneInchSwapInstructions>;
34
+ export declare const RewardClaimProtocolShape: CastedPattern<RewardClaimProtocol>;
35
+ export declare const SwapProviderShape: CastedPattern<SwapProvider>;
36
+ export declare const ClaimRewardsSelectorShape: CastedPattern<ClaimRewardsSelector>;
37
+ export declare const SwapSelectorShape: CastedPattern<SwapSelector>;
30
38
  export declare const PlanObservationsShape: CastedPattern<PlanObservations>;
31
39
  export declare const TokenMetadataShape: CastedPattern<TokenMetadata>;
32
40
  export declare const ChainTokenMetadataShape: CastedPattern<ChainTokenMetadata>;
@@ -1 +1 @@
1
- {"version":3,"file":"type-guards.d.ts","sourceRoot":"","sources":["type-guards.ts"],"names":[],"mappings":"AAAA,OAAO,EAAK,KAAK,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,KAAK,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACrE,OAAO,KAAK,EACV,iBAAiB,EACjB,oCAAoC,EACpC,iCAAiC,EACjC,kBAAkB,EAClB,cAAc,EACd,WAAW,EACX,aAAa,EACb,gBAAgB,EACjB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,qBAAqB,EACrB,2BAA2B,EAC3B,cAAc,EACd,sBAAsB,EACtB,sBAAsB,EACtB,0BAA0B,EAC1B,oBAAoB,EACpB,cAAc,GACf,MAAM,aAAa,CAAC;AACrB,YAAY,EACV,kBAAkB,EAClB,uBAAuB,EACvB,UAAU,EACV,aAAa,GACd,MAAM,aAAa,CAAC;AAQrB,eAAO,MAAM,eAAe,kEAA6B,CAAC;AAG1D,kFAAkF;AAClF,eAAO,MAAM,mBAAmB,EAAE,aAAa,CAAC,cAAc,CAG7D,CAAC;AAGF,+EAA+E;AAC/E,eAAO,MAAM,gBAAgB,EAAE,aAAa,CAAC,WAAW,CAYvD,CAAC;AAGF,e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