All files / evm-wallet-experiment/src/vats redeemer-vat.ts

92.85% Statements 13/14
83.33% Branches 5/6
85.71% Functions 6/7
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58              1x                               10x     3x                 13x 13x 6x   7x       10x   11x 11x     2x 2x     8x        
import { makeDefaultExo } from '@metamask/kernel-utils/exo';
import type { Baggage } from '@metamask/ocap-kernel';
import { create } from '@metamask/superstruct';
 
import type { DelegationGrant } from '../types.ts';
import { DelegationGrantStruct } from '../types.ts';
 
const harden = globalThis.harden ?? (<T>(value: T): T => value);
 
/**
 * Build the root object for the redeemer vat.
 *
 * @param _vatPowers - Special powers granted to this vat (unused).
 * @param _parameters - Initialization parameters (unused).
 * @param baggage - Root of vat's persistent state.
 * @returns The root object for the redeemer vat.
 */
export function buildRootObject(
  _vatPowers: unknown,
  _parameters: unknown,
  baggage: Baggage,
): object {
  // Restore from baggage on resuscitation
  const grants: Map<string, DelegationGrant> = baggage.has('grants')
    ? new Map(
        Object.entries(baggage.get('grants') as Record<string, unknown>).map(
          ([id, raw]) => [id, create(raw, DelegationGrantStruct)],
        ),
      )
    : new Map();
 
  /**
   * Persist grants map to baggage (handles both init and update).
   */
  function persistGrants(): void {
    const serialized = harden(Object.fromEntries(grants));
    if (baggage.has('grants')) {
      baggage.set('grants', serialized);
    } else {
      baggage.init('grants', serialized);
    }
  }
 
  return makeDefaultExo('walletRedeemer', {
    async receiveGrant(grant: DelegationGrant): Promise<void> {
      grants.set(grant.delegation.id, grant);
      persistGrants();
    },
    async removeGrant(id: string): Promise<void> {
      grants.delete(id);
      persistGrants();
    },
    async listGrants(): Promise<DelegationGrant[]> {
      return harden([...grants.values()]);
    },
  });
}