Skip to content

Instantly share code, notes, and snippets.

@dckc
Forked from warner/bootstrap.js
Last active August 2, 2020 21:06
Show Gist options
  • Save dckc/f8e0b5d838079a994784d599c282cce7 to your computer and use it in GitHub Desktop.
Save dckc/f8e0b5d838079a994784d599c282cce7 to your computer and use it in GitHub Desktop.
make-vat-transcript
/dist/
/scripts/
/xs_modules/
/swingset/
/* global module */
module.exports = {
// parser: "babel-eslint",
extends: ['airbnb-base', 'plugin:prettier/recommended'],
env: {
es6: true, // supports new ES6 globals (e.g., new types such as Set)
},
globals: {
"harden": "readonly",
},
rules: {
'implicit-arrow-linebreak': 'off',
'function-paren-newline': 'off',
'arrow-parens': 'off',
strict: 'off',
'prefer-destructuring': 'off',
'no-else-return': 'off',
'no-console': 'off',
'no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
'no-return-assign': 'off',
'no-param-reassign': 'off',
'no-restricted-syntax': ['off', 'ForOfStatement'],
'no-unused-expressions': 'off',
'no-loop-func': 'off',
'import/prefer-default-export': 'off', // contrary to Agoric standard
},
};
# Demo
demo
# scripts
scripts
# test
test
# Travis CI
.travis.yml
{
"trailingComma": "all",
"singleQuote": true
}
import { E } from '@agoric/eventual-send';
import { producePromise } from '@agoric/produce-promise';
function ignore(p) {
p.then(
() => 0,
() => 0,
);
}
export function buildRootObject() {
const callbackObj = harden({
callback(arg1, arg2) {
console.log(`callback`, arg1, arg2);
return ['data', callbackObj]; // four, resolves pF
},
});
const precD = producePromise();
const precE = producePromise();
return harden({
bootstrap(_argv, vats) {
const pA = E(vats.target).zero(callbackObj, precD.promise, precE.promise);
E(vats.target).one();
precD.resolve(callbackObj); // two
precE.reject(Error('four')); // three
pA.then(([pB, pC]) => {
ignore(pB);
ignore(pC);
});
},
});
}
/** console for xs platform */
/* global trace, globalThis */
const harden = x => Object.freeze(x, true);
const text = it => (typeof it === 'object' ? JSON.stringify(it) : `${it}`);
const combine = (...things) => `${things.map(text).join(' ')}\n`;
export function makeConsole(write_) {
const write = write_ || trace; // note ocap exception for tracing / logging
return harden({
log(...things) {
write(combine(...things));
},
// node.js docs say this is just an alias for error
warn(...things) {
write(combine('WARNING: ', ...things));
},
// node docs say this goes to stderr
error(...things) {
write(combine('ERROR: ', ...things));
},
});
}
globalThis.console = makeConsole();
/**
* ref Netstrings 19970201 by Bernstein
* https://cr.yp.to/proto/netstrings.txt
*
* Moddable in C
* https://github.com/Moddable-OpenSource/moddable/blob/public/documentation/xs/XS%20in%20C.md
*
* stdio
* https://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdio.h.html
*/
#include <assert.h>
#include <stdio.h>
#include "xsAll.h"
#include "xs.h"
void xs_Reader(xsMachine *the) {
int argc = xsToInteger(xsArgc);
if (argc < 1) {
mxTypeError("expected fd");
}
int fd = xsToInteger(xsArg(0));
FILE *inStream = fdopen(fd, "rb");
if (!inStream) {
mxUnknownError("fdopen failed");
}
xsSetHostData(xsThis, (void *)((uintptr_t)inStream));
// modInstrumentationAdjust(Files, +1);
}
void xs_Writer(xsMachine *the) {
int argc = xsToInteger(xsArgc);
if (argc < 1) {
mxTypeError("expected fd");
}
int fd = xsToInteger(xsArg(0));
FILE *outStream = fdopen(fd, "wb");
if (!outStream) {
mxUnknownError("fdopen failed");
}
xsSetHostData(xsThis, (void *)((uintptr_t)outStream));
// modInstrumentationAdjust(Files, +1);
}
void xs_read_netstring(xsMachine *the) {
size_t len;
char* buf = NULL;
FILE *inStream = xsGetHostData(xsThis);
assert(inStream);
if (fscanf(inStream, "%9lu", &len) < 1) { goto BARF; } /* >999999999 bytes is bad */
// fprintf(stderr, "xs_stdin_read_netstring len %lu\n", len);
if (fgetc(inStream) != ':') { goto BARF; }
buf = malloc(len + 1); /* malloc(0) is not portable */
if (!buf) { goto BARF; }
if (fread(buf, 1, len, inStream) < len) { goto BARF; }
if (fgetc(inStream) != ',') { goto BARF; }
xsResult = xsStringBuffer(buf, len);
free(buf);
// fprintf(stderr, "xs_stdin_read_nestring return\n");
return;
BARF:
free(buf);
xsUnknownError("getline failed");
}
void xs_fdchan_destructor() {
}
export class Reader @ "xs_fdchan_destructor" {
constructor(fd) @ "xs_Reader"
read_netstring() @ "xs_read_netstring";
}
export class Writer @ "xs_fdchan_destructor" {
constructor(fd) @ "xs_Writer"
write(...items) @ "xs_file_write";
}
// vatWorker driver for node.js
// contrast with main.js for xs
import '@agoric/install-ses';
import { main as vatWorker } from './vatWorker';
const INFD = 3;
const OUTFD = 4;
function makePipe(io, sleep) {
function write(data) {
let done = 0;
for (;;) {
try {
done += io.writeSync(OUTFD, data.slice(done));
if (done >= data.length) {
return done;
}
} catch (writeFailed) {
if (writeFailed.code === 'EAGAIN') {
sleep(0.1);
// try again
} else {
throw writeFailed;
}
}
}
}
return harden({
writeMessage(msg) {
write(`${msg.length}:`);
write(msg);
write(',');
},
readMessage(EOF) {
let buf = Buffer.from('999999999:', 'utf-8');
let len = null;
let colonPos = null;
let offset = 0;
for (;;) {
// console.error('readMessage', { length: buf.length, len, colonPos, offset });
try {
offset += io.readSync(INFD, buf, {
offset,
length: buf.length - offset,
});
} catch (err) {
if (err.code === 'EAGAIN') {
sleep(0.1);
// eslint-disable-next-line no-continue
continue;
} else if (err.code === 'EOF') {
throw EOF;
} else {
throw err;
}
}
if (len === null) {
colonPos = buf.indexOf(':');
if (colonPos > 0) {
const digits = buf.slice(0, colonPos).toString('utf-8');
len = parseInt(digits, 10);
const rest = Buffer.alloc(len + 1);
// console.error('parsed len. copy', { digits, len, targetStart: 0, sourceStart: colonPos + 1, sourceEnd: offset });
buf.copy(rest, 0, colonPos + 1, offset);
buf = rest;
offset -= colonPos + 1;
}
} else if (offset === len + 1) {
const delim = buf.slice(-1).toString('utf-8');
if (delim !== ',') {
throw new Error(
`bad netstring: length ${len} expected , found [${delim}]`,
);
}
const result = buf.slice(0, -1).toString('utf-8');
// console.error({ colon: colonPos, len, result: result.slice(0, 20) });
return result;
}
}
},
});
}
async function main({ setImmediate, fs, spawnSync }) {
const sleep = secs => spawnSync('sleep', [secs]);
const pipe = makePipe(fs, sleep);
return vatWorker({
readMessage: pipe.readMessage,
writeMessage: pipe.writeMessage,
setImmediate,
});
}
main({
setImmediate,
// eslint-disable-next-line global-require
spawnSync: require('child_process').spawnSync,
fs: {
// eslint-disable-next-line global-require
readSync: require('fs').readSync,
// eslint-disable-next-line global-require
writeSync: require('fs').writeSync,
},
})
.catch(err => {
console.error(err);
})
.then(() => process.exit(0));
// Usage: node -r esm kernelSimulator.js
// context: https://github.com/Agoric/agoric-sdk/issues/1299
import '@agoric/install-ses';
import { readNetstring, writeNetstring } from '../src/netstring';
const INFD = 3;
const OUTFD = 4;
function options(env) {
return {
vat1: env.VAT1 || 'vat-target.js',
transcript: env.TRANSCRIPT || 'transcript.txt',
workerBin: env.WORKERBIN || './build/bin/lin/release/xs-vat-worker',
};
}
function makeWorker(child) {
const format = obj => JSON.stringify(obj);
const send = obj => writeNetstring(child.stdio[INFD], format(obj));
child.stdio[OUTFD].pause();
const expect = async msgtype => {
const txt = await readNetstring(child.stdio[OUTFD]);
let msg;
try {
msg = JSON.parse(txt);
} catch (badJSON) {
console.error('bad JSON ', txt.length, ' chars: [', txt, ']', badJSON);
throw badJSON;
}
if (msg.msgtype !== msgtype) {
throw new Error(`expected ${msgtype}; found: ${msg.msgtype}; error: ${msg.error} [${JSON.stringify(msg)}]`);
}
return msg;
};
return harden({
async loadVat(bundle) {
await send({ msgtype: 'load-bundle', bundle });
return expect('load-bundle-ack');
},
async dispatch({ d, syscalls, _crankNumber }) {
await send({ msgtype: 'dispatch', type: d[0], args: d.slice(1) });
for (const syscall of syscalls) {
// eslint-disable-next-line no-await-in-loop
const request = await expect('syscall');
console.log('syscall request', request);
// eslint-disable-next-line no-await-in-loop
await send({ msgtype: 'syscall-ack', response: syscall.response });
}
return expect('dispatch-ack');
},
async finish() {
await send({ msgtype: 'finish' });
await expect('finish-ack');
},
});
}
async function runTranscript(w1, bundle, transcript) {
await w1.loadVat(bundle);
console.log('loadVat done.');
const events = transcript.split('\n');
while (events.length > 0) {
const event = events.shift();
if (!event) {
// eslint-disable-next-line no-continue
continue;
}
const found = event.match(/^(?<id>[^ ]+) :: (?<payload>.*)/);
if (!found) {
console.log('unexpected transcript format', { line: event });
// eslint-disable-next-line no-continue
continue;
}
const { id, payload } = found.groups;
const obj = JSON.parse(payload);
if (typeof obj !== 'object') {
console.log('not a dispatch event', id, obj);
// eslint-disable-next-line no-continue
continue;
}
console.log('dispatching:', id);
// eslint-disable-next-line no-await-in-loop
await w1.dispatch(obj);
console.log('dispatch done:', id);
}
await w1.finish();
console.log('END OF TRANSCRIPT.');
}
// eslint-disable-next-line no-shadow
export async function main(argv, { env, io, bundleSource, spawn }) {
const { vat1, transcript, workerBin } = options(env);
const bundle = await bundleSource(vat1);
console.log('spawning', { workerBin });
const child = await spawn(workerBin, [], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'],
});
child.on('exit', (code, signal) => {
if (code !== 0) {
console.error('unexpected exit:', { code, signal });
}
});
const w1 = makeWorker(child);
const text = await io.readFile(transcript, 'utf-8');
await runTranscript(w1, bundle, text);
}
if (require.main === module) {
main(process.argv, {
env: process.env,
// eslint-disable-next-line global-require
io: {
// eslint-disable-next-line global-require
readFile: require('fs').promises.readFile,
},
// eslint-disable-next-line global-require
bundleSource: require('@agoric/bundle-source').default,
// eslint-disable-next-line global-require
spawn: require('child_process').spawn,
}).catch(err => {
console.error(err);
});
}
// add harden; align xs's Compartment with Agoric's
// ISSUE: use a different module name?
import '@agoric/install-ses';
import './console'; // sets globalThis.console. ew.
import './timer-ticks'; // globalThis.setTimeout. ew.
import { main as vatWorker } from './vatWorker';
import { Reader, Writer } from './fdchan';
const INFD = 3;
const OUTFD = 4;
export default async function main() {
const inStream = new Reader(INFD);
const outStream = new Writer(OUTFD);
return vatWorker({
setImmediate,
readMessage: () => inStream.read_netstring(),
writeMessage: message => {
// ISSUE: should be byte length
outStream.write(`${message.length}:`, message, ',');
},
});
}
NODE_ESM=node -r esm
transcript.txt: swingset-kernel-state
$(NODE_ESM) ../swingset-runner/bin/kerneldump --filedb ./swingset-kernel-state | grep v1.t |sort >$@
swingset-kernel-state: bootstrap.js vat-target.js
$(NODE_ESM) ../swingset-runner/bin/runner --filedb run
ZOE1=../zoe/test/swingsetTests/zoe
zoe: transcript-zoe.txt ./node-vat-worker index.js vatWorker.js kernelSimulator.js
VAT1=$(ZOE1)/vat-zoe.js TRANSCRIPT=transcript-zoe.txt node -r esm kernelSimulator.js
zoe-node: transcript-zoe.txt ./node-vat-worker index.js vatWorker.js kernelSimulator.js
VAT1=$(ZOE1)/vat-zoe.js TRANSCRIPT=transcript-zoe.txt WORKERBIN=./node-vat-worker node -r esm kernelSimulator.js
transcript-zoe.txt: $(ZOE1)/swingset-kernel-state
$(NODE_ESM) ../swingset-runner/bin/kerneldump --filedb $(ZOE1)/swingset-kernel-state | grep ^v5.t | grep -v nextID >,zoe-all
python sort_transcript.py <,zoe-all >$@
$(ZOE1)/swingset-kernel-state: ,zoe-patched
(cd $(ZOE1) && $(NODE_ESM) ../../../../swingset-runner/bin/runner --filedb run)
,zoe-patched: $(ZOE1)/bootstrap.js zoe-test.patch
cd ../.. && patch -p1 <packages/xs-vat-worker/zoe-test.patch
touch $@
{
"include": [
"$(MODDABLE)/examples/manifest_base.json"
],
"$note": [
"horrible @agoric/E KLUDGE below",
"liveSlots is a bit KLUDGy too"
],
"creation": {
"keys": {
"available": 4096
},
"stack": 4096,
"parser": {
"buffer": 32768
}
},
"strip": [],
"modules": {
"files": [ "$(MODULES)/files/file/*", "$(MODULES)/files/file/lin/*" ],
"fdchan": [ "./fdchan" ],
"timer": [
"$(MODULES)/base/timer/timer",
"$(MODULES)/base/timer/lin/*",
],
"@agoric/nat": "xs_modules/@agoric/nat/nat.esm",
"@agoric/install-ses": "xs_modules/@agoric/install-ses/install-ses",
"@agoric/import-bundle": "xs_modules/@agoric/import-bundle/index",
"@agoric/compartment-wrapper": "xs_modules/@agoric/import-bundle/compartment-wrapper",
"@agoric/eventual-send": [
"xs_modules/@agoric/eventual-send/index"
],
"@agoric/E": "xs_modules/@agoric/eventual-send/E",
"@agoric/marshal": "xs_modules/@agoric/marshal/marshal",
"@agoric/produce-promise": "xs_modules/@agoric/produce-promise/producePromise",
"@agoric/assert": "xs_modules/@agoric/assert/assert",
"@agoric/types": "xs_modules/@agoric/assert/types",
"swingset/capdata": "./swingset/capdata",
"swingset/parseVatSlots": "./swingset/parseVatSlots",
"swingset/kernel/liveSlots": "./swingset/kernel/liveSlots",
"*": [
"./main",
"./console",
"./timer-ticks",
"./vatWorker"
]
}
}
export async function readNetstring(input) {
let prefix = Buffer.from([]);
let colonPos = -1;
const nextChunk = () =>
new Promise((resolve, _reject) => {
const rx = data => {
input.pause();
input.removeListener('data', rx);
resolve(data);
};
input.on('data', rx);
input.resume();
});
while (colonPos < 0) {
// eslint-disable-next-line no-await-in-loop
const more = await nextChunk();
prefix = Buffer.concat([prefix, more]);
colonPos = prefix.indexOf(':');
}
let len;
const digits = prefix.slice(0, colonPos).toString('utf-8');
try {
len = parseInt(digits, 10);
} catch (badLen) {
throw new Error(`bad netstring length ${digits}`);
}
// console.error('readNetstring parsed len', { digits, len });
let data = prefix.slice(colonPos + 1);
while (data.length <= len) {
// console.log('netstring: looking for payload', data.length, len);
// eslint-disable-next-line no-await-in-loop
const more = await nextChunk(input);
data = Buffer.concat([data, more]);
}
if (data.slice(len).toString('utf-8') !== ',') {
throw new Error(
`bad netstring: expected , got ${data.slice(-1)} [${data.slice(-20)}]`,
);
}
return data.slice(0, len).toString('utf-8');
}
export async function writeNetstring(out, payload) {
// ISSUE: non-ASCII length
// console.log('kernelSimulator send size', content.length);
await out.write(`${payload.length}:`);
await out.write(payload);
await out.write(',');
}
#!/bin/sh
node -r esm ./src/index.js
{
"name": "@agoric/xs-vat-worker",
"version": "0.0.1",
"description": "???",
"main": "dist/vat-worker.cjs.js",
"module": "dist/vat-worker.esm.js",
"browser": "dist/vat-worker.umd.js",
"scripts": {
"xs-build": "mkdir -p build; mcconfig -o build -p x-cli-lin -m -d",
"xs-run": "yarn xs-build && ./build/bin/lin/debug/make-vat-transcript",
"xs-build-release": "mkdir -p build; mcconfig -o build -p x-cli-lin -m",
"xs-run-release": "yarn xs-build-release && ./build/bin/lin/release/make-vat-transcript",
"test": "tape -r esm 'test/**/test-*.js'",
"build": "exit 0",
"lint-fix": "eslint --fix '**/*.{js,jsx}'",
"lint-check": "eslint '**/*.{js,jsx}'",
"lint-fix-jessie": "eslint -c '.eslintrc-jessie.js' --fix '**/*.{js,jsx}'",
"lint-check-jessie": "eslint -c '.eslintrc-jessie.js' '**/*.{js,jsx}'"
},
"devDependencies": {
"eslint": "^6.1.0",
"eslint-config-airbnb-base": "^14.0.0",
"eslint-config-jessie": "0.0.3",
"eslint-config-prettier": "^6.0.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-prettier": "^3.1.0",
"prettier": "^1.18.2",
"tap-spec": "^5.0.0",
"tape": "^4.11.0",
"tape-promise": "^4.0.0"
},
"dependencies": {
"@agoric/assert": "^0.0.8",
"@agoric/bundle-source": "^1.1.6",
"@agoric/eventual-send": "^0.9.3",
"@agoric/import-bundle": "^0.0.8",
"@agoric/install-ses": "^0.2.0",
"@agoric/produce-promise": "^0.1.3",
"@agoric/swingset-vat": "^0.6.0",
"anylogger": "^1.0.4",
"esm": "^3.2.5"
},
"keywords": [],
"files": [
"dist"
],
"repository": {
"type": "git",
"url": "https://gist.github.com/f8e0b5d838079a994784d599c282cce7.git"
},
"author": "Agoric",
"license": "Apache-2.0",
"bugs": {
"url": "https://gist.github.com/dckc/f8e0b5d838079a994784d599c282cce7"
},
"homepage": "https://gist.github.com/dckc/f8e0b5d838079a994784d599c282cce7"
}
import sys
lines = sys.stdin.readlines()
lines.sort(key=lambda line: int(line.split(" ", 1)[0].split(".")[2]))
for line in lines:
sys.stdout.write(line)
import { test } from 'tape-promise/tape';
import { main } from './kernelSimulator';
const resolve = p => new URL(p, import.meta.url).toString().slice('file://'.length);
test('replay simple transcript with node vatWorker', async t => {
process.env.WORKERBIN = resolve('../bin/node-vat-worker');
process.env.VAT1 = resolve('./vat-target.js');
process.env.TRANSCRIPT = resolve('./transcript.txt');
process.chdir(resolve('..')); // so node-vat-worker can find stuff in src/
await main(process.argv, {
env: process.env,
// eslint-disable-next-line global-require
io: {
// eslint-disable-next-line global-require
readFile: require('fs').promises.readFile,
},
// eslint-disable-next-line global-require
bundleSource: require('@agoric/bundle-source').default,
// eslint-disable-next-line global-require
spawn: require('child_process').spawn,
});
t.ok('did not crash');
t.end();
})
// ref moddable/examples/base/timers/main.js
/* global globalThis */
// eslint-disable-next-line import/no-unresolved
import Timer from 'timer'; // moddable timer
globalThis.setImmediate = callback => {
Timer.set(callback);
};
globalThis.setTimeout = (callback, delay) => {
Timer.set(callback, delay);
};
globalThis.setInterval = (callback, delay) => {
Timer.repeat(callback, delay);
};
import { importBundle } from '@agoric/import-bundle';
import { HandledPromise } from '@agoric/eventual-send';
// TODO? import anylogger from 'anylogger';
import { makeLiveSlots } from '@agoric/swingset-vat/src/kernel/liveSlots';
const EOF = new Error('EOF');
// from SwingSet/src/controller.js
function makeConsole(_tag) {
const log = console; // TODO? anylogger(tag);
const cons = {};
for (const level of ['debug', 'log', 'info', 'warn', 'error']) {
cons[level] = log[level];
}
return harden(cons);
}
function makeVatEndowments(consoleTag) {
return harden({
console: makeConsole(`SwingSet:${consoleTag}`),
HandledPromise,
// TODO: re2 is a RegExp work-a-like that disables backtracking expressions for
// safer memory consumption
RegExp,
});
}
// see also: detecting an empty vat promise queue (end of "crank")
// https://github.com/Agoric/agoric-sdk/issues/45
function endOfCrank(setImmediate) {
return new Promise((resolve, _reject) => {
setImmediate(() => {
// console.log('hello from setImmediate callback. The promise queue is presumably empty.');
resolve();
});
});
}
function makeWorker(io, setImmediate) {
let vatNS = null;
let dispatch;
let state;
const format = msg => JSON.stringify(msg);
const sync = (method, args) => {
io.writeMessage(format({ msgtype: 'syscall', method, args }));
return JSON.parse(io.readMessage());
};
const syscall = harden({
subscribe(...args) {
return sync('subscribe', args);
},
send(...args) {
return sync('send', args);
},
fulfillToData(...args) {
return sync('fulfillToData', args);
},
fulfillToPresence(...args) {
return sync('fulfillToPresence', args);
},
reject(...args) {
return sync('reject', args);
},
});
async function loadBundle(name, bundle) {
if (vatNS !== null) {
throw new Error('bundle already loaded');
}
vatNS = await importBundle(bundle, {
filePrefix: name,
endowments: makeVatEndowments(name),
});
// TODO: be sure console.log isn't mixed with protocol stream
// console.log('loaded bundle with methods', Object.keys(vatNS));
state = {}; // ??
dispatch = makeLiveSlots(syscall, state, vatNS.buildRootObject);
}
function turnCrank(dispatchType, args) {
return new Promise((resolve, reject) => {
try {
dispatch[dispatchType](...args);
} catch (error) {
// console.log({ dispatchError: error });
reject(error);
return;
}
endOfCrank(setImmediate).then(resolve);
});
}
const name = 'WORKER'; // TODO?
async function handle(message) {
switch (message.msgtype) {
case 'load-bundle':
try {
await loadBundle(name, message.bundle);
} catch (error) {
// console.log('load-bundle failed:', error);
io.writeMessage(
format({ msgtype: 'load-bundle-nak', error: error.message }),
);
break;
}
io.writeMessage(format({ msgtype: 'load-bundle-ack' }));
break;
case 'dispatch':
try {
await turnCrank(message.type, message.args);
} catch (error) {
io.writeMessage(
format({
msgtype: 'dispatch-nak',
error: error instanceof Error ? error.message : error,
}),
);
break;
}
io.writeMessage(format({ msgtype: 'dispatch-ack' }));
break;
case 'finish':
io.writeMessage(format({ msgtype: 'finish-ack' }));
break;
default:
console.warn('unexpected msgtype', message.msgtype);
}
return message.msgtype;
}
return harden({ handle });
}
export async function main({ readMessage, writeMessage, setImmediate }) {
const worker = makeWorker({ readMessage, writeMessage }, setImmediate);
for (;;) {
let message;
try {
// eslint-disable-next-line no-await-in-loop
message = JSON.parse(readMessage(EOF));
} catch (noMessage) {
if (noMessage === EOF) {
return;
}
console.warn('problem getting message:', noMessage);
// eslint-disable-next-line no-continue
continue;
}
// eslint-disable-next-line no-await-in-loop
const msgtype = await worker.handle(message);
if (msgtype === 'finish') {
break;
}
}
}
View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

This file has been truncated, but you can view the full file.
v5.t.0 :: {"d":["deliver","o+0","buildZoe",{"body":"[{\"@qclass\":\"slot\",\"index\":0}]","slots":["o-50"]},"p-60"],"syscalls":[{"d":["fulfillToPresence","p-60","o+1"],"response":null}],"crankNumber":4}
v5.t.1 :: {"d":["deliver","o+1","install",{"body":"[{\"source\":\"function getExportWithNestedEvaluate(filePrefix) {\\n 'use strict';\\n // Serialised sources.\\n if (filePrefix === undefined) {\\n filePrefix = \\\"/bundled-source\\\";\\n }\\n const moduleFormat = \\\"nestedEvaluate\\\";\\n const entrypoint = \\\"automaticRefund.js\\\";\\n const sourceBundle = {\\n \\\"automaticRefund.js\\\": \\\"'use strict';\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* global harden */ /* @ts-check*/ /**\\\\n * This is a very trivial contract to explain and test Zoe.\\\\n * AutomaticRefund just gives you back what you put in.\\\\n * AutomaticRefund tells Zoe to complete the\\\\n * offer, which gives the user their payout through Zoe. Other\\\\n * contracts will use these same steps, but they will have more\\\\n * sophisticated logic and interfaces.\\\\n *\\\\n * Since the contract doesn't attempt any reallocation, the offer can contain\\\\n * anything in `give` and `want`. The amount in `give` will be returned, and\\\\n * `want` will be ignored.\\\\n *\\\\n * @typedef {Ximport('../zoe').ContractFacet} ContractFacet\\\\n * @param {ContractFacet} zcf\\\\n */\\\\nconst makeContract = zcf => {\\\\n let offersCount = 0;\\\\n\\\\n const refundOfferHook = offerHandle => {\\\\n offersCount += 1;\\\\n zcf.complete(harden([offerHandle]));\\\\n return `The offer was accepted`;};\\\\n\\\\n const makeRefundInvite = () =>\\\\n zcf.makeInvitation(refundOfferHook, 'getRefund');\\\\n\\\\n zcf.initPublicAPI(\\\\n harden({\\\\n getOffersCount: () => offersCount,\\\\n makeInvite: makeRefundInvite }));\\\\n\\\\n\\\\n\\\\n return makeRefundInvite();};\\\\n\\\\n\\\\nharden(makeContract);exports.makeContract = makeContract;\\\"\\n};\\n const nsBundle = {};\\n\\n function createEvalString(filename) {\\n const code = sourceBundle[filename];\\n if (!code) {\\n return undefined;\\n }\\n return `\\\\\\n(function getExport(require, exports) { \\\\\\n 'use strict'; \\\\\\n const module = { exports }; \\\\\\n \\\\\\n ${code}\\n return module.exports;\\n})\\n//# sourceURL=${filePrefix}/${filename}\\n`;\\n }\\n\\n function computeExports(filename, exportPowers, exports) {\\n const { require: systemRequire, _log } = exportPowers;\\n // This captures the endowed require.\\n const match = filename.match(/^(.*)\\\\/[^/]+$/);\\n const thisdir = match ? match[1] : '.';\\n const contextRequire = mod => {\\n // Do path algebra to find the actual source.\\n const els = mod.split('/');\\n let prefix;\\n if (els[0][0] === '@') {\\n // Scoped name.\\n prefix = els.splice(0, 2).join('/');\\n } else if (els[0][0] === '.') {\\n // Relative.\\n els.unshift(...thisdir.split('/'));\\n } else {\\n // Bare or absolute.\\n prefix = els.splice(0, 1);\\n }\\n\\n const suffix = [];\\n for (const el of els) {\\n if (el === '.' || el === '') {\\n // Do nothing.\\n } else if (el === '..') {\\n // Traverse upwards.\\n suffix.pop();\\n } else {\\n suffix.push(el);\\n }\\n }\\n\\n // log(mod, prefix, suffix);\\n if (prefix !== undefined) {\\n suffix.unshift(prefix);\\n }\\n let modPath = suffix.join('/');\\n if (modPath.startsWith('./')) {\\n modPath = modPath.slice(2);\\n }\\n // log('requiring', modPath);\\n if (!(modPath in nsBundle)) {\\n // log('evaluating', modPath);\\n // Break cycles, but be tolerant of modules\\n // that completely override their exports object.\\n nsBundle[modPath] = {};\\n nsBundle[modPath] = computeExports(\\n modPath,\\n exportPowers,\\n nsBundle[modPath],\\n );\\n }\\n\\n // log('returning', nsBundle[modPath]);\\n return nsBundle[modPath];\\n };\\n\\n const code = createEvalString(filename);\\n if (!code) {\\n // log('missing code for', filename, sourceBundle);\\n if (systemRequire) {\\n return systemRequire(filename);\\n }\\n throw Error(\\n `require(${JSON.stringify(\\n filename,\\n )}) failed; no toplevel require endowment`,\\n );\\n }\\n\\n // log('evaluating', code);\\n return nestedEvaluate(code)(contextRequire, exports);\\n }\\n\\n // Evaluate the entrypoint recursively, seeding the exports.\\n const systemRequire = typeof require === 'undefined' ? undefined : require;\\n return computeExports(entrypoint, { require: systemRequire }, {});\\n}\\n//# sourceURL=/bundled-source-preamble.js\\n\",\"sourceMap\":\"//# sourceURL=/bundled-source-preamble.js\\n\",\"moduleFormat\":\"nestedEvaluate\"}]","slots":[]},"p-61"],"syscalls":[{"d":["fulfillToPresence","p-61","o+2"],"response":null}],"crankNumber":6}
v5.t.2 :: {"d":["deliver","o+1","install",{"body":"[{\"source\":\"function getExportWithNestedEvaluate(filePrefix) {\\n 'use strict';\\n // Serialised sources.\\n if (filePrefix === undefined) {\\n filePrefix = \\\"/bundled-source\\\";\\n }\\n const moduleFormat = \\\"nestedEvaluate\\\";\\n const entrypoint = \\\"packages/zoe/src/contracts/coveredCall.js\\\";\\n const sourceBundle = {\\n \\\"packages/zoe/src/contracts/coveredCall.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var zoeHelpers = require('../contractSupport/zoeHelpers.js');require('../contractSupport/index.js'); /* global harden */\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nconst rejectMsg = `The covered call option is expired.`;\\\\n\\\\n/**\\\\n * In a covered call, a digital asset's owner sells a call\\\\n * option. A call option is the right to buy the digital asset at a\\\\n * pre-determined price, called the strike price. The call option has an expiry\\\\n * date, when the contract will be cancelled.\\\\n *\\\\n * In this contract, the expiry date is the deadline when\\\\n * the offer escrowing the underlying assets is cancelled.\\\\n * Therefore, the proposal for the underlying assets must have an\\\\n * exit record with the key \\\\\\\"afterDeadline\\\\\\\".\\\\n *\\\\n * The invite received by the covered call creator is the call option. It has\\\\n * this additional information in the invite's value:\\\\n * { expirationDate, timerAuthority, underlyingAsset, strikePrice }\\\\n *\\\\n * The initial proposal should be:\\\\n * {\\\\n * give: { UnderlyingAsset: assetAmount },\\\\n * want: { StrikePrice: priceAmount },\\\\n * exit: { afterDeadline: { deadline: time, timer: timer } },\\\\n * }\\\\n * The result of the initial offer is { payout, outcome }, where payout will\\\\n * eventually resolve to the strikePrice, and outcome is an assayable invitation\\\\n * to buy the underlying asset. Since the contract provides assurance that the\\\\n * underlying asset is available on the specified terms, the invite itself can\\\\n * be traded as a valuable good.\\\\n *\\\\n * @typedef {Ximport('../zoe').ContractFacet} ContractFacet\\\\n * @param {ContractFacet} zcf\\\\n */\\\\nconst makeContract = zcf => {\\\\n const { swap, assertKeywords, checkHook } = zoeHelpers.makeZoeHelpers(zcf);\\\\n assertKeywords(harden(['UnderlyingAsset', 'StrikePrice']));\\\\n\\\\n const makeCallOptionInvite = sellerHandle => {\\\\n const {\\\\n proposal: { want, give, exit } } =\\\\n zcf.getOffer(sellerHandle);\\\\n\\\\n const exerciseOptionHook = (offerHandle) =>\\\\n swap(sellerHandle, offerHandle, rejectMsg);\\\\n const exerciseOptionExpected = harden({\\\\n give: { StrikePrice: null },\\\\n want: { UnderlyingAsset: null } });\\\\n\\\\n\\\\n return zcf.makeInvitation(\\\\n checkHook(exerciseOptionHook, exerciseOptionExpected),\\\\n 'exerciseOption',\\\\n harden({\\\\n customProperties: {\\\\n expirationDate: exit.afterDeadline.deadline,\\\\n timerAuthority: exit.afterDeadline.timer,\\\\n underlyingAsset: give.UnderlyingAsset,\\\\n strikePrice: want.StrikePrice } }));};\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n const writeOptionExpected = harden({\\\\n give: { UnderlyingAsset: null },\\\\n want: { StrikePrice: null },\\\\n exit: { afterDeadline: null } });\\\\n\\\\n\\\\n return zcf.makeInvitation(\\\\n checkHook(makeCallOptionInvite, writeOptionExpected),\\\\n 'makeCallOption');};\\\\n\\\\n\\\\n\\\\nharden(makeContract);exports.makeContract = makeContract;\\\",\\n \\\"packages/zoe/src/contractSupport/auctions.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true }); /* global harden */\\\\n\\\\nconst secondPriceLogic = (bidAmountMath, bidOfferHandles, bids) => {\\\\n let highestBid = bidAmountMath.getEmpty();\\\\n let secondHighestBid = bidAmountMath.getEmpty();\\\\n let highestBidOfferHandle;\\\\n /* eslint-disable-next-line array-callback-return*/\\\\n bidOfferHandles.map((offerHandle, i) => {\\\\n const bid = bids[i];\\\\n /* If the bid is greater than the highestBid, it's the new highestBid*/\\\\n if (bidAmountMath.isGTE(bid, highestBid)) {\\\\n secondHighestBid = highestBid;\\\\n highestBid = bid;\\\\n highestBidOfferHandle = offerHandle;} else\\\\n if (bidAmountMath.isGTE(bid, secondHighestBid)) {\\\\n /* If the bid is not greater than the highest bid, but is greater*/\\\\n /* than the second highest bid, it is the new second highest bid.*/\\\\n secondHighestBid = bid;}});\\\\n\\\\n\\\\n return harden({\\\\n winnerOfferHandle: highestBidOfferHandle,\\\\n winnerBid: highestBid,\\\\n price: secondHighestBid });};\\\\n\\\\n\\\\n\\\\nconst closeAuction = (\\\\nzcf,\\\\n{ auctionLogicFn, sellerOfferHandle, allBidHandles }) =>\\\\n{\\\\n const { brandKeywordRecord } = zcf.getInstanceRecord();\\\\n const bidAmountMath = zcf.getAmountMath(brandKeywordRecord.Ask);\\\\n const assetAmountMath = zcf.getAmountMath(brandKeywordRecord.Asset);\\\\n\\\\n /* Filter out any inactive bids*/\\\\n const { active: activeBidHandles } = zcf.getOfferStatuses(\\\\n harden(allBidHandles));\\\\n\\\\n\\\\n const getBids = amountsKeywordRecord => amountsKeywordRecord.Bid;\\\\n const bids = zcf.getCurrentAllocations(activeBidHandles).map(getBids);\\\\n const assetAmount = zcf.getOffer(sellerOfferHandle).proposal.give.Asset;\\\\n\\\\n const { winnerOfferHandle, winnerBid, price } = auctionLogicFn(\\\\n bidAmountMath,\\\\n activeBidHandles,\\\\n bids);\\\\n\\\\n\\\\n /* The winner gets to keep the difference between their bid and the*/\\\\n /* price paid.*/\\\\n const winnerRefund = bidAmountMath.subtract(winnerBid, price);\\\\n\\\\n const newSellerAmounts = { Asset: assetAmountMath.getEmpty(), Ask: price };\\\\n const newWinnerAmounts = { Asset: assetAmount, Bid: winnerRefund };\\\\n\\\\n /* Everyone else gets a refund so their values remain the*/\\\\n /* same.*/\\\\n zcf.reallocate(\\\\n harden([sellerOfferHandle, winnerOfferHandle]),\\\\n harden([newSellerAmounts, newWinnerAmounts]));\\\\n\\\\n const allOfferHandles = harden([sellerOfferHandle, ...activeBidHandles]);\\\\n zcf.complete(allOfferHandles);};exports.closeAuction = closeAuction;exports.secondPriceLogic = secondPriceLogic;\\\",\\n \\\"packages/assert/src/assert.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* Copyright (C) 2019 Agoric, under Apache License 2.0*/ /* @ts-check*/ /* This module assumes the de-facto standard `console` host object.*/ /* To the extent that this `console` is considered a resource,*/ /* this module must be considered a resource module.*/ /**\\\\n * Prepend the correct indefinite article onto a noun, typically a typeof result\\\\n * e.g., \\\\\\\"an Object\\\\\\\" vs. \\\\\\\"a Number\\\\\\\"\\\\n *\\\\n * @param {string} str The noun to prepend\\\\n * @returns {string} The noun prepended with a/an\\\\n */\\\\nfunction an(str) {\\\\n str = `${str}`;\\\\n if (str.length >= 1 && 'aeiouAEIOU'.includes(str[0])) {\\\\n return `an ${str}`;}\\\\n\\\\n return `a ${str}`;}\\\\n\\\\nharden(an);\\\\n\\\\n/**\\\\n * Like `JSON.stringify` but does not blow up if given a cycle. This is not\\\\n * intended to be a serialization to support any useful unserialization,\\\\n * or any programmatic use of the resulting string. The string is intended\\\\n * only for showing a human, in order to be informative enough for some\\\\n * logging purposes. As such, this `cycleTolerantStringify` has an\\\\n * imprecise specification and may change over time.\\\\n *\\\\n * The current `cycleTolerantStringify` possibly emits too many \\\\\\\"seen\\\\\\\"\\\\n * markings: Not only for cycles, but also for repeated subtrees by\\\\n * object identity.\\\\n */\\\\nfunction cycleTolerantStringify(payload) {\\\\n const seenSet = new Set();\\\\n const replacer = (_, val) => {\\\\n if (typeof val === 'object' && val !== null) {\\\\n if (seenSet.has(val)) {\\\\n return '<**seen**>';}\\\\n\\\\n seenSet.add(val);}\\\\n\\\\n return val;};\\\\n\\\\n return JSON.stringify(payload, replacer);}\\\\n\\\\n\\\\nconst declassifiers = new WeakSet();\\\\n\\\\n/**\\\\n * To \\\\\\\"declassify\\\\\\\" and quote a substitution value used in a\\\\n * details`...` template literal, enclose that substitution expression\\\\n * in a call to `q`. This states that the argument should appear quoted (with\\\\n * `JSON.stringify`), in the error message of the thrown error. The payload\\\\n * itself is still passed unquoted to the console as it would be without q.\\\\n *\\\\n * Starting from the example in the `details` comment, say instead that the\\\\n * color the sky is supposed to be is also computed. Say that we still don't\\\\n * want to reveal the sky's actual color, but we do want the thrown error's\\\\n * message to reveal what color the sky was supposed to be:\\\\n * ```js\\\\n * assert.equal(\\\\n * sky.color,\\\\n * color,\\\\n * details`${sky.color} should be ${q(color)}`,\\\\n * );\\\\n * ```\\\\n *\\\\n * @typedef {Object} StringablePayload\\\\n * @property {*} payload The original payload\\\\n * @property {() => string} toString How to print the payload\\\\n *\\\\n * @param {*} payload What to declassify\\\\n * @returns {StringablePayload} The declassified payload\\\\n */\\\\nfunction q(payload) {\\\\n /* Don't harden the payload*/\\\\n const result = Object.freeze({\\\\n payload,\\\\n toString: Object.freeze(() => cycleTolerantStringify(payload)) });\\\\n\\\\n declassifiers.add(result);\\\\n return result;}\\\\n\\\\nharden(q);\\\\n\\\\n/**\\\\n * Use the `details` function as a template literal tag to create\\\\n * informative error messages. The assertion functions take such messages\\\\n * as optional arguments:\\\\n * ```js\\\\n * assert(sky.isBlue(), details`${sky.color} should be \\\\\\\"blue\\\\\\\"`);\\\\n * ```\\\\n * The details template tag returns an object that can print itself with the\\\\n * formatted message in two ways. It will report the real details to the\\\\n * console but include only the typeof information in the thrown error\\\\n * to prevent revealing secrets up the exceptional path. In the example\\\\n * above, the thrown error may reveal only that `sky.color` is a string,\\\\n * whereas the same diagnostic printed to the console reveals that the\\\\n * sky was green.\\\\n *\\\\n * WARNING: this function currently returns an unhardened result, as hardening\\\\n * proved to cause significant performance degradation. Consequently, callers\\\\n * should take care to use it only in contexts where this lack of hardening\\\\n * does not present a hazard. In current usage, a `details` template literal\\\\n * may only appear either as an argument to `assert`, where we know hardening\\\\n * won't matter, or inside another hardened object graph, where hardening is\\\\n * already ensured. However, there is currently no means to enfoce these\\\\n * constraints, so users are required to employ this function with caution.\\\\n * Our intent is to eventually have a lint rule that will check for\\\\n * inappropriate uses or find an alternative means of implementing `details`\\\\n * that does not encounter the performance issue. The final disposition of\\\\n * this is being discussed and tracked in issue #679 in the agoric-sdk\\\\n * repository.\\\\n *\\\\n * @typedef {Object} Complainer An object that has custom assert behaviour\\\\n * @property {() => Error} complain Return an Error to throw, and print details to console\\\\n *\\\\n * @typedef {string|Complainer} Details Either a plain string, or made by details``\\\\n *\\\\n * @param {TemplateStringsArray | string[]} template The template to format\\\\n * @param {any[]} args Arguments to the template\\\\n * @returns {Complainer} The complainer for these details\\\\n */\\\\nfunction details(template, ...args) {\\\\n /* const complainer = harden({ // remove harden per above discussion*/\\\\n const complainer = {\\\\n complain() {\\\\n const interleaved = [template[0]];\\\\n const parts = [template[0]];\\\\n for (let i = 0; i < args.length; i += 1) {\\\\n let arg = args[i];\\\\n let argStr;\\\\n if (declassifiers.has(arg)) {\\\\n argStr = `${arg}`;\\\\n arg = arg.payload;} else\\\\n {\\\\n argStr = `(${an(typeof arg)})`;}\\\\n\\\\n\\\\n /* Remove the extra spaces (since console.error puts them*/\\\\n /* between each interleaved).*/\\\\n const priorWithoutSpace = (interleaved.pop() || '').replace(/ $/, '');\\\\n if (priorWithoutSpace !== '') {\\\\n interleaved.push(priorWithoutSpace);}\\\\n\\\\n\\\\n const nextWithoutSpace = template[i + 1].replace(/^ /, '');\\\\n interleaved.push(arg, nextWithoutSpace);\\\\n\\\\n parts.push(argStr, template[i + 1]);}\\\\n\\\\n if (interleaved[interleaved.length - 1] === '') {\\\\n interleaved.pop();}\\\\n\\\\n if (args.length >= 1) {\\\\n parts.push('\\\\\\\\nSee console for error data.');}\\\\n\\\\n const err = new Error(parts.join(''));\\\\n console.error('LOGGED ERROR:', ...interleaved, err);\\\\n /* eslint-disable-next-line no-debugger*/\\\\n debugger;\\\\n return err;} };\\\\n\\\\n\\\\n /* });*/\\\\n return complainer;}\\\\n\\\\nharden(details);\\\\n\\\\n/**\\\\n * Fail an assertion, recording details to the console and\\\\n * raising an exception with just type information.\\\\n *\\\\n * The optional `optDetails` can be a string for backwards compatibility\\\\n * with the nodejs assertion library.\\\\n * @param {Details} [optDetails] The details of what was asserted\\\\n * @returns {never}\\\\n */\\\\nfunction fail(optDetails = details`Assert failed`) {\\\\n if (typeof optDetails === 'string') {\\\\n /* If it is a string, use it as the literal part of the template so*/\\\\n /* it doesn't get quoted.*/\\\\n optDetails = details([optDetails]);}\\\\n\\\\n throw optDetails.complain();}\\\\n\\\\n\\\\n/**\\\\n * @param {*} flag The truthy/falsy value\\\\n * @param {Details} [optDetails] The details to throw\\\\n * @returns {asserts flag}\\\\n */\\\\nfunction assert(flag, optDetails = details`Check failed`) {\\\\n if (!flag) {\\\\n throw fail(optDetails);}}\\\\n\\\\n\\\\n\\\\n/**\\\\n * Assert that two values must be `Object.is`.\\\\n * @param {*} actual The value we received\\\\n * @param {*} expected What we wanted\\\\n * @param {Details} [optDetails] The details to throw\\\\n * @returns {void}\\\\n */\\\\nfunction equal(\\\\nactual,\\\\nexpected,\\\\noptDetails = details`Expected ${actual} is same as ${expected}`)\\\\n{\\\\n assert(Object.is(actual, expected), optDetails);}\\\\n\\\\n\\\\n/**\\\\n * Assert an expected typeof result.\\\\n * @type {AssertTypeof}\\\\n * @param {any} specimen The value to get the typeof\\\\n * @param {string} typename The expected name\\\\n * @param {Details} [optDetails] The details to throw\\\\n */\\\\nconst assertTypeof = (specimen, typename, optDetails) => {\\\\n assert(\\\\n typeof typename === 'string',\\\\n details`${q(typename)} must be a string`);\\\\n\\\\n if (optDetails === undefined) {\\\\n /* Like*/\\\\n /* ```js*/\\\\n /* optDetails = details`${specimen} must be ${q(an(typename))}`;*/\\\\n /* ```*/\\\\n /* except it puts the typename into the literal part of the template*/\\\\n /* so it doesn't get quoted.*/\\\\n optDetails = details(['', ` must be ${an(typename)}`], specimen);}\\\\n\\\\n equal(typeof specimen, typename, optDetails);};\\\\n\\\\n\\\\n/**\\\\n * assert that expr is truthy, with an optional details to describe\\\\n * the assertion. It is a tagged template literal like\\\\n * ```js\\\\n * assert(expr, details`....`);`\\\\n * ```\\\\n * If expr is falsy, then the template contents are reported to the\\\\n * console and also in a thrown error.\\\\n *\\\\n * The literal portions of the template are assumed non-sensitive, as\\\\n * are the `typeof` types of the substitution values. These are\\\\n * assembled into the thrown error message. The actual contents of the\\\\n * substitution values are assumed sensitive, to be revealed to the\\\\n * console only. We assume only the virtual platform's owner can read\\\\n * what is written to the console, where the owner is in a privileged\\\\n * position over computation running on that platform.\\\\n *\\\\n * The optional `optDetails` can be a string for backwards compatibility\\\\n * with the nodejs assertion library.\\\\n * @type {typeof assert & { typeof: AssertTypeof, fail: typeof fail, equal: typeof equal }}\\\\n */\\\\nconst assertCombined = Object.assign(assert, {\\\\n equal,\\\\n fail,\\\\n typeof: assertTypeof });\\\\n\\\\nharden(assertCombined);exports.an = an;exports.assert = assertCombined;exports.details = details;exports.q = q;\\\",\\n \\\"node_modules/@agoric/nat/dist/nat.esm.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* Copyright (C) 2011 Google Inc.*/ /* Copyright (C) 2018 Agoric*/ /**/ /* Licensed under the Apache License, Version 2.0 (the \\\\\\\"License\\\\\\\");*/ /* you may not use this file except in compliance with the License.*/ /* You may obtain a copy of the License at*/ /**/ /* http://www.apache.org/licenses/LICENSE-2.0*/ /**/ /* Unless required by applicable law or agreed to in writing, software*/ /* distributed under the License is distributed on an \\\\\\\"AS IS\\\\\\\" BASIS,*/ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*/ /* See the License for the specific language governing permissions and*/ /* limitations under the License.*/ /**\\\\n * Is allegedNum a number in the contiguous range of exactly and\\\\n * unambiguously representable natural numbers (non-negative integers)?\\\\n *\\\\n * <p>See <a href=\\\\n * \\\\\\\"https://code.google.com/p/google-caja/issues/detail?id=1801\\\\\\\"\\\\n * >Issue 1801: Nat must include at most (2**53)-1</a>\\\\n * and <a href=\\\\n * \\\\\\\"https://mail.mozilla.org/pipermail/es-discuss/2013-July/031716.html\\\\\\\"\\\\n * >Allen Wirfs-Brock's suggested phrasing</a> on es-discuss.\\\\n */\\\\n\\\\nfunction Nat(allegedNum) {\\\\n if (!Number.isSafeInteger(allegedNum)) {\\\\n throw new RangeError('not a safe integer');}\\\\n\\\\n\\\\n if (allegedNum < 0) {\\\\n throw new RangeError('negative');}\\\\n\\\\n\\\\n return allegedNum;}exports.default = Nat;\\\",\\n \\\"packages/zoe/src/contractSupport/safeMath.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\nnat_esm = require('../../../../node_modules/@agoric/nat/dist/nat.esm.js'); /* global harden */ /**\\\\n * These operations should be used for calculations with the\\\\n * values of basic fungible tokens.\\\\n */\\\\nconst natSafeMath = harden({\\\\n add: (x, y) => nat_esm.default(x + y),\\\\n subtract: (x, y) => nat_esm.default(x - y),\\\\n multiply: (x, y) => nat_esm.default(x * y),\\\\n floorDivide: (x, y) => nat_esm.default(Math.floor(x / y)) });exports.natSafeMath = natSafeMath;\\\",\\n \\\"packages/zoe/src/contractSupport/bondingCurves.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../../assert/src/assert.js');var safeMath = require('./safeMath.js');\\\\n\\\\n\\\\nconst { add, subtract, multiply, floorDivide } = safeMath.natSafeMath;\\\\n\\\\n/**\\\\n * Contains the logic for calculating how much should be given\\\\n * back to the user in exchange for what they sent in. It also\\\\n * calculates the new amount of the assets in the pool. Reused in\\\\n * several different places, including to check whether an offer\\\\n * is valid, getting the current price for an asset on user\\\\n * request, and to do the actual reallocation after an offer has\\\\n * been made.\\\\n * @param {Object} params\\\\n * @param {number} params.inputValue - the value of the asset sent\\\\n * in to be swapped\\\\n * @param {number} params.inputReserve - the value in the liquidity\\\\n * pool of the kind of asset sent in\\\\n * @param {number} params.outputReserve - the value in the liquidity\\\\n * pool of the kind of asset to be sent out\\\\n * @param {number} params.feeBasisPoints=30 - the fee taken in\\\\n * basis points. The default is 0.3% or 30 basis points. The fee is taken from\\\\n * inputValue\\\\n * @returns {number} outputValue - the current price, in value form\\\\n */\\\\nconst getInputPrice = ({\\\\n inputValue,\\\\n inputReserve,\\\\n outputReserve,\\\\n feeBasisPoints = 30 }) =>\\\\n{\\\\n const oneMinusFeeInTenThousandths = subtract(10000, feeBasisPoints);\\\\n const inputWithFee = multiply(inputValue, oneMinusFeeInTenThousandths);\\\\n const numerator = multiply(inputWithFee, outputReserve);\\\\n const denominator = add(multiply(inputReserve, 10000), inputWithFee);\\\\n\\\\n const outputValue = floorDivide(numerator, denominator);\\\\n return outputValue;};\\\\n\\\\n\\\\nfunction assertDefined(label, value) {\\\\n assert.assert(value !== undefined, assert.details`${label} value required`);}\\\\n\\\\n\\\\n/* Calculate how many liquidity tokens we should be minting to send back to the*/\\\\n/* user when adding liquidity. Calculations are based on the comparing the*/\\\\n/* inputValue to the inputReserve. If the current supply is zero, just return*/\\\\n/* the inputValue.*/\\\\nconst calcLiqValueToMint = ({\\\\n liqTokenSupply,\\\\n inputValue,\\\\n inputReserve }) =>\\\\n{\\\\n assertDefined('liqTokenSupply', liqTokenSupply);\\\\n assertDefined('inputValue', inputValue);\\\\n assertDefined('inputReserve', inputReserve);\\\\n return liqTokenSupply > 0 ?\\\\n floorDivide(multiply(inputValue, liqTokenSupply), inputReserve) :\\\\n inputValue;};\\\\n\\\\n\\\\n/* Calculate how many underlying tokens (in the form of a value) should be*/\\\\n/* returned when removing liquidity.*/\\\\nconst calcValueToRemove = ({\\\\n liqTokenSupply,\\\\n poolValue,\\\\n liquidityValueIn }) =>\\\\n{\\\\n assertDefined('liqTokenSupply', liqTokenSupply);\\\\n assertDefined('liquidityValueIn', liquidityValueIn);\\\\n assertDefined('poolValue', poolValue);\\\\n\\\\n return floorDivide(multiply(liquidityValueIn, poolValue), liqTokenSupply);};exports.calcLiqValueToMint = calcLiqValueToMint;exports.calcValueToRemove = calcValueToRemove;exports.getInputPrice = getInputPrice;\\\",\\n \\\"packages/zoe/src/contractSupport/stateMachine.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\nassert = require('../../../assert/src/assert.js'); /* global harden */ /* allowedTransitions is an array of arrays which gets turned into a\\\\n * map. The map maps string states to an array of potential next\\\\n * states. For example,\\\\n * const allowedTransitions = [\\\\n ['open', ['closed']],\\\\n ['closed', []],\\\\n * ];\\\\n */\\\\nconst makeStateMachine = (initialState, allowedTransitionsArray) => {\\\\n let state = initialState;\\\\n const allowedTransitions = new Map(allowedTransitionsArray);\\\\n return harden({\\\\n canTransitionTo: (nextState) =>\\\\n allowedTransitions.get(state).includes(nextState),\\\\n transitionTo: nextState => {\\\\n assert.assert(allowedTransitions.get(state).includes(nextState));\\\\n state = nextState;},\\\\n\\\\n getStatus: _ => state });};\\\\n\\\\n\\\\nharden(makeStateMachine);exports.makeStateMachine = makeStateMachine;\\\",\\n \\\"packages/eventual-send/src/E.js\\\": \\\"'use strict';\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* global harden */ /* eslint-disable-next-line spaced-comment*/ /*/ <reference path=\\\\\\\"index.d.ts\\\\\\\" />*/\\\\n\\\\nconst readOnlyProxy = {\\\\n set(_target, _prop, _value) {\\\\n return false;},\\\\n\\\\n isExtensible(_target) {\\\\n return false;},\\\\n\\\\n setPrototypeOf(_target, _value) {\\\\n return false;},\\\\n\\\\n deleteProperty(_target, _prop) {\\\\n return false;} };\\\\n\\\\n\\\\n\\\\n/**\\\\n * A Proxy handler for E(x).\\\\n *\\\\n * @param {*} x Any value passed to E(x)\\\\n * @returns {ProxyHandler} the Proxy handler\\\\n */\\\\nfunction EProxyHandler(x, HandledPromise) {\\\\n return harden({\\\\n ...readOnlyProxy,\\\\n get(_target, p, _receiver) {\\\\n if (`${p}` !== p) {\\\\n return undefined;}\\\\n\\\\n /* Harden this Promise because it's our only opportunity to ensure*/\\\\n /* p1=E(x).foo() is hardened. The Handled Promise API does not (yet)*/\\\\n /* allow the handler to synchronously influence the promise returned*/\\\\n /* by the handled methods, so we must freeze it from the outside. See*/\\\\n /* #95 for details.*/\\\\n return (...args) => harden(HandledPromise.applyMethod(x, p, args));},\\\\n\\\\n apply(_target, _thisArg, argArray = []) {\\\\n return harden(HandledPromise.applyFunction(x, argArray));},\\\\n\\\\n has(_target, _p) {\\\\n /* We just pretend everything exists.*/\\\\n return true;} });}\\\\n\\\\n\\\\n\\\\n\\\\nfunction makeE(HandledPromise) {\\\\n function E(x) {\\\\n const handler = EProxyHandler(x, HandledPromise);\\\\n return harden(new Proxy(() => {}, handler));}\\\\n\\\\n\\\\n const makeEGetterProxy = (x) =>\\\\n new Proxy(Object.create(null), {\\\\n ...readOnlyProxy,\\\\n has(_target, _prop) {\\\\n return true;},\\\\n\\\\n get(_target, prop) {\\\\n return harden(HandledPromise.get(x, prop));} });\\\\n\\\\n\\\\n\\\\n E.G = makeEGetterProxy;\\\\n E.resolve = HandledPromise.resolve;\\\\n E.unwrap = HandledPromise.unwrap;\\\\n\\\\n E.when = (x, onfulfilled = undefined, onrejected = undefined) =>\\\\n HandledPromise.resolve(x).then(onfulfilled, onrejected);\\\\n\\\\n return harden(E);}exports.default = makeE;\\\",\\n \\\"packages/eventual-send/src/index.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var E$1 = require('./E.js'); /* global harden HandledPromise */\\\\n\\\\n\\\\n\\\\nconst {\\\\n defineProperties,\\\\n getOwnPropertyDescriptors,\\\\n getOwnPropertyDescriptor: gopd,\\\\n getPrototypeOf,\\\\n isFrozen } =\\\\nObject;\\\\n\\\\nconst { prototype: promiseProto } = Promise;\\\\nconst { then: originalThen } = promiseProto;\\\\n\\\\n/* 'E' and 'HandledPromise' are exports of the module*/\\\\n\\\\n/* For now:*/\\\\n/* import { HandledPromise, E } from '@agoric/eventual-send';*/\\\\n/* ...*/\\\\n\\\\nconst hp =\\\\ntypeof HandledPromise === 'undefined' ?\\\\n/* eslint-disable-next-line no-use-before-define*/\\\\nmakeHandledPromise(Promise) :\\\\nharden(HandledPromise);\\\\n\\\\n\\\\n\\\\nconst E = E$1.default(hp);\\\\n\\\\n/* the following method (makeHandledPromise) is part*/\\\\n/* of the shim, and will not be exported by the module once the feature*/\\\\n/* becomes a part of standard javascript*/\\\\n\\\\n/**\\\\n * Create a HandledPromise class to have it support eventual send\\\\n * (wavy-dot) operations.\\\\n *\\\\n * Based heavily on nanoq\\\\n * https://github.com/drses/nanoq/blob/master/src/nanoq.js\\\\n *\\\\n * Original spec for the infix-bang (predecessor to wavy-dot) desugaring:\\\\n * https://web.archive.org/web/20161026162206/http://wiki.ecmascript.org/doku.php?id=strawman:concurrency\\\\n *\\\\n * @return {typeof HandledPromise} Handled promise\\\\n */\\\\nfunction makeHandledPromise(Promise) {\\\\n /* xs doesn't support WeakMap in pre-loaded closures*/\\\\n /* aka \\\\\\\"vetted customization code\\\\\\\"*/\\\\n let presenceToHandler;\\\\n let presenceToPromise;\\\\n let promiseToUnsettledHandler;\\\\n let promiseToPresence; /* only for HandledPromise.unwrap*/\\\\n let forwardedPromiseToPromise; /* forwarding, union-find-ish*/\\\\n function ensureMaps() {\\\\n if (!presenceToHandler) {\\\\n presenceToHandler = new WeakMap();\\\\n presenceToPromise = new WeakMap();\\\\n promiseToUnsettledHandler = new WeakMap();\\\\n promiseToPresence = new WeakMap();\\\\n forwardedPromiseToPromise = new WeakMap();}}\\\\n\\\\n\\\\n\\\\n /**\\\\n * You can imagine a forest of trees in which the roots of each tree is an\\\\n * unresolved HandledPromise or a non-Promise, and each node's parent is the\\\\n * HandledPromise to which it was forwarded. We maintain that mapping of\\\\n * forwarded HandledPromise to its resolution in forwardedPromiseToPromise.\\\\n *\\\\n * We use something like the description of \\\\\\\"Find\\\\\\\" with \\\\\\\"Path splitting\\\\\\\"\\\\n * to propagate changes down to the children efficiently:\\\\n * https://en.wikipedia.org/wiki/Disjoint-set_data_structure\\\\n *\\\\n * @param {*} target Any value.\\\\n * @returns {*} If the target was a HandledPromise, the most-resolved parent of it, otherwise the target.\\\\n */\\\\n function shorten(target) {\\\\n let p = target;\\\\n /* Find the most-resolved value for p.*/\\\\n while (forwardedPromiseToPromise.has(p)) {\\\\n p = forwardedPromiseToPromise.get(p);}\\\\n\\\\n const presence = promiseToPresence.get(p);\\\\n if (presence) {\\\\n /* Presences are final, so it is ok to propagate*/\\\\n /* this upstream.*/\\\\n while (target !== p) {\\\\n const parent = forwardedPromiseToPromise.get(target);\\\\n forwardedPromiseToPromise.delete(target);\\\\n promiseToUnsettledHandler.delete(target);\\\\n promiseToPresence.set(target, presence);\\\\n target = parent;}} else\\\\n\\\\n {\\\\n /* We propagate p and remove all other unsettled handlers*/\\\\n /* upstream.*/\\\\n /* Note that everything except presences is covered here.*/\\\\n while (target !== p) {\\\\n const parent = forwardedPromiseToPromise.get(target);\\\\n forwardedPromiseToPromise.set(target, p);\\\\n promiseToUnsettledHandler.delete(target);\\\\n target = parent;}}\\\\n\\\\n\\\\n return target;}\\\\n\\\\n\\\\n /* This special handler accepts Promises, and forwards*/\\\\n /* handled Promises to their corresponding fulfilledHandler.*/\\\\n let forwardingHandler;\\\\n let handle;\\\\n let promiseResolve;\\\\n\\\\n function HandledPromise(executor, unsettledHandler = undefined) {\\\\n if (new.target === undefined) {\\\\n throw new Error('must be invoked with \\\\\\\"new\\\\\\\"');}\\\\n\\\\n let handledResolve;\\\\n let handledReject;\\\\n let resolved = false;\\\\n let resolvedTarget = null;\\\\n let handledP;\\\\n let continueForwarding = () => {};\\\\n const superExecutor = (superResolve, superReject) => {\\\\n handledResolve = value => {\\\\n if (resolved) {\\\\n return resolvedTarget;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n value = shorten(value);\\\\n let targetP;\\\\n if (\\\\n promiseToUnsettledHandler.has(value) ||\\\\n promiseToPresence.has(value))\\\\n {\\\\n targetP = value;} else\\\\n {\\\\n /* We're resolving to a non-promise, so remove our handler.*/\\\\n promiseToUnsettledHandler.delete(handledP);\\\\n targetP = presenceToPromise.get(value);}\\\\n\\\\n /* Ensure our data structure is a propert tree (avoid cycles).*/\\\\n if (targetP && targetP !== handledP) {\\\\n forwardedPromiseToPromise.set(handledP, targetP);} else\\\\n {\\\\n forwardedPromiseToPromise.delete(handledP);}\\\\n\\\\n\\\\n /* Remove stale unsettled handlers, set to canonical form.*/\\\\n shorten(handledP);\\\\n\\\\n /* Ensure our unsettledHandler is cleaned up if not already.*/\\\\n if (promiseToUnsettledHandler.has(handledP)) {\\\\n handledP.then(_ => promiseToUnsettledHandler.delete(handledP));}\\\\n\\\\n\\\\n /* Finish the resolution.*/\\\\n superResolve(value);\\\\n resolved = true;\\\\n resolvedTarget = value;\\\\n\\\\n /* We're resolved, so forward any postponed operations to us.*/\\\\n continueForwarding();\\\\n return resolvedTarget;};\\\\n\\\\n handledReject = err => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n promiseToUnsettledHandler.delete(handledP);\\\\n resolved = true;\\\\n superReject(err);\\\\n continueForwarding();};};\\\\n\\\\n\\\\n handledP = harden(Reflect.construct(Promise, [superExecutor], new.target));\\\\n\\\\n ensureMaps();\\\\n\\\\n const makePostponedHandler = () => {\\\\n /* Create a simple postponedHandler that just postpones until the*/\\\\n /* fulfilledHandler is set.*/\\\\n let donePostponing;\\\\n const interlockP = new Promise(resolve => {\\\\n donePostponing = () => resolve();});\\\\n\\\\n\\\\n const makePostponedOperation = postponedOperation => {\\\\n /* Just wait until the handler is resolved/rejected.*/\\\\n return function postpone(x, ...args) {\\\\n /* console.log(`forwarding ${postponedOperation} ${args[0]}`);*/\\\\n return new HandledPromise((resolve, reject) => {\\\\n interlockP.\\\\n then(_ => {\\\\n /* If targetP is a handled promise, use it, otherwise x.*/\\\\n resolve(HandledPromise[postponedOperation](x, ...args));}).\\\\n\\\\n catch(reject);});};};\\\\n\\\\n\\\\n\\\\n\\\\n const postponedHandler = {\\\\n get: makePostponedOperation('get'),\\\\n applyMethod: makePostponedOperation('applyMethod') };\\\\n\\\\n return [postponedHandler, donePostponing];};\\\\n\\\\n\\\\n if (!unsettledHandler) {\\\\n /* This is insufficient for actual remote handled Promises*/\\\\n /* (too many round-trips), but is an easy way to create a*/\\\\n /* local handled Promise.*/\\\\n [unsettledHandler, continueForwarding] = makePostponedHandler();}\\\\n\\\\n\\\\n const validateHandler = h => {\\\\n if (Object(h) !== h) {\\\\n throw TypeError(`Handler ${h} cannot be a primitive`);}};\\\\n\\\\n\\\\n validateHandler(unsettledHandler);\\\\n\\\\n /* Until the handled promise is resolved, we use the unsettledHandler.*/\\\\n promiseToUnsettledHandler.set(handledP, unsettledHandler);\\\\n\\\\n const rejectHandled = reason => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n handledReject(reason);};\\\\n\\\\n\\\\n const resolveWithPresence = presenceHandler => {\\\\n if (resolved) {\\\\n return resolvedTarget;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n try {\\\\n /* Sanity checks.*/\\\\n validateHandler(presenceHandler);\\\\n\\\\n /* Validate and install our mapped target (i.e. presence).*/\\\\n resolvedTarget = Object.create(null);\\\\n\\\\n /* Create table entries for the presence mapped to the*/\\\\n /* fulfilledHandler.*/\\\\n presenceToPromise.set(resolvedTarget, handledP);\\\\n promiseToPresence.set(handledP, resolvedTarget);\\\\n presenceToHandler.set(resolvedTarget, presenceHandler);\\\\n\\\\n /* We committed to this presence, so resolve.*/\\\\n handledResolve(resolvedTarget);\\\\n return resolvedTarget;}\\\\n catch (e) {\\\\n handledReject(e);\\\\n throw e;}};\\\\n\\\\n\\\\n\\\\n const resolveHandled = async (target, deprecatedPresenceHandler) => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n try {\\\\n if (deprecatedPresenceHandler) {\\\\n throw TypeError(\\\\n `resolveHandled no longer accepts a handler; use resolveWithPresence`);}\\\\n\\\\n\\\\n\\\\n /* Resolve the target.*/\\\\n handledResolve(target);}\\\\n catch (e) {\\\\n handledReject(e);}};\\\\n\\\\n\\\\n\\\\n /* Invoke the callback to let the user resolve/reject.*/\\\\n executor(\\\\n (...args) => {\\\\n resolveHandled(...args);},\\\\n\\\\n rejectHandled,\\\\n resolveWithPresence);\\\\n\\\\n return handledP;}\\\\n\\\\n\\\\n HandledPromise.prototype = promiseProto;\\\\n Object.setPrototypeOf(HandledPromise, Promise);\\\\n\\\\n function isFrozenPromiseThen(p) {\\\\n return (\\\\n isFrozen(p) &&\\\\n getPrototypeOf(p) === promiseProto &&\\\\n promiseResolve(p) === p &&\\\\n gopd(p, 'then') === undefined &&\\\\n gopd(promiseProto, 'then').value === originalThen /* unnecessary under SES*/);}\\\\n\\\\n\\\\n\\\\n const staticMethods = harden({\\\\n get(target, key) {\\\\n return handle(target, 'get', key);},\\\\n\\\\n getSendOnly(target, key) {\\\\n handle(target, 'get', key);},\\\\n\\\\n applyFunction(target, args) {\\\\n return handle(target, 'applyMethod', undefined, args);},\\\\n\\\\n applyFunctionSendOnly(target, args) {\\\\n handle(target, 'applyMethod', undefined, args);},\\\\n\\\\n applyMethod(target, key, args) {\\\\n return handle(target, 'applyMethod', key, args);},\\\\n\\\\n applyMethodSendOnly(target, key, args) {\\\\n handle(target, 'applyMethod', key, args);},\\\\n\\\\n resolve(value) {\\\\n ensureMaps();\\\\n /* Resolving a Presence returns the pre-registered handled promise.*/\\\\n let resolvedPromise = presenceToPromise.get(value);\\\\n if (!resolvedPromise) {\\\\n resolvedPromise = promiseResolve(value);}\\\\n\\\\n /* Prevent any proxy trickery.*/\\\\n harden(resolvedPromise);\\\\n if (isFrozenPromiseThen(resolvedPromise)) {\\\\n return resolvedPromise;}\\\\n\\\\n /* Assimilate the thenable.*/\\\\n const executeThen = (resolve, reject) =>\\\\n resolvedPromise.then(resolve, reject);\\\\n return harden(\\\\n promiseResolve().then(_ => new HandledPromise(executeThen)));},\\\\n\\\\n\\\\n /* TODO verify that this is safe to provide universally, i.e.,*/\\\\n /* that by itself it doesn't provide access to mutable state in*/\\\\n /* ways that violate normal ocap module purity rules. The claim*/\\\\n /* that it does not rests on the handled promise itself being*/\\\\n /* necessary to perceive this mutable state. In that sense, we*/\\\\n /* can think of the right to perceive it, and of access to the*/\\\\n /* target, as being in the handled promise. Note that a .then on*/\\\\n /* the handled promise will already provide async access to the*/\\\\n /* target, so the only additional authorities are: 1)*/\\\\n /* synchronous access for handled promises only, and thus 2) the*/\\\\n /* ability to tell, from the client side, whether a promise is*/\\\\n /* handled. Or, at least, the ability to tell given that the*/\\\\n /* promise is already fulfilled.*/\\\\n unwrap(value) {\\\\n /* This check for Thenable is safe, since in a remote-object*/\\\\n /* environment, our comms system will defend against remote*/\\\\n /* objects being represented as a tricky local Proxy, otherwise*/\\\\n /* it is guaranteed to be local and therefore synchronous enough.*/\\\\n if (Object(value) !== value || !('then' in value)) {\\\\n /* Not a Thenable, so return it.*/\\\\n /* This means that local objects will pass through without error.*/\\\\n return value;}\\\\n\\\\n\\\\n /* Try to look up the HandledPromise.*/\\\\n ensureMaps();\\\\n const pr = presenceToPromise.get(value) || value;\\\\n\\\\n /* Find the fulfilled presence for that HandledPromise.*/\\\\n const presence = promiseToPresence.get(pr);\\\\n if (!presence) {\\\\n throw TypeError(\\\\n `Value is a Thenble but not a HandledPromise fulfilled to a presence`);}\\\\n\\\\n\\\\n return presence;} });\\\\n\\\\n\\\\n\\\\n defineProperties(HandledPromise, getOwnPropertyDescriptors(staticMethods));\\\\n\\\\n function makeForwarder(operation, localImpl) {\\\\n return (o, ...args) => {\\\\n /* We are in another turn already, and have the naked object.*/\\\\n const fulfilledHandler = presenceToHandler.get(o);\\\\n if (\\\\n fulfilledHandler &&\\\\n typeof fulfilledHandler[operation] === 'function')\\\\n {\\\\n /* The handler was resolved, so use it.*/\\\\n return fulfilledHandler[operation](o, ...args);}\\\\n\\\\n\\\\n /* Not handled, so use the local implementation.*/\\\\n return localImpl(o, ...args);};}\\\\n\\\\n\\\\n\\\\n /* eslint-disable-next-line prefer-const*/\\\\n forwardingHandler = {\\\\n get: makeForwarder('get', (o, key) => o[key]),\\\\n applyMethod: makeForwarder('applyMethod', (o, optKey, args) => {\\\\n if (optKey === undefined || optKey === null) {\\\\n return o(...args);}\\\\n\\\\n /* console.log(`sending`, optKey, o[optKey], o);*/\\\\n if (typeof o[optKey] !== 'function') {\\\\n throw TypeError(`o[${JSON.stringify(optKey)}] is not a function`);}\\\\n\\\\n return o[optKey](...args);}) };\\\\n\\\\n\\\\n\\\\n handle = (p, operation, ...opArgs) => {\\\\n ensureMaps();\\\\n const returnedP = new HandledPromise((resolve, reject) => {\\\\n /* We run in a future turn to prevent synchronous attacks,*/\\\\n let raceIsOver = false;\\\\n function win(handlerName, handler, o) {\\\\n if (raceIsOver) {\\\\n return;}\\\\n\\\\n if (typeof handler[operation] !== 'function') {\\\\n throw TypeError(`${handlerName}.${operation} is not a function`);}\\\\n\\\\n try {\\\\n resolve(handler[operation](o, ...opArgs, returnedP));}\\\\n catch (reason) {\\\\n reject(reason);}\\\\n\\\\n raceIsOver = true;}\\\\n\\\\n\\\\n function lose(e) {\\\\n if (raceIsOver) {\\\\n return;}\\\\n\\\\n reject(e);\\\\n raceIsOver = true;}\\\\n\\\\n\\\\n /* This contestant tries to win with the target's resolution.*/\\\\n HandledPromise.resolve(p).\\\\n then(o => win('forwardingHandler', forwardingHandler, o)).\\\\n catch(lose);\\\\n\\\\n /* This contestant sleeps a turn, but then tries to win immediately.*/\\\\n HandledPromise.resolve().\\\\n then(() => {\\\\n p = shorten(p);\\\\n const unsettledHandler = promiseToUnsettledHandler.get(p);\\\\n if (\\\\n unsettledHandler &&\\\\n typeof unsettledHandler[operation] === 'function')\\\\n {\\\\n /* and resolve to the answer from the specific unsettled handler,*/\\\\n /* opArgs are something like [prop] or [method, args],*/\\\\n /* so we don't risk the user's args leaking into this expansion.*/\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n win('unsettledHandler', unsettledHandler, p);} else\\\\n if (Object(p) !== p || !('then' in p)) {\\\\n /* Not a Thenable, so use it.*/\\\\n win('forwardingHandler', forwardingHandler, p);} else\\\\n if (promiseToPresence.has(p)) {\\\\n /* We have the object synchronously, so resolve with it.*/\\\\n const o = promiseToPresence.get(p);\\\\n win('forwardingHandler', forwardingHandler, o);}\\\\n\\\\n /* If we made it here without winning, then we will wait*/\\\\n /* for the other contestant to win instead.*/}).\\\\n\\\\n catch(lose);});\\\\n\\\\n\\\\n /* We return a handled promise with the default unsettled handler.*/\\\\n /* This prevents a race between the above Promise.resolves and*/\\\\n /* pipelining.*/\\\\n return returnedP;};\\\\n\\\\n\\\\n promiseResolve = Promise.resolve.bind(Promise);\\\\n return harden(HandledPromise);}exports.E = E;exports.HandledPromise = hp;exports.makeHandledPromise = makeHandledPromise;\\\",\\n \\\"packages/produce-promise/src/producePromise.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nindex = require('../../eventual-send/src/index.js'); /* global harden */ /**\\\\n * @template U,V\\\\n * @typedef {Object} PromiseRecord A reified Promise\\\\n * @property {(value?: U) => void} resolve\\\\n * @property {(reason?: V) => void} reject\\\\n * @property {Promise.<U, V>} promise\\\\n */ /**\\\\n * producePromise() builds a HandledPromise object, and returns a record\\\\n * containing the promise itself, as well as separate facets for resolving\\\\n * and rejecting it.\\\\n *\\\\n * @template U,V\\\\n * @returns {PromiseRecord.<U,V>}\\\\n */function producePromise() {let res;let rej; /* We use a HandledPromise so that we can run HandledPromise.unwrap(p)*/ /* even if p doesn't travel through a comms system (like SwingSet's).*/const p = new index.HandledPromise((resolve, reject) => {\\\\n res = resolve;\\\\n rej = reject;});\\\\n\\\\n /* Node.js adds the `domain` property which is not a standard*/\\\\n /* property on Promise. Because we do not know it to be ocap-safe,*/\\\\n /* we remove it.*/\\\\n if (p.domain) {\\\\n /* deleting p.domain may break functionality. To retain current*/\\\\n /* functionality at the expense of safety, set unsafe to true.*/\\\\n const unsafe = false;\\\\n if (unsafe) {\\\\n const originalDomain = p.domain;\\\\n Object.defineProperty(p, 'domain', {\\\\n get() {\\\\n return originalDomain;} });} else\\\\n\\\\n\\\\n {\\\\n delete p.domain;}}\\\\n\\\\n\\\\n return harden({ promise: p, resolve: res, reject: rej });}\\\\n\\\\nharden(producePromise);\\\\n\\\\n/**\\\\n * Determine if the argument is a Promise.\\\\n *\\\\n * @param {Promise} maybePromise The value to examine\\\\n * @returns {boolean} Whether it is a promise\\\\n */\\\\nfunction isPromise(maybePromise) {\\\\n return index.HandledPromise.resolve(maybePromise) === maybePromise;}\\\\n\\\\nharden(isPromise);exports.isPromise = isPromise;exports.producePromise = producePromise;\\\",\\n \\\"packages/marshal/marshal.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var nat_esm = require('../../node_modules/@agoric/nat/dist/nat.esm.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nproducePromise = require('../produce-promise/src/producePromise.js'); /* global harden */ /* TODO: Use just 'remote' when we're willing to make a breaking change.*/\\\\nconst REMOTE_STYLE = 'presence';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n/**\\\\n * This is an interface specification.\\\\n * For now, it is just a string, but will eventually become something\\\\n * much richer (anything that pureCopy accepts).\\\\n * @typedef {string} InterfaceSpec\\\\n */\\\\n\\\\n/**\\\\n * @type {WeakMap<Object, InterfaceSpec>}\\\\n */\\\\nconst remotableToInterface = new WeakMap();\\\\n\\\\n/**\\\\n * Simple semantics, just tell what interface (or undefined) a remotable has.\\\\n *\\\\n * @param {*} maybeRemotable the value to check\\\\n * @returns {InterfaceSpec} the interface specification, or undefined if not a Remotable\\\\n */\\\\nfunction getInterfaceOf(maybeRemotable) {\\\\n return remotableToInterface.get(maybeRemotable);}\\\\n\\\\n\\\\n/**\\\\n * Do a deep copy of the object, handling Proxies and recursion.\\\\n * The resulting copy is guaranteed to be pure data, as well as hardened.\\\\n * Such a hardened, pure copy cannot be used as a communications path.\\\\n *\\\\n * @template T\\\\n * @param {T} val input value. NOTE: Must be hardened!\\\\n * @returns {T} pure, hardened copy\\\\n */\\\\nfunction pureCopy(val, already = new WeakMap()) {\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n const passStyle = passStyleOf(val);\\\\n switch (passStyle) {\\\\n case 'bigint':\\\\n case 'boolean':\\\\n case 'null':\\\\n case 'number':\\\\n case 'string':\\\\n case 'undefined':\\\\n return val;\\\\n\\\\n case 'copyArray':\\\\n case 'copyRecord':{\\\\n const obj = /** @type {Object} */val;\\\\n if (already.has(obj)) {\\\\n return already.get(obj);}\\\\n\\\\n\\\\n /* Create a new identity.*/\\\\n const copy = /** @type {T} */passStyle === 'copyArray' ? [] : {};\\\\n\\\\n /* Prevent recursion.*/\\\\n already.set(obj, copy);\\\\n\\\\n /* Make a deep copy on the new identity.*/\\\\n /* Object.entries(obj) takes a snapshot (even if a Proxy).*/\\\\n Object.entries(obj).forEach(([prop, value]) => {\\\\n copy[prop] = pureCopy(value, already);});\\\\n\\\\n return harden(copy);}\\\\n\\\\n\\\\n case 'copyError':{\\\\n const unk = /** @type {unknown} */val;\\\\n const err = /** @type {Error} */unk;\\\\n\\\\n if (already.has(err)) {\\\\n return already.get(err);}\\\\n\\\\n\\\\n const { name, message } = err;\\\\n\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n const EC = getErrorConstructor(`${name}`) || Error;\\\\n const copy = harden(new EC(`${message}`));\\\\n already.set(err, copy);\\\\n\\\\n const unk2 = /** @type {unknown} */harden(copy);\\\\n return (/** @type {T} */unk2);}\\\\n\\\\n\\\\n case REMOTE_STYLE:{\\\\n throw TypeError(\\\\n `Input value ${passStyle} cannot be copied as must be passed by reference`);}\\\\n\\\\n\\\\n\\\\n default:\\\\n throw TypeError(`Input value ${passStyle} is not recognized as data`);}}\\\\n\\\\n\\\\nharden(pureCopy);\\\\n\\\\n\\\\n/* Special property name that indicates an encoding that needs special*/\\\\n/* decoding.*/\\\\nconst QCLASS = '@qclass';\\\\n\\\\n\\\\n/* objects can only be passed in one of two/three forms:*/\\\\n/* 1: pass-by-remote: all properties (own and inherited) are methods,*/\\\\n/* the object itself is of type object, not function*/\\\\n/* 2: pass-by-copy: all string-named own properties are data, not methods*/\\\\n/* the object must inherit from Object.prototype or null*/\\\\n/* 3: the empty object is pass-by-remote, for identity comparison*/\\\\n\\\\n/* all objects must be frozen*/\\\\n\\\\n/* anything else will throw an error if you try to serialize it*/\\\\n\\\\n/* with these restrictions, our remote call/copy protocols expose all useful*/\\\\n/* behavior of these objects: pass-by-remote objects have no other data (so*/\\\\n/* there's nothing else to copy), and pass-by-copy objects have no other*/\\\\n/* behavior (so there's nothing else to invoke)*/\\\\n\\\\nconst errorConstructors = new Map([\\\\n['Error', Error],\\\\n['EvalError', EvalError],\\\\n['RangeError', RangeError],\\\\n['ReferenceError', ReferenceError],\\\\n['SyntaxError', SyntaxError],\\\\n['TypeError', TypeError],\\\\n['URIError', URIError]]);\\\\n\\\\n\\\\nfunction getErrorConstructor(name) {\\\\n return errorConstructors.get(name);}\\\\n\\\\n\\\\nfunction isPassByCopyError(val) {\\\\n /* TODO: Need a better test than instanceof*/\\\\n if (!(val instanceof Error)) {\\\\n return false;}\\\\n\\\\n const proto = Object.getPrototypeOf(val);\\\\n const { name } = val;\\\\n const EC = getErrorConstructor(name);\\\\n if (!EC || EC.prototype !== proto) {\\\\n throw TypeError(`Must inherit from an error class .prototype ${val}`);}\\\\n\\\\n\\\\n const {\\\\n message: { value: messageStr } = { value: '' },\\\\n /* Allow but ignore only extraneous own `stack` property.*/\\\\n /* TODO: I began the variable below with \\\\\\\"_\\\\\\\". Why do I still need*/\\\\n /* to suppress the lint complaint?*/\\\\n /* eslint-disable-next-line no-unused-vars*/\\\\n stack: _optStackDesc,\\\\n ...restDescs } =\\\\n Object.getOwnPropertyDescriptors(val);\\\\n const restNames = Object.keys(restDescs);\\\\n if (restNames.length >= 1) {\\\\n throw new TypeError(`Unexpected own properties in error: ${restNames}`);}\\\\n\\\\n if (typeof messageStr !== 'string') {\\\\n throw new TypeError(`malformed error object: ${val}`);}\\\\n\\\\n return true;}\\\\n\\\\n\\\\nfunction isPassByCopyArray(val) {\\\\n if (!Array.isArray(val)) {\\\\n return false;}\\\\n\\\\n if (Object.getPrototypeOf(val) !== Array.prototype) {\\\\n throw new TypeError(`malformed array: ${val}`);}\\\\n\\\\n const len = val.length;\\\\n const descs = Object.getOwnPropertyDescriptors(val);\\\\n for (let i = 0; i < len; i += 1) {\\\\n const desc = descs[i];\\\\n if (!desc) {\\\\n throw new TypeError(`arrays must not contain holes`);}\\\\n\\\\n if (!('value' in desc)) {\\\\n throw new TypeError(`arrays must not contain accessors`);}\\\\n\\\\n if (typeof desc.value === 'function') {\\\\n throw new TypeError(`arrays must not contain methods`);}}\\\\n\\\\n\\\\n if (Object.keys(descs).length !== len + 1) {\\\\n throw new TypeError(`array must not have non-indexes ${val}`);}\\\\n\\\\n return true;}\\\\n\\\\n\\\\nfunction isPassByCopyRecord(val) {\\\\n if (Object.getPrototypeOf(val) !== Object.prototype) {\\\\n return false;}\\\\n\\\\n const descList = Object.values(Object.getOwnPropertyDescriptors(val));\\\\n if (descList.length === 0) {\\\\n /* empty non-array objects are pass-by-remote, not pass-by-copy*/\\\\n return false;}\\\\n\\\\n for (const desc of descList) {\\\\n if (!('value' in desc)) {\\\\n /* Should we error if we see an accessor here?*/\\\\n return false;}\\\\n\\\\n if (typeof desc.value === 'function') {\\\\n return false;}}\\\\n\\\\n\\\\n return true;}\\\\n\\\\n\\\\n/**\\\\n * Ensure that val could become a legitimate remotable. This is used internally both\\\\n * in the construction of a new remotable and mustPassByRemote.\\\\n *\\\\n * @param {*} val The remotable candidate to check\\\\n */\\\\nfunction assertCanBeRemotable(val) {\\\\n /* throws exception if cannot*/\\\\n if (typeof val !== 'object') {\\\\n throw new Error(`cannot serialize non-objects like ${val}`);}\\\\n\\\\n if (Array.isArray(val)) {\\\\n throw new Error(`Arrays cannot be pass-by-remote`);}\\\\n\\\\n if (val === null) {\\\\n throw new Error(`null cannot be pass-by-remote`);}\\\\n\\\\n\\\\n const names = Object.getOwnPropertyNames(val);\\\\n names.forEach(name => {\\\\n if (typeof val[name] !== 'function') {\\\\n throw new Error(\\\\n `cannot serialize objects with non-methods like the .${name} in ${val}`);\\\\n\\\\n /* return false;*/}});\\\\n\\\\n\\\\n\\\\n /* ok!*/}\\\\n\\\\n\\\\nfunction mustPassByRemote(val) {\\\\n if (!Object.isFrozen(val)) {\\\\n throw new Error(`cannot serialize non-frozen objects like ${val}`);}\\\\n\\\\n\\\\n if (getInterfaceOf(val) === undefined) {\\\\n /* Not a registered Remotable, so check its contents.*/\\\\n assertCanBeRemotable(val);}\\\\n\\\\n\\\\n /* It's not a registered Remotable, so enforce the prototype check.*/\\\\n const p = Object.getPrototypeOf(val);\\\\n if (p !== null && p !== Object.prototype) {\\\\n mustPassByRemote(p);}}\\\\n\\\\n\\\\n\\\\n/* This is the equality comparison used by JavaScript's Map and Set*/\\\\n/* abstractions, where NaN is the same as NaN and -0 is the same as*/\\\\n/* 0. Marshal serializes -0 as zero, so the semantics of our distributed*/\\\\n/* object system does not distinguish 0 from -0.*/\\\\n/**/\\\\n/* `sameValueZero` is the EcmaScript spec name for this equality comparison,*/\\\\n/* but TODO we need a better name for the API.*/\\\\nfunction sameValueZero(x, y) {\\\\n return x === y || Object.is(x, y);}\\\\n\\\\n\\\\n/* How would val be passed? For primitive values, the answer is*/\\\\n/* * 'null' for null*/\\\\n/* * throwing an error for a symbol, whether registered or not.*/\\\\n/* * that value's typeof string for all other primitive values*/\\\\n/* For frozen objects, the possible answers*/\\\\n/* * 'copyRecord' for non-empty records with only data properties*/\\\\n/* * 'copyArray' for arrays with only data properties*/\\\\n/* * 'copyError' for instances of Error with only data properties*/\\\\n/* * REMOTE_STYLE for non-array objects with only method properties*/\\\\n/* * 'promise' for genuine promises only*/\\\\n/* * throwing an error on anything else, including thenables.*/\\\\n/* We export passStyleOf so other algorithms can use this module's*/\\\\n/* classification.*/\\\\nfunction passStyleOf(val) {\\\\n const typestr = typeof val;\\\\n switch (typestr) {\\\\n case 'object':{\\\\n if (getInterfaceOf(val)) {\\\\n return REMOTE_STYLE;}\\\\n\\\\n if (val === null) {\\\\n return 'null';}\\\\n\\\\n if (QCLASS in val) {\\\\n /* TODO Hilbert hotel*/\\\\n throw new Error(`property \\\\\\\"${QCLASS}\\\\\\\" reserved`);}\\\\n\\\\n if (!Object.isFrozen(val)) {\\\\n throw new Error(\\\\n `Cannot pass non-frozen objects like ${val}. Use harden()`);}\\\\n\\\\n\\\\n if (producePromise.isPromise(val)) {\\\\n return 'promise';}\\\\n\\\\n if (typeof val.then === 'function') {\\\\n throw new Error(`Cannot pass non-promise thenables`);}\\\\n\\\\n if (isPassByCopyError(val)) {\\\\n return 'copyError';}\\\\n\\\\n if (isPassByCopyArray(val)) {\\\\n return 'copyArray';}\\\\n\\\\n if (isPassByCopyRecord(val)) {\\\\n return 'copyRecord';}\\\\n\\\\n mustPassByRemote(val);\\\\n return REMOTE_STYLE;}\\\\n\\\\n case 'function':{\\\\n throw new Error(`Bare functions like ${val} are disabled for now`);}\\\\n\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'bigint':{\\\\n return typestr;}\\\\n\\\\n case 'symbol':{\\\\n throw new TypeError('Cannot pass symbols');}\\\\n\\\\n default:{\\\\n throw new TypeError(`Unrecognized typeof ${typestr}`);}}}\\\\n\\\\n\\\\n\\\\n\\\\n/* The ibid logic relies on*/\\\\n/* * JSON.stringify on an array visiting array indexes from 0 to*/\\\\n/* arr.length -1 in order, and not visiting anything else.*/\\\\n/* * JSON.parse of a record (a plain object) creating an object on*/\\\\n/* which a getOwnPropertyNames will enumerate properties in the*/\\\\n/* same order in which they appeared in the parsed JSON string.*/\\\\n\\\\nfunction makeReplacerIbidTable() {\\\\n const ibidMap = new Map();\\\\n let ibidCount = 0;\\\\n\\\\n return harden({\\\\n has(obj) {\\\\n return ibidMap.has(obj);},\\\\n\\\\n get(obj) {\\\\n return ibidMap.get(obj);},\\\\n\\\\n add(obj) {\\\\n ibidMap.set(obj, ibidCount);\\\\n ibidCount += 1;} });}\\\\n\\\\n\\\\n\\\\n\\\\nfunction makeReviverIbidTable(cyclePolicy) {\\\\n const ibids = [];\\\\n const unfinishedIbids = new WeakSet();\\\\n\\\\n return harden({\\\\n get(allegedIndex) {\\\\n const index = nat_esm.default(allegedIndex);\\\\n if (index >= ibids.length) {\\\\n throw new RangeError(`ibid out of range: ${index}`);}\\\\n\\\\n const result = ibids[index];\\\\n if (unfinishedIbids.has(result)) {\\\\n switch (cyclePolicy) {\\\\n case 'allowCycles':{\\\\n break;}\\\\n\\\\n case 'warnOfCycles':{\\\\n console.log(`Warning: ibid cycle at ${index}`);\\\\n break;}\\\\n\\\\n case 'forbidCycles':{\\\\n throw new TypeError(`Ibid cycle at ${index}`);}\\\\n\\\\n default:{\\\\n throw new TypeError(`Unrecognized cycle policy: ${cyclePolicy}`);}}}\\\\n\\\\n\\\\n\\\\n return result;},\\\\n\\\\n register(obj) {\\\\n ibids.push(obj);\\\\n return obj;},\\\\n\\\\n start(obj) {\\\\n ibids.push(obj);\\\\n unfinishedIbids.add(obj);\\\\n return obj;},\\\\n\\\\n finish(obj) {\\\\n unfinishedIbids.delete(obj);\\\\n return obj;} });}\\\\n\\\\n\\\\n\\\\n\\\\nconst identityFn = x => x;\\\\n\\\\nfunction makeMarshal(\\\\nconvertValToSlot = identityFn,\\\\nconvertSlotToVal = identityFn)\\\\n{\\\\n function serializeSlot(val, slots, slotMap) {\\\\n let slotIndex;\\\\n if (slotMap.has(val)) {\\\\n slotIndex = slotMap.get(val);} else\\\\n {\\\\n const slot = convertValToSlot(val);\\\\n\\\\n slotIndex = slots.length;\\\\n slots.push(slot);\\\\n slotMap.set(val, slotIndex);}\\\\n\\\\n\\\\n return harden({\\\\n [QCLASS]: 'slot',\\\\n index: slotIndex });}\\\\n\\\\n\\\\n\\\\n function makeReplacer(slots, slotMap) {\\\\n const ibidTable = makeReplacerIbidTable();\\\\n\\\\n return function replacer(_, val) {\\\\n /* First we handle all primitives. Some can be represented directly as*/\\\\n /* JSON, and some must be encoded as [QCLASS] composites.*/\\\\n const passStyle = passStyleOf(val);\\\\n switch (passStyle) {\\\\n case 'null':{\\\\n return null;}\\\\n\\\\n case 'undefined':{\\\\n return harden({ [QCLASS]: 'undefined' });}\\\\n\\\\n case 'string':\\\\n case 'boolean':{\\\\n return val;}\\\\n\\\\n case 'number':{\\\\n if (Number.isNaN(val)) {\\\\n return harden({ [QCLASS]: 'NaN' });}\\\\n\\\\n if (Object.is(val, -0)) {\\\\n return 0;}\\\\n\\\\n if (val === Infinity) {\\\\n return harden({ [QCLASS]: 'Infinity' });}\\\\n\\\\n if (val === -Infinity) {\\\\n return harden({ [QCLASS]: '-Infinity' });}\\\\n\\\\n return val;}\\\\n\\\\n case 'bigint':{\\\\n return harden({\\\\n [QCLASS]: 'bigint',\\\\n digits: String(val) });}\\\\n\\\\n\\\\n default:{\\\\n /* if we've seen this object before, serialize a backref*/\\\\n if (ibidTable.has(val)) {\\\\n /* Backreference to prior occurrence*/\\\\n return harden({\\\\n [QCLASS]: 'ibid',\\\\n index: ibidTable.get(val) });}\\\\n\\\\n\\\\n ibidTable.add(val);\\\\n\\\\n switch (passStyle) {\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n /* console.log(`canPassByCopy: ${val}`);*/\\\\n /* Purposely in-band for readability, but creates need for*/\\\\n /* Hilbert hotel.*/\\\\n return val;}\\\\n\\\\n case 'copyError':{\\\\n /* We deliberately do not share the stack, but it would*/\\\\n /* be useful to log the stack locally so someone who has*/\\\\n /* privileged access to the throwing Vat can correlate*/\\\\n /* the problem with the remote Vat that gets this*/\\\\n /* summary. If we do that, we could allocate some random*/\\\\n /* identifier and include it in the message, to help*/\\\\n /* with the correlation.*/\\\\n return harden({\\\\n [QCLASS]: 'error',\\\\n name: `${val.name}`,\\\\n message: `${val.message}` });}\\\\n\\\\n\\\\n case REMOTE_STYLE:\\\\n case 'promise':{\\\\n /* console.log(`serializeSlot: ${val}`);*/\\\\n return serializeSlot(val, slots, slotMap);}\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${passStyle}`);}}}}};}\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n /* val might be a primitive, a pass by (shallow) copy object, a*/\\\\n /* remote reference, or other. We treat all other as a local object*/\\\\n /* to be exported as a local webkey.*/\\\\n function serialize(val) {\\\\n const slots = [];\\\\n const slotMap = new Map(); /* maps val (promise or remotable) to*/\\\\n /* index of slots[]*/\\\\n return harden({\\\\n body: JSON.stringify(val, makeReplacer(slots, slotMap)),\\\\n slots });}\\\\n\\\\n\\\\n\\\\n function makeFullRevive(slots, cyclePolicy) {\\\\n /* ibid table is shared across recursive calls to fullRevive.*/\\\\n const ibidTable = makeReviverIbidTable(cyclePolicy);\\\\n\\\\n /* We stay close to the algorith at*/\\\\n /* https://tc39.github.io/ecma262/#sec-json.parse , where*/\\\\n /* fullRevive(JSON.parse(str)) is like JSON.parse(str, revive))*/\\\\n /* for a similar reviver. But with the following differences:*/\\\\n /**/\\\\n /* Rather than pass a reviver to JSON.parse, we first call a plain*/\\\\n /* (one argument) JSON.parse to get rawTree, and then post-process*/\\\\n /* the rawTree with fullRevive. The kind of revive function*/\\\\n /* handled by JSON.parse only does one step in post-order, with*/\\\\n /* JSON.parse doing the recursion. By contrast, fullParse does its*/\\\\n /* own recursion, enabling it to interpret ibids in the same*/\\\\n /* pre-order in which the replacer visited them, and enabling it*/\\\\n /* to break cycles.*/\\\\n /**/\\\\n /* In order to break cycles, the potentially cyclic objects are*/\\\\n /* not frozen during the recursion. Rather, the whole graph is*/\\\\n /* hardened before being returned. Error objects are not*/\\\\n /* potentially recursive, and so may be harmlessly hardened when*/\\\\n /* they are produced.*/\\\\n /**/\\\\n /* fullRevive can produce properties whose value is undefined,*/\\\\n /* which a JSON.parse on a reviver cannot do. If a reviver returns*/\\\\n /* undefined to JSON.parse, JSON.parse will delete the property*/\\\\n /* instead.*/\\\\n /**/\\\\n /* fullRevive creates and returns a new graph, rather than*/\\\\n /* modifying the original tree in place.*/\\\\n /**/\\\\n /* fullRevive may rely on rawTree being the result of a plain call*/\\\\n /* to JSON.parse. However, it *cannot* rely on it having been*/\\\\n /* produced by JSON.stringify on the replacer above, i.e., it*/\\\\n /* cannot rely on it being a valid marshalled*/\\\\n /* representation. Rather, fullRevive must validate that.*/\\\\n return function fullRevive(rawTree) {\\\\n if (Object(rawTree) !== rawTree) {\\\\n /* primitives pass through*/\\\\n return rawTree;}\\\\n\\\\n if (QCLASS in rawTree) {\\\\n const qclass = rawTree[QCLASS];\\\\n if (typeof qclass !== 'string') {\\\\n throw new TypeError(`invalid qclass typeof ${typeof qclass}`);}\\\\n\\\\n switch (qclass) {\\\\n /* Encoding of primitives not handled by JSON*/\\\\n case 'undefined':{\\\\n return undefined;}\\\\n\\\\n case 'NaN':{\\\\n return NaN;}\\\\n\\\\n case 'Infinity':{\\\\n return Infinity;}\\\\n\\\\n case '-Infinity':{\\\\n return -Infinity;}\\\\n\\\\n case 'bigint':{\\\\n if (typeof rawTree.digits !== 'string') {\\\\n throw new TypeError(\\\\n `invalid digits typeof ${typeof rawTree.digits}`);}\\\\n\\\\n\\\\n /* eslint-disable-next-line no-undef */\\\\n return BigInt(rawTree.digits);}\\\\n\\\\n\\\\n case 'ibid':{\\\\n return ibidTable.get(rawTree.index);}\\\\n\\\\n\\\\n case 'error':{\\\\n if (typeof rawTree.name !== 'string') {\\\\n throw new TypeError(\\\\n `invalid error name typeof ${typeof rawTree.name}`);}\\\\n\\\\n\\\\n if (typeof rawTree.message !== 'string') {\\\\n throw new TypeError(\\\\n `invalid error message typeof ${typeof rawTree.message}`);}\\\\n\\\\n\\\\n const EC = getErrorConstructor(`${rawTree.name}`) || Error;\\\\n return ibidTable.register(harden(new EC(`${rawTree.message}`)));}\\\\n\\\\n\\\\n case 'slot':{\\\\n const slot = slots[nat_esm.default(rawTree.index)];\\\\n return ibidTable.register(convertSlotToVal(slot));}\\\\n\\\\n\\\\n default:{\\\\n /* TODO reverse Hilbert hotel*/\\\\n throw new TypeError(`unrecognized ${QCLASS} ${qclass}`);}}} else\\\\n\\\\n\\\\n if (Array.isArray(rawTree)) {\\\\n const result = ibidTable.start([]);\\\\n const len = rawTree.length;\\\\n for (let i = 0; i < len; i += 1) {\\\\n result[i] = fullRevive(rawTree[i]);}\\\\n\\\\n return ibidTable.finish(result);} else\\\\n {\\\\n const result = ibidTable.start({});\\\\n const names = Object.getOwnPropertyNames(rawTree);\\\\n for (const name of names) {\\\\n result[name] = fullRevive(rawTree[name]);}\\\\n\\\\n return ibidTable.finish(result);}};}\\\\n\\\\n\\\\n\\\\n\\\\n function unserialize(data, cyclePolicy = 'forbidCycles') {\\\\n if (data.body !== `${data.body}`) {\\\\n throw new Error(\\\\n `unserialize() given non-capdata (.body is ${data.body}, not string)`);}\\\\n\\\\n\\\\n if (!Array.isArray(data.slots)) {\\\\n throw new Error(`unserialize() given non-capdata (.slots are not Array)`);}\\\\n\\\\n const rawTree = harden(JSON.parse(data.body));\\\\n const fullRevive = makeFullRevive(data.slots, cyclePolicy);\\\\n return harden(fullRevive(rawTree));}\\\\n\\\\n\\\\n return harden({\\\\n serialize,\\\\n unserialize });}\\\\n\\\\n\\\\n\\\\n/**\\\\n * Create and register a Remotable. After this, getInterfaceOf(remotable)\\\\n * returns iface.\\\\n *\\\\n * // https://github.com/Agoric/agoric-sdk/issues/804\\\\n *\\\\n * @param {InterfaceSpec} [iface='Remotable'] The interface specification for the remotable\\\\n * @param {object} [props={}] Own-properties are copied to the remotable\\\\n * @param {object} [remotable={}] The object used as the remotable\\\\n * @returns {object} remotable, modified for debuggability\\\\n */\\\\nfunction Remotable(iface = 'Remotable', props = {}, remotable = {}) {\\\\n iface = pureCopy(harden(iface));\\\\n const ifaceType = typeof iface;\\\\n\\\\n /* Find the alleged name.*/\\\\n if (ifaceType !== 'string') {\\\\n throw Error(`Interface must be a string, not ${ifaceType}; unimplemented`);}\\\\n\\\\n\\\\n /* TODO: When iface is richer than just string, we need to get the allegedName*/\\\\n /* in a different way.*/\\\\n const allegedName = iface;\\\\n\\\\n /* Fail fast: check that the unmodified object is able to become a Remotable.*/\\\\n assertCanBeRemotable(remotable);\\\\n\\\\n /* Ensure that the remotable isn't already registered.*/\\\\n if (remotableToInterface.has(remotable)) {\\\\n throw Error(`Remotable ${remotable} is already mapped to an interface`);}\\\\n\\\\n\\\\n /* A prototype for debuggability.*/\\\\n const oldRemotableProto = harden(Object.getPrototypeOf(remotable));\\\\n\\\\n /* Fail fast: create a fresh empty object with the old*/\\\\n /* prototype in order to check it against our rules.*/\\\\n mustPassByRemote(harden(Object.create(oldRemotableProto)));\\\\n\\\\n /* Assign the arrow function to a variable to set its .name.*/\\\\n const toString = () => `[${allegedName}]`;\\\\n const remotableProto = harden(\\\\n Object.create(oldRemotableProto, {\\\\n toString: {\\\\n value: toString,\\\\n enumerable: false },\\\\n\\\\n [Symbol.toStringTag]: {\\\\n value: allegedName,\\\\n enumerable: false } }));\\\\n\\\\n\\\\n\\\\n\\\\n /* Take a static copy of the properties.*/\\\\n const propEntries = Object.entries(props);\\\\n const mutateHardenAndCheck = target => {\\\\n /* Add the snapshotted properties.*/\\\\n /** @type {PropertyDescriptorMap} */\\\\n const newProps = {};\\\\n propEntries.forEach(([prop, value]) => newProps[prop] = { value });\\\\n Object.defineProperties(target, newProps);\\\\n\\\\n /* Set the prototype for debuggability.*/\\\\n Object.setPrototypeOf(target, remotableProto);\\\\n harden(remotableProto);\\\\n\\\\n harden(target);\\\\n assertCanBeRemotable(target);\\\\n return target;};\\\\n\\\\n\\\\n /* Fail fast: check a fresh remotable to see if our rules fit.*/\\\\n const throwawayRemotable = Object.create(oldRemotableProto);\\\\n mutateHardenAndCheck(throwawayRemotable);\\\\n\\\\n /* Actually finish the new remotable.*/\\\\n mutateHardenAndCheck(remotable);\\\\n\\\\n /* COMMITTED!*/\\\\n /* We're committed, so keep the interface for future reference.*/\\\\n remotableToInterface.set(remotable, iface);\\\\n return remotable;}\\\\n\\\\n\\\\nharden(Remotable);exports.QCLASS = QCLASS;exports.Remotable = Remotable;exports.getErrorConstructor = getErrorConstructor;exports.getInterfaceOf = getInterfaceOf;exports.makeMarshal = makeMarshal;exports.mustPassByPresence = mustPassByRemote;exports.mustPassByRemote = mustPassByRemote;exports.passStyleOf = passStyleOf;exports.pureCopy = pureCopy;exports.sameValueZero = sameValueZero;\\\",\\n \\\"packages/same-structure/src/sameStructure.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../assert/src/assert.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nmarshal = require('../../marshal/marshal.js'); /* global harden */ /* Shim of Object.fromEntries from*/ /* https://github.com/tc39/proposal-object-from-entries/blob/master/polyfill.js*/\\\\nfunction ObjectFromEntries(iter) {\\\\n const obj = {};\\\\n\\\\n for (const pair of iter) {\\\\n if (Object(pair) !== pair) {\\\\n throw new TypeError('iterable for fromEntries should yield objects');}\\\\n\\\\n\\\\n /* Consistency with Map: contract is that entry has \\\\\\\"0\\\\\\\" and \\\\\\\"1\\\\\\\" keys, not*/\\\\n /* that it is an array or iterable.*/\\\\n\\\\n const { '0': key, '1': val } = pair;\\\\n\\\\n Object.defineProperty(obj, key, {\\\\n configurable: true,\\\\n enumerable: true,\\\\n writable: true,\\\\n value: val });}\\\\n\\\\n\\\\n\\\\n return obj;}\\\\n\\\\n\\\\n/* A *passable* is something that may be marshalled. It consists of a*/\\\\n/* graph of pass-by-copy data terminating in leaves of passable*/\\\\n/* non-pass-by-copy data. These leaves may be promises, or*/\\\\n/* pass-by-presence objects. A *comparable* is a passable whose leaves*/\\\\n/* contain no promises. Two comparables can be synchronously compared*/\\\\n/* for structural equivalence.*/\\\\n/**/\\\\n/* TODO: Currently, all algorithms here treat the pass-by-copy*/\\\\n/* superstructure as a tree. This means that dags are unwound at*/\\\\n/* potentially exponential cost, and cycles cause failure to*/\\\\n/* terminate. We must fix both problems, making all these algorithms*/\\\\n/* graph-aware.*/\\\\n\\\\n/* We say that a function *reveals* an X when it returns either an X*/\\\\n/* or a promise for an X.*/\\\\n\\\\n/* Given a passable, reveal a corresponding comparable, where each*/\\\\n/* leaf promise of the passable has been replaced with its*/\\\\n/* corresponding comparable.*/\\\\nfunction allComparable(passable) {\\\\n const passStyle = marshal.passStyleOf(passable);\\\\n switch (passStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':\\\\n case 'copyError':{\\\\n return passable;}\\\\n\\\\n case 'promise':{\\\\n return passable.then(nonp => allComparable(nonp));}\\\\n\\\\n case 'copyArray':{\\\\n const valPs = passable.map(p => allComparable(p));\\\\n return Promise.all(valPs).then(vals => harden(vals));}\\\\n\\\\n case 'copyRecord':{\\\\n const names = Object.getOwnPropertyNames(passable);\\\\n const valPs = names.map(name => allComparable(passable[name]));\\\\n return Promise.all(valPs).then((vals) =>\\\\n harden(ObjectFromEntries(vals.map((val, i) => [names[i], val]))));}\\\\n\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${passStyle}`);}}}\\\\n\\\\n\\\\n\\\\nharden(allComparable);\\\\n\\\\n/* Are left and right structurally equivalent comparables? This*/\\\\n/* compares pass-by-copy data deeply until non-pass-by-copy values are*/\\\\n/* reached. The non-pass-by-copy values at the leaves of the*/\\\\n/* comparison may only be pass-by-presence objects. If they are*/\\\\n/* anything else, including promises, throw an error.*/\\\\n/**/\\\\n/* Pass-by-presence objects compare identities.*/\\\\n\\\\nfunction sameStructure(left, right) {\\\\n const leftStyle = marshal.passStyleOf(left);\\\\n const rightStyle = marshal.passStyleOf(right);\\\\n assert.assert(\\\\n leftStyle !== 'promise',\\\\n assert.details`Cannot structurally compare promises: ${left}`);\\\\n\\\\n assert.assert(\\\\n rightStyle !== 'promise',\\\\n assert.details`Cannot structurally compare promises: ${right}`);\\\\n\\\\n\\\\n if (leftStyle !== rightStyle) {\\\\n return false;}\\\\n\\\\n switch (leftStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':{\\\\n return marshal.sameValueZero(left, right);}\\\\n\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n const leftNames = Object.getOwnPropertyNames(left);\\\\n const rightNames = Object.getOwnPropertyNames(right);\\\\n if (leftNames.length !== rightNames.length) {\\\\n return false;}\\\\n\\\\n for (const name of leftNames) {\\\\n /* TODO: Better hasOwnProperty check*/\\\\n if (!Object.getOwnPropertyDescriptor(right, name)) {\\\\n return false;}\\\\n\\\\n /* TODO: Make cycle tolerant*/\\\\n if (!sameStructure(left[name], right[name])) {\\\\n return false;}}\\\\n\\\\n\\\\n return true;}\\\\n\\\\n case 'copyError':{\\\\n return left.name === right.name && left.message === right.message;}\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${leftStyle}`);}}}\\\\n\\\\n\\\\n\\\\nharden(sameStructure);\\\\n\\\\nfunction pathStr(path) {\\\\n if (path === null) {\\\\n return 'top';}\\\\n\\\\n const [base, index] = path;\\\\n let i = index;\\\\n const baseStr = pathStr(base);\\\\n if (typeof i === 'string' && /^[a-zA-Z]\\\\\\\\w*$/.test(i)) {\\\\n return `${baseStr}.${i}`;}\\\\n\\\\n if (typeof i === 'string' && `${+i}` === i) {\\\\n i = +i;}\\\\n\\\\n return `${baseStr}[${JSON.stringify(i)}]`;}\\\\n\\\\n\\\\n/* TODO: Reduce redundancy between sameStructure and*/\\\\n/* mustBeSameStructureInternal*/\\\\nfunction mustBeSameStructureInternal(left, right, message, path) {\\\\n function complain(problem) {\\\\n assert.assert.fail(\\\\n assert.details`${assert.q(message)}: ${assert.q(problem)} at ${assert.q(\\\\n pathStr(path))\\\\n }: (${left}) vs (${right})`);}\\\\n\\\\n\\\\n\\\\n const leftStyle = marshal.passStyleOf(left);\\\\n const rightStyle = marshal.passStyleOf(right);\\\\n if (leftStyle === 'promise') {\\\\n complain('Promise on left');}\\\\n\\\\n if (rightStyle === 'promise') {\\\\n complain('Promise on right');}\\\\n\\\\n\\\\n if (leftStyle !== rightStyle) {\\\\n complain('different passing style');}\\\\n\\\\n switch (leftStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':{\\\\n if (!marshal.sameValueZero(left, right)) {\\\\n complain('different');}\\\\n\\\\n break;}\\\\n\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n const leftNames = Object.getOwnPropertyNames(left);\\\\n const rightNames = Object.getOwnPropertyNames(right);\\\\n if (leftNames.length !== rightNames.length) {\\\\n complain(`${leftNames.length} vs ${rightNames.length} own properties`);}\\\\n\\\\n for (const name of leftNames) {\\\\n /* TODO: Better hasOwnProperty check*/\\\\n if (!Object.getOwnPropertyDescriptor(right, name)) {\\\\n complain(`${name} not found on right`);}\\\\n\\\\n /* TODO: Make cycle tolerant*/\\\\n mustBeSameStructureInternal(left[name], right[name], message, [\\\\n path,\\\\n name]);}\\\\n\\\\n\\\\n break;}\\\\n\\\\n case 'copyError':{\\\\n if (left.name !== right.name) {\\\\n complain(`different error name: ${left.name} vs ${right.name}`);}\\\\n\\\\n if (left.message !== right.message) {\\\\n complain(\\\\n `different error message: ${left.message} vs ${right.message}`);}\\\\n\\\\n\\\\n break;}\\\\n\\\\n default:{\\\\n complain(`unrecognized passStyle ${leftStyle}`);\\\\n break;}}}\\\\n\\\\n\\\\n\\\\nfunction mustBeSameStructure(left, right, message) {\\\\n mustBeSameStructureInternal(left, right, `${message}`, null);}\\\\n\\\\nharden(mustBeSameStructure);\\\\n\\\\n/* If `val` would be a valid input to `sameStructure`, return*/\\\\n/* normally. Otherwise error.*/\\\\nfunction mustBeComparable(val) {\\\\n mustBeSameStructure(val, val, 'not comparable');}exports.allComparable = allComparable;exports.mustBeComparable = mustBeComparable;exports.mustBeSameStructure = mustBeSameStructure;exports.sameStructure = sameStructure;\\\",\\n \\\"packages/zoe/src/offerSafety.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /**\\\\n * @typedef {Ximport('@agoric/ertp/src/issuer').Brand} Brand\\\\n * @typedef {Ximport('@agoric/ertp/src/issuer').AmountMath} AmountMath\\\\n * @typedef {Ximport('./zoe').Proposal} Proposal\\\\n * @typedef {Ximport('./zoe').AmountKeywordRecord} AmountKeywordRecord\\\\n */ /**\\\\n * Helper to perform satisfiesWant and satisfiesGive. Is\\\\n * allocationAmount greater than or equal to requiredAmount for every\\\\n * keyword of giveOrWant?\\\\n * @param {(Brand) => AmountMath} getAmountMath\\\\n * @param {Proposal[\\\\\\\"give\\\\\\\"] | Proposal[\\\\\\\"want\\\\\\\"]} giveOrWant\\\\n * @param {AmountKeywordRecord} allocation\\\\n */const satisfiesInternal = (getAmountMath, giveOrWant, allocation) => {const isGTEByKeyword = ([keyword, requiredAmount]) => {/* If there is no allocation for a keyword, we know the giveOrWant*/ /* is not satisfied without checking further.*/if (allocation[keyword] === undefined) {\\\\n return false;}\\\\n\\\\n const amountMath = getAmountMath(requiredAmount.brand);\\\\n const allocationAmount = allocation[keyword];\\\\n return amountMath.isGTE(allocationAmount, requiredAmount);};\\\\n\\\\n return Object.entries(giveOrWant).every(isGTEByKeyword);};\\\\n\\\\n\\\\n/**\\\\n * For this allocation to satisfy what the user wanted, their\\\\n * allocated amounts must be greater than or equal to proposal.want.\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.want.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nconst satisfiesWant = (getAmountMath, proposal, allocation) =>\\\\nsatisfiesInternal(getAmountMath, proposal.want, allocation);\\\\n\\\\n/**\\\\n * For this allocation to count as a full refund, the allocated\\\\n * amounts must be greater than or equal to what was originally\\\\n * offered (proposal.give).\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.give.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nconst satisfiesGive = (getAmountMath, proposal, allocation) =>\\\\nsatisfiesInternal(getAmountMath, proposal.give, allocation);\\\\n\\\\n/**\\\\n * `isOfferSafe` checks offer safety for a single offer.\\\\n *\\\\n * Note: This implementation checks whether we fully satisfy\\\\n * `proposal.give` (giving a refund) or whether we fully satisfy\\\\n * `proposal.want`. Both can be fully satisfied.\\\\n *\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.want and\\\\n * proposal.give.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nfunction isOfferSafe(getAmountMath, proposal, allocation) {\\\\n return (\\\\n satisfiesGive(getAmountMath, proposal, allocation) ||\\\\n satisfiesWant(getAmountMath, proposal, allocation));}exports.isOfferSafe = isOfferSafe;exports.satisfiesWant = satisfiesWant;\\\",\\n \\\"packages/zoe/src/contractSupport/zoeHelpers.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../../assert/src/assert.js');var index = require('../../../eventual-send/src/index.js');var sameStructure = require('../../../same-structure/src/sameStructure.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nofferSafety = require('../offerSafety.js'); /* global harden */ /**\\\\n * @typedef {Ximport('../zoe').OfferHandle} OfferHandle\\\\n * @typedef {Ximport('../zoe').Invite} Invite\\\\n * @typedef {Ximport('../zoe').OfferHook} OfferHook\\\\n * @typedef {Ximport('../zoe').CustomProperties} CustomProperties\\\\n * @typedef {Ximport('../zoe').ContractFacet} ContractFacet\\\\n * @typedef {Ximport('../zoe').Keyword} Keyword\\\\n * @typedef {Ximport('../zoe').AmountKeywordRecord} AmountKeywordRecord\\\\n * @typedef {Ximport('../zoe').Amount} Amount\\\\n * @typedef {Ximport('../zoe').Payment} Payment\\\\n */\\\\n\\\\nconst defaultRejectMsg = `The offer was invalid. Please check your refund.`;\\\\nconst defaultAcceptanceMsg = `The offer has been accepted. Once the contract has been completed, please check your payout`;\\\\n\\\\nconst getKeys = obj => harden(Object.getOwnPropertyNames(obj || {}));\\\\nconst getKeysSorted = (obj) =>\\\\nharden(Object.getOwnPropertyNames(obj || {}).sort());\\\\n/**\\\\n * @function makeZoeHelpers - makes an object with helper functions useful to zoe contracts.\\\\n *\\\\n * @param {ContractFacet} zcf\\\\n */\\\\n/* zcf only picks up the type if the param is in parens, which eslint dislikes*/\\\\n/* eslint-disable-next-line*/\\\\nconst makeZoeHelpers = zcf => {\\\\n const zoeService = zcf.getZoeService();\\\\n\\\\n const rejectOffer = (offerHandle, msg = defaultRejectMsg) => {\\\\n zcf.complete(harden([offerHandle]));\\\\n assert.assert.fail(msg);};\\\\n\\\\n\\\\n /* Compare the keys of actual with expected keys and reject offer if*/\\\\n /* not sameStructure. If expectedKeys is undefined, no comparison occurs.*/\\\\n const rejectKeysIf = (\\\\n offerHandle,\\\\n actual,\\\\n expected,\\\\n msg = defaultRejectMsg) =>\\\\n /* eslint-disable-next-line consistent-return*/\\\\n {\\\\n if (expected !== undefined) {\\\\n if (!sameStructure.sameStructure(getKeysSorted(actual), getKeysSorted(expected))) {\\\\n return rejectOffer(offerHandle, msg);}}};\\\\n\\\\n\\\\n\\\\n /* Compare actual keys to expected keys. If expectedKeys is*/\\\\n /* undefined, return true trivially.*/\\\\n const checkKeys = (actual, expected) => {\\\\n if (expected === undefined) {\\\\n return true;}\\\\n\\\\n return sameStructure.sameStructure(getKeysSorted(actual), getKeysSorted(expected));};\\\\n\\\\n\\\\n /**\\\\n * Given toGains (an AmountKeywordRecord), and allocations (a pair,\\\\n * 'to' and 'from', of AmountKeywordRecords), all the entries in\\\\n * toGains will be added to 'to'. If fromLosses is defined, all the\\\\n * entries in fromLosses are subtracted from 'from'. (If fromLosses\\\\n * is not defined, toGains is subtracted from 'from'.)\\\\n *\\\\n * @param {FromToAllocations} allocations - the 'to' and 'from'\\\\n * allocations\\\\n * @param {AmountKeywordRecord} toGains - what should be gained in\\\\n * the 'to' allocation\\\\n * @param {AmountKeywordRecord} fromLosses - what should be lost in\\\\n * the 'from' allocation. If not defined, fromLosses is equal to\\\\n * toGains. Note that the total amounts should always be equal; it\\\\n * is the keywords that might be different.\\\\n * @returns {FromToAllocations} allocations - new allocations\\\\n *\\\\n * @typedef FromToAllocations\\\\n * @property {AmountKeywordRecord} from\\\\n * @property {AmountKeywordRecord} to\\\\n */\\\\n const calcNewAllocations = (allocations, toGains, fromLosses = undefined) => {\\\\n if (fromLosses === undefined) {\\\\n fromLosses = toGains;}\\\\n\\\\n\\\\n const subtract = (amount, amountToSubtract) => {\\\\n const { brand } = amount;\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n if (amountToSubtract !== undefined) {\\\\n return amountMath.subtract(amount, amountToSubtract);}\\\\n\\\\n return amount;};\\\\n\\\\n\\\\n const add = (amount, amountToAdd) => {\\\\n if (amount && amountToAdd) {\\\\n const { brand } = amount;\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n return amountMath.add(amount, amountToAdd);}\\\\n\\\\n return amount || amountToAdd;};\\\\n\\\\n\\\\n const newFromAllocation = Object.fromEntries(\\\\n Object.entries(allocations.from).map(([keyword, allocAmount]) => {\\\\n return [keyword, subtract(allocAmount, fromLosses[keyword])];}));\\\\n\\\\n\\\\n\\\\n const allToKeywords = [\\\\n ...Object.keys(toGains),\\\\n ...Object.keys(allocations.to)];\\\\n\\\\n\\\\n const newToAllocation = Object.fromEntries(\\\\n allToKeywords.map(keyword => [\\\\n keyword,\\\\n add(allocations.to[keyword], toGains[keyword])]));\\\\n\\\\n\\\\n\\\\n return harden({\\\\n from: newFromAllocation,\\\\n to: newToAllocation });};\\\\n\\\\n\\\\n\\\\n const mergeAllocations = (currentAllocation, allocation) => {\\\\n const newAllocation = {\\\\n ...currentAllocation,\\\\n ...allocation };\\\\n\\\\n return newAllocation;};\\\\n\\\\n\\\\n const helpers = harden({\\\\n getKeys,\\\\n assertKeywords: expected => {\\\\n const { issuerKeywordRecord } = zcf.getInstanceRecord();\\\\n const actual = getKeysSorted(issuerKeywordRecord);\\\\n expected = [...expected]; /* in case hardened*/\\\\n expected.sort();\\\\n assert.assert(\\\\n sameStructure.sameStructure(actual, harden(expected)),\\\\n assert.details`keywords: ${actual} were not as expected: ${expected}`);},\\\\n\\\\n\\\\n rejectIfNotProposal: (offerHandle, expected) => {\\\\n const { proposal: actual } = zcf.getOffer(offerHandle);\\\\n rejectKeysIf(offerHandle, actual.give, expected.give);\\\\n rejectKeysIf(offerHandle, actual.want, expected.want);\\\\n rejectKeysIf(offerHandle, actual.exit, expected.exit);},\\\\n\\\\n checkIfProposal: (offerHandle, expected) => {\\\\n const { proposal: actual } = zcf.getOffer(offerHandle);\\\\n return (\\\\n /* Check that the \\\\\\\"give\\\\\\\" keys match expected keys.*/\\\\n checkKeys(actual.give, expected.give) &&\\\\n /* Check that the \\\\\\\"want\\\\\\\" keys match expected keys.*/\\\\n checkKeys(actual.want, expected.want) &&\\\\n /* Check that the \\\\\\\"exit\\\\\\\" key (i.e. \\\\\\\"onDemand\\\\\\\") matches the expected key.*/\\\\n checkKeys(actual.exit, expected.exit));},\\\\n\\\\n\\\\n getActiveOffers: (handles) =>\\\\n zcf.getOffers(zcf.getOfferStatuses(handles).active),\\\\n rejectOffer,\\\\n\\\\n /**\\\\n * Check whether an update to currentAllocation satisfies\\\\n * proposal.want. Note that this is half of the offer safety\\\\n * check; whether the allocation constitutes a refund is not\\\\n * checked. Allocation is merged with currentAllocation\\\\n * (allocations' values prevailing if the keywords are the same)\\\\n * to produce the newAllocation.\\\\n * @param {OfferHandle} offerHandle\\\\n * @param {allocation} amountKeywordRecord\\\\n * @returns {boolean}\\\\n */\\\\n satisfies: (offerHandle, allocation) => {\\\\n const currentAllocation = zcf.getCurrentAllocation(offerHandle);\\\\n const newAllocation = mergeAllocations(currentAllocation, allocation);\\\\n const { proposal } = zcf.getOffer(offerHandle);\\\\n return offerSafety.satisfiesWant(zcf.getAmountMath, proposal, newAllocation);},\\\\n\\\\n\\\\n /**\\\\n * Check whether an update to currentAllocation satisfies offer\\\\n * safety. Note that this is the equivalent of `satisfiesWant` ||\\\\n * `satisfiesGive`. Allocation is merged with currentAllocation\\\\n * (allocations' values prevailing if the keywords are the same)\\\\n * to produce the newAllocation.\\\\n * @param {OfferHandle} offerHandle\\\\n * @param {AmountKeywordRecord} allocation\\\\n * @returns {boolean}\\\\n */\\\\n\\\\n isOfferSafe: (offerHandle, allocation) => {\\\\n const currentAllocation = zcf.getCurrentAllocation(offerHandle);\\\\n const newAllocation = mergeAllocations(currentAllocation, allocation);\\\\n const { proposal } = zcf.getOffer(offerHandle);\\\\n return offerSafety.isOfferSafe(zcf.getAmountMath, proposal, newAllocation);},\\\\n\\\\n\\\\n /**\\\\n * Trade between left and right so that left and right end up with\\\\n * the declared gains.\\\\n * @param {offerHandleGainsLossesRecord} keepLeft\\\\n * @param {offerHandleGainsLossesRecord} tryRight\\\\n * @returns {undefined | Error}\\\\n *\\\\n * @typedef {object} offerHandleGainsLossesRecord\\\\n * @property {OfferHandle} offerHandle\\\\n * @property {AmountKeywordRecord} gains - what the offer will\\\\n * gain as a result of this trade\\\\n * @property {AmountKeywordRecord=} losses - what the offer will\\\\n * give up as a result of this trade. Losses is optional, but can\\\\n * only be omitted if the keywords for both offers are the same.\\\\n * If losses is not defined, the gains of the other offer is\\\\n * subtracted.\\\\n */\\\\n trade: (keepLeft, tryRight) => {\\\\n assert.assert(\\\\n keepLeft.offerHandle !== tryRight.offerHandle,\\\\n assert.details`an offer cannot trade with itself`);\\\\n\\\\n let leftAllocation = zcf.getCurrentAllocation(keepLeft.offerHandle);\\\\n let rightAllocation = zcf.getCurrentAllocation(tryRight.offerHandle);\\\\n\\\\n try {\\\\n /* for all the keywords and amounts in leftGains, transfer from*/\\\\n /* right to left*/\\\\n ({ from: rightAllocation, to: leftAllocation } = calcNewAllocations(\\\\n { from: rightAllocation, to: leftAllocation },\\\\n keepLeft.gains,\\\\n tryRight.losses));\\\\n\\\\n /* For all the keywords and amounts in rightGains, transfer from*/\\\\n /* left to right*/\\\\n ({ from: leftAllocation, to: rightAllocation } = calcNewAllocations(\\\\n { from: leftAllocation, to: rightAllocation },\\\\n tryRight.gains,\\\\n keepLeft.losses));}\\\\n\\\\n catch (err) {\\\\n return rejectOffer(tryRight.offerHandle);}\\\\n\\\\n\\\\n /* Check whether reallocate would error before calling. If*/\\\\n /* it would error, reject the right offer and return.*/\\\\n const offerSafeForLeft = helpers.isOfferSafe(\\\\n keepLeft.offerHandle,\\\\n leftAllocation);\\\\n\\\\n const offerSafeForRight = helpers.isOfferSafe(\\\\n tryRight.offerHandle,\\\\n rightAllocation);\\\\n\\\\n if (!(offerSafeForLeft && offerSafeForRight)) {\\\\n console.log(\\\\n `currentLeftAllocation`,\\\\n zcf.getCurrentAllocation(keepLeft.offerHandle));\\\\n\\\\n console.log(\\\\n `currentRightAllocation`,\\\\n zcf.getCurrentAllocation(tryRight.offerHandle));\\\\n\\\\n console.log(`proposed left reallocation`, leftAllocation);\\\\n console.log(`proposed right reallocation`, rightAllocation);\\\\n /* show the contraints*/\\\\n console.log(\\\\n `left want`,\\\\n zcf.getOffer(keepLeft.offerHandle).proposal.want);\\\\n\\\\n console.log(\\\\n `right want`,\\\\n zcf.getOffer(tryRight.offerHandle).proposal.want);\\\\n\\\\n\\\\n if (!offerSafeForLeft) {\\\\n console.log(`offer not safe for left`);}\\\\n\\\\n if (!offerSafeForRight) {\\\\n console.log(`offer not safe for right`);}\\\\n\\\\n return rejectOffer(tryRight.offerHandle);}\\\\n\\\\n zcf.reallocate(\\\\n [keepLeft.offerHandle, tryRight.offerHandle],\\\\n [leftAllocation, rightAllocation]);\\\\n\\\\n return undefined;},\\\\n\\\\n\\\\n /**\\\\n * If the two handles can trade, then swap their compatible assets,\\\\n * marking both offers as complete.\\\\n *\\\\n * The surplus remains with the original offer. For example if\\\\n * offer A gives 5 moola and offer B only wants 3 moola, offer A\\\\n * retains 2 moola.\\\\n *\\\\n * If the keep offer is no longer active (it was already completed), the try\\\\n * offer will be rejected with a message (provided by 'keepHandleInactiveMsg').\\\\n *\\\\n * TODO: If the try offer is no longer active, swap() should terminate with\\\\n * a useful error message, like defaultRejectMsg.\\\\n *\\\\n * If the swap fails, no assets are transferred, and the 'try' offer is rejected.\\\\n *\\\\n * @param {OfferHandle} keepHandle\\\\n * @param {OfferHandle} tryHandle\\\\n * @param {String} [keepHandleInactiveMsg]\\\\n */\\\\n swap: (\\\\n keepHandle,\\\\n tryHandle,\\\\n keepHandleInactiveMsg = 'prior offer is unavailable') =>\\\\n {\\\\n if (!zcf.isOfferActive(keepHandle)) {\\\\n throw helpers.rejectOffer(tryHandle, keepHandleInactiveMsg);}\\\\n\\\\n\\\\n helpers.trade(\\\\n {\\\\n offerHandle: keepHandle,\\\\n gains: zcf.getOffer(keepHandle).proposal.want },\\\\n\\\\n {\\\\n offerHandle: tryHandle,\\\\n gains: zcf.getOffer(tryHandle).proposal.want });\\\\n\\\\n\\\\n\\\\n zcf.complete([keepHandle, tryHandle]);\\\\n return defaultAcceptanceMsg;},\\\\n\\\\n\\\\n /**\\\\n * Make an offerHook that wraps the provided `offerHook`, to first\\\\n * check the submitted offer against an `expected` record that says\\\\n * what shape of proposal is acceptable.\\\\n *\\\\n * This ExpectedRecord is like a Proposal, but the amounts in 'want'\\\\n * and 'give' should be null; the exit clause should specify a rule with\\\\n * null contents. If the client submits an Offer which does not match\\\\n * these expectations, that offer will be rejected (and refunded).\\\\n *\\\\n * @param {OfferHook} offerHook\\\\n * @param {ExpectedRecord} expected\\\\n *\\\\n * @typedef ExpectedRecord\\\\n * @property {TODO} [want]\\\\n * @property {TODO} [give]\\\\n * @property {TODO} [exit]\\\\n */\\\\n checkHook: (offerHook, expected) => offerHandle => {\\\\n helpers.rejectIfNotProposal(offerHandle, expected);\\\\n return offerHook(offerHandle);},\\\\n\\\\n\\\\n /**\\\\n * Return a Promise for an OfferHandle.\\\\n *\\\\n * This offer will have an empty 'give' and 'want', making it useful\\\\n * for contracts to use for unrestricted internal asset reallocation.\\\\n * One example is the Autoswap contract, which uses an empty offer\\\\n * to manage internal escrowed assets.\\\\n *\\\\n * @returns {Promise<OfferHandle>}\\\\n */\\\\n makeEmptyOffer: () =>\\\\n new index.HandledPromise(resolve => {\\\\n const invite = zcf.makeInvitation(\\\\n offerHandle => resolve(offerHandle),\\\\n 'empty offer');\\\\n\\\\n index.E(zoeService).offer(invite);}),\\\\n\\\\n\\\\n /**\\\\n * Escrow a payment with Zoe and reallocate the amount of the\\\\n * payment to a recipient.\\\\n *\\\\n * @param {Object} obj\\\\n * @param {Amount} obj.amount\\\\n * @param {Payment} obj.payment\\\\n * @param {String} obj.keyword\\\\n * @param {OfferHandle} obj.recipientHandle\\\\n * @returns {Promise<undefined>}\\\\n */\\\\n escrowAndAllocateTo: ({ amount, payment, keyword, recipientHandle }) => {\\\\n /* We will create a temporary offer to be able to escrow our payment*/\\\\n /* with Zoe.*/\\\\n let tempHandle;\\\\n\\\\n /* We need to make an invite and store the offerHandle of that*/\\\\n /* invite for future use.*/\\\\n const contractSelfInvite = zcf.makeInvitation(\\\\n offerHandle => tempHandle = offerHandle,\\\\n 'self invite');\\\\n\\\\n /* To escrow the payment, we must get the Zoe Service facet and*/\\\\n /* make an offer*/\\\\n const proposal = harden({ give: { Temp: amount } });\\\\n const payments = harden({ Temp: payment });\\\\n\\\\n return index.E(zcf.getZoeService()).\\\\n offer(contractSelfInvite, proposal, payments).\\\\n then(() => {\\\\n /* At this point, the temporary offer has the amount from the*/\\\\n /* payment but nothing else. The recipient offer may have any*/\\\\n /* allocation, so we can't assume the allocation is currently empty for this*/\\\\n /* keyword.*/\\\\n\\\\n helpers.trade(\\\\n {\\\\n offerHandle: tempHandle,\\\\n gains: {},\\\\n losses: { Temp: amount } },\\\\n\\\\n {\\\\n offerHandle: recipientHandle,\\\\n gains: { [keyword]: amount } });\\\\n\\\\n\\\\n\\\\n /* Complete the temporary offerHandle*/\\\\n zcf.complete([tempHandle]);\\\\n\\\\n /* Now, the temporary offer no longer exists, but the recipient*/\\\\n /* offer is allocated the value of the payment.*/});},\\\\n\\\\n\\\\n /* * Given a brand, assert that the mathHelpers for that issuer\\\\n * are 'nat' mathHelpers\\\\n */\\\\n\\\\n assertNatMathHelpers: brand => {\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n assert.assert(\\\\n amountMath.getMathHelpersName() === 'nat',\\\\n assert.details`issuer must have natMathHelpers`);} });\\\\n\\\\n\\\\n\\\\n return helpers;};exports.defaultAcceptanceMsg = defaultAcceptanceMsg;exports.defaultRejectMsg = defaultRejectMsg;exports.makeZoeHelpers = makeZoeHelpers;\\\",\\n \\\"packages/zoe/src/contractSupport/index.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var auctions = require('./auctions.js');var safeMath = require('./safeMath.js');var bondingCurves = require('./bondingCurves.js');var stateMachine = require('./stateMachine.js');var zoeHelpers = require('./zoeHelpers.js');exports.closeAuction = auctions.closeAuction;exports.secondPriceLogic = auctions.secondPriceLogic;exports.natSafeMath = safeMath.natSafeMath;exports.calcLiqValueToMint = bondingCurves.calcLiqValueToMint;exports.calcValueToRemove = bondingCurves.calcValueToRemove;exports.getInputPrice = bondingCurves.getInputPrice;exports.makeStateMachine = stateMachine.makeStateMachine;exports.defaultAcceptanceMsg = zoeHelpers.defaultAcceptanceMsg;exports.defaultRejectMsg = zoeHelpers.defaultRejectMsg;exports.makeZoeHelpers = zoeHelpers.makeZoeHelpers;\\\"\\n};\\n const nsBundle = {};\\n\\n function createEvalString(filename) {\\n const code = sourceBundle[filename];\\n if (!code) {\\n return undefined;\\n }\\n return `\\\\\\n(function getExport(require, exports) { \\\\\\n 'use strict'; \\\\\\n const module = { exports }; \\\\\\n \\\\\\n ${code}\\n return module.exports;\\n})\\n//# sourceURL=${filePrefix}/${filename}\\n`;\\n }\\n\\n function computeExports(filename, exportPowers, exports) {\\n const { require: systemRequire, _log } = exportPowers;\\n // This captures the endowed require.\\n const match = filename.match(/^(.*)\\\\/[^/]+$/);\\n const thisdir = match ? match[1] : '.';\\n const contextRequire = mod => {\\n // Do path algebra to find the actual source.\\n const els = mod.split('/');\\n let prefix;\\n if (els[0][0] === '@') {\\n // Scoped name.\\n prefix = els.splice(0, 2).join('/');\\n } else if (els[0][0] === '.') {\\n // Relative.\\n els.unshift(...thisdir.split('/'));\\n } else {\\n // Bare or absolute.\\n prefix = els.splice(0, 1);\\n }\\n\\n const suffix = [];\\n for (const el of els) {\\n if (el === '.' || el === '') {\\n // Do nothing.\\n } else if (el === '..') {\\n // Traverse upwards.\\n suffix.pop();\\n } else {\\n suffix.push(el);\\n }\\n }\\n\\n // log(mod, prefix, suffix);\\n if (prefix !== undefined) {\\n suffix.unshift(prefix);\\n }\\n let modPath = suffix.join('/');\\n if (modPath.startsWith('./')) {\\n modPath = modPath.slice(2);\\n }\\n // log('requiring', modPath);\\n if (!(modPath in nsBundle)) {\\n // log('evaluating', modPath);\\n // Break cycles, but be tolerant of modules\\n // that completely override their exports object.\\n nsBundle[modPath] = {};\\n nsBundle[modPath] = computeExports(\\n modPath,\\n exportPowers,\\n nsBundle[modPath],\\n );\\n }\\n\\n // log('returning', nsBundle[modPath]);\\n return nsBundle[modPath];\\n };\\n\\n const code = createEvalString(filename);\\n if (!code) {\\n // log('missing code for', filename, sourceBundle);\\n if (systemRequire) {\\n return systemRequire(filename);\\n }\\n throw Error(\\n `require(${JSON.stringify(\\n filename,\\n )}) failed; no toplevel require endowment`,\\n );\\n }\\n\\n // log('evaluating', code);\\n return nestedEvaluate(code)(contextRequire, exports);\\n }\\n\\n // Evaluate the entrypoint recursively, seeding the exports.\\n const systemRequire = typeof require === 'undefined' ? undefined : require;\\n return computeExports(entrypoint, { require: systemRequire }, {});\\n}\\n//# sourceURL=/bundled-source-preamble.js\\n\",\"sourceMap\":\"//# sourceURL=/bundled-source-preamble.js\\n\",\"moduleFormat\":\"nestedEvaluate\"}]","slots":[]},"p-62"],"syscalls":[{"d":["fulfillToPresence","p-62","o+3"],"response":null}],"crankNumber":8}
v5.t.3 :: {"d":["deliver","o+1","install",{"body":"[{\"source\":\"function getExportWithNestedEvaluate(filePrefix) {\\n 'use strict';\\n // Serialised sources.\\n if (filePrefix === undefined) {\\n filePrefix = \\\"/bundled-source\\\";\\n }\\n const moduleFormat = \\\"nestedEvaluate\\\";\\n const entrypoint = \\\"packages/zoe/src/contracts/publicAuction.js\\\";\\n const sourceBundle = {\\n \\\"packages/zoe/src/contracts/publicAuction.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var nat_esm = require('../../../../node_modules/@agoric/nat/dist/nat.esm.js');var auctions = require('../contractSupport/auctions.js');var zoeHelpers = require('../contractSupport/zoeHelpers.js');\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nrequire('../contractSupport/index.js'); /* global harden */ /**\\\\n * An auction contract in which the seller offers an Asset for sale, and states\\\\n * a minimum price. A pre-announced number of bidders compete to offer the best\\\\n * price. When the appropriate number of bids have been received, the second\\\\n * price rule is followed, so the highest bidder pays the amount bid by the\\\\n * second highest bidder.\\\\n *\\\\n * makeInstance() specifies the issuers and terms ({ numBidsAllowed }) specify\\\\n * the number of bids required. An invitation for the seller is returned. The\\\\n * seller's offer should look like\\\\n * { give: { Asset: asset }, want: { Ask: minimumBidAmount } }\\\\n * The asset can be non-fungible, but the Ask amount should be of a fungible\\\\n * brand.\\\\n * The bidder invitations are available from await E(publicAPI).makeInvites(n). Each\\\\n * bidder can submit an offer: { give: { Bid: null } want: { Asset: null } }.\\\\n *\\\\n * publicAPI also has methods to find out what's being auctioned\\\\n * (getAuctionedAssetsAmounts()), or the minimum bid (getMinimumBid()).\\\\n *\\\\n * @typedef {Ximport('../zoe').ContractFacet} ContractFacet\\\\n * @param {ContractFacet} zcf\\\\n */\\\\nconst makeContract = zcf => {\\\\n const { rejectOffer, satisfies, assertKeywords, checkHook } = zoeHelpers.makeZoeHelpers(\\\\n zcf);\\\\n\\\\n\\\\n let {\\\\n terms: { numBidsAllowed } } =\\\\n zcf.getInstanceRecord();\\\\n numBidsAllowed = nat_esm.default(numBidsAllowed !== undefined ? numBidsAllowed : 3);\\\\n\\\\n let sellerOfferHandle;\\\\n let minimumBid;\\\\n let auctionedAssets;\\\\n const allBidHandles = [];\\\\n\\\\n /* seller will use 'Asset' and 'Ask'. buyer will use 'Asset' and 'Bid'*/\\\\n assertKeywords(harden(['Asset', 'Ask']));\\\\n\\\\n const bidderOfferHook = offerHandle => {\\\\n /* Check that the item is still up for auction*/\\\\n if (!zcf.isOfferActive(sellerOfferHandle)) {\\\\n const rejectMsg = `The item up for auction is not available or the auction has completed`;\\\\n throw rejectOffer(offerHandle, rejectMsg);}\\\\n\\\\n if (allBidHandles.length >= numBidsAllowed) {\\\\n throw rejectOffer(offerHandle, `No further bids allowed.`);}\\\\n\\\\n const sellerSatisfied = satisfies(sellerOfferHandle, {\\\\n Ask: zcf.getCurrentAllocation(offerHandle).Bid,\\\\n Asset: zcf.getAmountMath(auctionedAssets.brand).getEmpty() });\\\\n\\\\n const bidderSatisfied = satisfies(offerHandle, {\\\\n Asset: zcf.getCurrentAllocation(sellerOfferHandle).Asset,\\\\n Bid: zcf.getAmountMath(minimumBid.brand).getEmpty() });\\\\n\\\\n if (!(sellerSatisfied && bidderSatisfied)) {\\\\n const rejectMsg = `Bid was under minimum bid or for the wrong assets`;\\\\n throw rejectOffer(offerHandle, rejectMsg);}\\\\n\\\\n\\\\n /* Save valid bid and try to close.*/\\\\n allBidHandles.push(offerHandle);\\\\n if (allBidHandles.length >= numBidsAllowed) {\\\\n auctions.closeAuction(zcf, {\\\\n auctionLogicFn: auctions.secondPriceLogic,\\\\n sellerOfferHandle,\\\\n allBidHandles });}\\\\n\\\\n\\\\n return zoeHelpers.defaultAcceptanceMsg;};\\\\n\\\\n\\\\n const bidderOfferExpected = harden({\\\\n give: { Bid: null },\\\\n want: { Asset: null } });\\\\n\\\\n\\\\n const makeBidderInvite = () =>\\\\n zcf.makeInvitation(\\\\n checkHook(bidderOfferHook, bidderOfferExpected),\\\\n 'bid',\\\\n harden({\\\\n customProperties: {\\\\n auctionedAssets,\\\\n minimumBid } }));\\\\n\\\\n\\\\n\\\\n\\\\n const sellerOfferHook = offerHandle => {\\\\n if (auctionedAssets) {\\\\n throw rejectOffer(offerHandle, `assets already present`);}\\\\n\\\\n /* Save the valid offer*/\\\\n sellerOfferHandle = offerHandle;\\\\n const { proposal } = zcf.getOffer(offerHandle);\\\\n auctionedAssets = proposal.give.Asset;\\\\n minimumBid = proposal.want.Ask;\\\\n return zoeHelpers.defaultAcceptanceMsg;};\\\\n\\\\n\\\\n const sellerOfferExpected = harden({\\\\n give: { Asset: null },\\\\n want: { Ask: null } });\\\\n\\\\n\\\\n const makeSellerInvite = () =>\\\\n zcf.makeInvitation(\\\\n checkHook(sellerOfferHook, sellerOfferExpected),\\\\n 'sellAssets');\\\\n\\\\n\\\\n zcf.initPublicAPI(\\\\n harden({\\\\n makeInvites: numInvites => {\\\\n if (auctionedAssets === undefined) {\\\\n throw new Error(`No assets are up for auction.`);}\\\\n\\\\n const invites = [];\\\\n for (let i = 0; i < numInvites; i += 1) {\\\\n invites.push(makeBidderInvite());}\\\\n\\\\n return invites;},\\\\n\\\\n getAuctionedAssetsAmounts: () => auctionedAssets,\\\\n getMinimumBid: () => minimumBid }));\\\\n\\\\n\\\\n\\\\n return makeSellerInvite();};\\\\n\\\\n\\\\nharden(makeContract);exports.makeContract = makeContract;\\\",\\n \\\"node_modules/@agoric/nat/dist/nat.esm.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* Copyright (C) 2011 Google Inc.*/ /* Copyright (C) 2018 Agoric*/ /**/ /* Licensed under the Apache License, Version 2.0 (the \\\\\\\"License\\\\\\\");*/ /* you may not use this file except in compliance with the License.*/ /* You may obtain a copy of the License at*/ /**/ /* http://www.apache.org/licenses/LICENSE-2.0*/ /**/ /* Unless required by applicable law or agreed to in writing, software*/ /* distributed under the License is distributed on an \\\\\\\"AS IS\\\\\\\" BASIS,*/ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*/ /* See the License for the specific language governing permissions and*/ /* limitations under the License.*/ /**\\\\n * Is allegedNum a number in the contiguous range of exactly and\\\\n * unambiguously representable natural numbers (non-negative integers)?\\\\n *\\\\n * <p>See <a href=\\\\n * \\\\\\\"https://code.google.com/p/google-caja/issues/detail?id=1801\\\\\\\"\\\\n * >Issue 1801: Nat must include at most (2**53)-1</a>\\\\n * and <a href=\\\\n * \\\\\\\"https://mail.mozilla.org/pipermail/es-discuss/2013-July/031716.html\\\\\\\"\\\\n * >Allen Wirfs-Brock's suggested phrasing</a> on es-discuss.\\\\n */\\\\n\\\\nfunction Nat(allegedNum) {\\\\n if (!Number.isSafeInteger(allegedNum)) {\\\\n throw new RangeError('not a safe integer');}\\\\n\\\\n\\\\n if (allegedNum < 0) {\\\\n throw new RangeError('negative');}\\\\n\\\\n\\\\n return allegedNum;}exports.default = Nat;\\\",\\n \\\"packages/zoe/src/contractSupport/auctions.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true }); /* global harden */\\\\n\\\\nconst secondPriceLogic = (bidAmountMath, bidOfferHandles, bids) => {\\\\n let highestBid = bidAmountMath.getEmpty();\\\\n let secondHighestBid = bidAmountMath.getEmpty();\\\\n let highestBidOfferHandle;\\\\n /* eslint-disable-next-line array-callback-return*/\\\\n bidOfferHandles.map((offerHandle, i) => {\\\\n const bid = bids[i];\\\\n /* If the bid is greater than the highestBid, it's the new highestBid*/\\\\n if (bidAmountMath.isGTE(bid, highestBid)) {\\\\n secondHighestBid = highestBid;\\\\n highestBid = bid;\\\\n highestBidOfferHandle = offerHandle;} else\\\\n if (bidAmountMath.isGTE(bid, secondHighestBid)) {\\\\n /* If the bid is not greater than the highest bid, but is greater*/\\\\n /* than the second highest bid, it is the new second highest bid.*/\\\\n secondHighestBid = bid;}});\\\\n\\\\n\\\\n return harden({\\\\n winnerOfferHandle: highestBidOfferHandle,\\\\n winnerBid: highestBid,\\\\n price: secondHighestBid });};\\\\n\\\\n\\\\n\\\\nconst closeAuction = (\\\\nzcf,\\\\n{ auctionLogicFn, sellerOfferHandle, allBidHandles }) =>\\\\n{\\\\n const { brandKeywordRecord } = zcf.getInstanceRecord();\\\\n const bidAmountMath = zcf.getAmountMath(brandKeywordRecord.Ask);\\\\n const assetAmountMath = zcf.getAmountMath(brandKeywordRecord.Asset);\\\\n\\\\n /* Filter out any inactive bids*/\\\\n const { active: activeBidHandles } = zcf.getOfferStatuses(\\\\n harden(allBidHandles));\\\\n\\\\n\\\\n const getBids = amountsKeywordRecord => amountsKeywordRecord.Bid;\\\\n const bids = zcf.getCurrentAllocations(activeBidHandles).map(getBids);\\\\n const assetAmount = zcf.getOffer(sellerOfferHandle).proposal.give.Asset;\\\\n\\\\n const { winnerOfferHandle, winnerBid, price } = auctionLogicFn(\\\\n bidAmountMath,\\\\n activeBidHandles,\\\\n bids);\\\\n\\\\n\\\\n /* The winner gets to keep the difference between their bid and the*/\\\\n /* price paid.*/\\\\n const winnerRefund = bidAmountMath.subtract(winnerBid, price);\\\\n\\\\n const newSellerAmounts = { Asset: assetAmountMath.getEmpty(), Ask: price };\\\\n const newWinnerAmounts = { Asset: assetAmount, Bid: winnerRefund };\\\\n\\\\n /* Everyone else gets a refund so their values remain the*/\\\\n /* same.*/\\\\n zcf.reallocate(\\\\n harden([sellerOfferHandle, winnerOfferHandle]),\\\\n harden([newSellerAmounts, newWinnerAmounts]));\\\\n\\\\n const allOfferHandles = harden([sellerOfferHandle, ...activeBidHandles]);\\\\n zcf.complete(allOfferHandles);};exports.closeAuction = closeAuction;exports.secondPriceLogic = secondPriceLogic;\\\",\\n \\\"packages/assert/src/assert.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* Copyright (C) 2019 Agoric, under Apache License 2.0*/ /* @ts-check*/ /* This module assumes the de-facto standard `console` host object.*/ /* To the extent that this `console` is considered a resource,*/ /* this module must be considered a resource module.*/ /**\\\\n * Prepend the correct indefinite article onto a noun, typically a typeof result\\\\n * e.g., \\\\\\\"an Object\\\\\\\" vs. \\\\\\\"a Number\\\\\\\"\\\\n *\\\\n * @param {string} str The noun to prepend\\\\n * @returns {string} The noun prepended with a/an\\\\n */\\\\nfunction an(str) {\\\\n str = `${str}`;\\\\n if (str.length >= 1 && 'aeiouAEIOU'.includes(str[0])) {\\\\n return `an ${str}`;}\\\\n\\\\n return `a ${str}`;}\\\\n\\\\nharden(an);\\\\n\\\\n/**\\\\n * Like `JSON.stringify` but does not blow up if given a cycle. This is not\\\\n * intended to be a serialization to support any useful unserialization,\\\\n * or any programmatic use of the resulting string. The string is intended\\\\n * only for showing a human, in order to be informative enough for some\\\\n * logging purposes. As such, this `cycleTolerantStringify` has an\\\\n * imprecise specification and may change over time.\\\\n *\\\\n * The current `cycleTolerantStringify` possibly emits too many \\\\\\\"seen\\\\\\\"\\\\n * markings: Not only for cycles, but also for repeated subtrees by\\\\n * object identity.\\\\n */\\\\nfunction cycleTolerantStringify(payload) {\\\\n const seenSet = new Set();\\\\n const replacer = (_, val) => {\\\\n if (typeof val === 'object' && val !== null) {\\\\n if (seenSet.has(val)) {\\\\n return '<**seen**>';}\\\\n\\\\n seenSet.add(val);}\\\\n\\\\n return val;};\\\\n\\\\n return JSON.stringify(payload, replacer);}\\\\n\\\\n\\\\nconst declassifiers = new WeakSet();\\\\n\\\\n/**\\\\n * To \\\\\\\"declassify\\\\\\\" and quote a substitution value used in a\\\\n * details`...` template literal, enclose that substitution expression\\\\n * in a call to `q`. This states that the argument should appear quoted (with\\\\n * `JSON.stringify`), in the error message of the thrown error. The payload\\\\n * itself is still passed unquoted to the console as it would be without q.\\\\n *\\\\n * Starting from the example in the `details` comment, say instead that the\\\\n * color the sky is supposed to be is also computed. Say that we still don't\\\\n * want to reveal the sky's actual color, but we do want the thrown error's\\\\n * message to reveal what color the sky was supposed to be:\\\\n * ```js\\\\n * assert.equal(\\\\n * sky.color,\\\\n * color,\\\\n * details`${sky.color} should be ${q(color)}`,\\\\n * );\\\\n * ```\\\\n *\\\\n * @typedef {Object} StringablePayload\\\\n * @property {*} payload The original payload\\\\n * @property {() => string} toString How to print the payload\\\\n *\\\\n * @param {*} payload What to declassify\\\\n * @returns {StringablePayload} The declassified payload\\\\n */\\\\nfunction q(payload) {\\\\n /* Don't harden the payload*/\\\\n const result = Object.freeze({\\\\n payload,\\\\n toString: Object.freeze(() => cycleTolerantStringify(payload)) });\\\\n\\\\n declassifiers.add(result);\\\\n return result;}\\\\n\\\\nharden(q);\\\\n\\\\n/**\\\\n * Use the `details` function as a template literal tag to create\\\\n * informative error messages. The assertion functions take such messages\\\\n * as optional arguments:\\\\n * ```js\\\\n * assert(sky.isBlue(), details`${sky.color} should be \\\\\\\"blue\\\\\\\"`);\\\\n * ```\\\\n * The details template tag returns an object that can print itself with the\\\\n * formatted message in two ways. It will report the real details to the\\\\n * console but include only the typeof information in the thrown error\\\\n * to prevent revealing secrets up the exceptional path. In the example\\\\n * above, the thrown error may reveal only that `sky.color` is a string,\\\\n * whereas the same diagnostic printed to the console reveals that the\\\\n * sky was green.\\\\n *\\\\n * WARNING: this function currently returns an unhardened result, as hardening\\\\n * proved to cause significant performance degradation. Consequently, callers\\\\n * should take care to use it only in contexts where this lack of hardening\\\\n * does not present a hazard. In current usage, a `details` template literal\\\\n * may only appear either as an argument to `assert`, where we know hardening\\\\n * won't matter, or inside another hardened object graph, where hardening is\\\\n * already ensured. However, there is currently no means to enfoce these\\\\n * constraints, so users are required to employ this function with caution.\\\\n * Our intent is to eventually have a lint rule that will check for\\\\n * inappropriate uses or find an alternative means of implementing `details`\\\\n * that does not encounter the performance issue. The final disposition of\\\\n * this is being discussed and tracked in issue #679 in the agoric-sdk\\\\n * repository.\\\\n *\\\\n * @typedef {Object} Complainer An object that has custom assert behaviour\\\\n * @property {() => Error} complain Return an Error to throw, and print details to console\\\\n *\\\\n * @typedef {string|Complainer} Details Either a plain string, or made by details``\\\\n *\\\\n * @param {TemplateStringsArray | string[]} template The template to format\\\\n * @param {any[]} args Arguments to the template\\\\n * @returns {Complainer} The complainer for these details\\\\n */\\\\nfunction details(template, ...args) {\\\\n /* const complainer = harden({ // remove harden per above discussion*/\\\\n const complainer = {\\\\n complain() {\\\\n const interleaved = [template[0]];\\\\n const parts = [template[0]];\\\\n for (let i = 0; i < args.length; i += 1) {\\\\n let arg = args[i];\\\\n let argStr;\\\\n if (declassifiers.has(arg)) {\\\\n argStr = `${arg}`;\\\\n arg = arg.payload;} else\\\\n {\\\\n argStr = `(${an(typeof arg)})`;}\\\\n\\\\n\\\\n /* Remove the extra spaces (since console.error puts them*/\\\\n /* between each interleaved).*/\\\\n const priorWithoutSpace = (interleaved.pop() || '').replace(/ $/, '');\\\\n if (priorWithoutSpace !== '') {\\\\n interleaved.push(priorWithoutSpace);}\\\\n\\\\n\\\\n const nextWithoutSpace = template[i + 1].replace(/^ /, '');\\\\n interleaved.push(arg, nextWithoutSpace);\\\\n\\\\n parts.push(argStr, template[i + 1]);}\\\\n\\\\n if (interleaved[interleaved.length - 1] === '') {\\\\n interleaved.pop();}\\\\n\\\\n if (args.length >= 1) {\\\\n parts.push('\\\\\\\\nSee console for error data.');}\\\\n\\\\n const err = new Error(parts.join(''));\\\\n console.error('LOGGED ERROR:', ...interleaved, err);\\\\n /* eslint-disable-next-line no-debugger*/\\\\n debugger;\\\\n return err;} };\\\\n\\\\n\\\\n /* });*/\\\\n return complainer;}\\\\n\\\\nharden(details);\\\\n\\\\n/**\\\\n * Fail an assertion, recording details to the console and\\\\n * raising an exception with just type information.\\\\n *\\\\n * The optional `optDetails` can be a string for backwards compatibility\\\\n * with the nodejs assertion library.\\\\n * @param {Details} [optDetails] The details of what was asserted\\\\n * @returns {never}\\\\n */\\\\nfunction fail(optDetails = details`Assert failed`) {\\\\n if (typeof optDetails === 'string') {\\\\n /* If it is a string, use it as the literal part of the template so*/\\\\n /* it doesn't get quoted.*/\\\\n optDetails = details([optDetails]);}\\\\n\\\\n throw optDetails.complain();}\\\\n\\\\n\\\\n/**\\\\n * @param {*} flag The truthy/falsy value\\\\n * @param {Details} [optDetails] The details to throw\\\\n * @returns {asserts flag}\\\\n */\\\\nfunction assert(flag, optDetails = details`Check failed`) {\\\\n if (!flag) {\\\\n throw fail(optDetails);}}\\\\n\\\\n\\\\n\\\\n/**\\\\n * Assert that two values must be `Object.is`.\\\\n * @param {*} actual The value we received\\\\n * @param {*} expected What we wanted\\\\n * @param {Details} [optDetails] The details to throw\\\\n * @returns {void}\\\\n */\\\\nfunction equal(\\\\nactual,\\\\nexpected,\\\\noptDetails = details`Expected ${actual} is same as ${expected}`)\\\\n{\\\\n assert(Object.is(actual, expected), optDetails);}\\\\n\\\\n\\\\n/**\\\\n * Assert an expected typeof result.\\\\n * @type {AssertTypeof}\\\\n * @param {any} specimen The value to get the typeof\\\\n * @param {string} typename The expected name\\\\n * @param {Details} [optDetails] The details to throw\\\\n */\\\\nconst assertTypeof = (specimen, typename, optDetails) => {\\\\n assert(\\\\n typeof typename === 'string',\\\\n details`${q(typename)} must be a string`);\\\\n\\\\n if (optDetails === undefined) {\\\\n /* Like*/\\\\n /* ```js*/\\\\n /* optDetails = details`${specimen} must be ${q(an(typename))}`;*/\\\\n /* ```*/\\\\n /* except it puts the typename into the literal part of the template*/\\\\n /* so it doesn't get quoted.*/\\\\n optDetails = details(['', ` must be ${an(typename)}`], specimen);}\\\\n\\\\n equal(typeof specimen, typename, optDetails);};\\\\n\\\\n\\\\n/**\\\\n * assert that expr is truthy, with an optional details to describe\\\\n * the assertion. It is a tagged template literal like\\\\n * ```js\\\\n * assert(expr, details`....`);`\\\\n * ```\\\\n * If expr is falsy, then the template contents are reported to the\\\\n * console and also in a thrown error.\\\\n *\\\\n * The literal portions of the template are assumed non-sensitive, as\\\\n * are the `typeof` types of the substitution values. These are\\\\n * assembled into the thrown error message. The actual contents of the\\\\n * substitution values are assumed sensitive, to be revealed to the\\\\n * console only. We assume only the virtual platform's owner can read\\\\n * what is written to the console, where the owner is in a privileged\\\\n * position over computation running on that platform.\\\\n *\\\\n * The optional `optDetails` can be a string for backwards compatibility\\\\n * with the nodejs assertion library.\\\\n * @type {typeof assert & { typeof: AssertTypeof, fail: typeof fail, equal: typeof equal }}\\\\n */\\\\nconst assertCombined = Object.assign(assert, {\\\\n equal,\\\\n fail,\\\\n typeof: assertTypeof });\\\\n\\\\nharden(assertCombined);exports.an = an;exports.assert = assertCombined;exports.details = details;exports.q = q;\\\",\\n \\\"packages/zoe/src/contractSupport/safeMath.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\nnat_esm = require('../../../../node_modules/@agoric/nat/dist/nat.esm.js'); /* global harden */ /**\\\\n * These operations should be used for calculations with the\\\\n * values of basic fungible tokens.\\\\n */\\\\nconst natSafeMath = harden({\\\\n add: (x, y) => nat_esm.default(x + y),\\\\n subtract: (x, y) => nat_esm.default(x - y),\\\\n multiply: (x, y) => nat_esm.default(x * y),\\\\n floorDivide: (x, y) => nat_esm.default(Math.floor(x / y)) });exports.natSafeMath = natSafeMath;\\\",\\n \\\"packages/zoe/src/contractSupport/bondingCurves.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../../assert/src/assert.js');var safeMath = require('./safeMath.js');\\\\n\\\\n\\\\nconst { add, subtract, multiply, floorDivide } = safeMath.natSafeMath;\\\\n\\\\n/**\\\\n * Contains the logic for calculating how much should be given\\\\n * back to the user in exchange for what they sent in. It also\\\\n * calculates the new amount of the assets in the pool. Reused in\\\\n * several different places, including to check whether an offer\\\\n * is valid, getting the current price for an asset on user\\\\n * request, and to do the actual reallocation after an offer has\\\\n * been made.\\\\n * @param {Object} params\\\\n * @param {number} params.inputValue - the value of the asset sent\\\\n * in to be swapped\\\\n * @param {number} params.inputReserve - the value in the liquidity\\\\n * pool of the kind of asset sent in\\\\n * @param {number} params.outputReserve - the value in the liquidity\\\\n * pool of the kind of asset to be sent out\\\\n * @param {number} params.feeBasisPoints=30 - the fee taken in\\\\n * basis points. The default is 0.3% or 30 basis points. The fee is taken from\\\\n * inputValue\\\\n * @returns {number} outputValue - the current price, in value form\\\\n */\\\\nconst getInputPrice = ({\\\\n inputValue,\\\\n inputReserve,\\\\n outputReserve,\\\\n feeBasisPoints = 30 }) =>\\\\n{\\\\n const oneMinusFeeInTenThousandths = subtract(10000, feeBasisPoints);\\\\n const inputWithFee = multiply(inputValue, oneMinusFeeInTenThousandths);\\\\n const numerator = multiply(inputWithFee, outputReserve);\\\\n const denominator = add(multiply(inputReserve, 10000), inputWithFee);\\\\n\\\\n const outputValue = floorDivide(numerator, denominator);\\\\n return outputValue;};\\\\n\\\\n\\\\nfunction assertDefined(label, value) {\\\\n assert.assert(value !== undefined, assert.details`${label} value required`);}\\\\n\\\\n\\\\n/* Calculate how many liquidity tokens we should be minting to send back to the*/\\\\n/* user when adding liquidity. Calculations are based on the comparing the*/\\\\n/* inputValue to the inputReserve. If the current supply is zero, just return*/\\\\n/* the inputValue.*/\\\\nconst calcLiqValueToMint = ({\\\\n liqTokenSupply,\\\\n inputValue,\\\\n inputReserve }) =>\\\\n{\\\\n assertDefined('liqTokenSupply', liqTokenSupply);\\\\n assertDefined('inputValue', inputValue);\\\\n assertDefined('inputReserve', inputReserve);\\\\n return liqTokenSupply > 0 ?\\\\n floorDivide(multiply(inputValue, liqTokenSupply), inputReserve) :\\\\n inputValue;};\\\\n\\\\n\\\\n/* Calculate how many underlying tokens (in the form of a value) should be*/\\\\n/* returned when removing liquidity.*/\\\\nconst calcValueToRemove = ({\\\\n liqTokenSupply,\\\\n poolValue,\\\\n liquidityValueIn }) =>\\\\n{\\\\n assertDefined('liqTokenSupply', liqTokenSupply);\\\\n assertDefined('liquidityValueIn', liquidityValueIn);\\\\n assertDefined('poolValue', poolValue);\\\\n\\\\n return floorDivide(multiply(liquidityValueIn, poolValue), liqTokenSupply);};exports.calcLiqValueToMint = calcLiqValueToMint;exports.calcValueToRemove = calcValueToRemove;exports.getInputPrice = getInputPrice;\\\",\\n \\\"packages/zoe/src/contractSupport/stateMachine.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\nassert = require('../../../assert/src/assert.js'); /* global harden */ /* allowedTransitions is an array of arrays which gets turned into a\\\\n * map. The map maps string states to an array of potential next\\\\n * states. For example,\\\\n * const allowedTransitions = [\\\\n ['open', ['closed']],\\\\n ['closed', []],\\\\n * ];\\\\n */\\\\nconst makeStateMachine = (initialState, allowedTransitionsArray) => {\\\\n let state = initialState;\\\\n const allowedTransitions = new Map(allowedTransitionsArray);\\\\n return harden({\\\\n canTransitionTo: (nextState) =>\\\\n allowedTransitions.get(state).includes(nextState),\\\\n transitionTo: nextState => {\\\\n assert.assert(allowedTransitions.get(state).includes(nextState));\\\\n state = nextState;},\\\\n\\\\n getStatus: _ => state });};\\\\n\\\\n\\\\nharden(makeStateMachine);exports.makeStateMachine = makeStateMachine;\\\",\\n \\\"packages/eventual-send/src/E.js\\\": \\\"'use strict';\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* global harden */ /* eslint-disable-next-line spaced-comment*/ /*/ <reference path=\\\\\\\"index.d.ts\\\\\\\" />*/\\\\n\\\\nconst readOnlyProxy = {\\\\n set(_target, _prop, _value) {\\\\n return false;},\\\\n\\\\n isExtensible(_target) {\\\\n return false;},\\\\n\\\\n setPrototypeOf(_target, _value) {\\\\n return false;},\\\\n\\\\n deleteProperty(_target, _prop) {\\\\n return false;} };\\\\n\\\\n\\\\n\\\\n/**\\\\n * A Proxy handler for E(x).\\\\n *\\\\n * @param {*} x Any value passed to E(x)\\\\n * @returns {ProxyHandler} the Proxy handler\\\\n */\\\\nfunction EProxyHandler(x, HandledPromise) {\\\\n return harden({\\\\n ...readOnlyProxy,\\\\n get(_target, p, _receiver) {\\\\n if (`${p}` !== p) {\\\\n return undefined;}\\\\n\\\\n /* Harden this Promise because it's our only opportunity to ensure*/\\\\n /* p1=E(x).foo() is hardened. The Handled Promise API does not (yet)*/\\\\n /* allow the handler to synchronously influence the promise returned*/\\\\n /* by the handled methods, so we must freeze it from the outside. See*/\\\\n /* #95 for details.*/\\\\n return (...args) => harden(HandledPromise.applyMethod(x, p, args));},\\\\n\\\\n apply(_target, _thisArg, argArray = []) {\\\\n return harden(HandledPromise.applyFunction(x, argArray));},\\\\n\\\\n has(_target, _p) {\\\\n /* We just pretend everything exists.*/\\\\n return true;} });}\\\\n\\\\n\\\\n\\\\n\\\\nfunction makeE(HandledPromise) {\\\\n function E(x) {\\\\n const handler = EProxyHandler(x, HandledPromise);\\\\n return harden(new Proxy(() => {}, handler));}\\\\n\\\\n\\\\n const makeEGetterProxy = (x) =>\\\\n new Proxy(Object.create(null), {\\\\n ...readOnlyProxy,\\\\n has(_target, _prop) {\\\\n return true;},\\\\n\\\\n get(_target, prop) {\\\\n return harden(HandledPromise.get(x, prop));} });\\\\n\\\\n\\\\n\\\\n E.G = makeEGetterProxy;\\\\n E.resolve = HandledPromise.resolve;\\\\n E.unwrap = HandledPromise.unwrap;\\\\n\\\\n E.when = (x, onfulfilled = undefined, onrejected = undefined) =>\\\\n HandledPromise.resolve(x).then(onfulfilled, onrejected);\\\\n\\\\n return harden(E);}exports.default = makeE;\\\",\\n \\\"packages/eventual-send/src/index.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var E$1 = require('./E.js'); /* global harden HandledPromise */\\\\n\\\\n\\\\n\\\\nconst {\\\\n defineProperties,\\\\n getOwnPropertyDescriptors,\\\\n getOwnPropertyDescriptor: gopd,\\\\n getPrototypeOf,\\\\n isFrozen } =\\\\nObject;\\\\n\\\\nconst { prototype: promiseProto } = Promise;\\\\nconst { then: originalThen } = promiseProto;\\\\n\\\\n/* 'E' and 'HandledPromise' are exports of the module*/\\\\n\\\\n/* For now:*/\\\\n/* import { HandledPromise, E } from '@agoric/eventual-send';*/\\\\n/* ...*/\\\\n\\\\nconst hp =\\\\ntypeof HandledPromise === 'undefined' ?\\\\n/* eslint-disable-next-line no-use-before-define*/\\\\nmakeHandledPromise(Promise) :\\\\nharden(HandledPromise);\\\\n\\\\n\\\\n\\\\nconst E = E$1.default(hp);\\\\n\\\\n/* the following method (makeHandledPromise) is part*/\\\\n/* of the shim, and will not be exported by the module once the feature*/\\\\n/* becomes a part of standard javascript*/\\\\n\\\\n/**\\\\n * Create a HandledPromise class to have it support eventual send\\\\n * (wavy-dot) operations.\\\\n *\\\\n * Based heavily on nanoq\\\\n * https://github.com/drses/nanoq/blob/master/src/nanoq.js\\\\n *\\\\n * Original spec for the infix-bang (predecessor to wavy-dot) desugaring:\\\\n * https://web.archive.org/web/20161026162206/http://wiki.ecmascript.org/doku.php?id=strawman:concurrency\\\\n *\\\\n * @return {typeof HandledPromise} Handled promise\\\\n */\\\\nfunction makeHandledPromise(Promise) {\\\\n /* xs doesn't support WeakMap in pre-loaded closures*/\\\\n /* aka \\\\\\\"vetted customization code\\\\\\\"*/\\\\n let presenceToHandler;\\\\n let presenceToPromise;\\\\n let promiseToUnsettledHandler;\\\\n let promiseToPresence; /* only for HandledPromise.unwrap*/\\\\n let forwardedPromiseToPromise; /* forwarding, union-find-ish*/\\\\n function ensureMaps() {\\\\n if (!presenceToHandler) {\\\\n presenceToHandler = new WeakMap();\\\\n presenceToPromise = new WeakMap();\\\\n promiseToUnsettledHandler = new WeakMap();\\\\n promiseToPresence = new WeakMap();\\\\n forwardedPromiseToPromise = new WeakMap();}}\\\\n\\\\n\\\\n\\\\n /**\\\\n * You can imagine a forest of trees in which the roots of each tree is an\\\\n * unresolved HandledPromise or a non-Promise, and each node's parent is the\\\\n * HandledPromise to which it was forwarded. We maintain that mapping of\\\\n * forwarded HandledPromise to its resolution in forwardedPromiseToPromise.\\\\n *\\\\n * We use something like the description of \\\\\\\"Find\\\\\\\" with \\\\\\\"Path splitting\\\\\\\"\\\\n * to propagate changes down to the children efficiently:\\\\n * https://en.wikipedia.org/wiki/Disjoint-set_data_structure\\\\n *\\\\n * @param {*} target Any value.\\\\n * @returns {*} If the target was a HandledPromise, the most-resolved parent of it, otherwise the target.\\\\n */\\\\n function shorten(target) {\\\\n let p = target;\\\\n /* Find the most-resolved value for p.*/\\\\n while (forwardedPromiseToPromise.has(p)) {\\\\n p = forwardedPromiseToPromise.get(p);}\\\\n\\\\n const presence = promiseToPresence.get(p);\\\\n if (presence) {\\\\n /* Presences are final, so it is ok to propagate*/\\\\n /* this upstream.*/\\\\n while (target !== p) {\\\\n const parent = forwardedPromiseToPromise.get(target);\\\\n forwardedPromiseToPromise.delete(target);\\\\n promiseToUnsettledHandler.delete(target);\\\\n promiseToPresence.set(target, presence);\\\\n target = parent;}} else\\\\n\\\\n {\\\\n /* We propagate p and remove all other unsettled handlers*/\\\\n /* upstream.*/\\\\n /* Note that everything except presences is covered here.*/\\\\n while (target !== p) {\\\\n const parent = forwardedPromiseToPromise.get(target);\\\\n forwardedPromiseToPromise.set(target, p);\\\\n promiseToUnsettledHandler.delete(target);\\\\n target = parent;}}\\\\n\\\\n\\\\n return target;}\\\\n\\\\n\\\\n /* This special handler accepts Promises, and forwards*/\\\\n /* handled Promises to their corresponding fulfilledHandler.*/\\\\n let forwardingHandler;\\\\n let handle;\\\\n let promiseResolve;\\\\n\\\\n function HandledPromise(executor, unsettledHandler = undefined) {\\\\n if (new.target === undefined) {\\\\n throw new Error('must be invoked with \\\\\\\"new\\\\\\\"');}\\\\n\\\\n let handledResolve;\\\\n let handledReject;\\\\n let resolved = false;\\\\n let resolvedTarget = null;\\\\n let handledP;\\\\n let continueForwarding = () => {};\\\\n const superExecutor = (superResolve, superReject) => {\\\\n handledResolve = value => {\\\\n if (resolved) {\\\\n return resolvedTarget;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n value = shorten(value);\\\\n let targetP;\\\\n if (\\\\n promiseToUnsettledHandler.has(value) ||\\\\n promiseToPresence.has(value))\\\\n {\\\\n targetP = value;} else\\\\n {\\\\n /* We're resolving to a non-promise, so remove our handler.*/\\\\n promiseToUnsettledHandler.delete(handledP);\\\\n targetP = presenceToPromise.get(value);}\\\\n\\\\n /* Ensure our data structure is a propert tree (avoid cycles).*/\\\\n if (targetP && targetP !== handledP) {\\\\n forwardedPromiseToPromise.set(handledP, targetP);} else\\\\n {\\\\n forwardedPromiseToPromise.delete(handledP);}\\\\n\\\\n\\\\n /* Remove stale unsettled handlers, set to canonical form.*/\\\\n shorten(handledP);\\\\n\\\\n /* Ensure our unsettledHandler is cleaned up if not already.*/\\\\n if (promiseToUnsettledHandler.has(handledP)) {\\\\n handledP.then(_ => promiseToUnsettledHandler.delete(handledP));}\\\\n\\\\n\\\\n /* Finish the resolution.*/\\\\n superResolve(value);\\\\n resolved = true;\\\\n resolvedTarget = value;\\\\n\\\\n /* We're resolved, so forward any postponed operations to us.*/\\\\n continueForwarding();\\\\n return resolvedTarget;};\\\\n\\\\n handledReject = err => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n promiseToUnsettledHandler.delete(handledP);\\\\n resolved = true;\\\\n superReject(err);\\\\n continueForwarding();};};\\\\n\\\\n\\\\n handledP = harden(Reflect.construct(Promise, [superExecutor], new.target));\\\\n\\\\n ensureMaps();\\\\n\\\\n const makePostponedHandler = () => {\\\\n /* Create a simple postponedHandler that just postpones until the*/\\\\n /* fulfilledHandler is set.*/\\\\n let donePostponing;\\\\n const interlockP = new Promise(resolve => {\\\\n donePostponing = () => resolve();});\\\\n\\\\n\\\\n const makePostponedOperation = postponedOperation => {\\\\n /* Just wait until the handler is resolved/rejected.*/\\\\n return function postpone(x, ...args) {\\\\n /* console.log(`forwarding ${postponedOperation} ${args[0]}`);*/\\\\n return new HandledPromise((resolve, reject) => {\\\\n interlockP.\\\\n then(_ => {\\\\n /* If targetP is a handled promise, use it, otherwise x.*/\\\\n resolve(HandledPromise[postponedOperation](x, ...args));}).\\\\n\\\\n catch(reject);});};};\\\\n\\\\n\\\\n\\\\n\\\\n const postponedHandler = {\\\\n get: makePostponedOperation('get'),\\\\n applyMethod: makePostponedOperation('applyMethod') };\\\\n\\\\n return [postponedHandler, donePostponing];};\\\\n\\\\n\\\\n if (!unsettledHandler) {\\\\n /* This is insufficient for actual remote handled Promises*/\\\\n /* (too many round-trips), but is an easy way to create a*/\\\\n /* local handled Promise.*/\\\\n [unsettledHandler, continueForwarding] = makePostponedHandler();}\\\\n\\\\n\\\\n const validateHandler = h => {\\\\n if (Object(h) !== h) {\\\\n throw TypeError(`Handler ${h} cannot be a primitive`);}};\\\\n\\\\n\\\\n validateHandler(unsettledHandler);\\\\n\\\\n /* Until the handled promise is resolved, we use the unsettledHandler.*/\\\\n promiseToUnsettledHandler.set(handledP, unsettledHandler);\\\\n\\\\n const rejectHandled = reason => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n handledReject(reason);};\\\\n\\\\n\\\\n const resolveWithPresence = presenceHandler => {\\\\n if (resolved) {\\\\n return resolvedTarget;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n try {\\\\n /* Sanity checks.*/\\\\n validateHandler(presenceHandler);\\\\n\\\\n /* Validate and install our mapped target (i.e. presence).*/\\\\n resolvedTarget = Object.create(null);\\\\n\\\\n /* Create table entries for the presence mapped to the*/\\\\n /* fulfilledHandler.*/\\\\n presenceToPromise.set(resolvedTarget, handledP);\\\\n promiseToPresence.set(handledP, resolvedTarget);\\\\n presenceToHandler.set(resolvedTarget, presenceHandler);\\\\n\\\\n /* We committed to this presence, so resolve.*/\\\\n handledResolve(resolvedTarget);\\\\n return resolvedTarget;}\\\\n catch (e) {\\\\n handledReject(e);\\\\n throw e;}};\\\\n\\\\n\\\\n\\\\n const resolveHandled = async (target, deprecatedPresenceHandler) => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n try {\\\\n if (deprecatedPresenceHandler) {\\\\n throw TypeError(\\\\n `resolveHandled no longer accepts a handler; use resolveWithPresence`);}\\\\n\\\\n\\\\n\\\\n /* Resolve the target.*/\\\\n handledResolve(target);}\\\\n catch (e) {\\\\n handledReject(e);}};\\\\n\\\\n\\\\n\\\\n /* Invoke the callback to let the user resolve/reject.*/\\\\n executor(\\\\n (...args) => {\\\\n resolveHandled(...args);},\\\\n\\\\n rejectHandled,\\\\n resolveWithPresence);\\\\n\\\\n return handledP;}\\\\n\\\\n\\\\n HandledPromise.prototype = promiseProto;\\\\n Object.setPrototypeOf(HandledPromise, Promise);\\\\n\\\\n function isFrozenPromiseThen(p) {\\\\n return (\\\\n isFrozen(p) &&\\\\n getPrototypeOf(p) === promiseProto &&\\\\n promiseResolve(p) === p &&\\\\n gopd(p, 'then') === undefined &&\\\\n gopd(promiseProto, 'then').value === originalThen /* unnecessary under SES*/);}\\\\n\\\\n\\\\n\\\\n const staticMethods = harden({\\\\n get(target, key) {\\\\n return handle(target, 'get', key);},\\\\n\\\\n getSendOnly(target, key) {\\\\n handle(target, 'get', key);},\\\\n\\\\n applyFunction(target, args) {\\\\n return handle(target, 'applyMethod', undefined, args);},\\\\n\\\\n applyFunctionSendOnly(target, args) {\\\\n handle(target, 'applyMethod', undefined, args);},\\\\n\\\\n applyMethod(target, key, args) {\\\\n return handle(target, 'applyMethod', key, args);},\\\\n\\\\n applyMethodSendOnly(target, key, args) {\\\\n handle(target, 'applyMethod', key, args);},\\\\n\\\\n resolve(value) {\\\\n ensureMaps();\\\\n /* Resolving a Presence returns the pre-registered handled promise.*/\\\\n let resolvedPromise = presenceToPromise.get(value);\\\\n if (!resolvedPromise) {\\\\n resolvedPromise = promiseResolve(value);}\\\\n\\\\n /* Prevent any proxy trickery.*/\\\\n harden(resolvedPromise);\\\\n if (isFrozenPromiseThen(resolvedPromise)) {\\\\n return resolvedPromise;}\\\\n\\\\n /* Assimilate the thenable.*/\\\\n const executeThen = (resolve, reject) =>\\\\n resolvedPromise.then(resolve, reject);\\\\n return harden(\\\\n promiseResolve().then(_ => new HandledPromise(executeThen)));},\\\\n\\\\n\\\\n /* TODO verify that this is safe to provide universally, i.e.,*/\\\\n /* that by itself it doesn't provide access to mutable state in*/\\\\n /* ways that violate normal ocap module purity rules. The claim*/\\\\n /* that it does not rests on the handled promise itself being*/\\\\n /* necessary to perceive this mutable state. In that sense, we*/\\\\n /* can think of the right to perceive it, and of access to the*/\\\\n /* target, as being in the handled promise. Note that a .then on*/\\\\n /* the handled promise will already provide async access to the*/\\\\n /* target, so the only additional authorities are: 1)*/\\\\n /* synchronous access for handled promises only, and thus 2) the*/\\\\n /* ability to tell, from the client side, whether a promise is*/\\\\n /* handled. Or, at least, the ability to tell given that the*/\\\\n /* promise is already fulfilled.*/\\\\n unwrap(value) {\\\\n /* This check for Thenable is safe, since in a remote-object*/\\\\n /* environment, our comms system will defend against remote*/\\\\n /* objects being represented as a tricky local Proxy, otherwise*/\\\\n /* it is guaranteed to be local and therefore synchronous enough.*/\\\\n if (Object(value) !== value || !('then' in value)) {\\\\n /* Not a Thenable, so return it.*/\\\\n /* This means that local objects will pass through without error.*/\\\\n return value;}\\\\n\\\\n\\\\n /* Try to look up the HandledPromise.*/\\\\n ensureMaps();\\\\n const pr = presenceToPromise.get(value) || value;\\\\n\\\\n /* Find the fulfilled presence for that HandledPromise.*/\\\\n const presence = promiseToPresence.get(pr);\\\\n if (!presence) {\\\\n throw TypeError(\\\\n `Value is a Thenble but not a HandledPromise fulfilled to a presence`);}\\\\n\\\\n\\\\n return presence;} });\\\\n\\\\n\\\\n\\\\n defineProperties(HandledPromise, getOwnPropertyDescriptors(staticMethods));\\\\n\\\\n function makeForwarder(operation, localImpl) {\\\\n return (o, ...args) => {\\\\n /* We are in another turn already, and have the naked object.*/\\\\n const fulfilledHandler = presenceToHandler.get(o);\\\\n if (\\\\n fulfilledHandler &&\\\\n typeof fulfilledHandler[operation] === 'function')\\\\n {\\\\n /* The handler was resolved, so use it.*/\\\\n return fulfilledHandler[operation](o, ...args);}\\\\n\\\\n\\\\n /* Not handled, so use the local implementation.*/\\\\n return localImpl(o, ...args);};}\\\\n\\\\n\\\\n\\\\n /* eslint-disable-next-line prefer-const*/\\\\n forwardingHandler = {\\\\n get: makeForwarder('get', (o, key) => o[key]),\\\\n applyMethod: makeForwarder('applyMethod', (o, optKey, args) => {\\\\n if (optKey === undefined || optKey === null) {\\\\n return o(...args);}\\\\n\\\\n /* console.log(`sending`, optKey, o[optKey], o);*/\\\\n if (typeof o[optKey] !== 'function') {\\\\n throw TypeError(`o[${JSON.stringify(optKey)}] is not a function`);}\\\\n\\\\n return o[optKey](...args);}) };\\\\n\\\\n\\\\n\\\\n handle = (p, operation, ...opArgs) => {\\\\n ensureMaps();\\\\n const returnedP = new HandledPromise((resolve, reject) => {\\\\n /* We run in a future turn to prevent synchronous attacks,*/\\\\n let raceIsOver = false;\\\\n function win(handlerName, handler, o) {\\\\n if (raceIsOver) {\\\\n return;}\\\\n\\\\n if (typeof handler[operation] !== 'function') {\\\\n throw TypeError(`${handlerName}.${operation} is not a function`);}\\\\n\\\\n try {\\\\n resolve(handler[operation](o, ...opArgs, returnedP));}\\\\n catch (reason) {\\\\n reject(reason);}\\\\n\\\\n raceIsOver = true;}\\\\n\\\\n\\\\n function lose(e) {\\\\n if (raceIsOver) {\\\\n return;}\\\\n\\\\n reject(e);\\\\n raceIsOver = true;}\\\\n\\\\n\\\\n /* This contestant tries to win with the target's resolution.*/\\\\n HandledPromise.resolve(p).\\\\n then(o => win('forwardingHandler', forwardingHandler, o)).\\\\n catch(lose);\\\\n\\\\n /* This contestant sleeps a turn, but then tries to win immediately.*/\\\\n HandledPromise.resolve().\\\\n then(() => {\\\\n p = shorten(p);\\\\n const unsettledHandler = promiseToUnsettledHandler.get(p);\\\\n if (\\\\n unsettledHandler &&\\\\n typeof unsettledHandler[operation] === 'function')\\\\n {\\\\n /* and resolve to the answer from the specific unsettled handler,*/\\\\n /* opArgs are something like [prop] or [method, args],*/\\\\n /* so we don't risk the user's args leaking into this expansion.*/\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n win('unsettledHandler', unsettledHandler, p);} else\\\\n if (Object(p) !== p || !('then' in p)) {\\\\n /* Not a Thenable, so use it.*/\\\\n win('forwardingHandler', forwardingHandler, p);} else\\\\n if (promiseToPresence.has(p)) {\\\\n /* We have the object synchronously, so resolve with it.*/\\\\n const o = promiseToPresence.get(p);\\\\n win('forwardingHandler', forwardingHandler, o);}\\\\n\\\\n /* If we made it here without winning, then we will wait*/\\\\n /* for the other contestant to win instead.*/}).\\\\n\\\\n catch(lose);});\\\\n\\\\n\\\\n /* We return a handled promise with the default unsettled handler.*/\\\\n /* This prevents a race between the above Promise.resolves and*/\\\\n /* pipelining.*/\\\\n return returnedP;};\\\\n\\\\n\\\\n promiseResolve = Promise.resolve.bind(Promise);\\\\n return harden(HandledPromise);}exports.E = E;exports.HandledPromise = hp;exports.makeHandledPromise = makeHandledPromise;\\\",\\n \\\"packages/produce-promise/src/producePromise.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nindex = require('../../eventual-send/src/index.js'); /* global harden */ /**\\\\n * @template U,V\\\\n * @typedef {Object} PromiseRecord A reified Promise\\\\n * @property {(value?: U) => void} resolve\\\\n * @property {(reason?: V) => void} reject\\\\n * @property {Promise.<U, V>} promise\\\\n */ /**\\\\n * producePromise() builds a HandledPromise object, and returns a record\\\\n * containing the promise itself, as well as separate facets for resolving\\\\n * and rejecting it.\\\\n *\\\\n * @template U,V\\\\n * @returns {PromiseRecord.<U,V>}\\\\n */function producePromise() {let res;let rej; /* We use a HandledPromise so that we can run HandledPromise.unwrap(p)*/ /* even if p doesn't travel through a comms system (like SwingSet's).*/const p = new index.HandledPromise((resolve, reject) => {\\\\n res = resolve;\\\\n rej = reject;});\\\\n\\\\n /* Node.js adds the `domain` property which is not a standard*/\\\\n /* property on Promise. Because we do not know it to be ocap-safe,*/\\\\n /* we remove it.*/\\\\n if (p.domain) {\\\\n /* deleting p.domain may break functionality. To retain current*/\\\\n /* functionality at the expense of safety, set unsafe to true.*/\\\\n const unsafe = false;\\\\n if (unsafe) {\\\\n const originalDomain = p.domain;\\\\n Object.defineProperty(p, 'domain', {\\\\n get() {\\\\n return originalDomain;} });} else\\\\n\\\\n\\\\n {\\\\n delete p.domain;}}\\\\n\\\\n\\\\n return harden({ promise: p, resolve: res, reject: rej });}\\\\n\\\\nharden(producePromise);\\\\n\\\\n/**\\\\n * Determine if the argument is a Promise.\\\\n *\\\\n * @param {Promise} maybePromise The value to examine\\\\n * @returns {boolean} Whether it is a promise\\\\n */\\\\nfunction isPromise(maybePromise) {\\\\n return index.HandledPromise.resolve(maybePromise) === maybePromise;}\\\\n\\\\nharden(isPromise);exports.isPromise = isPromise;exports.producePromise = producePromise;\\\",\\n \\\"packages/marshal/marshal.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var nat_esm = require('../../node_modules/@agoric/nat/dist/nat.esm.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nproducePromise = require('../produce-promise/src/producePromise.js'); /* global harden */ /* TODO: Use just 'remote' when we're willing to make a breaking change.*/\\\\nconst REMOTE_STYLE = 'presence';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n/**\\\\n * This is an interface specification.\\\\n * For now, it is just a string, but will eventually become something\\\\n * much richer (anything that pureCopy accepts).\\\\n * @typedef {string} InterfaceSpec\\\\n */\\\\n\\\\n/**\\\\n * @type {WeakMap<Object, InterfaceSpec>}\\\\n */\\\\nconst remotableToInterface = new WeakMap();\\\\n\\\\n/**\\\\n * Simple semantics, just tell what interface (or undefined) a remotable has.\\\\n *\\\\n * @param {*} maybeRemotable the value to check\\\\n * @returns {InterfaceSpec} the interface specification, or undefined if not a Remotable\\\\n */\\\\nfunction getInterfaceOf(maybeRemotable) {\\\\n return remotableToInterface.get(maybeRemotable);}\\\\n\\\\n\\\\n/**\\\\n * Do a deep copy of the object, handling Proxies and recursion.\\\\n * The resulting copy is guaranteed to be pure data, as well as hardened.\\\\n * Such a hardened, pure copy cannot be used as a communications path.\\\\n *\\\\n * @template T\\\\n * @param {T} val input value. NOTE: Must be hardened!\\\\n * @returns {T} pure, hardened copy\\\\n */\\\\nfunction pureCopy(val, already = new WeakMap()) {\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n const passStyle = passStyleOf(val);\\\\n switch (passStyle) {\\\\n case 'bigint':\\\\n case 'boolean':\\\\n case 'null':\\\\n case 'number':\\\\n case 'string':\\\\n case 'undefined':\\\\n return val;\\\\n\\\\n case 'copyArray':\\\\n case 'copyRecord':{\\\\n const obj = /** @type {Object} */val;\\\\n if (already.has(obj)) {\\\\n return already.get(obj);}\\\\n\\\\n\\\\n /* Create a new identity.*/\\\\n const copy = /** @type {T} */passStyle === 'copyArray' ? [] : {};\\\\n\\\\n /* Prevent recursion.*/\\\\n already.set(obj, copy);\\\\n\\\\n /* Make a deep copy on the new identity.*/\\\\n /* Object.entries(obj) takes a snapshot (even if a Proxy).*/\\\\n Object.entries(obj).forEach(([prop, value]) => {\\\\n copy[prop] = pureCopy(value, already);});\\\\n\\\\n return harden(copy);}\\\\n\\\\n\\\\n case 'copyError':{\\\\n const unk = /** @type {unknown} */val;\\\\n const err = /** @type {Error} */unk;\\\\n\\\\n if (already.has(err)) {\\\\n return already.get(err);}\\\\n\\\\n\\\\n const { name, message } = err;\\\\n\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n const EC = getErrorConstructor(`${name}`) || Error;\\\\n const copy = harden(new EC(`${message}`));\\\\n already.set(err, copy);\\\\n\\\\n const unk2 = /** @type {unknown} */harden(copy);\\\\n return (/** @type {T} */unk2);}\\\\n\\\\n\\\\n case REMOTE_STYLE:{\\\\n throw TypeError(\\\\n `Input value ${passStyle} cannot be copied as must be passed by reference`);}\\\\n\\\\n\\\\n\\\\n default:\\\\n throw TypeError(`Input value ${passStyle} is not recognized as data`);}}\\\\n\\\\n\\\\nharden(pureCopy);\\\\n\\\\n\\\\n/* Special property name that indicates an encoding that needs special*/\\\\n/* decoding.*/\\\\nconst QCLASS = '@qclass';\\\\n\\\\n\\\\n/* objects can only be passed in one of two/three forms:*/\\\\n/* 1: pass-by-remote: all properties (own and inherited) are methods,*/\\\\n/* the object itself is of type object, not function*/\\\\n/* 2: pass-by-copy: all string-named own properties are data, not methods*/\\\\n/* the object must inherit from Object.prototype or null*/\\\\n/* 3: the empty object is pass-by-remote, for identity comparison*/\\\\n\\\\n/* all objects must be frozen*/\\\\n\\\\n/* anything else will throw an error if you try to serialize it*/\\\\n\\\\n/* with these restrictions, our remote call/copy protocols expose all useful*/\\\\n/* behavior of these objects: pass-by-remote objects have no other data (so*/\\\\n/* there's nothing else to copy), and pass-by-copy objects have no other*/\\\\n/* behavior (so there's nothing else to invoke)*/\\\\n\\\\nconst errorConstructors = new Map([\\\\n['Error', Error],\\\\n['EvalError', EvalError],\\\\n['RangeError', RangeError],\\\\n['ReferenceError', ReferenceError],\\\\n['SyntaxError', SyntaxError],\\\\n['TypeError', TypeError],\\\\n['URIError', URIError]]);\\\\n\\\\n\\\\nfunction getErrorConstructor(name) {\\\\n return errorConstructors.get(name);}\\\\n\\\\n\\\\nfunction isPassByCopyError(val) {\\\\n /* TODO: Need a better test than instanceof*/\\\\n if (!(val instanceof Error)) {\\\\n return false;}\\\\n\\\\n const proto = Object.getPrototypeOf(val);\\\\n const { name } = val;\\\\n const EC = getErrorConstructor(name);\\\\n if (!EC || EC.prototype !== proto) {\\\\n throw TypeError(`Must inherit from an error class .prototype ${val}`);}\\\\n\\\\n\\\\n const {\\\\n message: { value: messageStr } = { value: '' },\\\\n /* Allow but ignore only extraneous own `stack` property.*/\\\\n /* TODO: I began the variable below with \\\\\\\"_\\\\\\\". Why do I still need*/\\\\n /* to suppress the lint complaint?*/\\\\n /* eslint-disable-next-line no-unused-vars*/\\\\n stack: _optStackDesc,\\\\n ...restDescs } =\\\\n Object.getOwnPropertyDescriptors(val);\\\\n const restNames = Object.keys(restDescs);\\\\n if (restNames.length >= 1) {\\\\n throw new TypeError(`Unexpected own properties in error: ${restNames}`);}\\\\n\\\\n if (typeof messageStr !== 'string') {\\\\n throw new TypeError(`malformed error object: ${val}`);}\\\\n\\\\n return true;}\\\\n\\\\n\\\\nfunction isPassByCopyArray(val) {\\\\n if (!Array.isArray(val)) {\\\\n return false;}\\\\n\\\\n if (Object.getPrototypeOf(val) !== Array.prototype) {\\\\n throw new TypeError(`malformed array: ${val}`);}\\\\n\\\\n const len = val.length;\\\\n const descs = Object.getOwnPropertyDescriptors(val);\\\\n for (let i = 0; i < len; i += 1) {\\\\n const desc = descs[i];\\\\n if (!desc) {\\\\n throw new TypeError(`arrays must not contain holes`);}\\\\n\\\\n if (!('value' in desc)) {\\\\n throw new TypeError(`arrays must not contain accessors`);}\\\\n\\\\n if (typeof desc.value === 'function') {\\\\n throw new TypeError(`arrays must not contain methods`);}}\\\\n\\\\n\\\\n if (Object.keys(descs).length !== len + 1) {\\\\n throw new TypeError(`array must not have non-indexes ${val}`);}\\\\n\\\\n return true;}\\\\n\\\\n\\\\nfunction isPassByCopyRecord(val) {\\\\n if (Object.getPrototypeOf(val) !== Object.prototype) {\\\\n return false;}\\\\n\\\\n const descList = Object.values(Object.getOwnPropertyDescriptors(val));\\\\n if (descList.length === 0) {\\\\n /* empty non-array objects are pass-by-remote, not pass-by-copy*/\\\\n return false;}\\\\n\\\\n for (const desc of descList) {\\\\n if (!('value' in desc)) {\\\\n /* Should we error if we see an accessor here?*/\\\\n return false;}\\\\n\\\\n if (typeof desc.value === 'function') {\\\\n return false;}}\\\\n\\\\n\\\\n return true;}\\\\n\\\\n\\\\n/**\\\\n * Ensure that val could become a legitimate remotable. This is used internally both\\\\n * in the construction of a new remotable and mustPassByRemote.\\\\n *\\\\n * @param {*} val The remotable candidate to check\\\\n */\\\\nfunction assertCanBeRemotable(val) {\\\\n /* throws exception if cannot*/\\\\n if (typeof val !== 'object') {\\\\n throw new Error(`cannot serialize non-objects like ${val}`);}\\\\n\\\\n if (Array.isArray(val)) {\\\\n throw new Error(`Arrays cannot be pass-by-remote`);}\\\\n\\\\n if (val === null) {\\\\n throw new Error(`null cannot be pass-by-remote`);}\\\\n\\\\n\\\\n const names = Object.getOwnPropertyNames(val);\\\\n names.forEach(name => {\\\\n if (typeof val[name] !== 'function') {\\\\n throw new Error(\\\\n `cannot serialize objects with non-methods like the .${name} in ${val}`);\\\\n\\\\n /* return false;*/}});\\\\n\\\\n\\\\n\\\\n /* ok!*/}\\\\n\\\\n\\\\nfunction mustPassByRemote(val) {\\\\n if (!Object.isFrozen(val)) {\\\\n throw new Error(`cannot serialize non-frozen objects like ${val}`);}\\\\n\\\\n\\\\n if (getInterfaceOf(val) === undefined) {\\\\n /* Not a registered Remotable, so check its contents.*/\\\\n assertCanBeRemotable(val);}\\\\n\\\\n\\\\n /* It's not a registered Remotable, so enforce the prototype check.*/\\\\n const p = Object.getPrototypeOf(val);\\\\n if (p !== null && p !== Object.prototype) {\\\\n mustPassByRemote(p);}}\\\\n\\\\n\\\\n\\\\n/* This is the equality comparison used by JavaScript's Map and Set*/\\\\n/* abstractions, where NaN is the same as NaN and -0 is the same as*/\\\\n/* 0. Marshal serializes -0 as zero, so the semantics of our distributed*/\\\\n/* object system does not distinguish 0 from -0.*/\\\\n/**/\\\\n/* `sameValueZero` is the EcmaScript spec name for this equality comparison,*/\\\\n/* but TODO we need a better name for the API.*/\\\\nfunction sameValueZero(x, y) {\\\\n return x === y || Object.is(x, y);}\\\\n\\\\n\\\\n/* How would val be passed? For primitive values, the answer is*/\\\\n/* * 'null' for null*/\\\\n/* * throwing an error for a symbol, whether registered or not.*/\\\\n/* * that value's typeof string for all other primitive values*/\\\\n/* For frozen objects, the possible answers*/\\\\n/* * 'copyRecord' for non-empty records with only data properties*/\\\\n/* * 'copyArray' for arrays with only data properties*/\\\\n/* * 'copyError' for instances of Error with only data properties*/\\\\n/* * REMOTE_STYLE for non-array objects with only method properties*/\\\\n/* * 'promise' for genuine promises only*/\\\\n/* * throwing an error on anything else, including thenables.*/\\\\n/* We export passStyleOf so other algorithms can use this module's*/\\\\n/* classification.*/\\\\nfunction passStyleOf(val) {\\\\n const typestr = typeof val;\\\\n switch (typestr) {\\\\n case 'object':{\\\\n if (getInterfaceOf(val)) {\\\\n return REMOTE_STYLE;}\\\\n\\\\n if (val === null) {\\\\n return 'null';}\\\\n\\\\n if (QCLASS in val) {\\\\n /* TODO Hilbert hotel*/\\\\n throw new Error(`property \\\\\\\"${QCLASS}\\\\\\\" reserved`);}\\\\n\\\\n if (!Object.isFrozen(val)) {\\\\n throw new Error(\\\\n `Cannot pass non-frozen objects like ${val}. Use harden()`);}\\\\n\\\\n\\\\n if (producePromise.isPromise(val)) {\\\\n return 'promise';}\\\\n\\\\n if (typeof val.then === 'function') {\\\\n throw new Error(`Cannot pass non-promise thenables`);}\\\\n\\\\n if (isPassByCopyError(val)) {\\\\n return 'copyError';}\\\\n\\\\n if (isPassByCopyArray(val)) {\\\\n return 'copyArray';}\\\\n\\\\n if (isPassByCopyRecord(val)) {\\\\n return 'copyRecord';}\\\\n\\\\n mustPassByRemote(val);\\\\n return REMOTE_STYLE;}\\\\n\\\\n case 'function':{\\\\n throw new Error(`Bare functions like ${val} are disabled for now`);}\\\\n\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'bigint':{\\\\n return typestr;}\\\\n\\\\n case 'symbol':{\\\\n throw new TypeError('Cannot pass symbols');}\\\\n\\\\n default:{\\\\n throw new TypeError(`Unrecognized typeof ${typestr}`);}}}\\\\n\\\\n\\\\n\\\\n\\\\n/* The ibid logic relies on*/\\\\n/* * JSON.stringify on an array visiting array indexes from 0 to*/\\\\n/* arr.length -1 in order, and not visiting anything else.*/\\\\n/* * JSON.parse of a record (a plain object) creating an object on*/\\\\n/* which a getOwnPropertyNames will enumerate properties in the*/\\\\n/* same order in which they appeared in the parsed JSON string.*/\\\\n\\\\nfunction makeReplacerIbidTable() {\\\\n const ibidMap = new Map();\\\\n let ibidCount = 0;\\\\n\\\\n return harden({\\\\n has(obj) {\\\\n return ibidMap.has(obj);},\\\\n\\\\n get(obj) {\\\\n return ibidMap.get(obj);},\\\\n\\\\n add(obj) {\\\\n ibidMap.set(obj, ibidCount);\\\\n ibidCount += 1;} });}\\\\n\\\\n\\\\n\\\\n\\\\nfunction makeReviverIbidTable(cyclePolicy) {\\\\n const ibids = [];\\\\n const unfinishedIbids = new WeakSet();\\\\n\\\\n return harden({\\\\n get(allegedIndex) {\\\\n const index = nat_esm.default(allegedIndex);\\\\n if (index >= ibids.length) {\\\\n throw new RangeError(`ibid out of range: ${index}`);}\\\\n\\\\n const result = ibids[index];\\\\n if (unfinishedIbids.has(result)) {\\\\n switch (cyclePolicy) {\\\\n case 'allowCycles':{\\\\n break;}\\\\n\\\\n case 'warnOfCycles':{\\\\n console.log(`Warning: ibid cycle at ${index}`);\\\\n break;}\\\\n\\\\n case 'forbidCycles':{\\\\n throw new TypeError(`Ibid cycle at ${index}`);}\\\\n\\\\n default:{\\\\n throw new TypeError(`Unrecognized cycle policy: ${cyclePolicy}`);}}}\\\\n\\\\n\\\\n\\\\n return result;},\\\\n\\\\n register(obj) {\\\\n ibids.push(obj);\\\\n return obj;},\\\\n\\\\n start(obj) {\\\\n ibids.push(obj);\\\\n unfinishedIbids.add(obj);\\\\n return obj;},\\\\n\\\\n finish(obj) {\\\\n unfinishedIbids.delete(obj);\\\\n return obj;} });}\\\\n\\\\n\\\\n\\\\n\\\\nconst identityFn = x => x;\\\\n\\\\nfunction makeMarshal(\\\\nconvertValToSlot = identityFn,\\\\nconvertSlotToVal = identityFn)\\\\n{\\\\n function serializeSlot(val, slots, slotMap) {\\\\n let slotIndex;\\\\n if (slotMap.has(val)) {\\\\n slotIndex = slotMap.get(val);} else\\\\n {\\\\n const slot = convertValToSlot(val);\\\\n\\\\n slotIndex = slots.length;\\\\n slots.push(slot);\\\\n slotMap.set(val, slotIndex);}\\\\n\\\\n\\\\n return harden({\\\\n [QCLASS]: 'slot',\\\\n index: slotIndex });}\\\\n\\\\n\\\\n\\\\n function makeReplacer(slots, slotMap) {\\\\n const ibidTable = makeReplacerIbidTable();\\\\n\\\\n return function replacer(_, val) {\\\\n /* First we handle all primitives. Some can be represented directly as*/\\\\n /* JSON, and some must be encoded as [QCLASS] composites.*/\\\\n const passStyle = passStyleOf(val);\\\\n switch (passStyle) {\\\\n case 'null':{\\\\n return null;}\\\\n\\\\n case 'undefined':{\\\\n return harden({ [QCLASS]: 'undefined' });}\\\\n\\\\n case 'string':\\\\n case 'boolean':{\\\\n return val;}\\\\n\\\\n case 'number':{\\\\n if (Number.isNaN(val)) {\\\\n return harden({ [QCLASS]: 'NaN' });}\\\\n\\\\n if (Object.is(val, -0)) {\\\\n return 0;}\\\\n\\\\n if (val === Infinity) {\\\\n return harden({ [QCLASS]: 'Infinity' });}\\\\n\\\\n if (val === -Infinity) {\\\\n return harden({ [QCLASS]: '-Infinity' });}\\\\n\\\\n return val;}\\\\n\\\\n case 'bigint':{\\\\n return harden({\\\\n [QCLASS]: 'bigint',\\\\n digits: String(val) });}\\\\n\\\\n\\\\n default:{\\\\n /* if we've seen this object before, serialize a backref*/\\\\n if (ibidTable.has(val)) {\\\\n /* Backreference to prior occurrence*/\\\\n return harden({\\\\n [QCLASS]: 'ibid',\\\\n index: ibidTable.get(val) });}\\\\n\\\\n\\\\n ibidTable.add(val);\\\\n\\\\n switch (passStyle) {\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n /* console.log(`canPassByCopy: ${val}`);*/\\\\n /* Purposely in-band for readability, but creates need for*/\\\\n /* Hilbert hotel.*/\\\\n return val;}\\\\n\\\\n case 'copyError':{\\\\n /* We deliberately do not share the stack, but it would*/\\\\n /* be useful to log the stack locally so someone who has*/\\\\n /* privileged access to the throwing Vat can correlate*/\\\\n /* the problem with the remote Vat that gets this*/\\\\n /* summary. If we do that, we could allocate some random*/\\\\n /* identifier and include it in the message, to help*/\\\\n /* with the correlation.*/\\\\n return harden({\\\\n [QCLASS]: 'error',\\\\n name: `${val.name}`,\\\\n message: `${val.message}` });}\\\\n\\\\n\\\\n case REMOTE_STYLE:\\\\n case 'promise':{\\\\n /* console.log(`serializeSlot: ${val}`);*/\\\\n return serializeSlot(val, slots, slotMap);}\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${passStyle}`);}}}}};}\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n /* val might be a primitive, a pass by (shallow) copy object, a*/\\\\n /* remote reference, or other. We treat all other as a local object*/\\\\n /* to be exported as a local webkey.*/\\\\n function serialize(val) {\\\\n const slots = [];\\\\n const slotMap = new Map(); /* maps val (promise or remotable) to*/\\\\n /* index of slots[]*/\\\\n return harden({\\\\n body: JSON.stringify(val, makeReplacer(slots, slotMap)),\\\\n slots });}\\\\n\\\\n\\\\n\\\\n function makeFullRevive(slots, cyclePolicy) {\\\\n /* ibid table is shared across recursive calls to fullRevive.*/\\\\n const ibidTable = makeReviverIbidTable(cyclePolicy);\\\\n\\\\n /* We stay close to the algorith at*/\\\\n /* https://tc39.github.io/ecma262/#sec-json.parse , where*/\\\\n /* fullRevive(JSON.parse(str)) is like JSON.parse(str, revive))*/\\\\n /* for a similar reviver. But with the following differences:*/\\\\n /**/\\\\n /* Rather than pass a reviver to JSON.parse, we first call a plain*/\\\\n /* (one argument) JSON.parse to get rawTree, and then post-process*/\\\\n /* the rawTree with fullRevive. The kind of revive function*/\\\\n /* handled by JSON.parse only does one step in post-order, with*/\\\\n /* JSON.parse doing the recursion. By contrast, fullParse does its*/\\\\n /* own recursion, enabling it to interpret ibids in the same*/\\\\n /* pre-order in which the replacer visited them, and enabling it*/\\\\n /* to break cycles.*/\\\\n /**/\\\\n /* In order to break cycles, the potentially cyclic objects are*/\\\\n /* not frozen during the recursion. Rather, the whole graph is*/\\\\n /* hardened before being returned. Error objects are not*/\\\\n /* potentially recursive, and so may be harmlessly hardened when*/\\\\n /* they are produced.*/\\\\n /**/\\\\n /* fullRevive can produce properties whose value is undefined,*/\\\\n /* which a JSON.parse on a reviver cannot do. If a reviver returns*/\\\\n /* undefined to JSON.parse, JSON.parse will delete the property*/\\\\n /* instead.*/\\\\n /**/\\\\n /* fullRevive creates and returns a new graph, rather than*/\\\\n /* modifying the original tree in place.*/\\\\n /**/\\\\n /* fullRevive may rely on rawTree being the result of a plain call*/\\\\n /* to JSON.parse. However, it *cannot* rely on it having been*/\\\\n /* produced by JSON.stringify on the replacer above, i.e., it*/\\\\n /* cannot rely on it being a valid marshalled*/\\\\n /* representation. Rather, fullRevive must validate that.*/\\\\n return function fullRevive(rawTree) {\\\\n if (Object(rawTree) !== rawTree) {\\\\n /* primitives pass through*/\\\\n return rawTree;}\\\\n\\\\n if (QCLASS in rawTree) {\\\\n const qclass = rawTree[QCLASS];\\\\n if (typeof qclass !== 'string') {\\\\n throw new TypeError(`invalid qclass typeof ${typeof qclass}`);}\\\\n\\\\n switch (qclass) {\\\\n /* Encoding of primitives not handled by JSON*/\\\\n case 'undefined':{\\\\n return undefined;}\\\\n\\\\n case 'NaN':{\\\\n return NaN;}\\\\n\\\\n case 'Infinity':{\\\\n return Infinity;}\\\\n\\\\n case '-Infinity':{\\\\n return -Infinity;}\\\\n\\\\n case 'bigint':{\\\\n if (typeof rawTree.digits !== 'string') {\\\\n throw new TypeError(\\\\n `invalid digits typeof ${typeof rawTree.digits}`);}\\\\n\\\\n\\\\n /* eslint-disable-next-line no-undef */\\\\n return BigInt(rawTree.digits);}\\\\n\\\\n\\\\n case 'ibid':{\\\\n return ibidTable.get(rawTree.index);}\\\\n\\\\n\\\\n case 'error':{\\\\n if (typeof rawTree.name !== 'string') {\\\\n throw new TypeError(\\\\n `invalid error name typeof ${typeof rawTree.name}`);}\\\\n\\\\n\\\\n if (typeof rawTree.message !== 'string') {\\\\n throw new TypeError(\\\\n `invalid error message typeof ${typeof rawTree.message}`);}\\\\n\\\\n\\\\n const EC = getErrorConstructor(`${rawTree.name}`) || Error;\\\\n return ibidTable.register(harden(new EC(`${rawTree.message}`)));}\\\\n\\\\n\\\\n case 'slot':{\\\\n const slot = slots[nat_esm.default(rawTree.index)];\\\\n return ibidTable.register(convertSlotToVal(slot));}\\\\n\\\\n\\\\n default:{\\\\n /* TODO reverse Hilbert hotel*/\\\\n throw new TypeError(`unrecognized ${QCLASS} ${qclass}`);}}} else\\\\n\\\\n\\\\n if (Array.isArray(rawTree)) {\\\\n const result = ibidTable.start([]);\\\\n const len = rawTree.length;\\\\n for (let i = 0; i < len; i += 1) {\\\\n result[i] = fullRevive(rawTree[i]);}\\\\n\\\\n return ibidTable.finish(result);} else\\\\n {\\\\n const result = ibidTable.start({});\\\\n const names = Object.getOwnPropertyNames(rawTree);\\\\n for (const name of names) {\\\\n result[name] = fullRevive(rawTree[name]);}\\\\n\\\\n return ibidTable.finish(result);}};}\\\\n\\\\n\\\\n\\\\n\\\\n function unserialize(data, cyclePolicy = 'forbidCycles') {\\\\n if (data.body !== `${data.body}`) {\\\\n throw new Error(\\\\n `unserialize() given non-capdata (.body is ${data.body}, not string)`);}\\\\n\\\\n\\\\n if (!Array.isArray(data.slots)) {\\\\n throw new Error(`unserialize() given non-capdata (.slots are not Array)`);}\\\\n\\\\n const rawTree = harden(JSON.parse(data.body));\\\\n const fullRevive = makeFullRevive(data.slots, cyclePolicy);\\\\n return harden(fullRevive(rawTree));}\\\\n\\\\n\\\\n return harden({\\\\n serialize,\\\\n unserialize });}\\\\n\\\\n\\\\n\\\\n/**\\\\n * Create and register a Remotable. After this, getInterfaceOf(remotable)\\\\n * returns iface.\\\\n *\\\\n * // https://github.com/Agoric/agoric-sdk/issues/804\\\\n *\\\\n * @param {InterfaceSpec} [iface='Remotable'] The interface specification for the remotable\\\\n * @param {object} [props={}] Own-properties are copied to the remotable\\\\n * @param {object} [remotable={}] The object used as the remotable\\\\n * @returns {object} remotable, modified for debuggability\\\\n */\\\\nfunction Remotable(iface = 'Remotable', props = {}, remotable = {}) {\\\\n iface = pureCopy(harden(iface));\\\\n const ifaceType = typeof iface;\\\\n\\\\n /* Find the alleged name.*/\\\\n if (ifaceType !== 'string') {\\\\n throw Error(`Interface must be a string, not ${ifaceType}; unimplemented`);}\\\\n\\\\n\\\\n /* TODO: When iface is richer than just string, we need to get the allegedName*/\\\\n /* in a different way.*/\\\\n const allegedName = iface;\\\\n\\\\n /* Fail fast: check that the unmodified object is able to become a Remotable.*/\\\\n assertCanBeRemotable(remotable);\\\\n\\\\n /* Ensure that the remotable isn't already registered.*/\\\\n if (remotableToInterface.has(remotable)) {\\\\n throw Error(`Remotable ${remotable} is already mapped to an interface`);}\\\\n\\\\n\\\\n /* A prototype for debuggability.*/\\\\n const oldRemotableProto = harden(Object.getPrototypeOf(remotable));\\\\n\\\\n /* Fail fast: create a fresh empty object with the old*/\\\\n /* prototype in order to check it against our rules.*/\\\\n mustPassByRemote(harden(Object.create(oldRemotableProto)));\\\\n\\\\n /* Assign the arrow function to a variable to set its .name.*/\\\\n const toString = () => `[${allegedName}]`;\\\\n const remotableProto = harden(\\\\n Object.create(oldRemotableProto, {\\\\n toString: {\\\\n value: toString,\\\\n enumerable: false },\\\\n\\\\n [Symbol.toStringTag]: {\\\\n value: allegedName,\\\\n enumerable: false } }));\\\\n\\\\n\\\\n\\\\n\\\\n /* Take a static copy of the properties.*/\\\\n const propEntries = Object.entries(props);\\\\n const mutateHardenAndCheck = target => {\\\\n /* Add the snapshotted properties.*/\\\\n /** @type {PropertyDescriptorMap} */\\\\n const newProps = {};\\\\n propEntries.forEach(([prop, value]) => newProps[prop] = { value });\\\\n Object.defineProperties(target, newProps);\\\\n\\\\n /* Set the prototype for debuggability.*/\\\\n Object.setPrototypeOf(target, remotableProto);\\\\n harden(remotableProto);\\\\n\\\\n harden(target);\\\\n assertCanBeRemotable(target);\\\\n return target;};\\\\n\\\\n\\\\n /* Fail fast: check a fresh remotable to see if our rules fit.*/\\\\n const throwawayRemotable = Object.create(oldRemotableProto);\\\\n mutateHardenAndCheck(throwawayRemotable);\\\\n\\\\n /* Actually finish the new remotable.*/\\\\n mutateHardenAndCheck(remotable);\\\\n\\\\n /* COMMITTED!*/\\\\n /* We're committed, so keep the interface for future reference.*/\\\\n remotableToInterface.set(remotable, iface);\\\\n return remotable;}\\\\n\\\\n\\\\nharden(Remotable);exports.QCLASS = QCLASS;exports.Remotable = Remotable;exports.getErrorConstructor = getErrorConstructor;exports.getInterfaceOf = getInterfaceOf;exports.makeMarshal = makeMarshal;exports.mustPassByPresence = mustPassByRemote;exports.mustPassByRemote = mustPassByRemote;exports.passStyleOf = passStyleOf;exports.pureCopy = pureCopy;exports.sameValueZero = sameValueZero;\\\",\\n \\\"packages/same-structure/src/sameStructure.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../assert/src/assert.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nmarshal = require('../../marshal/marshal.js'); /* global harden */ /* Shim of Object.fromEntries from*/ /* https://github.com/tc39/proposal-object-from-entries/blob/master/polyfill.js*/\\\\nfunction ObjectFromEntries(iter) {\\\\n const obj = {};\\\\n\\\\n for (const pair of iter) {\\\\n if (Object(pair) !== pair) {\\\\n throw new TypeError('iterable for fromEntries should yield objects');}\\\\n\\\\n\\\\n /* Consistency with Map: contract is that entry has \\\\\\\"0\\\\\\\" and \\\\\\\"1\\\\\\\" keys, not*/\\\\n /* that it is an array or iterable.*/\\\\n\\\\n const { '0': key, '1': val } = pair;\\\\n\\\\n Object.defineProperty(obj, key, {\\\\n configurable: true,\\\\n enumerable: true,\\\\n writable: true,\\\\n value: val });}\\\\n\\\\n\\\\n\\\\n return obj;}\\\\n\\\\n\\\\n/* A *passable* is something that may be marshalled. It consists of a*/\\\\n/* graph of pass-by-copy data terminating in leaves of passable*/\\\\n/* non-pass-by-copy data. These leaves may be promises, or*/\\\\n/* pass-by-presence objects. A *comparable* is a passable whose leaves*/\\\\n/* contain no promises. Two comparables can be synchronously compared*/\\\\n/* for structural equivalence.*/\\\\n/**/\\\\n/* TODO: Currently, all algorithms here treat the pass-by-copy*/\\\\n/* superstructure as a tree. This means that dags are unwound at*/\\\\n/* potentially exponential cost, and cycles cause failure to*/\\\\n/* terminate. We must fix both problems, making all these algorithms*/\\\\n/* graph-aware.*/\\\\n\\\\n/* We say that a function *reveals* an X when it returns either an X*/\\\\n/* or a promise for an X.*/\\\\n\\\\n/* Given a passable, reveal a corresponding comparable, where each*/\\\\n/* leaf promise of the passable has been replaced with its*/\\\\n/* corresponding comparable.*/\\\\nfunction allComparable(passable) {\\\\n const passStyle = marshal.passStyleOf(passable);\\\\n switch (passStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':\\\\n case 'copyError':{\\\\n return passable;}\\\\n\\\\n case 'promise':{\\\\n return passable.then(nonp => allComparable(nonp));}\\\\n\\\\n case 'copyArray':{\\\\n const valPs = passable.map(p => allComparable(p));\\\\n return Promise.all(valPs).then(vals => harden(vals));}\\\\n\\\\n case 'copyRecord':{\\\\n const names = Object.getOwnPropertyNames(passable);\\\\n const valPs = names.map(name => allComparable(passable[name]));\\\\n return Promise.all(valPs).then((vals) =>\\\\n harden(ObjectFromEntries(vals.map((val, i) => [names[i], val]))));}\\\\n\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${passStyle}`);}}}\\\\n\\\\n\\\\n\\\\nharden(allComparable);\\\\n\\\\n/* Are left and right structurally equivalent comparables? This*/\\\\n/* compares pass-by-copy data deeply until non-pass-by-copy values are*/\\\\n/* reached. The non-pass-by-copy values at the leaves of the*/\\\\n/* comparison may only be pass-by-presence objects. If they are*/\\\\n/* anything else, including promises, throw an error.*/\\\\n/**/\\\\n/* Pass-by-presence objects compare identities.*/\\\\n\\\\nfunction sameStructure(left, right) {\\\\n const leftStyle = marshal.passStyleOf(left);\\\\n const rightStyle = marshal.passStyleOf(right);\\\\n assert.assert(\\\\n leftStyle !== 'promise',\\\\n assert.details`Cannot structurally compare promises: ${left}`);\\\\n\\\\n assert.assert(\\\\n rightStyle !== 'promise',\\\\n assert.details`Cannot structurally compare promises: ${right}`);\\\\n\\\\n\\\\n if (leftStyle !== rightStyle) {\\\\n return false;}\\\\n\\\\n switch (leftStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':{\\\\n return marshal.sameValueZero(left, right);}\\\\n\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n const leftNames = Object.getOwnPropertyNames(left);\\\\n const rightNames = Object.getOwnPropertyNames(right);\\\\n if (leftNames.length !== rightNames.length) {\\\\n return false;}\\\\n\\\\n for (const name of leftNames) {\\\\n /* TODO: Better hasOwnProperty check*/\\\\n if (!Object.getOwnPropertyDescriptor(right, name)) {\\\\n return false;}\\\\n\\\\n /* TODO: Make cycle tolerant*/\\\\n if (!sameStructure(left[name], right[name])) {\\\\n return false;}}\\\\n\\\\n\\\\n return true;}\\\\n\\\\n case 'copyError':{\\\\n return left.name === right.name && left.message === right.message;}\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${leftStyle}`);}}}\\\\n\\\\n\\\\n\\\\nharden(sameStructure);\\\\n\\\\nfunction pathStr(path) {\\\\n if (path === null) {\\\\n return 'top';}\\\\n\\\\n const [base, index] = path;\\\\n let i = index;\\\\n const baseStr = pathStr(base);\\\\n if (typeof i === 'string' && /^[a-zA-Z]\\\\\\\\w*$/.test(i)) {\\\\n return `${baseStr}.${i}`;}\\\\n\\\\n if (typeof i === 'string' && `${+i}` === i) {\\\\n i = +i;}\\\\n\\\\n return `${baseStr}[${JSON.stringify(i)}]`;}\\\\n\\\\n\\\\n/* TODO: Reduce redundancy between sameStructure and*/\\\\n/* mustBeSameStructureInternal*/\\\\nfunction mustBeSameStructureInternal(left, right, message, path) {\\\\n function complain(problem) {\\\\n assert.assert.fail(\\\\n assert.details`${assert.q(message)}: ${assert.q(problem)} at ${assert.q(\\\\n pathStr(path))\\\\n }: (${left}) vs (${right})`);}\\\\n\\\\n\\\\n\\\\n const leftStyle = marshal.passStyleOf(left);\\\\n const rightStyle = marshal.passStyleOf(right);\\\\n if (leftStyle === 'promise') {\\\\n complain('Promise on left');}\\\\n\\\\n if (rightStyle === 'promise') {\\\\n complain('Promise on right');}\\\\n\\\\n\\\\n if (leftStyle !== rightStyle) {\\\\n complain('different passing style');}\\\\n\\\\n switch (leftStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':{\\\\n if (!marshal.sameValueZero(left, right)) {\\\\n complain('different');}\\\\n\\\\n break;}\\\\n\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n const leftNames = Object.getOwnPropertyNames(left);\\\\n const rightNames = Object.getOwnPropertyNames(right);\\\\n if (leftNames.length !== rightNames.length) {\\\\n complain(`${leftNames.length} vs ${rightNames.length} own properties`);}\\\\n\\\\n for (const name of leftNames) {\\\\n /* TODO: Better hasOwnProperty check*/\\\\n if (!Object.getOwnPropertyDescriptor(right, name)) {\\\\n complain(`${name} not found on right`);}\\\\n\\\\n /* TODO: Make cycle tolerant*/\\\\n mustBeSameStructureInternal(left[name], right[name], message, [\\\\n path,\\\\n name]);}\\\\n\\\\n\\\\n break;}\\\\n\\\\n case 'copyError':{\\\\n if (left.name !== right.name) {\\\\n complain(`different error name: ${left.name} vs ${right.name}`);}\\\\n\\\\n if (left.message !== right.message) {\\\\n complain(\\\\n `different error message: ${left.message} vs ${right.message}`);}\\\\n\\\\n\\\\n break;}\\\\n\\\\n default:{\\\\n complain(`unrecognized passStyle ${leftStyle}`);\\\\n break;}}}\\\\n\\\\n\\\\n\\\\nfunction mustBeSameStructure(left, right, message) {\\\\n mustBeSameStructureInternal(left, right, `${message}`, null);}\\\\n\\\\nharden(mustBeSameStructure);\\\\n\\\\n/* If `val` would be a valid input to `sameStructure`, return*/\\\\n/* normally. Otherwise error.*/\\\\nfunction mustBeComparable(val) {\\\\n mustBeSameStructure(val, val, 'not comparable');}exports.allComparable = allComparable;exports.mustBeComparable = mustBeComparable;exports.mustBeSameStructure = mustBeSameStructure;exports.sameStructure = sameStructure;\\\",\\n \\\"packages/zoe/src/offerSafety.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /**\\\\n * @typedef {Ximport('@agoric/ertp/src/issuer').Brand} Brand\\\\n * @typedef {Ximport('@agoric/ertp/src/issuer').AmountMath} AmountMath\\\\n * @typedef {Ximport('./zoe').Proposal} Proposal\\\\n * @typedef {Ximport('./zoe').AmountKeywordRecord} AmountKeywordRecord\\\\n */ /**\\\\n * Helper to perform satisfiesWant and satisfiesGive. Is\\\\n * allocationAmount greater than or equal to requiredAmount for every\\\\n * keyword of giveOrWant?\\\\n * @param {(Brand) => AmountMath} getAmountMath\\\\n * @param {Proposal[\\\\\\\"give\\\\\\\"] | Proposal[\\\\\\\"want\\\\\\\"]} giveOrWant\\\\n * @param {AmountKeywordRecord} allocation\\\\n */const satisfiesInternal = (getAmountMath, giveOrWant, allocation) => {const isGTEByKeyword = ([keyword, requiredAmount]) => {/* If there is no allocation for a keyword, we know the giveOrWant*/ /* is not satisfied without checking further.*/if (allocation[keyword] === undefined) {\\\\n return false;}\\\\n\\\\n const amountMath = getAmountMath(requiredAmount.brand);\\\\n const allocationAmount = allocation[keyword];\\\\n return amountMath.isGTE(allocationAmount, requiredAmount);};\\\\n\\\\n return Object.entries(giveOrWant).every(isGTEByKeyword);};\\\\n\\\\n\\\\n/**\\\\n * For this allocation to satisfy what the user wanted, their\\\\n * allocated amounts must be greater than or equal to proposal.want.\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.want.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nconst satisfiesWant = (getAmountMath, proposal, allocation) =>\\\\nsatisfiesInternal(getAmountMath, proposal.want, allocation);\\\\n\\\\n/**\\\\n * For this allocation to count as a full refund, the allocated\\\\n * amounts must be greater than or equal to what was originally\\\\n * offered (proposal.give).\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.give.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nconst satisfiesGive = (getAmountMath, proposal, allocation) =>\\\\nsatisfiesInternal(getAmountMath, proposal.give, allocation);\\\\n\\\\n/**\\\\n * `isOfferSafe` checks offer safety for a single offer.\\\\n *\\\\n * Note: This implementation checks whether we fully satisfy\\\\n * `proposal.give` (giving a refund) or whether we fully satisfy\\\\n * `proposal.want`. Both can be fully satisfied.\\\\n *\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.want and\\\\n * proposal.give.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nfunction isOfferSafe(getAmountMath, proposal, allocation) {\\\\n return (\\\\n satisfiesGive(getAmountMath, proposal, allocation) ||\\\\n satisfiesWant(getAmountMath, proposal, allocation));}exports.isOfferSafe = isOfferSafe;exports.satisfiesWant = satisfiesWant;\\\",\\n \\\"packages/zoe/src/contractSupport/zoeHelpers.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../../assert/src/assert.js');var index = require('../../../eventual-send/src/index.js');var sameStructure = require('../../../same-structure/src/sameStructure.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nofferSafety = require('../offerSafety.js'); /* global harden */ /**\\\\n * @typedef {Ximport('../zoe').OfferHandle} OfferHandle\\\\n * @typedef {Ximport('../zoe').Invite} Invite\\\\n * @typedef {Ximport('../zoe').OfferHook} OfferHook\\\\n * @typedef {Ximport('../zoe').CustomProperties} CustomProperties\\\\n * @typedef {Ximport('../zoe').ContractFacet} ContractFacet\\\\n * @typedef {Ximport('../zoe').Keyword} Keyword\\\\n * @typedef {Ximport('../zoe').AmountKeywordRecord} AmountKeywordRecord\\\\n * @typedef {Ximport('../zoe').Amount} Amount\\\\n * @typedef {Ximport('../zoe').Payment} Payment\\\\n */\\\\n\\\\nconst defaultRejectMsg = `The offer was invalid. Please check your refund.`;\\\\nconst defaultAcceptanceMsg = `The offer has been accepted. Once the contract has been completed, please check your payout`;\\\\n\\\\nconst getKeys = obj => harden(Object.getOwnPropertyNames(obj || {}));\\\\nconst getKeysSorted = (obj) =>\\\\nharden(Object.getOwnPropertyNames(obj || {}).sort());\\\\n/**\\\\n * @function makeZoeHelpers - makes an object with helper functions useful to zoe contracts.\\\\n *\\\\n * @param {ContractFacet} zcf\\\\n */\\\\n/* zcf only picks up the type if the param is in parens, which eslint dislikes*/\\\\n/* eslint-disable-next-line*/\\\\nconst makeZoeHelpers = zcf => {\\\\n const zoeService = zcf.getZoeService();\\\\n\\\\n const rejectOffer = (offerHandle, msg = defaultRejectMsg) => {\\\\n zcf.complete(harden([offerHandle]));\\\\n assert.assert.fail(msg);};\\\\n\\\\n\\\\n /* Compare the keys of actual with expected keys and reject offer if*/\\\\n /* not sameStructure. If expectedKeys is undefined, no comparison occurs.*/\\\\n const rejectKeysIf = (\\\\n offerHandle,\\\\n actual,\\\\n expected,\\\\n msg = defaultRejectMsg) =>\\\\n /* eslint-disable-next-line consistent-return*/\\\\n {\\\\n if (expected !== undefined) {\\\\n if (!sameStructure.sameStructure(getKeysSorted(actual), getKeysSorted(expected))) {\\\\n return rejectOffer(offerHandle, msg);}}};\\\\n\\\\n\\\\n\\\\n /* Compare actual keys to expected keys. If expectedKeys is*/\\\\n /* undefined, return true trivially.*/\\\\n const checkKeys = (actual, expected) => {\\\\n if (expected === undefined) {\\\\n return true;}\\\\n\\\\n return sameStructure.sameStructure(getKeysSorted(actual), getKeysSorted(expected));};\\\\n\\\\n\\\\n /**\\\\n * Given toGains (an AmountKeywordRecord), and allocations (a pair,\\\\n * 'to' and 'from', of AmountKeywordRecords), all the entries in\\\\n * toGains will be added to 'to'. If fromLosses is defined, all the\\\\n * entries in fromLosses are subtracted from 'from'. (If fromLosses\\\\n * is not defined, toGains is subtracted from 'from'.)\\\\n *\\\\n * @param {FromToAllocations} allocations - the 'to' and 'from'\\\\n * allocations\\\\n * @param {AmountKeywordRecord} toGains - what should be gained in\\\\n * the 'to' allocation\\\\n * @param {AmountKeywordRecord} fromLosses - what should be lost in\\\\n * the 'from' allocation. If not defined, fromLosses is equal to\\\\n * toGains. Note that the total amounts should always be equal; it\\\\n * is the keywords that might be different.\\\\n * @returns {FromToAllocations} allocations - new allocations\\\\n *\\\\n * @typedef FromToAllocations\\\\n * @property {AmountKeywordRecord} from\\\\n * @property {AmountKeywordRecord} to\\\\n */\\\\n const calcNewAllocations = (allocations, toGains, fromLosses = undefined) => {\\\\n if (fromLosses === undefined) {\\\\n fromLosses = toGains;}\\\\n\\\\n\\\\n const subtract = (amount, amountToSubtract) => {\\\\n const { brand } = amount;\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n if (amountToSubtract !== undefined) {\\\\n return amountMath.subtract(amount, amountToSubtract);}\\\\n\\\\n return amount;};\\\\n\\\\n\\\\n const add = (amount, amountToAdd) => {\\\\n if (amount && amountToAdd) {\\\\n const { brand } = amount;\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n return amountMath.add(amount, amountToAdd);}\\\\n\\\\n return amount || amountToAdd;};\\\\n\\\\n\\\\n const newFromAllocation = Object.fromEntries(\\\\n Object.entries(allocations.from).map(([keyword, allocAmount]) => {\\\\n return [keyword, subtract(allocAmount, fromLosses[keyword])];}));\\\\n\\\\n\\\\n\\\\n const allToKeywords = [\\\\n ...Object.keys(toGains),\\\\n ...Object.keys(allocations.to)];\\\\n\\\\n\\\\n const newToAllocation = Object.fromEntries(\\\\n allToKeywords.map(keyword => [\\\\n keyword,\\\\n add(allocations.to[keyword], toGains[keyword])]));\\\\n\\\\n\\\\n\\\\n return harden({\\\\n from: newFromAllocation,\\\\n to: newToAllocation });};\\\\n\\\\n\\\\n\\\\n const mergeAllocations = (currentAllocation, allocation) => {\\\\n const newAllocation = {\\\\n ...currentAllocation,\\\\n ...allocation };\\\\n\\\\n return newAllocation;};\\\\n\\\\n\\\\n const helpers = harden({\\\\n getKeys,\\\\n assertKeywords: expected => {\\\\n const { issuerKeywordRecord } = zcf.getInstanceRecord();\\\\n const actual = getKeysSorted(issuerKeywordRecord);\\\\n expected = [...expected]; /* in case hardened*/\\\\n expected.sort();\\\\n assert.assert(\\\\n sameStructure.sameStructure(actual, harden(expected)),\\\\n assert.details`keywords: ${actual} were not as expected: ${expected}`);},\\\\n\\\\n\\\\n rejectIfNotProposal: (offerHandle, expected) => {\\\\n const { proposal: actual } = zcf.getOffer(offerHandle);\\\\n rejectKeysIf(offerHandle, actual.give, expected.give);\\\\n rejectKeysIf(offerHandle, actual.want, expected.want);\\\\n rejectKeysIf(offerHandle, actual.exit, expected.exit);},\\\\n\\\\n checkIfProposal: (offerHandle, expected) => {\\\\n const { proposal: actual } = zcf.getOffer(offerHandle);\\\\n return (\\\\n /* Check that the \\\\\\\"give\\\\\\\" keys match expected keys.*/\\\\n checkKeys(actual.give, expected.give) &&\\\\n /* Check that the \\\\\\\"want\\\\\\\" keys match expected keys.*/\\\\n checkKeys(actual.want, expected.want) &&\\\\n /* Check that the \\\\\\\"exit\\\\\\\" key (i.e. \\\\\\\"onDemand\\\\\\\") matches the expected key.*/\\\\n checkKeys(actual.exit, expected.exit));},\\\\n\\\\n\\\\n getActiveOffers: (handles) =>\\\\n zcf.getOffers(zcf.getOfferStatuses(handles).active),\\\\n rejectOffer,\\\\n\\\\n /**\\\\n * Check whether an update to currentAllocation satisfies\\\\n * proposal.want. Note that this is half of the offer safety\\\\n * check; whether the allocation constitutes a refund is not\\\\n * checked. Allocation is merged with currentAllocation\\\\n * (allocations' values prevailing if the keywords are the same)\\\\n * to produce the newAllocation.\\\\n * @param {OfferHandle} offerHandle\\\\n * @param {allocation} amountKeywordRecord\\\\n * @returns {boolean}\\\\n */\\\\n satisfies: (offerHandle, allocation) => {\\\\n const currentAllocation = zcf.getCurrentAllocation(offerHandle);\\\\n const newAllocation = mergeAllocations(currentAllocation, allocation);\\\\n const { proposal } = zcf.getOffer(offerHandle);\\\\n return offerSafety.satisfiesWant(zcf.getAmountMath, proposal, newAllocation);},\\\\n\\\\n\\\\n /**\\\\n * Check whether an update to currentAllocation satisfies offer\\\\n * safety. Note that this is the equivalent of `satisfiesWant` ||\\\\n * `satisfiesGive`. Allocation is merged with currentAllocation\\\\n * (allocations' values prevailing if the keywords are the same)\\\\n * to produce the newAllocation.\\\\n * @param {OfferHandle} offerHandle\\\\n * @param {AmountKeywordRecord} allocation\\\\n * @returns {boolean}\\\\n */\\\\n\\\\n isOfferSafe: (offerHandle, allocation) => {\\\\n const currentAllocation = zcf.getCurrentAllocation(offerHandle);\\\\n const newAllocation = mergeAllocations(currentAllocation, allocation);\\\\n const { proposal } = zcf.getOffer(offerHandle);\\\\n return offerSafety.isOfferSafe(zcf.getAmountMath, proposal, newAllocation);},\\\\n\\\\n\\\\n /**\\\\n * Trade between left and right so that left and right end up with\\\\n * the declared gains.\\\\n * @param {offerHandleGainsLossesRecord} keepLeft\\\\n * @param {offerHandleGainsLossesRecord} tryRight\\\\n * @returns {undefined | Error}\\\\n *\\\\n * @typedef {object} offerHandleGainsLossesRecord\\\\n * @property {OfferHandle} offerHandle\\\\n * @property {AmountKeywordRecord} gains - what the offer will\\\\n * gain as a result of this trade\\\\n * @property {AmountKeywordRecord=} losses - what the offer will\\\\n * give up as a result of this trade. Losses is optional, but can\\\\n * only be omitted if the keywords for both offers are the same.\\\\n * If losses is not defined, the gains of the other offer is\\\\n * subtracted.\\\\n */\\\\n trade: (keepLeft, tryRight) => {\\\\n assert.assert(\\\\n keepLeft.offerHandle !== tryRight.offerHandle,\\\\n assert.details`an offer cannot trade with itself`);\\\\n\\\\n let leftAllocation = zcf.getCurrentAllocation(keepLeft.offerHandle);\\\\n let rightAllocation = zcf.getCurrentAllocation(tryRight.offerHandle);\\\\n\\\\n try {\\\\n /* for all the keywords and amounts in leftGains, transfer from*/\\\\n /* right to left*/\\\\n ({ from: rightAllocation, to: leftAllocation } = calcNewAllocations(\\\\n { from: rightAllocation, to: leftAllocation },\\\\n keepLeft.gains,\\\\n tryRight.losses));\\\\n\\\\n /* For all the keywords and amounts in rightGains, transfer from*/\\\\n /* left to right*/\\\\n ({ from: leftAllocation, to: rightAllocation } = calcNewAllocations(\\\\n { from: leftAllocation, to: rightAllocation },\\\\n tryRight.gains,\\\\n keepLeft.losses));}\\\\n\\\\n catch (err) {\\\\n return rejectOffer(tryRight.offerHandle);}\\\\n\\\\n\\\\n /* Check whether reallocate would error before calling. If*/\\\\n /* it would error, reject the right offer and return.*/\\\\n const offerSafeForLeft = helpers.isOfferSafe(\\\\n keepLeft.offerHandle,\\\\n leftAllocation);\\\\n\\\\n const offerSafeForRight = helpers.isOfferSafe(\\\\n tryRight.offerHandle,\\\\n rightAllocation);\\\\n\\\\n if (!(offerSafeForLeft && offerSafeForRight)) {\\\\n console.log(\\\\n `currentLeftAllocation`,\\\\n zcf.getCurrentAllocation(keepLeft.offerHandle));\\\\n\\\\n console.log(\\\\n `currentRightAllocation`,\\\\n zcf.getCurrentAllocation(tryRight.offerHandle));\\\\n\\\\n console.log(`proposed left reallocation`, leftAllocation);\\\\n console.log(`proposed right reallocation`, rightAllocation);\\\\n /* show the contraints*/\\\\n console.log(\\\\n `left want`,\\\\n zcf.getOffer(keepLeft.offerHandle).proposal.want);\\\\n\\\\n console.log(\\\\n `right want`,\\\\n zcf.getOffer(tryRight.offerHandle).proposal.want);\\\\n\\\\n\\\\n if (!offerSafeForLeft) {\\\\n console.log(`offer not safe for left`);}\\\\n\\\\n if (!offerSafeForRight) {\\\\n console.log(`offer not safe for right`);}\\\\n\\\\n return rejectOffer(tryRight.offerHandle);}\\\\n\\\\n zcf.reallocate(\\\\n [keepLeft.offerHandle, tryRight.offerHandle],\\\\n [leftAllocation, rightAllocation]);\\\\n\\\\n return undefined;},\\\\n\\\\n\\\\n /**\\\\n * If the two handles can trade, then swap their compatible assets,\\\\n * marking both offers as complete.\\\\n *\\\\n * The surplus remains with the original offer. For example if\\\\n * offer A gives 5 moola and offer B only wants 3 moola, offer A\\\\n * retains 2 moola.\\\\n *\\\\n * If the keep offer is no longer active (it was already completed), the try\\\\n * offer will be rejected with a message (provided by 'keepHandleInactiveMsg').\\\\n *\\\\n * TODO: If the try offer is no longer active, swap() should terminate with\\\\n * a useful error message, like defaultRejectMsg.\\\\n *\\\\n * If the swap fails, no assets are transferred, and the 'try' offer is rejected.\\\\n *\\\\n * @param {OfferHandle} keepHandle\\\\n * @param {OfferHandle} tryHandle\\\\n * @param {String} [keepHandleInactiveMsg]\\\\n */\\\\n swap: (\\\\n keepHandle,\\\\n tryHandle,\\\\n keepHandleInactiveMsg = 'prior offer is unavailable') =>\\\\n {\\\\n if (!zcf.isOfferActive(keepHandle)) {\\\\n throw helpers.rejectOffer(tryHandle, keepHandleInactiveMsg);}\\\\n\\\\n\\\\n helpers.trade(\\\\n {\\\\n offerHandle: keepHandle,\\\\n gains: zcf.getOffer(keepHandle).proposal.want },\\\\n\\\\n {\\\\n offerHandle: tryHandle,\\\\n gains: zcf.getOffer(tryHandle).proposal.want });\\\\n\\\\n\\\\n\\\\n zcf.complete([keepHandle, tryHandle]);\\\\n return defaultAcceptanceMsg;},\\\\n\\\\n\\\\n /**\\\\n * Make an offerHook that wraps the provided `offerHook`, to first\\\\n * check the submitted offer against an `expected` record that says\\\\n * what shape of proposal is acceptable.\\\\n *\\\\n * This ExpectedRecord is like a Proposal, but the amounts in 'want'\\\\n * and 'give' should be null; the exit clause should specify a rule with\\\\n * null contents. If the client submits an Offer which does not match\\\\n * these expectations, that offer will be rejected (and refunded).\\\\n *\\\\n * @param {OfferHook} offerHook\\\\n * @param {ExpectedRecord} expected\\\\n *\\\\n * @typedef ExpectedRecord\\\\n * @property {TODO} [want]\\\\n * @property {TODO} [give]\\\\n * @property {TODO} [exit]\\\\n */\\\\n checkHook: (offerHook, expected) => offerHandle => {\\\\n helpers.rejectIfNotProposal(offerHandle, expected);\\\\n return offerHook(offerHandle);},\\\\n\\\\n\\\\n /**\\\\n * Return a Promise for an OfferHandle.\\\\n *\\\\n * This offer will have an empty 'give' and 'want', making it useful\\\\n * for contracts to use for unrestricted internal asset reallocation.\\\\n * One example is the Autoswap contract, which uses an empty offer\\\\n * to manage internal escrowed assets.\\\\n *\\\\n * @returns {Promise<OfferHandle>}\\\\n */\\\\n makeEmptyOffer: () =>\\\\n new index.HandledPromise(resolve => {\\\\n const invite = zcf.makeInvitation(\\\\n offerHandle => resolve(offerHandle),\\\\n 'empty offer');\\\\n\\\\n index.E(zoeService).offer(invite);}),\\\\n\\\\n\\\\n /**\\\\n * Escrow a payment with Zoe and reallocate the amount of the\\\\n * payment to a recipient.\\\\n *\\\\n * @param {Object} obj\\\\n * @param {Amount} obj.amount\\\\n * @param {Payment} obj.payment\\\\n * @param {String} obj.keyword\\\\n * @param {OfferHandle} obj.recipientHandle\\\\n * @returns {Promise<undefined>}\\\\n */\\\\n escrowAndAllocateTo: ({ amount, payment, keyword, recipientHandle }) => {\\\\n /* We will create a temporary offer to be able to escrow our payment*/\\\\n /* with Zoe.*/\\\\n let tempHandle;\\\\n\\\\n /* We need to make an invite and store the offerHandle of that*/\\\\n /* invite for future use.*/\\\\n const contractSelfInvite = zcf.makeInvitation(\\\\n offerHandle => tempHandle = offerHandle,\\\\n 'self invite');\\\\n\\\\n /* To escrow the payment, we must get the Zoe Service facet and*/\\\\n /* make an offer*/\\\\n const proposal = harden({ give: { Temp: amount } });\\\\n const payments = harden({ Temp: payment });\\\\n\\\\n return index.E(zcf.getZoeService()).\\\\n offer(contractSelfInvite, proposal, payments).\\\\n then(() => {\\\\n /* At this point, the temporary offer has the amount from the*/\\\\n /* payment but nothing else. The recipient offer may have any*/\\\\n /* allocation, so we can't assume the allocation is currently empty for this*/\\\\n /* keyword.*/\\\\n\\\\n helpers.trade(\\\\n {\\\\n offerHandle: tempHandle,\\\\n gains: {},\\\\n losses: { Temp: amount } },\\\\n\\\\n {\\\\n offerHandle: recipientHandle,\\\\n gains: { [keyword]: amount } });\\\\n\\\\n\\\\n\\\\n /* Complete the temporary offerHandle*/\\\\n zcf.complete([tempHandle]);\\\\n\\\\n /* Now, the temporary offer no longer exists, but the recipient*/\\\\n /* offer is allocated the value of the payment.*/});},\\\\n\\\\n\\\\n /* * Given a brand, assert that the mathHelpers for that issuer\\\\n * are 'nat' mathHelpers\\\\n */\\\\n\\\\n assertNatMathHelpers: brand => {\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n assert.assert(\\\\n amountMath.getMathHelpersName() === 'nat',\\\\n assert.details`issuer must have natMathHelpers`);} });\\\\n\\\\n\\\\n\\\\n return helpers;};exports.defaultAcceptanceMsg = defaultAcceptanceMsg;exports.defaultRejectMsg = defaultRejectMsg;exports.makeZoeHelpers = makeZoeHelpers;\\\",\\n \\\"packages/zoe/src/contractSupport/index.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var auctions = require('./auctions.js');var safeMath = require('./safeMath.js');var bondingCurves = require('./bondingCurves.js');var stateMachine = require('./stateMachine.js');var zoeHelpers = require('./zoeHelpers.js');exports.closeAuction = auctions.closeAuction;exports.secondPriceLogic = auctions.secondPriceLogic;exports.natSafeMath = safeMath.natSafeMath;exports.calcLiqValueToMint = bondingCurves.calcLiqValueToMint;exports.calcValueToRemove = bondingCurves.calcValueToRemove;exports.getInputPrice = bondingCurves.getInputPrice;exports.makeStateMachine = stateMachine.makeStateMachine;exports.defaultAcceptanceMsg = zoeHelpers.defaultAcceptanceMsg;exports.defaultRejectMsg = zoeHelpers.defaultRejectMsg;exports.makeZoeHelpers = zoeHelpers.makeZoeHelpers;\\\"\\n};\\n const nsBundle = {};\\n\\n function createEvalString(filename) {\\n const code = sourceBundle[filename];\\n if (!code) {\\n return undefined;\\n }\\n return `\\\\\\n(function getExport(require, exports) { \\\\\\n 'use strict'; \\\\\\n const module = { exports }; \\\\\\n \\\\\\n ${code}\\n return module.exports;\\n})\\n//# sourceURL=${filePrefix}/${filename}\\n`;\\n }\\n\\n function computeExports(filename, exportPowers, exports) {\\n const { require: systemRequire, _log } = exportPowers;\\n // This captures the endowed require.\\n const match = filename.match(/^(.*)\\\\/[^/]+$/);\\n const thisdir = match ? match[1] : '.';\\n const contextRequire = mod => {\\n // Do path algebra to find the actual source.\\n const els = mod.split('/');\\n let prefix;\\n if (els[0][0] === '@') {\\n // Scoped name.\\n prefix = els.splice(0, 2).join('/');\\n } else if (els[0][0] === '.') {\\n // Relative.\\n els.unshift(...thisdir.split('/'));\\n } else {\\n // Bare or absolute.\\n prefix = els.splice(0, 1);\\n }\\n\\n const suffix = [];\\n for (const el of els) {\\n if (el === '.' || el === '') {\\n // Do nothing.\\n } else if (el === '..') {\\n // Traverse upwards.\\n suffix.pop();\\n } else {\\n suffix.push(el);\\n }\\n }\\n\\n // log(mod, prefix, suffix);\\n if (prefix !== undefined) {\\n suffix.unshift(prefix);\\n }\\n let modPath = suffix.join('/');\\n if (modPath.startsWith('./')) {\\n modPath = modPath.slice(2);\\n }\\n // log('requiring', modPath);\\n if (!(modPath in nsBundle)) {\\n // log('evaluating', modPath);\\n // Break cycles, but be tolerant of modules\\n // that completely override their exports object.\\n nsBundle[modPath] = {};\\n nsBundle[modPath] = computeExports(\\n modPath,\\n exportPowers,\\n nsBundle[modPath],\\n );\\n }\\n\\n // log('returning', nsBundle[modPath]);\\n return nsBundle[modPath];\\n };\\n\\n const code = createEvalString(filename);\\n if (!code) {\\n // log('missing code for', filename, sourceBundle);\\n if (systemRequire) {\\n return systemRequire(filename);\\n }\\n throw Error(\\n `require(${JSON.stringify(\\n filename,\\n )}) failed; no toplevel require endowment`,\\n );\\n }\\n\\n // log('evaluating', code);\\n return nestedEvaluate(code)(contextRequire, exports);\\n }\\n\\n // Evaluate the entrypoint recursively, seeding the exports.\\n const systemRequire = typeof require === 'undefined' ? undefined : require;\\n return computeExports(entrypoint, { require: systemRequire }, {});\\n}\\n//# sourceURL=/bundled-source-preamble.js\\n\",\"sourceMap\":\"//# sourceURL=/bundled-source-preamble.js\\n\",\"moduleFormat\":\"nestedEvaluate\"}]","slots":[]},"p-63"],"syscalls":[{"d":["fulfillToPresence","p-63","o+4"],"response":null}],"crankNumber":10}
v5.t.4 :: {"d":["deliver","o+1","install",{"body":"[{\"source\":\"function getExportWithNestedEvaluate(filePrefix) {\\n 'use strict';\\n // Serialised sources.\\n if (filePrefix === undefined) {\\n filePrefix = \\\"/bundled-source\\\";\\n }\\n const moduleFormat = \\\"nestedEvaluate\\\";\\n const entrypoint = \\\"packages/zoe/src/contracts/atomicSwap.js\\\";\\n const sourceBundle = {\\n \\\"packages/zoe/src/contracts/atomicSwap.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var zoeHelpers = require('../contractSupport/zoeHelpers.js');\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nrequire('../contractSupport/index.js'); /* global harden */ /**\\\\n * Trade one item for another.\\\\n *\\\\n * The initial offer is { give: { Asset: A }, want: { Price: B } }.\\\\n * The outcome from the first offer is an invitation for the second party,\\\\n * who should offer { give: { Price: B }, want: { Asset: A } }, with a want\\\\n * amount no greater than the original's give, and a give amount at least as\\\\n * large as the original's want.\\\\n *\\\\n * @typedef {Ximport('../zoe').ContractFacet} ContractFacet\\\\n * @param {ContractFacet} zcf\\\\n */\\\\nconst makeContract = zcf => {\\\\n const { swap, assertKeywords, checkHook } = zoeHelpers.makeZoeHelpers(zcf);\\\\n assertKeywords(harden(['Asset', 'Price']));\\\\n\\\\n const makeMatchingInvite = firstOfferHandle => {\\\\n const {\\\\n proposal: { want, give } } =\\\\n zcf.getOffer(firstOfferHandle);\\\\n\\\\n return zcf.makeInvitation(\\\\n offerHandle => swap(firstOfferHandle, offerHandle),\\\\n 'matchOffer',\\\\n harden({\\\\n customProperties: {\\\\n asset: give.Asset,\\\\n price: want.Price } }));};\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n const firstOfferExpected = harden({\\\\n give: { Asset: null },\\\\n want: { Price: null } });\\\\n\\\\n\\\\n return zcf.makeInvitation(\\\\n checkHook(makeMatchingInvite, firstOfferExpected),\\\\n 'firstOffer');};\\\\n\\\\n\\\\n\\\\nharden(makeContract);exports.makeContract = makeContract;\\\",\\n \\\"packages/zoe/src/contractSupport/auctions.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true }); /* global harden */\\\\n\\\\nconst secondPriceLogic = (bidAmountMath, bidOfferHandles, bids) => {\\\\n let highestBid = bidAmountMath.getEmpty();\\\\n let secondHighestBid = bidAmountMath.getEmpty();\\\\n let highestBidOfferHandle;\\\\n /* eslint-disable-next-line array-callback-return*/\\\\n bidOfferHandles.map((offerHandle, i) => {\\\\n const bid = bids[i];\\\\n /* If the bid is greater than the highestBid, it's the new highestBid*/\\\\n if (bidAmountMath.isGTE(bid, highestBid)) {\\\\n secondHighestBid = highestBid;\\\\n highestBid = bid;\\\\n highestBidOfferHandle = offerHandle;} else\\\\n if (bidAmountMath.isGTE(bid, secondHighestBid)) {\\\\n /* If the bid is not greater than the highest bid, but is greater*/\\\\n /* than the second highest bid, it is the new second highest bid.*/\\\\n secondHighestBid = bid;}});\\\\n\\\\n\\\\n return harden({\\\\n winnerOfferHandle: highestBidOfferHandle,\\\\n winnerBid: highestBid,\\\\n price: secondHighestBid });};\\\\n\\\\n\\\\n\\\\nconst closeAuction = (\\\\nzcf,\\\\n{ auctionLogicFn, sellerOfferHandle, allBidHandles }) =>\\\\n{\\\\n const { brandKeywordRecord } = zcf.getInstanceRecord();\\\\n const bidAmountMath = zcf.getAmountMath(brandKeywordRecord.Ask);\\\\n const assetAmountMath = zcf.getAmountMath(brandKeywordRecord.Asset);\\\\n\\\\n /* Filter out any inactive bids*/\\\\n const { active: activeBidHandles } = zcf.getOfferStatuses(\\\\n harden(allBidHandles));\\\\n\\\\n\\\\n const getBids = amountsKeywordRecord => amountsKeywordRecord.Bid;\\\\n const bids = zcf.getCurrentAllocations(activeBidHandles).map(getBids);\\\\n const assetAmount = zcf.getOffer(sellerOfferHandle).proposal.give.Asset;\\\\n\\\\n const { winnerOfferHandle, winnerBid, price } = auctionLogicFn(\\\\n bidAmountMath,\\\\n activeBidHandles,\\\\n bids);\\\\n\\\\n\\\\n /* The winner gets to keep the difference between their bid and the*/\\\\n /* price paid.*/\\\\n const winnerRefund = bidAmountMath.subtract(winnerBid, price);\\\\n\\\\n const newSellerAmounts = { Asset: assetAmountMath.getEmpty(), Ask: price };\\\\n const newWinnerAmounts = { Asset: assetAmount, Bid: winnerRefund };\\\\n\\\\n /* Everyone else gets a refund so their values remain the*/\\\\n /* same.*/\\\\n zcf.reallocate(\\\\n harden([sellerOfferHandle, winnerOfferHandle]),\\\\n harden([newSellerAmounts, newWinnerAmounts]));\\\\n\\\\n const allOfferHandles = harden([sellerOfferHandle, ...activeBidHandles]);\\\\n zcf.complete(allOfferHandles);};exports.closeAuction = closeAuction;exports.secondPriceLogic = secondPriceLogic;\\\",\\n \\\"packages/assert/src/assert.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* Copyright (C) 2019 Agoric, under Apache License 2.0*/ /* @ts-check*/ /* This module assumes the de-facto standard `console` host object.*/ /* To the extent that this `console` is considered a resource,*/ /* this module must be considered a resource module.*/ /**\\\\n * Prepend the correct indefinite article onto a noun, typically a typeof result\\\\n * e.g., \\\\\\\"an Object\\\\\\\" vs. \\\\\\\"a Number\\\\\\\"\\\\n *\\\\n * @param {string} str The noun to prepend\\\\n * @returns {string} The noun prepended with a/an\\\\n */\\\\nfunction an(str) {\\\\n str = `${str}`;\\\\n if (str.length >= 1 && 'aeiouAEIOU'.includes(str[0])) {\\\\n return `an ${str}`;}\\\\n\\\\n return `a ${str}`;}\\\\n\\\\nharden(an);\\\\n\\\\n/**\\\\n * Like `JSON.stringify` but does not blow up if given a cycle. This is not\\\\n * intended to be a serialization to support any useful unserialization,\\\\n * or any programmatic use of the resulting string. The string is intended\\\\n * only for showing a human, in order to be informative enough for some\\\\n * logging purposes. As such, this `cycleTolerantStringify` has an\\\\n * imprecise specification and may change over time.\\\\n *\\\\n * The current `cycleTolerantStringify` possibly emits too many \\\\\\\"seen\\\\\\\"\\\\n * markings: Not only for cycles, but also for repeated subtrees by\\\\n * object identity.\\\\n */\\\\nfunction cycleTolerantStringify(payload) {\\\\n const seenSet = new Set();\\\\n const replacer = (_, val) => {\\\\n if (typeof val === 'object' && val !== null) {\\\\n if (seenSet.has(val)) {\\\\n return '<**seen**>';}\\\\n\\\\n seenSet.add(val);}\\\\n\\\\n return val;};\\\\n\\\\n return JSON.stringify(payload, replacer);}\\\\n\\\\n\\\\nconst declassifiers = new WeakSet();\\\\n\\\\n/**\\\\n * To \\\\\\\"declassify\\\\\\\" and quote a substitution value used in a\\\\n * details`...` template literal, enclose that substitution expression\\\\n * in a call to `q`. This states that the argument should appear quoted (with\\\\n * `JSON.stringify`), in the error message of the thrown error. The payload\\\\n * itself is still passed unquoted to the console as it would be without q.\\\\n *\\\\n * Starting from the example in the `details` comment, say instead that the\\\\n * color the sky is supposed to be is also computed. Say that we still don't\\\\n * want to reveal the sky's actual color, but we do want the thrown error's\\\\n * message to reveal what color the sky was supposed to be:\\\\n * ```js\\\\n * assert.equal(\\\\n * sky.color,\\\\n * color,\\\\n * details`${sky.color} should be ${q(color)}`,\\\\n * );\\\\n * ```\\\\n *\\\\n * @typedef {Object} StringablePayload\\\\n * @property {*} payload The original payload\\\\n * @property {() => string} toString How to print the payload\\\\n *\\\\n * @param {*} payload What to declassify\\\\n * @returns {StringablePayload} The declassified payload\\\\n */\\\\nfunction q(payload) {\\\\n /* Don't harden the payload*/\\\\n const result = Object.freeze({\\\\n payload,\\\\n toString: Object.freeze(() => cycleTolerantStringify(payload)) });\\\\n\\\\n declassifiers.add(result);\\\\n return result;}\\\\n\\\\nharden(q);\\\\n\\\\n/**\\\\n * Use the `details` function as a template literal tag to create\\\\n * informative error messages. The assertion functions take such messages\\\\n * as optional arguments:\\\\n * ```js\\\\n * assert(sky.isBlue(), details`${sky.color} should be \\\\\\\"blue\\\\\\\"`);\\\\n * ```\\\\n * The details template tag returns an object that can print itself with the\\\\n * formatted message in two ways. It will report the real details to the\\\\n * console but include only the typeof information in the thrown error\\\\n * to prevent revealing secrets up the exceptional path. In the example\\\\n * above, the thrown error may reveal only that `sky.color` is a string,\\\\n * whereas the same diagnostic printed to the console reveals that the\\\\n * sky was green.\\\\n *\\\\n * WARNING: this function currently returns an unhardened result, as hardening\\\\n * proved to cause significant performance degradation. Consequently, callers\\\\n * should take care to use it only in contexts where this lack of hardening\\\\n * does not present a hazard. In current usage, a `details` template literal\\\\n * may only appear either as an argument to `assert`, where we know hardening\\\\n * won't matter, or inside another hardened object graph, where hardening is\\\\n * already ensured. However, there is currently no means to enfoce these\\\\n * constraints, so users are required to employ this function with caution.\\\\n * Our intent is to eventually have a lint rule that will check for\\\\n * inappropriate uses or find an alternative means of implementing `details`\\\\n * that does not encounter the performance issue. The final disposition of\\\\n * this is being discussed and tracked in issue #679 in the agoric-sdk\\\\n * repository.\\\\n *\\\\n * @typedef {Object} Complainer An object that has custom assert behaviour\\\\n * @property {() => Error} complain Return an Error to throw, and print details to console\\\\n *\\\\n * @typedef {string|Complainer} Details Either a plain string, or made by details``\\\\n *\\\\n * @param {TemplateStringsArray | string[]} template The template to format\\\\n * @param {any[]} args Arguments to the template\\\\n * @returns {Complainer} The complainer for these details\\\\n */\\\\nfunction details(template, ...args) {\\\\n /* const complainer = harden({ // remove harden per above discussion*/\\\\n const complainer = {\\\\n complain() {\\\\n const interleaved = [template[0]];\\\\n const parts = [template[0]];\\\\n for (let i = 0; i < args.length; i += 1) {\\\\n let arg = args[i];\\\\n let argStr;\\\\n if (declassifiers.has(arg)) {\\\\n argStr = `${arg}`;\\\\n arg = arg.payload;} else\\\\n {\\\\n argStr = `(${an(typeof arg)})`;}\\\\n\\\\n\\\\n /* Remove the extra spaces (since console.error puts them*/\\\\n /* between each interleaved).*/\\\\n const priorWithoutSpace = (interleaved.pop() || '').replace(/ $/, '');\\\\n if (priorWithoutSpace !== '') {\\\\n interleaved.push(priorWithoutSpace);}\\\\n\\\\n\\\\n const nextWithoutSpace = template[i + 1].replace(/^ /, '');\\\\n interleaved.push(arg, nextWithoutSpace);\\\\n\\\\n parts.push(argStr, template[i + 1]);}\\\\n\\\\n if (interleaved[interleaved.length - 1] === '') {\\\\n interleaved.pop();}\\\\n\\\\n if (args.length >= 1) {\\\\n parts.push('\\\\\\\\nSee console for error data.');}\\\\n\\\\n const err = new Error(parts.join(''));\\\\n console.error('LOGGED ERROR:', ...interleaved, err);\\\\n /* eslint-disable-next-line no-debugger*/\\\\n debugger;\\\\n return err;} };\\\\n\\\\n\\\\n /* });*/\\\\n return complainer;}\\\\n\\\\nharden(details);\\\\n\\\\n/**\\\\n * Fail an assertion, recording details to the console and\\\\n * raising an exception with just type information.\\\\n *\\\\n * The optional `optDetails` can be a string for backwards compatibility\\\\n * with the nodejs assertion library.\\\\n * @param {Details} [optDetails] The details of what was asserted\\\\n * @returns {never}\\\\n */\\\\nfunction fail(optDetails = details`Assert failed`) {\\\\n if (typeof optDetails === 'string') {\\\\n /* If it is a string, use it as the literal part of the template so*/\\\\n /* it doesn't get quoted.*/\\\\n optDetails = details([optDetails]);}\\\\n\\\\n throw optDetails.complain();}\\\\n\\\\n\\\\n/**\\\\n * @param {*} flag The truthy/falsy value\\\\n * @param {Details} [optDetails] The details to throw\\\\n * @returns {asserts flag}\\\\n */\\\\nfunction assert(flag, optDetails = details`Check failed`) {\\\\n if (!flag) {\\\\n throw fail(optDetails);}}\\\\n\\\\n\\\\n\\\\n/**\\\\n * Assert that two values must be `Object.is`.\\\\n * @param {*} actual The value we received\\\\n * @param {*} expected What we wanted\\\\n * @param {Details} [optDetails] The details to throw\\\\n * @returns {void}\\\\n */\\\\nfunction equal(\\\\nactual,\\\\nexpected,\\\\noptDetails = details`Expected ${actual} is same as ${expected}`)\\\\n{\\\\n assert(Object.is(actual, expected), optDetails);}\\\\n\\\\n\\\\n/**\\\\n * Assert an expected typeof result.\\\\n * @type {AssertTypeof}\\\\n * @param {any} specimen The value to get the typeof\\\\n * @param {string} typename The expected name\\\\n * @param {Details} [optDetails] The details to throw\\\\n */\\\\nconst assertTypeof = (specimen, typename, optDetails) => {\\\\n assert(\\\\n typeof typename === 'string',\\\\n details`${q(typename)} must be a string`);\\\\n\\\\n if (optDetails === undefined) {\\\\n /* Like*/\\\\n /* ```js*/\\\\n /* optDetails = details`${specimen} must be ${q(an(typename))}`;*/\\\\n /* ```*/\\\\n /* except it puts the typename into the literal part of the template*/\\\\n /* so it doesn't get quoted.*/\\\\n optDetails = details(['', ` must be ${an(typename)}`], specimen);}\\\\n\\\\n equal(typeof specimen, typename, optDetails);};\\\\n\\\\n\\\\n/**\\\\n * assert that expr is truthy, with an optional details to describe\\\\n * the assertion. It is a tagged template literal like\\\\n * ```js\\\\n * assert(expr, details`....`);`\\\\n * ```\\\\n * If expr is falsy, then the template contents are reported to the\\\\n * console and also in a thrown error.\\\\n *\\\\n * The literal portions of the template are assumed non-sensitive, as\\\\n * are the `typeof` types of the substitution values. These are\\\\n * assembled into the thrown error message. The actual contents of the\\\\n * substitution values are assumed sensitive, to be revealed to the\\\\n * console only. We assume only the virtual platform's owner can read\\\\n * what is written to the console, where the owner is in a privileged\\\\n * position over computation running on that platform.\\\\n *\\\\n * The optional `optDetails` can be a string for backwards compatibility\\\\n * with the nodejs assertion library.\\\\n * @type {typeof assert & { typeof: AssertTypeof, fail: typeof fail, equal: typeof equal }}\\\\n */\\\\nconst assertCombined = Object.assign(assert, {\\\\n equal,\\\\n fail,\\\\n typeof: assertTypeof });\\\\n\\\\nharden(assertCombined);exports.an = an;exports.assert = assertCombined;exports.details = details;exports.q = q;\\\",\\n \\\"node_modules/@agoric/nat/dist/nat.esm.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* Copyright (C) 2011 Google Inc.*/ /* Copyright (C) 2018 Agoric*/ /**/ /* Licensed under the Apache License, Version 2.0 (the \\\\\\\"License\\\\\\\");*/ /* you may not use this file except in compliance with the License.*/ /* You may obtain a copy of the License at*/ /**/ /* http://www.apache.org/licenses/LICENSE-2.0*/ /**/ /* Unless required by applicable law or agreed to in writing, software*/ /* distributed under the License is distributed on an \\\\\\\"AS IS\\\\\\\" BASIS,*/ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*/ /* See the License for the specific language governing permissions and*/ /* limitations under the License.*/ /**\\\\n * Is allegedNum a number in the contiguous range of exactly and\\\\n * unambiguously representable natural numbers (non-negative integers)?\\\\n *\\\\n * <p>See <a href=\\\\n * \\\\\\\"https://code.google.com/p/google-caja/issues/detail?id=1801\\\\\\\"\\\\n * >Issue 1801: Nat must include at most (2**53)-1</a>\\\\n * and <a href=\\\\n * \\\\\\\"https://mail.mozilla.org/pipermail/es-discuss/2013-July/031716.html\\\\\\\"\\\\n * >Allen Wirfs-Brock's suggested phrasing</a> on es-discuss.\\\\n */\\\\n\\\\nfunction Nat(allegedNum) {\\\\n if (!Number.isSafeInteger(allegedNum)) {\\\\n throw new RangeError('not a safe integer');}\\\\n\\\\n\\\\n if (allegedNum < 0) {\\\\n throw new RangeError('negative');}\\\\n\\\\n\\\\n return allegedNum;}exports.default = Nat;\\\",\\n \\\"packages/zoe/src/contractSupport/safeMath.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\nnat_esm = require('../../../../node_modules/@agoric/nat/dist/nat.esm.js'); /* global harden */ /**\\\\n * These operations should be used for calculations with the\\\\n * values of basic fungible tokens.\\\\n */\\\\nconst natSafeMath = harden({\\\\n add: (x, y) => nat_esm.default(x + y),\\\\n subtract: (x, y) => nat_esm.default(x - y),\\\\n multiply: (x, y) => nat_esm.default(x * y),\\\\n floorDivide: (x, y) => nat_esm.default(Math.floor(x / y)) });exports.natSafeMath = natSafeMath;\\\",\\n \\\"packages/zoe/src/contractSupport/bondingCurves.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../../assert/src/assert.js');var safeMath = require('./safeMath.js');\\\\n\\\\n\\\\nconst { add, subtract, multiply, floorDivide } = safeMath.natSafeMath;\\\\n\\\\n/**\\\\n * Contains the logic for calculating how much should be given\\\\n * back to the user in exchange for what they sent in. It also\\\\n * calculates the new amount of the assets in the pool. Reused in\\\\n * several different places, including to check whether an offer\\\\n * is valid, getting the current price for an asset on user\\\\n * request, and to do the actual reallocation after an offer has\\\\n * been made.\\\\n * @param {Object} params\\\\n * @param {number} params.inputValue - the value of the asset sent\\\\n * in to be swapped\\\\n * @param {number} params.inputReserve - the value in the liquidity\\\\n * pool of the kind of asset sent in\\\\n * @param {number} params.outputReserve - the value in the liquidity\\\\n * pool of the kind of asset to be sent out\\\\n * @param {number} params.feeBasisPoints=30 - the fee taken in\\\\n * basis points. The default is 0.3% or 30 basis points. The fee is taken from\\\\n * inputValue\\\\n * @returns {number} outputValue - the current price, in value form\\\\n */\\\\nconst getInputPrice = ({\\\\n inputValue,\\\\n inputReserve,\\\\n outputReserve,\\\\n feeBasisPoints = 30 }) =>\\\\n{\\\\n const oneMinusFeeInTenThousandths = subtract(10000, feeBasisPoints);\\\\n const inputWithFee = multiply(inputValue, oneMinusFeeInTenThousandths);\\\\n const numerator = multiply(inputWithFee, outputReserve);\\\\n const denominator = add(multiply(inputReserve, 10000), inputWithFee);\\\\n\\\\n const outputValue = floorDivide(numerator, denominator);\\\\n return outputValue;};\\\\n\\\\n\\\\nfunction assertDefined(label, value) {\\\\n assert.assert(value !== undefined, assert.details`${label} value required`);}\\\\n\\\\n\\\\n/* Calculate how many liquidity tokens we should be minting to send back to the*/\\\\n/* user when adding liquidity. Calculations are based on the comparing the*/\\\\n/* inputValue to the inputReserve. If the current supply is zero, just return*/\\\\n/* the inputValue.*/\\\\nconst calcLiqValueToMint = ({\\\\n liqTokenSupply,\\\\n inputValue,\\\\n inputReserve }) =>\\\\n{\\\\n assertDefined('liqTokenSupply', liqTokenSupply);\\\\n assertDefined('inputValue', inputValue);\\\\n assertDefined('inputReserve', inputReserve);\\\\n return liqTokenSupply > 0 ?\\\\n floorDivide(multiply(inputValue, liqTokenSupply), inputReserve) :\\\\n inputValue;};\\\\n\\\\n\\\\n/* Calculate how many underlying tokens (in the form of a value) should be*/\\\\n/* returned when removing liquidity.*/\\\\nconst calcValueToRemove = ({\\\\n liqTokenSupply,\\\\n poolValue,\\\\n liquidityValueIn }) =>\\\\n{\\\\n assertDefined('liqTokenSupply', liqTokenSupply);\\\\n assertDefined('liquidityValueIn', liquidityValueIn);\\\\n assertDefined('poolValue', poolValue);\\\\n\\\\n return floorDivide(multiply(liquidityValueIn, poolValue), liqTokenSupply);};exports.calcLiqValueToMint = calcLiqValueToMint;exports.calcValueToRemove = calcValueToRemove;exports.getInputPrice = getInputPrice;\\\",\\n \\\"packages/zoe/src/contractSupport/stateMachine.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\nassert = require('../../../assert/src/assert.js'); /* global harden */ /* allowedTransitions is an array of arrays which gets turned into a\\\\n * map. The map maps string states to an array of potential next\\\\n * states. For example,\\\\n * const allowedTransitions = [\\\\n ['open', ['closed']],\\\\n ['closed', []],\\\\n * ];\\\\n */\\\\nconst makeStateMachine = (initialState, allowedTransitionsArray) => {\\\\n let state = initialState;\\\\n const allowedTransitions = new Map(allowedTransitionsArray);\\\\n return harden({\\\\n canTransitionTo: (nextState) =>\\\\n allowedTransitions.get(state).includes(nextState),\\\\n transitionTo: nextState => {\\\\n assert.assert(allowedTransitions.get(state).includes(nextState));\\\\n state = nextState;},\\\\n\\\\n getStatus: _ => state });};\\\\n\\\\n\\\\nharden(makeStateMachine);exports.makeStateMachine = makeStateMachine;\\\",\\n \\\"packages/eventual-send/src/E.js\\\": \\\"'use strict';\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* global harden */ /* eslint-disable-next-line spaced-comment*/ /*/ <reference path=\\\\\\\"index.d.ts\\\\\\\" />*/\\\\n\\\\nconst readOnlyProxy = {\\\\n set(_target, _prop, _value) {\\\\n return false;},\\\\n\\\\n isExtensible(_target) {\\\\n return false;},\\\\n\\\\n setPrototypeOf(_target, _value) {\\\\n return false;},\\\\n\\\\n deleteProperty(_target, _prop) {\\\\n return false;} };\\\\n\\\\n\\\\n\\\\n/**\\\\n * A Proxy handler for E(x).\\\\n *\\\\n * @param {*} x Any value passed to E(x)\\\\n * @returns {ProxyHandler} the Proxy handler\\\\n */\\\\nfunction EProxyHandler(x, HandledPromise) {\\\\n return harden({\\\\n ...readOnlyProxy,\\\\n get(_target, p, _receiver) {\\\\n if (`${p}` !== p) {\\\\n return undefined;}\\\\n\\\\n /* Harden this Promise because it's our only opportunity to ensure*/\\\\n /* p1=E(x).foo() is hardened. The Handled Promise API does not (yet)*/\\\\n /* allow the handler to synchronously influence the promise returned*/\\\\n /* by the handled methods, so we must freeze it from the outside. See*/\\\\n /* #95 for details.*/\\\\n return (...args) => harden(HandledPromise.applyMethod(x, p, args));},\\\\n\\\\n apply(_target, _thisArg, argArray = []) {\\\\n return harden(HandledPromise.applyFunction(x, argArray));},\\\\n\\\\n has(_target, _p) {\\\\n /* We just pretend everything exists.*/\\\\n return true;} });}\\\\n\\\\n\\\\n\\\\n\\\\nfunction makeE(HandledPromise) {\\\\n function E(x) {\\\\n const handler = EProxyHandler(x, HandledPromise);\\\\n return harden(new Proxy(() => {}, handler));}\\\\n\\\\n\\\\n const makeEGetterProxy = (x) =>\\\\n new Proxy(Object.create(null), {\\\\n ...readOnlyProxy,\\\\n has(_target, _prop) {\\\\n return true;},\\\\n\\\\n get(_target, prop) {\\\\n return harden(HandledPromise.get(x, prop));} });\\\\n\\\\n\\\\n\\\\n E.G = makeEGetterProxy;\\\\n E.resolve = HandledPromise.resolve;\\\\n E.unwrap = HandledPromise.unwrap;\\\\n\\\\n E.when = (x, onfulfilled = undefined, onrejected = undefined) =>\\\\n HandledPromise.resolve(x).then(onfulfilled, onrejected);\\\\n\\\\n return harden(E);}exports.default = makeE;\\\",\\n \\\"packages/eventual-send/src/index.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var E$1 = require('./E.js'); /* global harden HandledPromise */\\\\n\\\\n\\\\n\\\\nconst {\\\\n defineProperties,\\\\n getOwnPropertyDescriptors,\\\\n getOwnPropertyDescriptor: gopd,\\\\n getPrototypeOf,\\\\n isFrozen } =\\\\nObject;\\\\n\\\\nconst { prototype: promiseProto } = Promise;\\\\nconst { then: originalThen } = promiseProto;\\\\n\\\\n/* 'E' and 'HandledPromise' are exports of the module*/\\\\n\\\\n/* For now:*/\\\\n/* import { HandledPromise, E } from '@agoric/eventual-send';*/\\\\n/* ...*/\\\\n\\\\nconst hp =\\\\ntypeof HandledPromise === 'undefined' ?\\\\n/* eslint-disable-next-line no-use-before-define*/\\\\nmakeHandledPromise(Promise) :\\\\nharden(HandledPromise);\\\\n\\\\n\\\\n\\\\nconst E = E$1.default(hp);\\\\n\\\\n/* the following method (makeHandledPromise) is part*/\\\\n/* of the shim, and will not be exported by the module once the feature*/\\\\n/* becomes a part of standard javascript*/\\\\n\\\\n/**\\\\n * Create a HandledPromise class to have it support eventual send\\\\n * (wavy-dot) operations.\\\\n *\\\\n * Based heavily on nanoq\\\\n * https://github.com/drses/nanoq/blob/master/src/nanoq.js\\\\n *\\\\n * Original spec for the infix-bang (predecessor to wavy-dot) desugaring:\\\\n * https://web.archive.org/web/20161026162206/http://wiki.ecmascript.org/doku.php?id=strawman:concurrency\\\\n *\\\\n * @return {typeof HandledPromise} Handled promise\\\\n */\\\\nfunction makeHandledPromise(Promise) {\\\\n /* xs doesn't support WeakMap in pre-loaded closures*/\\\\n /* aka \\\\\\\"vetted customization code\\\\\\\"*/\\\\n let presenceToHandler;\\\\n let presenceToPromise;\\\\n let promiseToUnsettledHandler;\\\\n let promiseToPresence; /* only for HandledPromise.unwrap*/\\\\n let forwardedPromiseToPromise; /* forwarding, union-find-ish*/\\\\n function ensureMaps() {\\\\n if (!presenceToHandler) {\\\\n presenceToHandler = new WeakMap();\\\\n presenceToPromise = new WeakMap();\\\\n promiseToUnsettledHandler = new WeakMap();\\\\n promiseToPresence = new WeakMap();\\\\n forwardedPromiseToPromise = new WeakMap();}}\\\\n\\\\n\\\\n\\\\n /**\\\\n * You can imagine a forest of trees in which the roots of each tree is an\\\\n * unresolved HandledPromise or a non-Promise, and each node's parent is the\\\\n * HandledPromise to which it was forwarded. We maintain that mapping of\\\\n * forwarded HandledPromise to its resolution in forwardedPromiseToPromise.\\\\n *\\\\n * We use something like the description of \\\\\\\"Find\\\\\\\" with \\\\\\\"Path splitting\\\\\\\"\\\\n * to propagate changes down to the children efficiently:\\\\n * https://en.wikipedia.org/wiki/Disjoint-set_data_structure\\\\n *\\\\n * @param {*} target Any value.\\\\n * @returns {*} If the target was a HandledPromise, the most-resolved parent of it, otherwise the target.\\\\n */\\\\n function shorten(target) {\\\\n let p = target;\\\\n /* Find the most-resolved value for p.*/\\\\n while (forwardedPromiseToPromise.has(p)) {\\\\n p = forwardedPromiseToPromise.get(p);}\\\\n\\\\n const presence = promiseToPresence.get(p);\\\\n if (presence) {\\\\n /* Presences are final, so it is ok to propagate*/\\\\n /* this upstream.*/\\\\n while (target !== p) {\\\\n const parent = forwardedPromiseToPromise.get(target);\\\\n forwardedPromiseToPromise.delete(target);\\\\n promiseToUnsettledHandler.delete(target);\\\\n promiseToPresence.set(target, presence);\\\\n target = parent;}} else\\\\n\\\\n {\\\\n /* We propagate p and remove all other unsettled handlers*/\\\\n /* upstream.*/\\\\n /* Note that everything except presences is covered here.*/\\\\n while (target !== p) {\\\\n const parent = forwardedPromiseToPromise.get(target);\\\\n forwardedPromiseToPromise.set(target, p);\\\\n promiseToUnsettledHandler.delete(target);\\\\n target = parent;}}\\\\n\\\\n\\\\n return target;}\\\\n\\\\n\\\\n /* This special handler accepts Promises, and forwards*/\\\\n /* handled Promises to their corresponding fulfilledHandler.*/\\\\n let forwardingHandler;\\\\n let handle;\\\\n let promiseResolve;\\\\n\\\\n function HandledPromise(executor, unsettledHandler = undefined) {\\\\n if (new.target === undefined) {\\\\n throw new Error('must be invoked with \\\\\\\"new\\\\\\\"');}\\\\n\\\\n let handledResolve;\\\\n let handledReject;\\\\n let resolved = false;\\\\n let resolvedTarget = null;\\\\n let handledP;\\\\n let continueForwarding = () => {};\\\\n const superExecutor = (superResolve, superReject) => {\\\\n handledResolve = value => {\\\\n if (resolved) {\\\\n return resolvedTarget;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n value = shorten(value);\\\\n let targetP;\\\\n if (\\\\n promiseToUnsettledHandler.has(value) ||\\\\n promiseToPresence.has(value))\\\\n {\\\\n targetP = value;} else\\\\n {\\\\n /* We're resolving to a non-promise, so remove our handler.*/\\\\n promiseToUnsettledHandler.delete(handledP);\\\\n targetP = presenceToPromise.get(value);}\\\\n\\\\n /* Ensure our data structure is a propert tree (avoid cycles).*/\\\\n if (targetP && targetP !== handledP) {\\\\n forwardedPromiseToPromise.set(handledP, targetP);} else\\\\n {\\\\n forwardedPromiseToPromise.delete(handledP);}\\\\n\\\\n\\\\n /* Remove stale unsettled handlers, set to canonical form.*/\\\\n shorten(handledP);\\\\n\\\\n /* Ensure our unsettledHandler is cleaned up if not already.*/\\\\n if (promiseToUnsettledHandler.has(handledP)) {\\\\n handledP.then(_ => promiseToUnsettledHandler.delete(handledP));}\\\\n\\\\n\\\\n /* Finish the resolution.*/\\\\n superResolve(value);\\\\n resolved = true;\\\\n resolvedTarget = value;\\\\n\\\\n /* We're resolved, so forward any postponed operations to us.*/\\\\n continueForwarding();\\\\n return resolvedTarget;};\\\\n\\\\n handledReject = err => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n promiseToUnsettledHandler.delete(handledP);\\\\n resolved = true;\\\\n superReject(err);\\\\n continueForwarding();};};\\\\n\\\\n\\\\n handledP = harden(Reflect.construct(Promise, [superExecutor], new.target));\\\\n\\\\n ensureMaps();\\\\n\\\\n const makePostponedHandler = () => {\\\\n /* Create a simple postponedHandler that just postpones until the*/\\\\n /* fulfilledHandler is set.*/\\\\n let donePostponing;\\\\n const interlockP = new Promise(resolve => {\\\\n donePostponing = () => resolve();});\\\\n\\\\n\\\\n const makePostponedOperation = postponedOperation => {\\\\n /* Just wait until the handler is resolved/rejected.*/\\\\n return function postpone(x, ...args) {\\\\n /* console.log(`forwarding ${postponedOperation} ${args[0]}`);*/\\\\n return new HandledPromise((resolve, reject) => {\\\\n interlockP.\\\\n then(_ => {\\\\n /* If targetP is a handled promise, use it, otherwise x.*/\\\\n resolve(HandledPromise[postponedOperation](x, ...args));}).\\\\n\\\\n catch(reject);});};};\\\\n\\\\n\\\\n\\\\n\\\\n const postponedHandler = {\\\\n get: makePostponedOperation('get'),\\\\n applyMethod: makePostponedOperation('applyMethod') };\\\\n\\\\n return [postponedHandler, donePostponing];};\\\\n\\\\n\\\\n if (!unsettledHandler) {\\\\n /* This is insufficient for actual remote handled Promises*/\\\\n /* (too many round-trips), but is an easy way to create a*/\\\\n /* local handled Promise.*/\\\\n [unsettledHandler, continueForwarding] = makePostponedHandler();}\\\\n\\\\n\\\\n const validateHandler = h => {\\\\n if (Object(h) !== h) {\\\\n throw TypeError(`Handler ${h} cannot be a primitive`);}};\\\\n\\\\n\\\\n validateHandler(unsettledHandler);\\\\n\\\\n /* Until the handled promise is resolved, we use the unsettledHandler.*/\\\\n promiseToUnsettledHandler.set(handledP, unsettledHandler);\\\\n\\\\n const rejectHandled = reason => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n handledReject(reason);};\\\\n\\\\n\\\\n const resolveWithPresence = presenceHandler => {\\\\n if (resolved) {\\\\n return resolvedTarget;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n try {\\\\n /* Sanity checks.*/\\\\n validateHandler(presenceHandler);\\\\n\\\\n /* Validate and install our mapped target (i.e. presence).*/\\\\n resolvedTarget = Object.create(null);\\\\n\\\\n /* Create table entries for the presence mapped to the*/\\\\n /* fulfilledHandler.*/\\\\n presenceToPromise.set(resolvedTarget, handledP);\\\\n promiseToPresence.set(handledP, resolvedTarget);\\\\n presenceToHandler.set(resolvedTarget, presenceHandler);\\\\n\\\\n /* We committed to this presence, so resolve.*/\\\\n handledResolve(resolvedTarget);\\\\n return resolvedTarget;}\\\\n catch (e) {\\\\n handledReject(e);\\\\n throw e;}};\\\\n\\\\n\\\\n\\\\n const resolveHandled = async (target, deprecatedPresenceHandler) => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n try {\\\\n if (deprecatedPresenceHandler) {\\\\n throw TypeError(\\\\n `resolveHandled no longer accepts a handler; use resolveWithPresence`);}\\\\n\\\\n\\\\n\\\\n /* Resolve the target.*/\\\\n handledResolve(target);}\\\\n catch (e) {\\\\n handledReject(e);}};\\\\n\\\\n\\\\n\\\\n /* Invoke the callback to let the user resolve/reject.*/\\\\n executor(\\\\n (...args) => {\\\\n resolveHandled(...args);},\\\\n\\\\n rejectHandled,\\\\n resolveWithPresence);\\\\n\\\\n return handledP;}\\\\n\\\\n\\\\n HandledPromise.prototype = promiseProto;\\\\n Object.setPrototypeOf(HandledPromise, Promise);\\\\n\\\\n function isFrozenPromiseThen(p) {\\\\n return (\\\\n isFrozen(p) &&\\\\n getPrototypeOf(p) === promiseProto &&\\\\n promiseResolve(p) === p &&\\\\n gopd(p, 'then') === undefined &&\\\\n gopd(promiseProto, 'then').value === originalThen /* unnecessary under SES*/);}\\\\n\\\\n\\\\n\\\\n const staticMethods = harden({\\\\n get(target, key) {\\\\n return handle(target, 'get', key);},\\\\n\\\\n getSendOnly(target, key) {\\\\n handle(target, 'get', key);},\\\\n\\\\n applyFunction(target, args) {\\\\n return handle(target, 'applyMethod', undefined, args);},\\\\n\\\\n applyFunctionSendOnly(target, args) {\\\\n handle(target, 'applyMethod', undefined, args);},\\\\n\\\\n applyMethod(target, key, args) {\\\\n return handle(target, 'applyMethod', key, args);},\\\\n\\\\n applyMethodSendOnly(target, key, args) {\\\\n handle(target, 'applyMethod', key, args);},\\\\n\\\\n resolve(value) {\\\\n ensureMaps();\\\\n /* Resolving a Presence returns the pre-registered handled promise.*/\\\\n let resolvedPromise = presenceToPromise.get(value);\\\\n if (!resolvedPromise) {\\\\n resolvedPromise = promiseResolve(value);}\\\\n\\\\n /* Prevent any proxy trickery.*/\\\\n harden(resolvedPromise);\\\\n if (isFrozenPromiseThen(resolvedPromise)) {\\\\n return resolvedPromise;}\\\\n\\\\n /* Assimilate the thenable.*/\\\\n const executeThen = (resolve, reject) =>\\\\n resolvedPromise.then(resolve, reject);\\\\n return harden(\\\\n promiseResolve().then(_ => new HandledPromise(executeThen)));},\\\\n\\\\n\\\\n /* TODO verify that this is safe to provide universally, i.e.,*/\\\\n /* that by itself it doesn't provide access to mutable state in*/\\\\n /* ways that violate normal ocap module purity rules. The claim*/\\\\n /* that it does not rests on the handled promise itself being*/\\\\n /* necessary to perceive this mutable state. In that sense, we*/\\\\n /* can think of the right to perceive it, and of access to the*/\\\\n /* target, as being in the handled promise. Note that a .then on*/\\\\n /* the handled promise will already provide async access to the*/\\\\n /* target, so the only additional authorities are: 1)*/\\\\n /* synchronous access for handled promises only, and thus 2) the*/\\\\n /* ability to tell, from the client side, whether a promise is*/\\\\n /* handled. Or, at least, the ability to tell given that the*/\\\\n /* promise is already fulfilled.*/\\\\n unwrap(value) {\\\\n /* This check for Thenable is safe, since in a remote-object*/\\\\n /* environment, our comms system will defend against remote*/\\\\n /* objects being represented as a tricky local Proxy, otherwise*/\\\\n /* it is guaranteed to be local and therefore synchronous enough.*/\\\\n if (Object(value) !== value || !('then' in value)) {\\\\n /* Not a Thenable, so return it.*/\\\\n /* This means that local objects will pass through without error.*/\\\\n return value;}\\\\n\\\\n\\\\n /* Try to look up the HandledPromise.*/\\\\n ensureMaps();\\\\n const pr = presenceToPromise.get(value) || value;\\\\n\\\\n /* Find the fulfilled presence for that HandledPromise.*/\\\\n const presence = promiseToPresence.get(pr);\\\\n if (!presence) {\\\\n throw TypeError(\\\\n `Value is a Thenble but not a HandledPromise fulfilled to a presence`);}\\\\n\\\\n\\\\n return presence;} });\\\\n\\\\n\\\\n\\\\n defineProperties(HandledPromise, getOwnPropertyDescriptors(staticMethods));\\\\n\\\\n function makeForwarder(operation, localImpl) {\\\\n return (o, ...args) => {\\\\n /* We are in another turn already, and have the naked object.*/\\\\n const fulfilledHandler = presenceToHandler.get(o);\\\\n if (\\\\n fulfilledHandler &&\\\\n typeof fulfilledHandler[operation] === 'function')\\\\n {\\\\n /* The handler was resolved, so use it.*/\\\\n return fulfilledHandler[operation](o, ...args);}\\\\n\\\\n\\\\n /* Not handled, so use the local implementation.*/\\\\n return localImpl(o, ...args);};}\\\\n\\\\n\\\\n\\\\n /* eslint-disable-next-line prefer-const*/\\\\n forwardingHandler = {\\\\n get: makeForwarder('get', (o, key) => o[key]),\\\\n applyMethod: makeForwarder('applyMethod', (o, optKey, args) => {\\\\n if (optKey === undefined || optKey === null) {\\\\n return o(...args);}\\\\n\\\\n /* console.log(`sending`, optKey, o[optKey], o);*/\\\\n if (typeof o[optKey] !== 'function') {\\\\n throw TypeError(`o[${JSON.stringify(optKey)}] is not a function`);}\\\\n\\\\n return o[optKey](...args);}) };\\\\n\\\\n\\\\n\\\\n handle = (p, operation, ...opArgs) => {\\\\n ensureMaps();\\\\n const returnedP = new HandledPromise((resolve, reject) => {\\\\n /* We run in a future turn to prevent synchronous attacks,*/\\\\n let raceIsOver = false;\\\\n function win(handlerName, handler, o) {\\\\n if (raceIsOver) {\\\\n return;}\\\\n\\\\n if (typeof handler[operation] !== 'function') {\\\\n throw TypeError(`${handlerName}.${operation} is not a function`);}\\\\n\\\\n try {\\\\n resolve(handler[operation](o, ...opArgs, returnedP));}\\\\n catch (reason) {\\\\n reject(reason);}\\\\n\\\\n raceIsOver = true;}\\\\n\\\\n\\\\n function lose(e) {\\\\n if (raceIsOver) {\\\\n return;}\\\\n\\\\n reject(e);\\\\n raceIsOver = true;}\\\\n\\\\n\\\\n /* This contestant tries to win with the target's resolution.*/\\\\n HandledPromise.resolve(p).\\\\n then(o => win('forwardingHandler', forwardingHandler, o)).\\\\n catch(lose);\\\\n\\\\n /* This contestant sleeps a turn, but then tries to win immediately.*/\\\\n HandledPromise.resolve().\\\\n then(() => {\\\\n p = shorten(p);\\\\n const unsettledHandler = promiseToUnsettledHandler.get(p);\\\\n if (\\\\n unsettledHandler &&\\\\n typeof unsettledHandler[operation] === 'function')\\\\n {\\\\n /* and resolve to the answer from the specific unsettled handler,*/\\\\n /* opArgs are something like [prop] or [method, args],*/\\\\n /* so we don't risk the user's args leaking into this expansion.*/\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n win('unsettledHandler', unsettledHandler, p);} else\\\\n if (Object(p) !== p || !('then' in p)) {\\\\n /* Not a Thenable, so use it.*/\\\\n win('forwardingHandler', forwardingHandler, p);} else\\\\n if (promiseToPresence.has(p)) {\\\\n /* We have the object synchronously, so resolve with it.*/\\\\n const o = promiseToPresence.get(p);\\\\n win('forwardingHandler', forwardingHandler, o);}\\\\n\\\\n /* If we made it here without winning, then we will wait*/\\\\n /* for the other contestant to win instead.*/}).\\\\n\\\\n catch(lose);});\\\\n\\\\n\\\\n /* We return a handled promise with the default unsettled handler.*/\\\\n /* This prevents a race between the above Promise.resolves and*/\\\\n /* pipelining.*/\\\\n return returnedP;};\\\\n\\\\n\\\\n promiseResolve = Promise.resolve.bind(Promise);\\\\n return harden(HandledPromise);}exports.E = E;exports.HandledPromise = hp;exports.makeHandledPromise = makeHandledPromise;\\\",\\n \\\"packages/produce-promise/src/producePromise.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nindex = require('../../eventual-send/src/index.js'); /* global harden */ /**\\\\n * @template U,V\\\\n * @typedef {Object} PromiseRecord A reified Promise\\\\n * @property {(value?: U) => void} resolve\\\\n * @property {(reason?: V) => void} reject\\\\n * @property {Promise.<U, V>} promise\\\\n */ /**\\\\n * producePromise() builds a HandledPromise object, and returns a record\\\\n * containing the promise itself, as well as separate facets for resolving\\\\n * and rejecting it.\\\\n *\\\\n * @template U,V\\\\n * @returns {PromiseRecord.<U,V>}\\\\n */function producePromise() {let res;let rej; /* We use a HandledPromise so that we can run HandledPromise.unwrap(p)*/ /* even if p doesn't travel through a comms system (like SwingSet's).*/const p = new index.HandledPromise((resolve, reject) => {\\\\n res = resolve;\\\\n rej = reject;});\\\\n\\\\n /* Node.js adds the `domain` property which is not a standard*/\\\\n /* property on Promise. Because we do not know it to be ocap-safe,*/\\\\n /* we remove it.*/\\\\n if (p.domain) {\\\\n /* deleting p.domain may break functionality. To retain current*/\\\\n /* functionality at the expense of safety, set unsafe to true.*/\\\\n const unsafe = false;\\\\n if (unsafe) {\\\\n const originalDomain = p.domain;\\\\n Object.defineProperty(p, 'domain', {\\\\n get() {\\\\n return originalDomain;} });} else\\\\n\\\\n\\\\n {\\\\n delete p.domain;}}\\\\n\\\\n\\\\n return harden({ promise: p, resolve: res, reject: rej });}\\\\n\\\\nharden(producePromise);\\\\n\\\\n/**\\\\n * Determine if the argument is a Promise.\\\\n *\\\\n * @param {Promise} maybePromise The value to examine\\\\n * @returns {boolean} Whether it is a promise\\\\n */\\\\nfunction isPromise(maybePromise) {\\\\n return index.HandledPromise.resolve(maybePromise) === maybePromise;}\\\\n\\\\nharden(isPromise);exports.isPromise = isPromise;exports.producePromise = producePromise;\\\",\\n \\\"packages/marshal/marshal.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var nat_esm = require('../../node_modules/@agoric/nat/dist/nat.esm.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nproducePromise = require('../produce-promise/src/producePromise.js'); /* global harden */ /* TODO: Use just 'remote' when we're willing to make a breaking change.*/\\\\nconst REMOTE_STYLE = 'presence';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n/**\\\\n * This is an interface specification.\\\\n * For now, it is just a string, but will eventually become something\\\\n * much richer (anything that pureCopy accepts).\\\\n * @typedef {string} InterfaceSpec\\\\n */\\\\n\\\\n/**\\\\n * @type {WeakMap<Object, InterfaceSpec>}\\\\n */\\\\nconst remotableToInterface = new WeakMap();\\\\n\\\\n/**\\\\n * Simple semantics, just tell what interface (or undefined) a remotable has.\\\\n *\\\\n * @param {*} maybeRemotable the value to check\\\\n * @returns {InterfaceSpec} the interface specification, or undefined if not a Remotable\\\\n */\\\\nfunction getInterfaceOf(maybeRemotable) {\\\\n return remotableToInterface.get(maybeRemotable);}\\\\n\\\\n\\\\n/**\\\\n * Do a deep copy of the object, handling Proxies and recursion.\\\\n * The resulting copy is guaranteed to be pure data, as well as hardened.\\\\n * Such a hardened, pure copy cannot be used as a communications path.\\\\n *\\\\n * @template T\\\\n * @param {T} val input value. NOTE: Must be hardened!\\\\n * @returns {T} pure, hardened copy\\\\n */\\\\nfunction pureCopy(val, already = new WeakMap()) {\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n const passStyle = passStyleOf(val);\\\\n switch (passStyle) {\\\\n case 'bigint':\\\\n case 'boolean':\\\\n case 'null':\\\\n case 'number':\\\\n case 'string':\\\\n case 'undefined':\\\\n return val;\\\\n\\\\n case 'copyArray':\\\\n case 'copyRecord':{\\\\n const obj = /** @type {Object} */val;\\\\n if (already.has(obj)) {\\\\n return already.get(obj);}\\\\n\\\\n\\\\n /* Create a new identity.*/\\\\n const copy = /** @type {T} */passStyle === 'copyArray' ? [] : {};\\\\n\\\\n /* Prevent recursion.*/\\\\n already.set(obj, copy);\\\\n\\\\n /* Make a deep copy on the new identity.*/\\\\n /* Object.entries(obj) takes a snapshot (even if a Proxy).*/\\\\n Object.entries(obj).forEach(([prop, value]) => {\\\\n copy[prop] = pureCopy(value, already);});\\\\n\\\\n return harden(copy);}\\\\n\\\\n\\\\n case 'copyError':{\\\\n const unk = /** @type {unknown} */val;\\\\n const err = /** @type {Error} */unk;\\\\n\\\\n if (already.has(err)) {\\\\n return already.get(err);}\\\\n\\\\n\\\\n const { name, message } = err;\\\\n\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n const EC = getErrorConstructor(`${name}`) || Error;\\\\n const copy = harden(new EC(`${message}`));\\\\n already.set(err, copy);\\\\n\\\\n const unk2 = /** @type {unknown} */harden(copy);\\\\n return (/** @type {T} */unk2);}\\\\n\\\\n\\\\n case REMOTE_STYLE:{\\\\n throw TypeError(\\\\n `Input value ${passStyle} cannot be copied as must be passed by reference`);}\\\\n\\\\n\\\\n\\\\n default:\\\\n throw TypeError(`Input value ${passStyle} is not recognized as data`);}}\\\\n\\\\n\\\\nharden(pureCopy);\\\\n\\\\n\\\\n/* Special property name that indicates an encoding that needs special*/\\\\n/* decoding.*/\\\\nconst QCLASS = '@qclass';\\\\n\\\\n\\\\n/* objects can only be passed in one of two/three forms:*/\\\\n/* 1: pass-by-remote: all properties (own and inherited) are methods,*/\\\\n/* the object itself is of type object, not function*/\\\\n/* 2: pass-by-copy: all string-named own properties are data, not methods*/\\\\n/* the object must inherit from Object.prototype or null*/\\\\n/* 3: the empty object is pass-by-remote, for identity comparison*/\\\\n\\\\n/* all objects must be frozen*/\\\\n\\\\n/* anything else will throw an error if you try to serialize it*/\\\\n\\\\n/* with these restrictions, our remote call/copy protocols expose all useful*/\\\\n/* behavior of these objects: pass-by-remote objects have no other data (so*/\\\\n/* there's nothing else to copy), and pass-by-copy objects have no other*/\\\\n/* behavior (so there's nothing else to invoke)*/\\\\n\\\\nconst errorConstructors = new Map([\\\\n['Error', Error],\\\\n['EvalError', EvalError],\\\\n['RangeError', RangeError],\\\\n['ReferenceError', ReferenceError],\\\\n['SyntaxError', SyntaxError],\\\\n['TypeError', TypeError],\\\\n['URIError', URIError]]);\\\\n\\\\n\\\\nfunction getErrorConstructor(name) {\\\\n return errorConstructors.get(name);}\\\\n\\\\n\\\\nfunction isPassByCopyError(val) {\\\\n /* TODO: Need a better test than instanceof*/\\\\n if (!(val instanceof Error)) {\\\\n return false;}\\\\n\\\\n const proto = Object.getPrototypeOf(val);\\\\n const { name } = val;\\\\n const EC = getErrorConstructor(name);\\\\n if (!EC || EC.prototype !== proto) {\\\\n throw TypeError(`Must inherit from an error class .prototype ${val}`);}\\\\n\\\\n\\\\n const {\\\\n message: { value: messageStr } = { value: '' },\\\\n /* Allow but ignore only extraneous own `stack` property.*/\\\\n /* TODO: I began the variable below with \\\\\\\"_\\\\\\\". Why do I still need*/\\\\n /* to suppress the lint complaint?*/\\\\n /* eslint-disable-next-line no-unused-vars*/\\\\n stack: _optStackDesc,\\\\n ...restDescs } =\\\\n Object.getOwnPropertyDescriptors(val);\\\\n const restNames = Object.keys(restDescs);\\\\n if (restNames.length >= 1) {\\\\n throw new TypeError(`Unexpected own properties in error: ${restNames}`);}\\\\n\\\\n if (typeof messageStr !== 'string') {\\\\n throw new TypeError(`malformed error object: ${val}`);}\\\\n\\\\n return true;}\\\\n\\\\n\\\\nfunction isPassByCopyArray(val) {\\\\n if (!Array.isArray(val)) {\\\\n return false;}\\\\n\\\\n if (Object.getPrototypeOf(val) !== Array.prototype) {\\\\n throw new TypeError(`malformed array: ${val}`);}\\\\n\\\\n const len = val.length;\\\\n const descs = Object.getOwnPropertyDescriptors(val);\\\\n for (let i = 0; i < len; i += 1) {\\\\n const desc = descs[i];\\\\n if (!desc) {\\\\n throw new TypeError(`arrays must not contain holes`);}\\\\n\\\\n if (!('value' in desc)) {\\\\n throw new TypeError(`arrays must not contain accessors`);}\\\\n\\\\n if (typeof desc.value === 'function') {\\\\n throw new TypeError(`arrays must not contain methods`);}}\\\\n\\\\n\\\\n if (Object.keys(descs).length !== len + 1) {\\\\n throw new TypeError(`array must not have non-indexes ${val}`);}\\\\n\\\\n return true;}\\\\n\\\\n\\\\nfunction isPassByCopyRecord(val) {\\\\n if (Object.getPrototypeOf(val) !== Object.prototype) {\\\\n return false;}\\\\n\\\\n const descList = Object.values(Object.getOwnPropertyDescriptors(val));\\\\n if (descList.length === 0) {\\\\n /* empty non-array objects are pass-by-remote, not pass-by-copy*/\\\\n return false;}\\\\n\\\\n for (const desc of descList) {\\\\n if (!('value' in desc)) {\\\\n /* Should we error if we see an accessor here?*/\\\\n return false;}\\\\n\\\\n if (typeof desc.value === 'function') {\\\\n return false;}}\\\\n\\\\n\\\\n return true;}\\\\n\\\\n\\\\n/**\\\\n * Ensure that val could become a legitimate remotable. This is used internally both\\\\n * in the construction of a new remotable and mustPassByRemote.\\\\n *\\\\n * @param {*} val The remotable candidate to check\\\\n */\\\\nfunction assertCanBeRemotable(val) {\\\\n /* throws exception if cannot*/\\\\n if (typeof val !== 'object') {\\\\n throw new Error(`cannot serialize non-objects like ${val}`);}\\\\n\\\\n if (Array.isArray(val)) {\\\\n throw new Error(`Arrays cannot be pass-by-remote`);}\\\\n\\\\n if (val === null) {\\\\n throw new Error(`null cannot be pass-by-remote`);}\\\\n\\\\n\\\\n const names = Object.getOwnPropertyNames(val);\\\\n names.forEach(name => {\\\\n if (typeof val[name] !== 'function') {\\\\n throw new Error(\\\\n `cannot serialize objects with non-methods like the .${name} in ${val}`);\\\\n\\\\n /* return false;*/}});\\\\n\\\\n\\\\n\\\\n /* ok!*/}\\\\n\\\\n\\\\nfunction mustPassByRemote(val) {\\\\n if (!Object.isFrozen(val)) {\\\\n throw new Error(`cannot serialize non-frozen objects like ${val}`);}\\\\n\\\\n\\\\n if (getInterfaceOf(val) === undefined) {\\\\n /* Not a registered Remotable, so check its contents.*/\\\\n assertCanBeRemotable(val);}\\\\n\\\\n\\\\n /* It's not a registered Remotable, so enforce the prototype check.*/\\\\n const p = Object.getPrototypeOf(val);\\\\n if (p !== null && p !== Object.prototype) {\\\\n mustPassByRemote(p);}}\\\\n\\\\n\\\\n\\\\n/* This is the equality comparison used by JavaScript's Map and Set*/\\\\n/* abstractions, where NaN is the same as NaN and -0 is the same as*/\\\\n/* 0. Marshal serializes -0 as zero, so the semantics of our distributed*/\\\\n/* object system does not distinguish 0 from -0.*/\\\\n/**/\\\\n/* `sameValueZero` is the EcmaScript spec name for this equality comparison,*/\\\\n/* but TODO we need a better name for the API.*/\\\\nfunction sameValueZero(x, y) {\\\\n return x === y || Object.is(x, y);}\\\\n\\\\n\\\\n/* How would val be passed? For primitive values, the answer is*/\\\\n/* * 'null' for null*/\\\\n/* * throwing an error for a symbol, whether registered or not.*/\\\\n/* * that value's typeof string for all other primitive values*/\\\\n/* For frozen objects, the possible answers*/\\\\n/* * 'copyRecord' for non-empty records with only data properties*/\\\\n/* * 'copyArray' for arrays with only data properties*/\\\\n/* * 'copyError' for instances of Error with only data properties*/\\\\n/* * REMOTE_STYLE for non-array objects with only method properties*/\\\\n/* * 'promise' for genuine promises only*/\\\\n/* * throwing an error on anything else, including thenables.*/\\\\n/* We export passStyleOf so other algorithms can use this module's*/\\\\n/* classification.*/\\\\nfunction passStyleOf(val) {\\\\n const typestr = typeof val;\\\\n switch (typestr) {\\\\n case 'object':{\\\\n if (getInterfaceOf(val)) {\\\\n return REMOTE_STYLE;}\\\\n\\\\n if (val === null) {\\\\n return 'null';}\\\\n\\\\n if (QCLASS in val) {\\\\n /* TODO Hilbert hotel*/\\\\n throw new Error(`property \\\\\\\"${QCLASS}\\\\\\\" reserved`);}\\\\n\\\\n if (!Object.isFrozen(val)) {\\\\n throw new Error(\\\\n `Cannot pass non-frozen objects like ${val}. Use harden()`);}\\\\n\\\\n\\\\n if (producePromise.isPromise(val)) {\\\\n return 'promise';}\\\\n\\\\n if (typeof val.then === 'function') {\\\\n throw new Error(`Cannot pass non-promise thenables`);}\\\\n\\\\n if (isPassByCopyError(val)) {\\\\n return 'copyError';}\\\\n\\\\n if (isPassByCopyArray(val)) {\\\\n return 'copyArray';}\\\\n\\\\n if (isPassByCopyRecord(val)) {\\\\n return 'copyRecord';}\\\\n\\\\n mustPassByRemote(val);\\\\n return REMOTE_STYLE;}\\\\n\\\\n case 'function':{\\\\n throw new Error(`Bare functions like ${val} are disabled for now`);}\\\\n\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'bigint':{\\\\n return typestr;}\\\\n\\\\n case 'symbol':{\\\\n throw new TypeError('Cannot pass symbols');}\\\\n\\\\n default:{\\\\n throw new TypeError(`Unrecognized typeof ${typestr}`);}}}\\\\n\\\\n\\\\n\\\\n\\\\n/* The ibid logic relies on*/\\\\n/* * JSON.stringify on an array visiting array indexes from 0 to*/\\\\n/* arr.length -1 in order, and not visiting anything else.*/\\\\n/* * JSON.parse of a record (a plain object) creating an object on*/\\\\n/* which a getOwnPropertyNames will enumerate properties in the*/\\\\n/* same order in which they appeared in the parsed JSON string.*/\\\\n\\\\nfunction makeReplacerIbidTable() {\\\\n const ibidMap = new Map();\\\\n let ibidCount = 0;\\\\n\\\\n return harden({\\\\n has(obj) {\\\\n return ibidMap.has(obj);},\\\\n\\\\n get(obj) {\\\\n return ibidMap.get(obj);},\\\\n\\\\n add(obj) {\\\\n ibidMap.set(obj, ibidCount);\\\\n ibidCount += 1;} });}\\\\n\\\\n\\\\n\\\\n\\\\nfunction makeReviverIbidTable(cyclePolicy) {\\\\n const ibids = [];\\\\n const unfinishedIbids = new WeakSet();\\\\n\\\\n return harden({\\\\n get(allegedIndex) {\\\\n const index = nat_esm.default(allegedIndex);\\\\n if (index >= ibids.length) {\\\\n throw new RangeError(`ibid out of range: ${index}`);}\\\\n\\\\n const result = ibids[index];\\\\n if (unfinishedIbids.has(result)) {\\\\n switch (cyclePolicy) {\\\\n case 'allowCycles':{\\\\n break;}\\\\n\\\\n case 'warnOfCycles':{\\\\n console.log(`Warning: ibid cycle at ${index}`);\\\\n break;}\\\\n\\\\n case 'forbidCycles':{\\\\n throw new TypeError(`Ibid cycle at ${index}`);}\\\\n\\\\n default:{\\\\n throw new TypeError(`Unrecognized cycle policy: ${cyclePolicy}`);}}}\\\\n\\\\n\\\\n\\\\n return result;},\\\\n\\\\n register(obj) {\\\\n ibids.push(obj);\\\\n return obj;},\\\\n\\\\n start(obj) {\\\\n ibids.push(obj);\\\\n unfinishedIbids.add(obj);\\\\n return obj;},\\\\n\\\\n finish(obj) {\\\\n unfinishedIbids.delete(obj);\\\\n return obj;} });}\\\\n\\\\n\\\\n\\\\n\\\\nconst identityFn = x => x;\\\\n\\\\nfunction makeMarshal(\\\\nconvertValToSlot = identityFn,\\\\nconvertSlotToVal = identityFn)\\\\n{\\\\n function serializeSlot(val, slots, slotMap) {\\\\n let slotIndex;\\\\n if (slotMap.has(val)) {\\\\n slotIndex = slotMap.get(val);} else\\\\n {\\\\n const slot = convertValToSlot(val);\\\\n\\\\n slotIndex = slots.length;\\\\n slots.push(slot);\\\\n slotMap.set(val, slotIndex);}\\\\n\\\\n\\\\n return harden({\\\\n [QCLASS]: 'slot',\\\\n index: slotIndex });}\\\\n\\\\n\\\\n\\\\n function makeReplacer(slots, slotMap) {\\\\n const ibidTable = makeReplacerIbidTable();\\\\n\\\\n return function replacer(_, val) {\\\\n /* First we handle all primitives. Some can be represented directly as*/\\\\n /* JSON, and some must be encoded as [QCLASS] composites.*/\\\\n const passStyle = passStyleOf(val);\\\\n switch (passStyle) {\\\\n case 'null':{\\\\n return null;}\\\\n\\\\n case 'undefined':{\\\\n return harden({ [QCLASS]: 'undefined' });}\\\\n\\\\n case 'string':\\\\n case 'boolean':{\\\\n return val;}\\\\n\\\\n case 'number':{\\\\n if (Number.isNaN(val)) {\\\\n return harden({ [QCLASS]: 'NaN' });}\\\\n\\\\n if (Object.is(val, -0)) {\\\\n return 0;}\\\\n\\\\n if (val === Infinity) {\\\\n return harden({ [QCLASS]: 'Infinity' });}\\\\n\\\\n if (val === -Infinity) {\\\\n return harden({ [QCLASS]: '-Infinity' });}\\\\n\\\\n return val;}\\\\n\\\\n case 'bigint':{\\\\n return harden({\\\\n [QCLASS]: 'bigint',\\\\n digits: String(val) });}\\\\n\\\\n\\\\n default:{\\\\n /* if we've seen this object before, serialize a backref*/\\\\n if (ibidTable.has(val)) {\\\\n /* Backreference to prior occurrence*/\\\\n return harden({\\\\n [QCLASS]: 'ibid',\\\\n index: ibidTable.get(val) });}\\\\n\\\\n\\\\n ibidTable.add(val);\\\\n\\\\n switch (passStyle) {\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n /* console.log(`canPassByCopy: ${val}`);*/\\\\n /* Purposely in-band for readability, but creates need for*/\\\\n /* Hilbert hotel.*/\\\\n return val;}\\\\n\\\\n case 'copyError':{\\\\n /* We deliberately do not share the stack, but it would*/\\\\n /* be useful to log the stack locally so someone who has*/\\\\n /* privileged access to the throwing Vat can correlate*/\\\\n /* the problem with the remote Vat that gets this*/\\\\n /* summary. If we do that, we could allocate some random*/\\\\n /* identifier and include it in the message, to help*/\\\\n /* with the correlation.*/\\\\n return harden({\\\\n [QCLASS]: 'error',\\\\n name: `${val.name}`,\\\\n message: `${val.message}` });}\\\\n\\\\n\\\\n case REMOTE_STYLE:\\\\n case 'promise':{\\\\n /* console.log(`serializeSlot: ${val}`);*/\\\\n return serializeSlot(val, slots, slotMap);}\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${passStyle}`);}}}}};}\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n /* val might be a primitive, a pass by (shallow) copy object, a*/\\\\n /* remote reference, or other. We treat all other as a local object*/\\\\n /* to be exported as a local webkey.*/\\\\n function serialize(val) {\\\\n const slots = [];\\\\n const slotMap = new Map(); /* maps val (promise or remotable) to*/\\\\n /* index of slots[]*/\\\\n return harden({\\\\n body: JSON.stringify(val, makeReplacer(slots, slotMap)),\\\\n slots });}\\\\n\\\\n\\\\n\\\\n function makeFullRevive(slots, cyclePolicy) {\\\\n /* ibid table is shared across recursive calls to fullRevive.*/\\\\n const ibidTable = makeReviverIbidTable(cyclePolicy);\\\\n\\\\n /* We stay close to the algorith at*/\\\\n /* https://tc39.github.io/ecma262/#sec-json.parse , where*/\\\\n /* fullRevive(JSON.parse(str)) is like JSON.parse(str, revive))*/\\\\n /* for a similar reviver. But with the following differences:*/\\\\n /**/\\\\n /* Rather than pass a reviver to JSON.parse, we first call a plain*/\\\\n /* (one argument) JSON.parse to get rawTree, and then post-process*/\\\\n /* the rawTree with fullRevive. The kind of revive function*/\\\\n /* handled by JSON.parse only does one step in post-order, with*/\\\\n /* JSON.parse doing the recursion. By contrast, fullParse does its*/\\\\n /* own recursion, enabling it to interpret ibids in the same*/\\\\n /* pre-order in which the replacer visited them, and enabling it*/\\\\n /* to break cycles.*/\\\\n /**/\\\\n /* In order to break cycles, the potentially cyclic objects are*/\\\\n /* not frozen during the recursion. Rather, the whole graph is*/\\\\n /* hardened before being returned. Error objects are not*/\\\\n /* potentially recursive, and so may be harmlessly hardened when*/\\\\n /* they are produced.*/\\\\n /**/\\\\n /* fullRevive can produce properties whose value is undefined,*/\\\\n /* which a JSON.parse on a reviver cannot do. If a reviver returns*/\\\\n /* undefined to JSON.parse, JSON.parse will delete the property*/\\\\n /* instead.*/\\\\n /**/\\\\n /* fullRevive creates and returns a new graph, rather than*/\\\\n /* modifying the original tree in place.*/\\\\n /**/\\\\n /* fullRevive may rely on rawTree being the result of a plain call*/\\\\n /* to JSON.parse. However, it *cannot* rely on it having been*/\\\\n /* produced by JSON.stringify on the replacer above, i.e., it*/\\\\n /* cannot rely on it being a valid marshalled*/\\\\n /* representation. Rather, fullRevive must validate that.*/\\\\n return function fullRevive(rawTree) {\\\\n if (Object(rawTree) !== rawTree) {\\\\n /* primitives pass through*/\\\\n return rawTree;}\\\\n\\\\n if (QCLASS in rawTree) {\\\\n const qclass = rawTree[QCLASS];\\\\n if (typeof qclass !== 'string') {\\\\n throw new TypeError(`invalid qclass typeof ${typeof qclass}`);}\\\\n\\\\n switch (qclass) {\\\\n /* Encoding of primitives not handled by JSON*/\\\\n case 'undefined':{\\\\n return undefined;}\\\\n\\\\n case 'NaN':{\\\\n return NaN;}\\\\n\\\\n case 'Infinity':{\\\\n return Infinity;}\\\\n\\\\n case '-Infinity':{\\\\n return -Infinity;}\\\\n\\\\n case 'bigint':{\\\\n if (typeof rawTree.digits !== 'string') {\\\\n throw new TypeError(\\\\n `invalid digits typeof ${typeof rawTree.digits}`);}\\\\n\\\\n\\\\n /* eslint-disable-next-line no-undef */\\\\n return BigInt(rawTree.digits);}\\\\n\\\\n\\\\n case 'ibid':{\\\\n return ibidTable.get(rawTree.index);}\\\\n\\\\n\\\\n case 'error':{\\\\n if (typeof rawTree.name !== 'string') {\\\\n throw new TypeError(\\\\n `invalid error name typeof ${typeof rawTree.name}`);}\\\\n\\\\n\\\\n if (typeof rawTree.message !== 'string') {\\\\n throw new TypeError(\\\\n `invalid error message typeof ${typeof rawTree.message}`);}\\\\n\\\\n\\\\n const EC = getErrorConstructor(`${rawTree.name}`) || Error;\\\\n return ibidTable.register(harden(new EC(`${rawTree.message}`)));}\\\\n\\\\n\\\\n case 'slot':{\\\\n const slot = slots[nat_esm.default(rawTree.index)];\\\\n return ibidTable.register(convertSlotToVal(slot));}\\\\n\\\\n\\\\n default:{\\\\n /* TODO reverse Hilbert hotel*/\\\\n throw new TypeError(`unrecognized ${QCLASS} ${qclass}`);}}} else\\\\n\\\\n\\\\n if (Array.isArray(rawTree)) {\\\\n const result = ibidTable.start([]);\\\\n const len = rawTree.length;\\\\n for (let i = 0; i < len; i += 1) {\\\\n result[i] = fullRevive(rawTree[i]);}\\\\n\\\\n return ibidTable.finish(result);} else\\\\n {\\\\n const result = ibidTable.start({});\\\\n const names = Object.getOwnPropertyNames(rawTree);\\\\n for (const name of names) {\\\\n result[name] = fullRevive(rawTree[name]);}\\\\n\\\\n return ibidTable.finish(result);}};}\\\\n\\\\n\\\\n\\\\n\\\\n function unserialize(data, cyclePolicy = 'forbidCycles') {\\\\n if (data.body !== `${data.body}`) {\\\\n throw new Error(\\\\n `unserialize() given non-capdata (.body is ${data.body}, not string)`);}\\\\n\\\\n\\\\n if (!Array.isArray(data.slots)) {\\\\n throw new Error(`unserialize() given non-capdata (.slots are not Array)`);}\\\\n\\\\n const rawTree = harden(JSON.parse(data.body));\\\\n const fullRevive = makeFullRevive(data.slots, cyclePolicy);\\\\n return harden(fullRevive(rawTree));}\\\\n\\\\n\\\\n return harden({\\\\n serialize,\\\\n unserialize });}\\\\n\\\\n\\\\n\\\\n/**\\\\n * Create and register a Remotable. After this, getInterfaceOf(remotable)\\\\n * returns iface.\\\\n *\\\\n * // https://github.com/Agoric/agoric-sdk/issues/804\\\\n *\\\\n * @param {InterfaceSpec} [iface='Remotable'] The interface specification for the remotable\\\\n * @param {object} [props={}] Own-properties are copied to the remotable\\\\n * @param {object} [remotable={}] The object used as the remotable\\\\n * @returns {object} remotable, modified for debuggability\\\\n */\\\\nfunction Remotable(iface = 'Remotable', props = {}, remotable = {}) {\\\\n iface = pureCopy(harden(iface));\\\\n const ifaceType = typeof iface;\\\\n\\\\n /* Find the alleged name.*/\\\\n if (ifaceType !== 'string') {\\\\n throw Error(`Interface must be a string, not ${ifaceType}; unimplemented`);}\\\\n\\\\n\\\\n /* TODO: When iface is richer than just string, we need to get the allegedName*/\\\\n /* in a different way.*/\\\\n const allegedName = iface;\\\\n\\\\n /* Fail fast: check that the unmodified object is able to become a Remotable.*/\\\\n assertCanBeRemotable(remotable);\\\\n\\\\n /* Ensure that the remotable isn't already registered.*/\\\\n if (remotableToInterface.has(remotable)) {\\\\n throw Error(`Remotable ${remotable} is already mapped to an interface`);}\\\\n\\\\n\\\\n /* A prototype for debuggability.*/\\\\n const oldRemotableProto = harden(Object.getPrototypeOf(remotable));\\\\n\\\\n /* Fail fast: create a fresh empty object with the old*/\\\\n /* prototype in order to check it against our rules.*/\\\\n mustPassByRemote(harden(Object.create(oldRemotableProto)));\\\\n\\\\n /* Assign the arrow function to a variable to set its .name.*/\\\\n const toString = () => `[${allegedName}]`;\\\\n const remotableProto = harden(\\\\n Object.create(oldRemotableProto, {\\\\n toString: {\\\\n value: toString,\\\\n enumerable: false },\\\\n\\\\n [Symbol.toStringTag]: {\\\\n value: allegedName,\\\\n enumerable: false } }));\\\\n\\\\n\\\\n\\\\n\\\\n /* Take a static copy of the properties.*/\\\\n const propEntries = Object.entries(props);\\\\n const mutateHardenAndCheck = target => {\\\\n /* Add the snapshotted properties.*/\\\\n /** @type {PropertyDescriptorMap} */\\\\n const newProps = {};\\\\n propEntries.forEach(([prop, value]) => newProps[prop] = { value });\\\\n Object.defineProperties(target, newProps);\\\\n\\\\n /* Set the prototype for debuggability.*/\\\\n Object.setPrototypeOf(target, remotableProto);\\\\n harden(remotableProto);\\\\n\\\\n harden(target);\\\\n assertCanBeRemotable(target);\\\\n return target;};\\\\n\\\\n\\\\n /* Fail fast: check a fresh remotable to see if our rules fit.*/\\\\n const throwawayRemotable = Object.create(oldRemotableProto);\\\\n mutateHardenAndCheck(throwawayRemotable);\\\\n\\\\n /* Actually finish the new remotable.*/\\\\n mutateHardenAndCheck(remotable);\\\\n\\\\n /* COMMITTED!*/\\\\n /* We're committed, so keep the interface for future reference.*/\\\\n remotableToInterface.set(remotable, iface);\\\\n return remotable;}\\\\n\\\\n\\\\nharden(Remotable);exports.QCLASS = QCLASS;exports.Remotable = Remotable;exports.getErrorConstructor = getErrorConstructor;exports.getInterfaceOf = getInterfaceOf;exports.makeMarshal = makeMarshal;exports.mustPassByPresence = mustPassByRemote;exports.mustPassByRemote = mustPassByRemote;exports.passStyleOf = passStyleOf;exports.pureCopy = pureCopy;exports.sameValueZero = sameValueZero;\\\",\\n \\\"packages/same-structure/src/sameStructure.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../assert/src/assert.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nmarshal = require('../../marshal/marshal.js'); /* global harden */ /* Shim of Object.fromEntries from*/ /* https://github.com/tc39/proposal-object-from-entries/blob/master/polyfill.js*/\\\\nfunction ObjectFromEntries(iter) {\\\\n const obj = {};\\\\n\\\\n for (const pair of iter) {\\\\n if (Object(pair) !== pair) {\\\\n throw new TypeError('iterable for fromEntries should yield objects');}\\\\n\\\\n\\\\n /* Consistency with Map: contract is that entry has \\\\\\\"0\\\\\\\" and \\\\\\\"1\\\\\\\" keys, not*/\\\\n /* that it is an array or iterable.*/\\\\n\\\\n const { '0': key, '1': val } = pair;\\\\n\\\\n Object.defineProperty(obj, key, {\\\\n configurable: true,\\\\n enumerable: true,\\\\n writable: true,\\\\n value: val });}\\\\n\\\\n\\\\n\\\\n return obj;}\\\\n\\\\n\\\\n/* A *passable* is something that may be marshalled. It consists of a*/\\\\n/* graph of pass-by-copy data terminating in leaves of passable*/\\\\n/* non-pass-by-copy data. These leaves may be promises, or*/\\\\n/* pass-by-presence objects. A *comparable* is a passable whose leaves*/\\\\n/* contain no promises. Two comparables can be synchronously compared*/\\\\n/* for structural equivalence.*/\\\\n/**/\\\\n/* TODO: Currently, all algorithms here treat the pass-by-copy*/\\\\n/* superstructure as a tree. This means that dags are unwound at*/\\\\n/* potentially exponential cost, and cycles cause failure to*/\\\\n/* terminate. We must fix both problems, making all these algorithms*/\\\\n/* graph-aware.*/\\\\n\\\\n/* We say that a function *reveals* an X when it returns either an X*/\\\\n/* or a promise for an X.*/\\\\n\\\\n/* Given a passable, reveal a corresponding comparable, where each*/\\\\n/* leaf promise of the passable has been replaced with its*/\\\\n/* corresponding comparable.*/\\\\nfunction allComparable(passable) {\\\\n const passStyle = marshal.passStyleOf(passable);\\\\n switch (passStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':\\\\n case 'copyError':{\\\\n return passable;}\\\\n\\\\n case 'promise':{\\\\n return passable.then(nonp => allComparable(nonp));}\\\\n\\\\n case 'copyArray':{\\\\n const valPs = passable.map(p => allComparable(p));\\\\n return Promise.all(valPs).then(vals => harden(vals));}\\\\n\\\\n case 'copyRecord':{\\\\n const names = Object.getOwnPropertyNames(passable);\\\\n const valPs = names.map(name => allComparable(passable[name]));\\\\n return Promise.all(valPs).then((vals) =>\\\\n harden(ObjectFromEntries(vals.map((val, i) => [names[i], val]))));}\\\\n\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${passStyle}`);}}}\\\\n\\\\n\\\\n\\\\nharden(allComparable);\\\\n\\\\n/* Are left and right structurally equivalent comparables? This*/\\\\n/* compares pass-by-copy data deeply until non-pass-by-copy values are*/\\\\n/* reached. The non-pass-by-copy values at the leaves of the*/\\\\n/* comparison may only be pass-by-presence objects. If they are*/\\\\n/* anything else, including promises, throw an error.*/\\\\n/**/\\\\n/* Pass-by-presence objects compare identities.*/\\\\n\\\\nfunction sameStructure(left, right) {\\\\n const leftStyle = marshal.passStyleOf(left);\\\\n const rightStyle = marshal.passStyleOf(right);\\\\n assert.assert(\\\\n leftStyle !== 'promise',\\\\n assert.details`Cannot structurally compare promises: ${left}`);\\\\n\\\\n assert.assert(\\\\n rightStyle !== 'promise',\\\\n assert.details`Cannot structurally compare promises: ${right}`);\\\\n\\\\n\\\\n if (leftStyle !== rightStyle) {\\\\n return false;}\\\\n\\\\n switch (leftStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':{\\\\n return marshal.sameValueZero(left, right);}\\\\n\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n const leftNames = Object.getOwnPropertyNames(left);\\\\n const rightNames = Object.getOwnPropertyNames(right);\\\\n if (leftNames.length !== rightNames.length) {\\\\n return false;}\\\\n\\\\n for (const name of leftNames) {\\\\n /* TODO: Better hasOwnProperty check*/\\\\n if (!Object.getOwnPropertyDescriptor(right, name)) {\\\\n return false;}\\\\n\\\\n /* TODO: Make cycle tolerant*/\\\\n if (!sameStructure(left[name], right[name])) {\\\\n return false;}}\\\\n\\\\n\\\\n return true;}\\\\n\\\\n case 'copyError':{\\\\n return left.name === right.name && left.message === right.message;}\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${leftStyle}`);}}}\\\\n\\\\n\\\\n\\\\nharden(sameStructure);\\\\n\\\\nfunction pathStr(path) {\\\\n if (path === null) {\\\\n return 'top';}\\\\n\\\\n const [base, index] = path;\\\\n let i = index;\\\\n const baseStr = pathStr(base);\\\\n if (typeof i === 'string' && /^[a-zA-Z]\\\\\\\\w*$/.test(i)) {\\\\n return `${baseStr}.${i}`;}\\\\n\\\\n if (typeof i === 'string' && `${+i}` === i) {\\\\n i = +i;}\\\\n\\\\n return `${baseStr}[${JSON.stringify(i)}]`;}\\\\n\\\\n\\\\n/* TODO: Reduce redundancy between sameStructure and*/\\\\n/* mustBeSameStructureInternal*/\\\\nfunction mustBeSameStructureInternal(left, right, message, path) {\\\\n function complain(problem) {\\\\n assert.assert.fail(\\\\n assert.details`${assert.q(message)}: ${assert.q(problem)} at ${assert.q(\\\\n pathStr(path))\\\\n }: (${left}) vs (${right})`);}\\\\n\\\\n\\\\n\\\\n const leftStyle = marshal.passStyleOf(left);\\\\n const rightStyle = marshal.passStyleOf(right);\\\\n if (leftStyle === 'promise') {\\\\n complain('Promise on left');}\\\\n\\\\n if (rightStyle === 'promise') {\\\\n complain('Promise on right');}\\\\n\\\\n\\\\n if (leftStyle !== rightStyle) {\\\\n complain('different passing style');}\\\\n\\\\n switch (leftStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':{\\\\n if (!marshal.sameValueZero(left, right)) {\\\\n complain('different');}\\\\n\\\\n break;}\\\\n\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n const leftNames = Object.getOwnPropertyNames(left);\\\\n const rightNames = Object.getOwnPropertyNames(right);\\\\n if (leftNames.length !== rightNames.length) {\\\\n complain(`${leftNames.length} vs ${rightNames.length} own properties`);}\\\\n\\\\n for (const name of leftNames) {\\\\n /* TODO: Better hasOwnProperty check*/\\\\n if (!Object.getOwnPropertyDescriptor(right, name)) {\\\\n complain(`${name} not found on right`);}\\\\n\\\\n /* TODO: Make cycle tolerant*/\\\\n mustBeSameStructureInternal(left[name], right[name], message, [\\\\n path,\\\\n name]);}\\\\n\\\\n\\\\n break;}\\\\n\\\\n case 'copyError':{\\\\n if (left.name !== right.name) {\\\\n complain(`different error name: ${left.name} vs ${right.name}`);}\\\\n\\\\n if (left.message !== right.message) {\\\\n complain(\\\\n `different error message: ${left.message} vs ${right.message}`);}\\\\n\\\\n\\\\n break;}\\\\n\\\\n default:{\\\\n complain(`unrecognized passStyle ${leftStyle}`);\\\\n break;}}}\\\\n\\\\n\\\\n\\\\nfunction mustBeSameStructure(left, right, message) {\\\\n mustBeSameStructureInternal(left, right, `${message}`, null);}\\\\n\\\\nharden(mustBeSameStructure);\\\\n\\\\n/* If `val` would be a valid input to `sameStructure`, return*/\\\\n/* normally. Otherwise error.*/\\\\nfunction mustBeComparable(val) {\\\\n mustBeSameStructure(val, val, 'not comparable');}exports.allComparable = allComparable;exports.mustBeComparable = mustBeComparable;exports.mustBeSameStructure = mustBeSameStructure;exports.sameStructure = sameStructure;\\\",\\n \\\"packages/zoe/src/offerSafety.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /**\\\\n * @typedef {Ximport('@agoric/ertp/src/issuer').Brand} Brand\\\\n * @typedef {Ximport('@agoric/ertp/src/issuer').AmountMath} AmountMath\\\\n * @typedef {Ximport('./zoe').Proposal} Proposal\\\\n * @typedef {Ximport('./zoe').AmountKeywordRecord} AmountKeywordRecord\\\\n */ /**\\\\n * Helper to perform satisfiesWant and satisfiesGive. Is\\\\n * allocationAmount greater than or equal to requiredAmount for every\\\\n * keyword of giveOrWant?\\\\n * @param {(Brand) => AmountMath} getAmountMath\\\\n * @param {Proposal[\\\\\\\"give\\\\\\\"] | Proposal[\\\\\\\"want\\\\\\\"]} giveOrWant\\\\n * @param {AmountKeywordRecord} allocation\\\\n */const satisfiesInternal = (getAmountMath, giveOrWant, allocation) => {const isGTEByKeyword = ([keyword, requiredAmount]) => {/* If there is no allocation for a keyword, we know the giveOrWant*/ /* is not satisfied without checking further.*/if (allocation[keyword] === undefined) {\\\\n return false;}\\\\n\\\\n const amountMath = getAmountMath(requiredAmount.brand);\\\\n const allocationAmount = allocation[keyword];\\\\n return amountMath.isGTE(allocationAmount, requiredAmount);};\\\\n\\\\n return Object.entries(giveOrWant).every(isGTEByKeyword);};\\\\n\\\\n\\\\n/**\\\\n * For this allocation to satisfy what the user wanted, their\\\\n * allocated amounts must be greater than or equal to proposal.want.\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.want.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nconst satisfiesWant = (getAmountMath, proposal, allocation) =>\\\\nsatisfiesInternal(getAmountMath, proposal.want, allocation);\\\\n\\\\n/**\\\\n * For this allocation to count as a full refund, the allocated\\\\n * amounts must be greater than or equal to what was originally\\\\n * offered (proposal.give).\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.give.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nconst satisfiesGive = (getAmountMath, proposal, allocation) =>\\\\nsatisfiesInternal(getAmountMath, proposal.give, allocation);\\\\n\\\\n/**\\\\n * `isOfferSafe` checks offer safety for a single offer.\\\\n *\\\\n * Note: This implementation checks whether we fully satisfy\\\\n * `proposal.give` (giving a refund) or whether we fully satisfy\\\\n * `proposal.want`. Both can be fully satisfied.\\\\n *\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.want and\\\\n * proposal.give.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nfunction isOfferSafe(getAmountMath, proposal, allocation) {\\\\n return (\\\\n satisfiesGive(getAmountMath, proposal, allocation) ||\\\\n satisfiesWant(getAmountMath, proposal, allocation));}exports.isOfferSafe = isOfferSafe;exports.satisfiesWant = satisfiesWant;\\\",\\n \\\"packages/zoe/src/contractSupport/zoeHelpers.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../../assert/src/assert.js');var index = require('../../../eventual-send/src/index.js');var sameStructure = require('../../../same-structure/src/sameStructure.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nofferSafety = require('../offerSafety.js'); /* global harden */ /**\\\\n * @typedef {Ximport('../zoe').OfferHandle} OfferHandle\\\\n * @typedef {Ximport('../zoe').Invite} Invite\\\\n * @typedef {Ximport('../zoe').OfferHook} OfferHook\\\\n * @typedef {Ximport('../zoe').CustomProperties} CustomProperties\\\\n * @typedef {Ximport('../zoe').ContractFacet} ContractFacet\\\\n * @typedef {Ximport('../zoe').Keyword} Keyword\\\\n * @typedef {Ximport('../zoe').AmountKeywordRecord} AmountKeywordRecord\\\\n * @typedef {Ximport('../zoe').Amount} Amount\\\\n * @typedef {Ximport('../zoe').Payment} Payment\\\\n */\\\\n\\\\nconst defaultRejectMsg = `The offer was invalid. Please check your refund.`;\\\\nconst defaultAcceptanceMsg = `The offer has been accepted. Once the contract has been completed, please check your payout`;\\\\n\\\\nconst getKeys = obj => harden(Object.getOwnPropertyNames(obj || {}));\\\\nconst getKeysSorted = (obj) =>\\\\nharden(Object.getOwnPropertyNames(obj || {}).sort());\\\\n/**\\\\n * @function makeZoeHelpers - makes an object with helper functions useful to zoe contracts.\\\\n *\\\\n * @param {ContractFacet} zcf\\\\n */\\\\n/* zcf only picks up the type if the param is in parens, which eslint dislikes*/\\\\n/* eslint-disable-next-line*/\\\\nconst makeZoeHelpers = zcf => {\\\\n const zoeService = zcf.getZoeService();\\\\n\\\\n const rejectOffer = (offerHandle, msg = defaultRejectMsg) => {\\\\n zcf.complete(harden([offerHandle]));\\\\n assert.assert.fail(msg);};\\\\n\\\\n\\\\n /* Compare the keys of actual with expected keys and reject offer if*/\\\\n /* not sameStructure. If expectedKeys is undefined, no comparison occurs.*/\\\\n const rejectKeysIf = (\\\\n offerHandle,\\\\n actual,\\\\n expected,\\\\n msg = defaultRejectMsg) =>\\\\n /* eslint-disable-next-line consistent-return*/\\\\n {\\\\n if (expected !== undefined) {\\\\n if (!sameStructure.sameStructure(getKeysSorted(actual), getKeysSorted(expected))) {\\\\n return rejectOffer(offerHandle, msg);}}};\\\\n\\\\n\\\\n\\\\n /* Compare actual keys to expected keys. If expectedKeys is*/\\\\n /* undefined, return true trivially.*/\\\\n const checkKeys = (actual, expected) => {\\\\n if (expected === undefined) {\\\\n return true;}\\\\n\\\\n return sameStructure.sameStructure(getKeysSorted(actual), getKeysSorted(expected));};\\\\n\\\\n\\\\n /**\\\\n * Given toGains (an AmountKeywordRecord), and allocations (a pair,\\\\n * 'to' and 'from', of AmountKeywordRecords), all the entries in\\\\n * toGains will be added to 'to'. If fromLosses is defined, all the\\\\n * entries in fromLosses are subtracted from 'from'. (If fromLosses\\\\n * is not defined, toGains is subtracted from 'from'.)\\\\n *\\\\n * @param {FromToAllocations} allocations - the 'to' and 'from'\\\\n * allocations\\\\n * @param {AmountKeywordRecord} toGains - what should be gained in\\\\n * the 'to' allocation\\\\n * @param {AmountKeywordRecord} fromLosses - what should be lost in\\\\n * the 'from' allocation. If not defined, fromLosses is equal to\\\\n * toGains. Note that the total amounts should always be equal; it\\\\n * is the keywords that might be different.\\\\n * @returns {FromToAllocations} allocations - new allocations\\\\n *\\\\n * @typedef FromToAllocations\\\\n * @property {AmountKeywordRecord} from\\\\n * @property {AmountKeywordRecord} to\\\\n */\\\\n const calcNewAllocations = (allocations, toGains, fromLosses = undefined) => {\\\\n if (fromLosses === undefined) {\\\\n fromLosses = toGains;}\\\\n\\\\n\\\\n const subtract = (amount, amountToSubtract) => {\\\\n const { brand } = amount;\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n if (amountToSubtract !== undefined) {\\\\n return amountMath.subtract(amount, amountToSubtract);}\\\\n\\\\n return amount;};\\\\n\\\\n\\\\n const add = (amount, amountToAdd) => {\\\\n if (amount && amountToAdd) {\\\\n const { brand } = amount;\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n return amountMath.add(amount, amountToAdd);}\\\\n\\\\n return amount || amountToAdd;};\\\\n\\\\n\\\\n const newFromAllocation = Object.fromEntries(\\\\n Object.entries(allocations.from).map(([keyword, allocAmount]) => {\\\\n return [keyword, subtract(allocAmount, fromLosses[keyword])];}));\\\\n\\\\n\\\\n\\\\n const allToKeywords = [\\\\n ...Object.keys(toGains),\\\\n ...Object.keys(allocations.to)];\\\\n\\\\n\\\\n const newToAllocation = Object.fromEntries(\\\\n allToKeywords.map(keyword => [\\\\n keyword,\\\\n add(allocations.to[keyword], toGains[keyword])]));\\\\n\\\\n\\\\n\\\\n return harden({\\\\n from: newFromAllocation,\\\\n to: newToAllocation });};\\\\n\\\\n\\\\n\\\\n const mergeAllocations = (currentAllocation, allocation) => {\\\\n const newAllocation = {\\\\n ...currentAllocation,\\\\n ...allocation };\\\\n\\\\n return newAllocation;};\\\\n\\\\n\\\\n const helpers = harden({\\\\n getKeys,\\\\n assertKeywords: expected => {\\\\n const { issuerKeywordRecord } = zcf.getInstanceRecord();\\\\n const actual = getKeysSorted(issuerKeywordRecord);\\\\n expected = [...expected]; /* in case hardened*/\\\\n expected.sort();\\\\n assert.assert(\\\\n sameStructure.sameStructure(actual, harden(expected)),\\\\n assert.details`keywords: ${actual} were not as expected: ${expected}`);},\\\\n\\\\n\\\\n rejectIfNotProposal: (offerHandle, expected) => {\\\\n const { proposal: actual } = zcf.getOffer(offerHandle);\\\\n rejectKeysIf(offerHandle, actual.give, expected.give);\\\\n rejectKeysIf(offerHandle, actual.want, expected.want);\\\\n rejectKeysIf(offerHandle, actual.exit, expected.exit);},\\\\n\\\\n checkIfProposal: (offerHandle, expected) => {\\\\n const { proposal: actual } = zcf.getOffer(offerHandle);\\\\n return (\\\\n /* Check that the \\\\\\\"give\\\\\\\" keys match expected keys.*/\\\\n checkKeys(actual.give, expected.give) &&\\\\n /* Check that the \\\\\\\"want\\\\\\\" keys match expected keys.*/\\\\n checkKeys(actual.want, expected.want) &&\\\\n /* Check that the \\\\\\\"exit\\\\\\\" key (i.e. \\\\\\\"onDemand\\\\\\\") matches the expected key.*/\\\\n checkKeys(actual.exit, expected.exit));},\\\\n\\\\n\\\\n getActiveOffers: (handles) =>\\\\n zcf.getOffers(zcf.getOfferStatuses(handles).active),\\\\n rejectOffer,\\\\n\\\\n /**\\\\n * Check whether an update to currentAllocation satisfies\\\\n * proposal.want. Note that this is half of the offer safety\\\\n * check; whether the allocation constitutes a refund is not\\\\n * checked. Allocation is merged with currentAllocation\\\\n * (allocations' values prevailing if the keywords are the same)\\\\n * to produce the newAllocation.\\\\n * @param {OfferHandle} offerHandle\\\\n * @param {allocation} amountKeywordRecord\\\\n * @returns {boolean}\\\\n */\\\\n satisfies: (offerHandle, allocation) => {\\\\n const currentAllocation = zcf.getCurrentAllocation(offerHandle);\\\\n const newAllocation = mergeAllocations(currentAllocation, allocation);\\\\n const { proposal } = zcf.getOffer(offerHandle);\\\\n return offerSafety.satisfiesWant(zcf.getAmountMath, proposal, newAllocation);},\\\\n\\\\n\\\\n /**\\\\n * Check whether an update to currentAllocation satisfies offer\\\\n * safety. Note that this is the equivalent of `satisfiesWant` ||\\\\n * `satisfiesGive`. Allocation is merged with currentAllocation\\\\n * (allocations' values prevailing if the keywords are the same)\\\\n * to produce the newAllocation.\\\\n * @param {OfferHandle} offerHandle\\\\n * @param {AmountKeywordRecord} allocation\\\\n * @returns {boolean}\\\\n */\\\\n\\\\n isOfferSafe: (offerHandle, allocation) => {\\\\n const currentAllocation = zcf.getCurrentAllocation(offerHandle);\\\\n const newAllocation = mergeAllocations(currentAllocation, allocation);\\\\n const { proposal } = zcf.getOffer(offerHandle);\\\\n return offerSafety.isOfferSafe(zcf.getAmountMath, proposal, newAllocation);},\\\\n\\\\n\\\\n /**\\\\n * Trade between left and right so that left and right end up with\\\\n * the declared gains.\\\\n * @param {offerHandleGainsLossesRecord} keepLeft\\\\n * @param {offerHandleGainsLossesRecord} tryRight\\\\n * @returns {undefined | Error}\\\\n *\\\\n * @typedef {object} offerHandleGainsLossesRecord\\\\n * @property {OfferHandle} offerHandle\\\\n * @property {AmountKeywordRecord} gains - what the offer will\\\\n * gain as a result of this trade\\\\n * @property {AmountKeywordRecord=} losses - what the offer will\\\\n * give up as a result of this trade. Losses is optional, but can\\\\n * only be omitted if the keywords for both offers are the same.\\\\n * If losses is not defined, the gains of the other offer is\\\\n * subtracted.\\\\n */\\\\n trade: (keepLeft, tryRight) => {\\\\n assert.assert(\\\\n keepLeft.offerHandle !== tryRight.offerHandle,\\\\n assert.details`an offer cannot trade with itself`);\\\\n\\\\n let leftAllocation = zcf.getCurrentAllocation(keepLeft.offerHandle);\\\\n let rightAllocation = zcf.getCurrentAllocation(tryRight.offerHandle);\\\\n\\\\n try {\\\\n /* for all the keywords and amounts in leftGains, transfer from*/\\\\n /* right to left*/\\\\n ({ from: rightAllocation, to: leftAllocation } = calcNewAllocations(\\\\n { from: rightAllocation, to: leftAllocation },\\\\n keepLeft.gains,\\\\n tryRight.losses));\\\\n\\\\n /* For all the keywords and amounts in rightGains, transfer from*/\\\\n /* left to right*/\\\\n ({ from: leftAllocation, to: rightAllocation } = calcNewAllocations(\\\\n { from: leftAllocation, to: rightAllocation },\\\\n tryRight.gains,\\\\n keepLeft.losses));}\\\\n\\\\n catch (err) {\\\\n return rejectOffer(tryRight.offerHandle);}\\\\n\\\\n\\\\n /* Check whether reallocate would error before calling. If*/\\\\n /* it would error, reject the right offer and return.*/\\\\n const offerSafeForLeft = helpers.isOfferSafe(\\\\n keepLeft.offerHandle,\\\\n leftAllocation);\\\\n\\\\n const offerSafeForRight = helpers.isOfferSafe(\\\\n tryRight.offerHandle,\\\\n rightAllocation);\\\\n\\\\n if (!(offerSafeForLeft && offerSafeForRight)) {\\\\n console.log(\\\\n `currentLeftAllocation`,\\\\n zcf.getCurrentAllocation(keepLeft.offerHandle));\\\\n\\\\n console.log(\\\\n `currentRightAllocation`,\\\\n zcf.getCurrentAllocation(tryRight.offerHandle));\\\\n\\\\n console.log(`proposed left reallocation`, leftAllocation);\\\\n console.log(`proposed right reallocation`, rightAllocation);\\\\n /* show the contraints*/\\\\n console.log(\\\\n `left want`,\\\\n zcf.getOffer(keepLeft.offerHandle).proposal.want);\\\\n\\\\n console.log(\\\\n `right want`,\\\\n zcf.getOffer(tryRight.offerHandle).proposal.want);\\\\n\\\\n\\\\n if (!offerSafeForLeft) {\\\\n console.log(`offer not safe for left`);}\\\\n\\\\n if (!offerSafeForRight) {\\\\n console.log(`offer not safe for right`);}\\\\n\\\\n return rejectOffer(tryRight.offerHandle);}\\\\n\\\\n zcf.reallocate(\\\\n [keepLeft.offerHandle, tryRight.offerHandle],\\\\n [leftAllocation, rightAllocation]);\\\\n\\\\n return undefined;},\\\\n\\\\n\\\\n /**\\\\n * If the two handles can trade, then swap their compatible assets,\\\\n * marking both offers as complete.\\\\n *\\\\n * The surplus remains with the original offer. For example if\\\\n * offer A gives 5 moola and offer B only wants 3 moola, offer A\\\\n * retains 2 moola.\\\\n *\\\\n * If the keep offer is no longer active (it was already completed), the try\\\\n * offer will be rejected with a message (provided by 'keepHandleInactiveMsg').\\\\n *\\\\n * TODO: If the try offer is no longer active, swap() should terminate with\\\\n * a useful error message, like defaultRejectMsg.\\\\n *\\\\n * If the swap fails, no assets are transferred, and the 'try' offer is rejected.\\\\n *\\\\n * @param {OfferHandle} keepHandle\\\\n * @param {OfferHandle} tryHandle\\\\n * @param {String} [keepHandleInactiveMsg]\\\\n */\\\\n swap: (\\\\n keepHandle,\\\\n tryHandle,\\\\n keepHandleInactiveMsg = 'prior offer is unavailable') =>\\\\n {\\\\n if (!zcf.isOfferActive(keepHandle)) {\\\\n throw helpers.rejectOffer(tryHandle, keepHandleInactiveMsg);}\\\\n\\\\n\\\\n helpers.trade(\\\\n {\\\\n offerHandle: keepHandle,\\\\n gains: zcf.getOffer(keepHandle).proposal.want },\\\\n\\\\n {\\\\n offerHandle: tryHandle,\\\\n gains: zcf.getOffer(tryHandle).proposal.want });\\\\n\\\\n\\\\n\\\\n zcf.complete([keepHandle, tryHandle]);\\\\n return defaultAcceptanceMsg;},\\\\n\\\\n\\\\n /**\\\\n * Make an offerHook that wraps the provided `offerHook`, to first\\\\n * check the submitted offer against an `expected` record that says\\\\n * what shape of proposal is acceptable.\\\\n *\\\\n * This ExpectedRecord is like a Proposal, but the amounts in 'want'\\\\n * and 'give' should be null; the exit clause should specify a rule with\\\\n * null contents. If the client submits an Offer which does not match\\\\n * these expectations, that offer will be rejected (and refunded).\\\\n *\\\\n * @param {OfferHook} offerHook\\\\n * @param {ExpectedRecord} expected\\\\n *\\\\n * @typedef ExpectedRecord\\\\n * @property {TODO} [want]\\\\n * @property {TODO} [give]\\\\n * @property {TODO} [exit]\\\\n */\\\\n checkHook: (offerHook, expected) => offerHandle => {\\\\n helpers.rejectIfNotProposal(offerHandle, expected);\\\\n return offerHook(offerHandle);},\\\\n\\\\n\\\\n /**\\\\n * Return a Promise for an OfferHandle.\\\\n *\\\\n * This offer will have an empty 'give' and 'want', making it useful\\\\n * for contracts to use for unrestricted internal asset reallocation.\\\\n * One example is the Autoswap contract, which uses an empty offer\\\\n * to manage internal escrowed assets.\\\\n *\\\\n * @returns {Promise<OfferHandle>}\\\\n */\\\\n makeEmptyOffer: () =>\\\\n new index.HandledPromise(resolve => {\\\\n const invite = zcf.makeInvitation(\\\\n offerHandle => resolve(offerHandle),\\\\n 'empty offer');\\\\n\\\\n index.E(zoeService).offer(invite);}),\\\\n\\\\n\\\\n /**\\\\n * Escrow a payment with Zoe and reallocate the amount of the\\\\n * payment to a recipient.\\\\n *\\\\n * @param {Object} obj\\\\n * @param {Amount} obj.amount\\\\n * @param {Payment} obj.payment\\\\n * @param {String} obj.keyword\\\\n * @param {OfferHandle} obj.recipientHandle\\\\n * @returns {Promise<undefined>}\\\\n */\\\\n escrowAndAllocateTo: ({ amount, payment, keyword, recipientHandle }) => {\\\\n /* We will create a temporary offer to be able to escrow our payment*/\\\\n /* with Zoe.*/\\\\n let tempHandle;\\\\n\\\\n /* We need to make an invite and store the offerHandle of that*/\\\\n /* invite for future use.*/\\\\n const contractSelfInvite = zcf.makeInvitation(\\\\n offerHandle => tempHandle = offerHandle,\\\\n 'self invite');\\\\n\\\\n /* To escrow the payment, we must get the Zoe Service facet and*/\\\\n /* make an offer*/\\\\n const proposal = harden({ give: { Temp: amount } });\\\\n const payments = harden({ Temp: payment });\\\\n\\\\n return index.E(zcf.getZoeService()).\\\\n offer(contractSelfInvite, proposal, payments).\\\\n then(() => {\\\\n /* At this point, the temporary offer has the amount from the*/\\\\n /* payment but nothing else. The recipient offer may have any*/\\\\n /* allocation, so we can't assume the allocation is currently empty for this*/\\\\n /* keyword.*/\\\\n\\\\n helpers.trade(\\\\n {\\\\n offerHandle: tempHandle,\\\\n gains: {},\\\\n losses: { Temp: amount } },\\\\n\\\\n {\\\\n offerHandle: recipientHandle,\\\\n gains: { [keyword]: amount } });\\\\n\\\\n\\\\n\\\\n /* Complete the temporary offerHandle*/\\\\n zcf.complete([tempHandle]);\\\\n\\\\n /* Now, the temporary offer no longer exists, but the recipient*/\\\\n /* offer is allocated the value of the payment.*/});},\\\\n\\\\n\\\\n /* * Given a brand, assert that the mathHelpers for that issuer\\\\n * are 'nat' mathHelpers\\\\n */\\\\n\\\\n assertNatMathHelpers: brand => {\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n assert.assert(\\\\n amountMath.getMathHelpersName() === 'nat',\\\\n assert.details`issuer must have natMathHelpers`);} });\\\\n\\\\n\\\\n\\\\n return helpers;};exports.defaultAcceptanceMsg = defaultAcceptanceMsg;exports.defaultRejectMsg = defaultRejectMsg;exports.makeZoeHelpers = makeZoeHelpers;\\\",\\n \\\"packages/zoe/src/contractSupport/index.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var auctions = require('./auctions.js');var safeMath = require('./safeMath.js');var bondingCurves = require('./bondingCurves.js');var stateMachine = require('./stateMachine.js');var zoeHelpers = require('./zoeHelpers.js');exports.closeAuction = auctions.closeAuction;exports.secondPriceLogic = auctions.secondPriceLogic;exports.natSafeMath = safeMath.natSafeMath;exports.calcLiqValueToMint = bondingCurves.calcLiqValueToMint;exports.calcValueToRemove = bondingCurves.calcValueToRemove;exports.getInputPrice = bondingCurves.getInputPrice;exports.makeStateMachine = stateMachine.makeStateMachine;exports.defaultAcceptanceMsg = zoeHelpers.defaultAcceptanceMsg;exports.defaultRejectMsg = zoeHelpers.defaultRejectMsg;exports.makeZoeHelpers = zoeHelpers.makeZoeHelpers;\\\"\\n};\\n const nsBundle = {};\\n\\n function createEvalString(filename) {\\n const code = sourceBundle[filename];\\n if (!code) {\\n return undefined;\\n }\\n return `\\\\\\n(function getExport(require, exports) { \\\\\\n 'use strict'; \\\\\\n const module = { exports }; \\\\\\n \\\\\\n ${code}\\n return module.exports;\\n})\\n//# sourceURL=${filePrefix}/${filename}\\n`;\\n }\\n\\n function computeExports(filename, exportPowers, exports) {\\n const { require: systemRequire, _log } = exportPowers;\\n // This captures the endowed require.\\n const match = filename.match(/^(.*)\\\\/[^/]+$/);\\n const thisdir = match ? match[1] : '.';\\n const contextRequire = mod => {\\n // Do path algebra to find the actual source.\\n const els = mod.split('/');\\n let prefix;\\n if (els[0][0] === '@') {\\n // Scoped name.\\n prefix = els.splice(0, 2).join('/');\\n } else if (els[0][0] === '.') {\\n // Relative.\\n els.unshift(...thisdir.split('/'));\\n } else {\\n // Bare or absolute.\\n prefix = els.splice(0, 1);\\n }\\n\\n const suffix = [];\\n for (const el of els) {\\n if (el === '.' || el === '') {\\n // Do nothing.\\n } else if (el === '..') {\\n // Traverse upwards.\\n suffix.pop();\\n } else {\\n suffix.push(el);\\n }\\n }\\n\\n // log(mod, prefix, suffix);\\n if (prefix !== undefined) {\\n suffix.unshift(prefix);\\n }\\n let modPath = suffix.join('/');\\n if (modPath.startsWith('./')) {\\n modPath = modPath.slice(2);\\n }\\n // log('requiring', modPath);\\n if (!(modPath in nsBundle)) {\\n // log('evaluating', modPath);\\n // Break cycles, but be tolerant of modules\\n // that completely override their exports object.\\n nsBundle[modPath] = {};\\n nsBundle[modPath] = computeExports(\\n modPath,\\n exportPowers,\\n nsBundle[modPath],\\n );\\n }\\n\\n // log('returning', nsBundle[modPath]);\\n return nsBundle[modPath];\\n };\\n\\n const code = createEvalString(filename);\\n if (!code) {\\n // log('missing code for', filename, sourceBundle);\\n if (systemRequire) {\\n return systemRequire(filename);\\n }\\n throw Error(\\n `require(${JSON.stringify(\\n filename,\\n )}) failed; no toplevel require endowment`,\\n );\\n }\\n\\n // log('evaluating', code);\\n return nestedEvaluate(code)(contextRequire, exports);\\n }\\n\\n // Evaluate the entrypoint recursively, seeding the exports.\\n const systemRequire = typeof require === 'undefined' ? undefined : require;\\n return computeExports(entrypoint, { require: systemRequire }, {});\\n}\\n//# sourceURL=/bundled-source-preamble.js\\n\",\"sourceMap\":\"//# sourceURL=/bundled-source-preamble.js\\n\",\"moduleFormat\":\"nestedEvaluate\"}]","slots":[]},"p-64"],"syscalls":[{"d":["fulfillToPresence","p-64","o+5"],"response":null}],"crankNumber":12}
v5.t.5 :: {"d":["deliver","o+1","install",{"body":"[{\"source\":\"function getExportWithNestedEvaluate(filePrefix) {\\n 'use strict';\\n // Serialised sources.\\n if (filePrefix === undefined) {\\n filePrefix = \\\"/bundled-source\\\";\\n }\\n const moduleFormat = \\\"nestedEvaluate\\\";\\n const entrypoint = \\\"packages/zoe/src/contracts/simpleExchange.js\\\";\\n const sourceBundle = {\\n \\\"packages/zoe/src/contracts/simpleExchange.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var notifier = require('../../../notifier/src/notifier.js');var zoeHelpers = require('../contractSupport/zoeHelpers.js');\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nrequire('../contractSupport/index.js'); /* global harden */ /**\\\\n * SimpleExchange is an exchange with a simple matching algorithm, which allows\\\\n * an unlimited number of parties to create new orders or accept existing\\\\n * orders. The notifier allows callers to find the current list of orders.\\\\n *\\\\n * The SimpleExchange uses Asset and Price as its keywords. The contract treats\\\\n * the two keywords symmetrically. New offers can be created and existing offers\\\\n * can be accepted in either direction.\\\\n *\\\\n * { give: { 'Asset', simoleans(5) }, want: { 'Price', quatloos(3) } }\\\\n * { give: { 'Price', quatloos(8) }, want: { 'Asset', simoleans(3) } }\\\\n *\\\\n * The Asset is treated as an exact amount to be exchanged, while the\\\\n * Price is a limit that may be improved on. This simple exchange does\\\\n * not partially fill orders.\\\\n *\\\\n * The invitation returned on installation of the contract is the same as what\\\\n * is returned by calling `await E(publicAPI).makeInvite().\\\\n *\\\\n * @typedef {Ximport('../zoe').ContractFacet} ContractFacet\\\\n * @param {ContractFacet} zcf\\\\n */\\\\nconst makeContract = zcf => {\\\\n let sellOfferHandles = [];\\\\n let buyOfferHandles = [];\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n const { notifier: notifier$1, updater } = notifier.makeNotifierKit(getBookOrders());\\\\n\\\\n const {\\\\n rejectOffer,\\\\n checkIfProposal,\\\\n swap,\\\\n satisfies,\\\\n getActiveOffers,\\\\n assertKeywords } =\\\\n zoeHelpers.makeZoeHelpers(zcf);\\\\n\\\\n assertKeywords(harden(['Asset', 'Price']));\\\\n\\\\n function flattenOffer(o) {\\\\n return {\\\\n want: o.proposal.want,\\\\n give: o.proposal.give };}\\\\n\\\\n\\\\n\\\\n function flattenOrders(offerHandles) {\\\\n const result = zcf.\\\\n getOffers(zcf.getOfferStatuses(offerHandles).active).\\\\n map(offerRecord => flattenOffer(offerRecord));\\\\n return result;}\\\\n\\\\n\\\\n function getBookOrders() {\\\\n return {\\\\n buys: flattenOrders(buyOfferHandles),\\\\n sells: flattenOrders(sellOfferHandles) };}\\\\n\\\\n\\\\n\\\\n function getOffer(offerHandle) {\\\\n for (const handle of [...sellOfferHandles, ...buyOfferHandles]) {\\\\n if (offerHandle === handle) {\\\\n return flattenOffer(getActiveOffers([offerHandle])[0]);}}\\\\n\\\\n\\\\n return 'not an active offer';}\\\\n\\\\n\\\\n /* Tell the notifier that there has been a change to the book orders*/\\\\n function bookOrdersChanged() {\\\\n updater.updateState(getBookOrders());}\\\\n\\\\n\\\\n /* If there's an existing offer that this offer is a match for, make the trade*/\\\\n /* and return the handle for the matched offer. If not, return undefined, so*/\\\\n /* the caller can know to add the new offer to the book.*/\\\\n function swapIfCanTrade(offerHandles, offerHandle) {\\\\n for (const iHandle of offerHandles) {\\\\n const satisfiedBy = (xHandle, yHandle) =>\\\\n satisfies(xHandle, zcf.getCurrentAllocation(yHandle));\\\\n if (\\\\n satisfiedBy(iHandle, offerHandle) &&\\\\n satisfiedBy(offerHandle, iHandle))\\\\n {\\\\n swap(offerHandle, iHandle);\\\\n /* return handle to remove*/\\\\n return iHandle;}}\\\\n\\\\n\\\\n return undefined;}\\\\n\\\\n\\\\n /* try to swap offerHandle with one of the counterOffers. If it works, remove*/\\\\n /* the matching offer and return the remaining counterOffers. If there's no*/\\\\n /* matching offer, add the offerHandle to the coOffers, and return the*/\\\\n /* unmodified counterOfffers*/\\\\n function swapIfCanTradeAndUpdateBook(counterOffers, coOffers, offerHandle) {\\\\n const handle = swapIfCanTrade(counterOffers, offerHandle);\\\\n if (handle) {\\\\n /* remove the matched offer.*/\\\\n counterOffers = counterOffers.filter(value => value !== handle);} else\\\\n {\\\\n /* Save the order in the book*/\\\\n coOffers.push(offerHandle);}\\\\n\\\\n\\\\n return counterOffers;}\\\\n\\\\n\\\\n const exchangeOfferHook = offerHandle => {\\\\n const buyAssetForPrice = harden({\\\\n give: { Price: null },\\\\n want: { Asset: null } });\\\\n\\\\n const sellAssetForPrice = harden({\\\\n give: { Asset: null },\\\\n want: { Price: null } });\\\\n\\\\n if (checkIfProposal(offerHandle, sellAssetForPrice)) {\\\\n buyOfferHandles = swapIfCanTradeAndUpdateBook(\\\\n buyOfferHandles,\\\\n sellOfferHandles,\\\\n offerHandle);\\\\n\\\\n /* eslint-disable no-else-return */} else\\\\n if (checkIfProposal(offerHandle, buyAssetForPrice)) {\\\\n sellOfferHandles = swapIfCanTradeAndUpdateBook(\\\\n sellOfferHandles,\\\\n buyOfferHandles,\\\\n offerHandle);} else\\\\n\\\\n {\\\\n /* Eject because the offer must be invalid*/\\\\n return rejectOffer(offerHandle);}\\\\n\\\\n bookOrdersChanged();\\\\n return zoeHelpers.defaultAcceptanceMsg;};\\\\n\\\\n\\\\n const makeExchangeInvite = () =>\\\\n zcf.makeInvitation(exchangeOfferHook, 'exchange');\\\\n\\\\n zcf.initPublicAPI(\\\\n harden({\\\\n makeInvite: makeExchangeInvite,\\\\n getOffer,\\\\n getNotifier: () => notifier$1 }));\\\\n\\\\n\\\\n\\\\n return makeExchangeInvite();};\\\\n\\\\n\\\\nharden(makeContract);exports.makeContract = makeContract;\\\",\\n \\\"packages/eventual-send/src/E.js\\\": \\\"'use strict';\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* global harden */ /* eslint-disable-next-line spaced-comment*/ /*/ <reference path=\\\\\\\"index.d.ts\\\\\\\" />*/\\\\n\\\\nconst readOnlyProxy = {\\\\n set(_target, _prop, _value) {\\\\n return false;},\\\\n\\\\n isExtensible(_target) {\\\\n return false;},\\\\n\\\\n setPrototypeOf(_target, _value) {\\\\n return false;},\\\\n\\\\n deleteProperty(_target, _prop) {\\\\n return false;} };\\\\n\\\\n\\\\n\\\\n/**\\\\n * A Proxy handler for E(x).\\\\n *\\\\n * @param {*} x Any value passed to E(x)\\\\n * @returns {ProxyHandler} the Proxy handler\\\\n */\\\\nfunction EProxyHandler(x, HandledPromise) {\\\\n return harden({\\\\n ...readOnlyProxy,\\\\n get(_target, p, _receiver) {\\\\n if (`${p}` !== p) {\\\\n return undefined;}\\\\n\\\\n /* Harden this Promise because it's our only opportunity to ensure*/\\\\n /* p1=E(x).foo() is hardened. The Handled Promise API does not (yet)*/\\\\n /* allow the handler to synchronously influence the promise returned*/\\\\n /* by the handled methods, so we must freeze it from the outside. See*/\\\\n /* #95 for details.*/\\\\n return (...args) => harden(HandledPromise.applyMethod(x, p, args));},\\\\n\\\\n apply(_target, _thisArg, argArray = []) {\\\\n return harden(HandledPromise.applyFunction(x, argArray));},\\\\n\\\\n has(_target, _p) {\\\\n /* We just pretend everything exists.*/\\\\n return true;} });}\\\\n\\\\n\\\\n\\\\n\\\\nfunction makeE(HandledPromise) {\\\\n function E(x) {\\\\n const handler = EProxyHandler(x, HandledPromise);\\\\n return harden(new Proxy(() => {}, handler));}\\\\n\\\\n\\\\n const makeEGetterProxy = (x) =>\\\\n new Proxy(Object.create(null), {\\\\n ...readOnlyProxy,\\\\n has(_target, _prop) {\\\\n return true;},\\\\n\\\\n get(_target, prop) {\\\\n return harden(HandledPromise.get(x, prop));} });\\\\n\\\\n\\\\n\\\\n E.G = makeEGetterProxy;\\\\n E.resolve = HandledPromise.resolve;\\\\n E.unwrap = HandledPromise.unwrap;\\\\n\\\\n E.when = (x, onfulfilled = undefined, onrejected = undefined) =>\\\\n HandledPromise.resolve(x).then(onfulfilled, onrejected);\\\\n\\\\n return harden(E);}exports.default = makeE;\\\",\\n \\\"packages/eventual-send/src/index.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var E$1 = require('./E.js'); /* global harden HandledPromise */\\\\n\\\\n\\\\n\\\\nconst {\\\\n defineProperties,\\\\n getOwnPropertyDescriptors,\\\\n getOwnPropertyDescriptor: gopd,\\\\n getPrototypeOf,\\\\n isFrozen } =\\\\nObject;\\\\n\\\\nconst { prototype: promiseProto } = Promise;\\\\nconst { then: originalThen } = promiseProto;\\\\n\\\\n/* 'E' and 'HandledPromise' are exports of the module*/\\\\n\\\\n/* For now:*/\\\\n/* import { HandledPromise, E } from '@agoric/eventual-send';*/\\\\n/* ...*/\\\\n\\\\nconst hp =\\\\ntypeof HandledPromise === 'undefined' ?\\\\n/* eslint-disable-next-line no-use-before-define*/\\\\nmakeHandledPromise(Promise) :\\\\nharden(HandledPromise);\\\\n\\\\n\\\\n\\\\nconst E = E$1.default(hp);\\\\n\\\\n/* the following method (makeHandledPromise) is part*/\\\\n/* of the shim, and will not be exported by the module once the feature*/\\\\n/* becomes a part of standard javascript*/\\\\n\\\\n/**\\\\n * Create a HandledPromise class to have it support eventual send\\\\n * (wavy-dot) operations.\\\\n *\\\\n * Based heavily on nanoq\\\\n * https://github.com/drses/nanoq/blob/master/src/nanoq.js\\\\n *\\\\n * Original spec for the infix-bang (predecessor to wavy-dot) desugaring:\\\\n * https://web.archive.org/web/20161026162206/http://wiki.ecmascript.org/doku.php?id=strawman:concurrency\\\\n *\\\\n * @return {typeof HandledPromise} Handled promise\\\\n */\\\\nfunction makeHandledPromise(Promise) {\\\\n /* xs doesn't support WeakMap in pre-loaded closures*/\\\\n /* aka \\\\\\\"vetted customization code\\\\\\\"*/\\\\n let presenceToHandler;\\\\n let presenceToPromise;\\\\n let promiseToUnsettledHandler;\\\\n let promiseToPresence; /* only for HandledPromise.unwrap*/\\\\n let forwardedPromiseToPromise; /* forwarding, union-find-ish*/\\\\n function ensureMaps() {\\\\n if (!presenceToHandler) {\\\\n presenceToHandler = new WeakMap();\\\\n presenceToPromise = new WeakMap();\\\\n promiseToUnsettledHandler = new WeakMap();\\\\n promiseToPresence = new WeakMap();\\\\n forwardedPromiseToPromise = new WeakMap();}}\\\\n\\\\n\\\\n\\\\n /**\\\\n * You can imagine a forest of trees in which the roots of each tree is an\\\\n * unresolved HandledPromise or a non-Promise, and each node's parent is the\\\\n * HandledPromise to which it was forwarded. We maintain that mapping of\\\\n * forwarded HandledPromise to its resolution in forwardedPromiseToPromise.\\\\n *\\\\n * We use something like the description of \\\\\\\"Find\\\\\\\" with \\\\\\\"Path splitting\\\\\\\"\\\\n * to propagate changes down to the children efficiently:\\\\n * https://en.wikipedia.org/wiki/Disjoint-set_data_structure\\\\n *\\\\n * @param {*} target Any value.\\\\n * @returns {*} If the target was a HandledPromise, the most-resolved parent of it, otherwise the target.\\\\n */\\\\n function shorten(target) {\\\\n let p = target;\\\\n /* Find the most-resolved value for p.*/\\\\n while (forwardedPromiseToPromise.has(p)) {\\\\n p = forwardedPromiseToPromise.get(p);}\\\\n\\\\n const presence = promiseToPresence.get(p);\\\\n if (presence) {\\\\n /* Presences are final, so it is ok to propagate*/\\\\n /* this upstream.*/\\\\n while (target !== p) {\\\\n const parent = forwardedPromiseToPromise.get(target);\\\\n forwardedPromiseToPromise.delete(target);\\\\n promiseToUnsettledHandler.delete(target);\\\\n promiseToPresence.set(target, presence);\\\\n target = parent;}} else\\\\n\\\\n {\\\\n /* We propagate p and remove all other unsettled handlers*/\\\\n /* upstream.*/\\\\n /* Note that everything except presences is covered here.*/\\\\n while (target !== p) {\\\\n const parent = forwardedPromiseToPromise.get(target);\\\\n forwardedPromiseToPromise.set(target, p);\\\\n promiseToUnsettledHandler.delete(target);\\\\n target = parent;}}\\\\n\\\\n\\\\n return target;}\\\\n\\\\n\\\\n /* This special handler accepts Promises, and forwards*/\\\\n /* handled Promises to their corresponding fulfilledHandler.*/\\\\n let forwardingHandler;\\\\n let handle;\\\\n let promiseResolve;\\\\n\\\\n function HandledPromise(executor, unsettledHandler = undefined) {\\\\n if (new.target === undefined) {\\\\n throw new Error('must be invoked with \\\\\\\"new\\\\\\\"');}\\\\n\\\\n let handledResolve;\\\\n let handledReject;\\\\n let resolved = false;\\\\n let resolvedTarget = null;\\\\n let handledP;\\\\n let continueForwarding = () => {};\\\\n const superExecutor = (superResolve, superReject) => {\\\\n handledResolve = value => {\\\\n if (resolved) {\\\\n return resolvedTarget;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n value = shorten(value);\\\\n let targetP;\\\\n if (\\\\n promiseToUnsettledHandler.has(value) ||\\\\n promiseToPresence.has(value))\\\\n {\\\\n targetP = value;} else\\\\n {\\\\n /* We're resolving to a non-promise, so remove our handler.*/\\\\n promiseToUnsettledHandler.delete(handledP);\\\\n targetP = presenceToPromise.get(value);}\\\\n\\\\n /* Ensure our data structure is a propert tree (avoid cycles).*/\\\\n if (targetP && targetP !== handledP) {\\\\n forwardedPromiseToPromise.set(handledP, targetP);} else\\\\n {\\\\n forwardedPromiseToPromise.delete(handledP);}\\\\n\\\\n\\\\n /* Remove stale unsettled handlers, set to canonical form.*/\\\\n shorten(handledP);\\\\n\\\\n /* Ensure our unsettledHandler is cleaned up if not already.*/\\\\n if (promiseToUnsettledHandler.has(handledP)) {\\\\n handledP.then(_ => promiseToUnsettledHandler.delete(handledP));}\\\\n\\\\n\\\\n /* Finish the resolution.*/\\\\n superResolve(value);\\\\n resolved = true;\\\\n resolvedTarget = value;\\\\n\\\\n /* We're resolved, so forward any postponed operations to us.*/\\\\n continueForwarding();\\\\n return resolvedTarget;};\\\\n\\\\n handledReject = err => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n promiseToUnsettledHandler.delete(handledP);\\\\n resolved = true;\\\\n superReject(err);\\\\n continueForwarding();};};\\\\n\\\\n\\\\n handledP = harden(Reflect.construct(Promise, [superExecutor], new.target));\\\\n\\\\n ensureMaps();\\\\n\\\\n const makePostponedHandler = () => {\\\\n /* Create a simple postponedHandler that just postpones until the*/\\\\n /* fulfilledHandler is set.*/\\\\n let donePostponing;\\\\n const interlockP = new Promise(resolve => {\\\\n donePostponing = () => resolve();});\\\\n\\\\n\\\\n const makePostponedOperation = postponedOperation => {\\\\n /* Just wait until the handler is resolved/rejected.*/\\\\n return function postpone(x, ...args) {\\\\n /* console.log(`forwarding ${postponedOperation} ${args[0]}`);*/\\\\n return new HandledPromise((resolve, reject) => {\\\\n interlockP.\\\\n then(_ => {\\\\n /* If targetP is a handled promise, use it, otherwise x.*/\\\\n resolve(HandledPromise[postponedOperation](x, ...args));}).\\\\n\\\\n catch(reject);});};};\\\\n\\\\n\\\\n\\\\n\\\\n const postponedHandler = {\\\\n get: makePostponedOperation('get'),\\\\n applyMethod: makePostponedOperation('applyMethod') };\\\\n\\\\n return [postponedHandler, donePostponing];};\\\\n\\\\n\\\\n if (!unsettledHandler) {\\\\n /* This is insufficient for actual remote handled Promises*/\\\\n /* (too many round-trips), but is an easy way to create a*/\\\\n /* local handled Promise.*/\\\\n [unsettledHandler, continueForwarding] = makePostponedHandler();}\\\\n\\\\n\\\\n const validateHandler = h => {\\\\n if (Object(h) !== h) {\\\\n throw TypeError(`Handler ${h} cannot be a primitive`);}};\\\\n\\\\n\\\\n validateHandler(unsettledHandler);\\\\n\\\\n /* Until the handled promise is resolved, we use the unsettledHandler.*/\\\\n promiseToUnsettledHandler.set(handledP, unsettledHandler);\\\\n\\\\n const rejectHandled = reason => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n handledReject(reason);};\\\\n\\\\n\\\\n const resolveWithPresence = presenceHandler => {\\\\n if (resolved) {\\\\n return resolvedTarget;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n try {\\\\n /* Sanity checks.*/\\\\n validateHandler(presenceHandler);\\\\n\\\\n /* Validate and install our mapped target (i.e. presence).*/\\\\n resolvedTarget = Object.create(null);\\\\n\\\\n /* Create table entries for the presence mapped to the*/\\\\n /* fulfilledHandler.*/\\\\n presenceToPromise.set(resolvedTarget, handledP);\\\\n promiseToPresence.set(handledP, resolvedTarget);\\\\n presenceToHandler.set(resolvedTarget, presenceHandler);\\\\n\\\\n /* We committed to this presence, so resolve.*/\\\\n handledResolve(resolvedTarget);\\\\n return resolvedTarget;}\\\\n catch (e) {\\\\n handledReject(e);\\\\n throw e;}};\\\\n\\\\n\\\\n\\\\n const resolveHandled = async (target, deprecatedPresenceHandler) => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n try {\\\\n if (deprecatedPresenceHandler) {\\\\n throw TypeError(\\\\n `resolveHandled no longer accepts a handler; use resolveWithPresence`);}\\\\n\\\\n\\\\n\\\\n /* Resolve the target.*/\\\\n handledResolve(target);}\\\\n catch (e) {\\\\n handledReject(e);}};\\\\n\\\\n\\\\n\\\\n /* Invoke the callback to let the user resolve/reject.*/\\\\n executor(\\\\n (...args) => {\\\\n resolveHandled(...args);},\\\\n\\\\n rejectHandled,\\\\n resolveWithPresence);\\\\n\\\\n return handledP;}\\\\n\\\\n\\\\n HandledPromise.prototype = promiseProto;\\\\n Object.setPrototypeOf(HandledPromise, Promise);\\\\n\\\\n function isFrozenPromiseThen(p) {\\\\n return (\\\\n isFrozen(p) &&\\\\n getPrototypeOf(p) === promiseProto &&\\\\n promiseResolve(p) === p &&\\\\n gopd(p, 'then') === undefined &&\\\\n gopd(promiseProto, 'then').value === originalThen /* unnecessary under SES*/);}\\\\n\\\\n\\\\n\\\\n const staticMethods = harden({\\\\n get(target, key) {\\\\n return handle(target, 'get', key);},\\\\n\\\\n getSendOnly(target, key) {\\\\n handle(target, 'get', key);},\\\\n\\\\n applyFunction(target, args) {\\\\n return handle(target, 'applyMethod', undefined, args);},\\\\n\\\\n applyFunctionSendOnly(target, args) {\\\\n handle(target, 'applyMethod', undefined, args);},\\\\n\\\\n applyMethod(target, key, args) {\\\\n return handle(target, 'applyMethod', key, args);},\\\\n\\\\n applyMethodSendOnly(target, key, args) {\\\\n handle(target, 'applyMethod', key, args);},\\\\n\\\\n resolve(value) {\\\\n ensureMaps();\\\\n /* Resolving a Presence returns the pre-registered handled promise.*/\\\\n let resolvedPromise = presenceToPromise.get(value);\\\\n if (!resolvedPromise) {\\\\n resolvedPromise = promiseResolve(value);}\\\\n\\\\n /* Prevent any proxy trickery.*/\\\\n harden(resolvedPromise);\\\\n if (isFrozenPromiseThen(resolvedPromise)) {\\\\n return resolvedPromise;}\\\\n\\\\n /* Assimilate the thenable.*/\\\\n const executeThen = (resolve, reject) =>\\\\n resolvedPromise.then(resolve, reject);\\\\n return harden(\\\\n promiseResolve().then(_ => new HandledPromise(executeThen)));},\\\\n\\\\n\\\\n /* TODO verify that this is safe to provide universally, i.e.,*/\\\\n /* that by itself it doesn't provide access to mutable state in*/\\\\n /* ways that violate normal ocap module purity rules. The claim*/\\\\n /* that it does not rests on the handled promise itself being*/\\\\n /* necessary to perceive this mutable state. In that sense, we*/\\\\n /* can think of the right to perceive it, and of access to the*/\\\\n /* target, as being in the handled promise. Note that a .then on*/\\\\n /* the handled promise will already provide async access to the*/\\\\n /* target, so the only additional authorities are: 1)*/\\\\n /* synchronous access for handled promises only, and thus 2) the*/\\\\n /* ability to tell, from the client side, whether a promise is*/\\\\n /* handled. Or, at least, the ability to tell given that the*/\\\\n /* promise is already fulfilled.*/\\\\n unwrap(value) {\\\\n /* This check for Thenable is safe, since in a remote-object*/\\\\n /* environment, our comms system will defend against remote*/\\\\n /* objects being represented as a tricky local Proxy, otherwise*/\\\\n /* it is guaranteed to be local and therefore synchronous enough.*/\\\\n if (Object(value) !== value || !('then' in value)) {\\\\n /* Not a Thenable, so return it.*/\\\\n /* This means that local objects will pass through without error.*/\\\\n return value;}\\\\n\\\\n\\\\n /* Try to look up the HandledPromise.*/\\\\n ensureMaps();\\\\n const pr = presenceToPromise.get(value) || value;\\\\n\\\\n /* Find the fulfilled presence for that HandledPromise.*/\\\\n const presence = promiseToPresence.get(pr);\\\\n if (!presence) {\\\\n throw TypeError(\\\\n `Value is a Thenble but not a HandledPromise fulfilled to a presence`);}\\\\n\\\\n\\\\n return presence;} });\\\\n\\\\n\\\\n\\\\n defineProperties(HandledPromise, getOwnPropertyDescriptors(staticMethods));\\\\n\\\\n function makeForwarder(operation, localImpl) {\\\\n return (o, ...args) => {\\\\n /* We are in another turn already, and have the naked object.*/\\\\n const fulfilledHandler = presenceToHandler.get(o);\\\\n if (\\\\n fulfilledHandler &&\\\\n typeof fulfilledHandler[operation] === 'function')\\\\n {\\\\n /* The handler was resolved, so use it.*/\\\\n return fulfilledHandler[operation](o, ...args);}\\\\n\\\\n\\\\n /* Not handled, so use the local implementation.*/\\\\n return localImpl(o, ...args);};}\\\\n\\\\n\\\\n\\\\n /* eslint-disable-next-line prefer-const*/\\\\n forwardingHandler = {\\\\n get: makeForwarder('get', (o, key) => o[key]),\\\\n applyMethod: makeForwarder('applyMethod', (o, optKey, args) => {\\\\n if (optKey === undefined || optKey === null) {\\\\n return o(...args);}\\\\n\\\\n /* console.log(`sending`, optKey, o[optKey], o);*/\\\\n if (typeof o[optKey] !== 'function') {\\\\n throw TypeError(`o[${JSON.stringify(optKey)}] is not a function`);}\\\\n\\\\n return o[optKey](...args);}) };\\\\n\\\\n\\\\n\\\\n handle = (p, operation, ...opArgs) => {\\\\n ensureMaps();\\\\n const returnedP = new HandledPromise((resolve, reject) => {\\\\n /* We run in a future turn to prevent synchronous attacks,*/\\\\n let raceIsOver = false;\\\\n function win(handlerName, handler, o) {\\\\n if (raceIsOver) {\\\\n return;}\\\\n\\\\n if (typeof handler[operation] !== 'function') {\\\\n throw TypeError(`${handlerName}.${operation} is not a function`);}\\\\n\\\\n try {\\\\n resolve(handler[operation](o, ...opArgs, returnedP));}\\\\n catch (reason) {\\\\n reject(reason);}\\\\n\\\\n raceIsOver = true;}\\\\n\\\\n\\\\n function lose(e) {\\\\n if (raceIsOver) {\\\\n return;}\\\\n\\\\n reject(e);\\\\n raceIsOver = true;}\\\\n\\\\n\\\\n /* This contestant tries to win with the target's resolution.*/\\\\n HandledPromise.resolve(p).\\\\n then(o => win('forwardingHandler', forwardingHandler, o)).\\\\n catch(lose);\\\\n\\\\n /* This contestant sleeps a turn, but then tries to win immediately.*/\\\\n HandledPromise.resolve().\\\\n then(() => {\\\\n p = shorten(p);\\\\n const unsettledHandler = promiseToUnsettledHandler.get(p);\\\\n if (\\\\n unsettledHandler &&\\\\n typeof unsettledHandler[operation] === 'function')\\\\n {\\\\n /* and resolve to the answer from the specific unsettled handler,*/\\\\n /* opArgs are something like [prop] or [method, args],*/\\\\n /* so we don't risk the user's args leaking into this expansion.*/\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n win('unsettledHandler', unsettledHandler, p);} else\\\\n if (Object(p) !== p || !('then' in p)) {\\\\n /* Not a Thenable, so use it.*/\\\\n win('forwardingHandler', forwardingHandler, p);} else\\\\n if (promiseToPresence.has(p)) {\\\\n /* We have the object synchronously, so resolve with it.*/\\\\n const o = promiseToPresence.get(p);\\\\n win('forwardingHandler', forwardingHandler, o);}\\\\n\\\\n /* If we made it here without winning, then we will wait*/\\\\n /* for the other contestant to win instead.*/}).\\\\n\\\\n catch(lose);});\\\\n\\\\n\\\\n /* We return a handled promise with the default unsettled handler.*/\\\\n /* This prevents a race between the above Promise.resolves and*/\\\\n /* pipelining.*/\\\\n return returnedP;};\\\\n\\\\n\\\\n promiseResolve = Promise.resolve.bind(Promise);\\\\n return harden(HandledPromise);}exports.E = E;exports.HandledPromise = hp;exports.makeHandledPromise = makeHandledPromise;\\\",\\n \\\"packages/produce-promise/src/producePromise.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nindex = require('../../eventual-send/src/index.js'); /* global harden */ /**\\\\n * @template U,V\\\\n * @typedef {Object} PromiseRecord A reified Promise\\\\n * @property {(value?: U) => void} resolve\\\\n * @property {(reason?: V) => void} reject\\\\n * @property {Promise.<U, V>} promise\\\\n */ /**\\\\n * producePromise() builds a HandledPromise object, and returns a record\\\\n * containing the promise itself, as well as separate facets for resolving\\\\n * and rejecting it.\\\\n *\\\\n * @template U,V\\\\n * @returns {PromiseRecord.<U,V>}\\\\n */function producePromise() {let res;let rej; /* We use a HandledPromise so that we can run HandledPromise.unwrap(p)*/ /* even if p doesn't travel through a comms system (like SwingSet's).*/const p = new index.HandledPromise((resolve, reject) => {\\\\n res = resolve;\\\\n rej = reject;});\\\\n\\\\n /* Node.js adds the `domain` property which is not a standard*/\\\\n /* property on Promise. Because we do not know it to be ocap-safe,*/\\\\n /* we remove it.*/\\\\n if (p.domain) {\\\\n /* deleting p.domain may break functionality. To retain current*/\\\\n /* functionality at the expense of safety, set unsafe to true.*/\\\\n const unsafe = false;\\\\n if (unsafe) {\\\\n const originalDomain = p.domain;\\\\n Object.defineProperty(p, 'domain', {\\\\n get() {\\\\n return originalDomain;} });} else\\\\n\\\\n\\\\n {\\\\n delete p.domain;}}\\\\n\\\\n\\\\n return harden({ promise: p, resolve: res, reject: rej });}\\\\n\\\\nharden(producePromise);\\\\n\\\\n/**\\\\n * Determine if the argument is a Promise.\\\\n *\\\\n * @param {Promise} maybePromise The value to examine\\\\n * @returns {boolean} Whether it is a promise\\\\n */\\\\nfunction isPromise(maybePromise) {\\\\n return index.HandledPromise.resolve(maybePromise) === maybePromise;}\\\\n\\\\nharden(isPromise);exports.isPromise = isPromise;exports.producePromise = producePromise;\\\",\\n \\\"packages/notifier/src/notifier.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nproducePromise = require('../../produce-promise/src/producePromise.js'); /* @ts-check*/ /**\\\\n * @typedef {number | undefined} UpdateCount a value used to mark the position\\\\n * in the update stream. For the last state, the updateCount is undefined.\\\\n */ /**\\\\n * @template T the type of the state value\\\\n * @typedef {Object} UpdateRecord<T>\\\\n * @property {T} value is whatever state the service wants to publish\\\\n * @property {UpdateCount} updateCount is a value that identifies the update\\\\n */ /**\\\\n * @template T the type of the notifier state\\\\n * @callback GetUpdateSince<T> Can be called repeatedly to get a sequence of\\\\n * update records\\\\n * @param {UpdateCount} [updateCount] return update record as of a handle\\\\n * If the handle argument is omitted or differs from the current handle,\\\\n * return the current record.\\\\n * Otherwise, after the next state change, the promise will resolve to the\\\\n * then-current value of the record.\\\\n * @returns {Promise<UpdateRecord<T>>} resolves to the corresponding update\\\\n */ /**\\\\n * @template T the type of the notifier state\\\\n * @typedef {Object} Notifier<T> an object that can be used to get the current\\\\n * state or updates\\\\n * @property {GetUpdateSince<T>} getUpdateSince return update record as of a\\\\n * handle\\\\n */ /**\\\\n * @template T the type of the notifier state\\\\n * @typedef {Object} Updater<T> an object that should be closely held, as\\\\n * anyone with access to\\\\n * it can provide updates\\\\n * @property {(state: T) => void} updateState sets the new state, and resolves\\\\n * the outstanding promise to send an update\\\\n * @property {(finalState: T) => void} finish sets the final state, sends a\\\\n * final update, and freezes the\\\\n * updater\\\\n * @property {(reason: T) => void} reject the stream becomes erroneously\\\\n * terminated, allegedly for the stated reason.\\\\n */ /**\\\\n * @template T the type of the notifier state\\\\n * @typedef {Object} NotifierRecord<T> the produced notifier/updater pair\\\\n * @property {Notifier<T>} notifier the (widely-held) notifier consumer\\\\n * @property {Updater<T>} updater the (closely-held) notifier producer\\\\n */ /**\\\\n * Whether to enable deprecated legacy features to support legacy clients\\\\n * during the transition. TODO once all clients are updated to the new API,\\\\n * remove this flag and all code enabled by this flag.\\\\n */const supportLegacy = true; /**\\\\n * Produces a pair of objects, which allow a service to produce a stream of\\\\n * update promises.\\\\n *\\\\n * @template T the type of the notifier state\\\\n * @param {T} [initialState] the first state to be returned\\\\n * @returns {NotifierRecord<T>} the notifier and updater\\\\n */ /* The initial state argument has to be truly optional even though it can*/ /* be any first class value including `undefined`. We need to distinguish the*/ /* presence vs the absence of it, which we cannot do with the optional argument*/ /* syntax. Rather we use the arity of the arguments array.*/ /**/ /* If no initial state is provided to `makeNotifierKit`, then it starts without*/ /* an initial state. Its initial state will instead be the state of the first*/ /* update.*/const makeNotifierKit = (...args) => {let nextPromiseKit = producePromise.producePromise();let currentUpdateCount = 1; /* avoid falsy numbers*/let currentResponse;const hasState = () => currentResponse !== undefined;const final = () => currentUpdateCount === undefined;const extraProperties = () => supportLegacy ? { updateHandle: currentUpdateCount, done: final() } : {};if (args.length >= 1) {/* start as hasState() && !final()*/currentResponse = harden({ value: args[0], updateCount: currentUpdateCount, ...extraProperties() });} /* else start as !hasState() && !final()*/ /* NaN matches nothing*/function getUpdateSince(updateCount = NaN) {if (\\\\n hasState() && (\\\\n final() || currentResponse.updateCount !== updateCount))\\\\n {\\\\n /* If hasState() and either it is final() or it is*/\\\\n /* not the state of updateCount, return the current state.*/\\\\n return Promise.resolve(currentResponse);}\\\\n\\\\n /* otherwise return a promise for the next state.*/\\\\n return nextPromiseKit.promise;}\\\\n\\\\n\\\\n function updateState(state) {\\\\n if (final()) {\\\\n throw new Error('Cannot update state after termination.');}\\\\n\\\\n\\\\n /* become hasState() && !final()*/\\\\n currentUpdateCount += 1;\\\\n currentResponse = harden({\\\\n value: state,\\\\n updateCount: currentUpdateCount,\\\\n ...extraProperties() });\\\\n\\\\n nextPromiseKit.resolve(currentResponse);\\\\n nextPromiseKit = producePromise.producePromise();}\\\\n\\\\n\\\\n function finish(finalState) {\\\\n if (final()) {\\\\n throw new Error('Cannot finish after termination.');}\\\\n\\\\n\\\\n /* become hasState() && final()*/\\\\n currentUpdateCount = undefined;\\\\n currentResponse = harden({\\\\n value: finalState,\\\\n updateCount: currentUpdateCount,\\\\n ...extraProperties() });\\\\n\\\\n nextPromiseKit.resolve(currentResponse);\\\\n nextPromiseKit = undefined;}\\\\n\\\\n\\\\n function reject(reason) {\\\\n if (final()) {\\\\n throw new Error('Cannot reject after termination.');}\\\\n\\\\n\\\\n /* become !hasState() && final()*/\\\\n currentUpdateCount = undefined;\\\\n currentResponse = undefined;\\\\n nextPromiseKit.reject(reason);}\\\\n\\\\n\\\\n /* notifier facet is separate so it can be handed out loosely while updater*/\\\\n /* is tightly held*/\\\\n const notifier = harden({ getUpdateSince });\\\\n const updater = harden({\\\\n updateState,\\\\n finish,\\\\n reject,\\\\n ...(supportLegacy ? { resolve: finish } : {}) });\\\\n\\\\n return harden({ notifier, updater });};\\\\n\\\\n\\\\n/* Deprecated. TODO remove once no clients need it.*/\\\\n/* Unlike makeNotifierKit, produceIssuerKit always produces*/\\\\n/* a notifier with an initial state, which defaults to undefined.*/\\\\nconst produceNotifier = (initialState = undefined) =>\\\\nmakeNotifierKit(initialState);exports.makeNotifierKit = makeNotifierKit;exports.produceNotifier = produceNotifier;\\\",\\n \\\"packages/zoe/src/contractSupport/auctions.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true }); /* global harden */\\\\n\\\\nconst secondPriceLogic = (bidAmountMath, bidOfferHandles, bids) => {\\\\n let highestBid = bidAmountMath.getEmpty();\\\\n let secondHighestBid = bidAmountMath.getEmpty();\\\\n let highestBidOfferHandle;\\\\n /* eslint-disable-next-line array-callback-return*/\\\\n bidOfferHandles.map((offerHandle, i) => {\\\\n const bid = bids[i];\\\\n /* If the bid is greater than the highestBid, it's the new highestBid*/\\\\n if (bidAmountMath.isGTE(bid, highestBid)) {\\\\n secondHighestBid = highestBid;\\\\n highestBid = bid;\\\\n highestBidOfferHandle = offerHandle;} else\\\\n if (bidAmountMath.isGTE(bid, secondHighestBid)) {\\\\n /* If the bid is not greater than the highest bid, but is greater*/\\\\n /* than the second highest bid, it is the new second highest bid.*/\\\\n secondHighestBid = bid;}});\\\\n\\\\n\\\\n return harden({\\\\n winnerOfferHandle: highestBidOfferHandle,\\\\n winnerBid: highestBid,\\\\n price: secondHighestBid });};\\\\n\\\\n\\\\n\\\\nconst closeAuction = (\\\\nzcf,\\\\n{ auctionLogicFn, sellerOfferHandle, allBidHandles }) =>\\\\n{\\\\n const { brandKeywordRecord } = zcf.getInstanceRecord();\\\\n const bidAmountMath = zcf.getAmountMath(brandKeywordRecord.Ask);\\\\n const assetAmountMath = zcf.getAmountMath(brandKeywordRecord.Asset);\\\\n\\\\n /* Filter out any inactive bids*/\\\\n const { active: activeBidHandles } = zcf.getOfferStatuses(\\\\n harden(allBidHandles));\\\\n\\\\n\\\\n const getBids = amountsKeywordRecord => amountsKeywordRecord.Bid;\\\\n const bids = zcf.getCurrentAllocations(activeBidHandles).map(getBids);\\\\n const assetAmount = zcf.getOffer(sellerOfferHandle).proposal.give.Asset;\\\\n\\\\n const { winnerOfferHandle, winnerBid, price } = auctionLogicFn(\\\\n bidAmountMath,\\\\n activeBidHandles,\\\\n bids);\\\\n\\\\n\\\\n /* The winner gets to keep the difference between their bid and the*/\\\\n /* price paid.*/\\\\n const winnerRefund = bidAmountMath.subtract(winnerBid, price);\\\\n\\\\n const newSellerAmounts = { Asset: assetAmountMath.getEmpty(), Ask: price };\\\\n const newWinnerAmounts = { Asset: assetAmount, Bid: winnerRefund };\\\\n\\\\n /* Everyone else gets a refund so their values remain the*/\\\\n /* same.*/\\\\n zcf.reallocate(\\\\n harden([sellerOfferHandle, winnerOfferHandle]),\\\\n harden([newSellerAmounts, newWinnerAmounts]));\\\\n\\\\n const allOfferHandles = harden([sellerOfferHandle, ...activeBidHandles]);\\\\n zcf.complete(allOfferHandles);};exports.closeAuction = closeAuction;exports.secondPriceLogic = secondPriceLogic;\\\",\\n \\\"packages/assert/src/assert.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* Copyright (C) 2019 Agoric, under Apache License 2.0*/ /* @ts-check*/ /* This module assumes the de-facto standard `console` host object.*/ /* To the extent that this `console` is considered a resource,*/ /* this module must be considered a resource module.*/ /**\\\\n * Prepend the correct indefinite article onto a noun, typically a typeof result\\\\n * e.g., \\\\\\\"an Object\\\\\\\" vs. \\\\\\\"a Number\\\\\\\"\\\\n *\\\\n * @param {string} str The noun to prepend\\\\n * @returns {string} The noun prepended with a/an\\\\n */\\\\nfunction an(str) {\\\\n str = `${str}`;\\\\n if (str.length >= 1 && 'aeiouAEIOU'.includes(str[0])) {\\\\n return `an ${str}`;}\\\\n\\\\n return `a ${str}`;}\\\\n\\\\nharden(an);\\\\n\\\\n/**\\\\n * Like `JSON.stringify` but does not blow up if given a cycle. This is not\\\\n * intended to be a serialization to support any useful unserialization,\\\\n * or any programmatic use of the resulting string. The string is intended\\\\n * only for showing a human, in order to be informative enough for some\\\\n * logging purposes. As such, this `cycleTolerantStringify` has an\\\\n * imprecise specification and may change over time.\\\\n *\\\\n * The current `cycleTolerantStringify` possibly emits too many \\\\\\\"seen\\\\\\\"\\\\n * markings: Not only for cycles, but also for repeated subtrees by\\\\n * object identity.\\\\n */\\\\nfunction cycleTolerantStringify(payload) {\\\\n const seenSet = new Set();\\\\n const replacer = (_, val) => {\\\\n if (typeof val === 'object' && val !== null) {\\\\n if (seenSet.has(val)) {\\\\n return '<**seen**>';}\\\\n\\\\n seenSet.add(val);}\\\\n\\\\n return val;};\\\\n\\\\n return JSON.stringify(payload, replacer);}\\\\n\\\\n\\\\nconst declassifiers = new WeakSet();\\\\n\\\\n/**\\\\n * To \\\\\\\"declassify\\\\\\\" and quote a substitution value used in a\\\\n * details`...` template literal, enclose that substitution expression\\\\n * in a call to `q`. This states that the argument should appear quoted (with\\\\n * `JSON.stringify`), in the error message of the thrown error. The payload\\\\n * itself is still passed unquoted to the console as it would be without q.\\\\n *\\\\n * Starting from the example in the `details` comment, say instead that the\\\\n * color the sky is supposed to be is also computed. Say that we still don't\\\\n * want to reveal the sky's actual color, but we do want the thrown error's\\\\n * message to reveal what color the sky was supposed to be:\\\\n * ```js\\\\n * assert.equal(\\\\n * sky.color,\\\\n * color,\\\\n * details`${sky.color} should be ${q(color)}`,\\\\n * );\\\\n * ```\\\\n *\\\\n * @typedef {Object} StringablePayload\\\\n * @property {*} payload The original payload\\\\n * @property {() => string} toString How to print the payload\\\\n *\\\\n * @param {*} payload What to declassify\\\\n * @returns {StringablePayload} The declassified payload\\\\n */\\\\nfunction q(payload) {\\\\n /* Don't harden the payload*/\\\\n const result = Object.freeze({\\\\n payload,\\\\n toString: Object.freeze(() => cycleTolerantStringify(payload)) });\\\\n\\\\n declassifiers.add(result);\\\\n return result;}\\\\n\\\\nharden(q);\\\\n\\\\n/**\\\\n * Use the `details` function as a template literal tag to create\\\\n * informative error messages. The assertion functions take such messages\\\\n * as optional arguments:\\\\n * ```js\\\\n * assert(sky.isBlue(), details`${sky.color} should be \\\\\\\"blue\\\\\\\"`);\\\\n * ```\\\\n * The details template tag returns an object that can print itself with the\\\\n * formatted message in two ways. It will report the real details to the\\\\n * console but include only the typeof information in the thrown error\\\\n * to prevent revealing secrets up the exceptional path. In the example\\\\n * above, the thrown error may reveal only that `sky.color` is a string,\\\\n * whereas the same diagnostic printed to the console reveals that the\\\\n * sky was green.\\\\n *\\\\n * WARNING: this function currently returns an unhardened result, as hardening\\\\n * proved to cause significant performance degradation. Consequently, callers\\\\n * should take care to use it only in contexts where this lack of hardening\\\\n * does not present a hazard. In current usage, a `details` template literal\\\\n * may only appear either as an argument to `assert`, where we know hardening\\\\n * won't matter, or inside another hardened object graph, where hardening is\\\\n * already ensured. However, there is currently no means to enfoce these\\\\n * constraints, so users are required to employ this function with caution.\\\\n * Our intent is to eventually have a lint rule that will check for\\\\n * inappropriate uses or find an alternative means of implementing `details`\\\\n * that does not encounter the performance issue. The final disposition of\\\\n * this is being discussed and tracked in issue #679 in the agoric-sdk\\\\n * repository.\\\\n *\\\\n * @typedef {Object} Complainer An object that has custom assert behaviour\\\\n * @property {() => Error} complain Return an Error to throw, and print details to console\\\\n *\\\\n * @typedef {string|Complainer} Details Either a plain string, or made by details``\\\\n *\\\\n * @param {TemplateStringsArray | string[]} template The template to format\\\\n * @param {any[]} args Arguments to the template\\\\n * @returns {Complainer} The complainer for these details\\\\n */\\\\nfunction details(template, ...args) {\\\\n /* const complainer = harden({ // remove harden per above discussion*/\\\\n const complainer = {\\\\n complain() {\\\\n const interleaved = [template[0]];\\\\n const parts = [template[0]];\\\\n for (let i = 0; i < args.length; i += 1) {\\\\n let arg = args[i];\\\\n let argStr;\\\\n if (declassifiers.has(arg)) {\\\\n argStr = `${arg}`;\\\\n arg = arg.payload;} else\\\\n {\\\\n argStr = `(${an(typeof arg)})`;}\\\\n\\\\n\\\\n /* Remove the extra spaces (since console.error puts them*/\\\\n /* between each interleaved).*/\\\\n const priorWithoutSpace = (interleaved.pop() || '').replace(/ $/, '');\\\\n if (priorWithoutSpace !== '') {\\\\n interleaved.push(priorWithoutSpace);}\\\\n\\\\n\\\\n const nextWithoutSpace = template[i + 1].replace(/^ /, '');\\\\n interleaved.push(arg, nextWithoutSpace);\\\\n\\\\n parts.push(argStr, template[i + 1]);}\\\\n\\\\n if (interleaved[interleaved.length - 1] === '') {\\\\n interleaved.pop();}\\\\n\\\\n if (args.length >= 1) {\\\\n parts.push('\\\\\\\\nSee console for error data.');}\\\\n\\\\n const err = new Error(parts.join(''));\\\\n console.error('LOGGED ERROR:', ...interleaved, err);\\\\n /* eslint-disable-next-line no-debugger*/\\\\n debugger;\\\\n return err;} };\\\\n\\\\n\\\\n /* });*/\\\\n return complainer;}\\\\n\\\\nharden(details);\\\\n\\\\n/**\\\\n * Fail an assertion, recording details to the console and\\\\n * raising an exception with just type information.\\\\n *\\\\n * The optional `optDetails` can be a string for backwards compatibility\\\\n * with the nodejs assertion library.\\\\n * @param {Details} [optDetails] The details of what was asserted\\\\n * @returns {never}\\\\n */\\\\nfunction fail(optDetails = details`Assert failed`) {\\\\n if (typeof optDetails === 'string') {\\\\n /* If it is a string, use it as the literal part of the template so*/\\\\n /* it doesn't get quoted.*/\\\\n optDetails = details([optDetails]);}\\\\n\\\\n throw optDetails.complain();}\\\\n\\\\n\\\\n/**\\\\n * @param {*} flag The truthy/falsy value\\\\n * @param {Details} [optDetails] The details to throw\\\\n * @returns {asserts flag}\\\\n */\\\\nfunction assert(flag, optDetails = details`Check failed`) {\\\\n if (!flag) {\\\\n throw fail(optDetails);}}\\\\n\\\\n\\\\n\\\\n/**\\\\n * Assert that two values must be `Object.is`.\\\\n * @param {*} actual The value we received\\\\n * @param {*} expected What we wanted\\\\n * @param {Details} [optDetails] The details to throw\\\\n * @returns {void}\\\\n */\\\\nfunction equal(\\\\nactual,\\\\nexpected,\\\\noptDetails = details`Expected ${actual} is same as ${expected}`)\\\\n{\\\\n assert(Object.is(actual, expected), optDetails);}\\\\n\\\\n\\\\n/**\\\\n * Assert an expected typeof result.\\\\n * @type {AssertTypeof}\\\\n * @param {any} specimen The value to get the typeof\\\\n * @param {string} typename The expected name\\\\n * @param {Details} [optDetails] The details to throw\\\\n */\\\\nconst assertTypeof = (specimen, typename, optDetails) => {\\\\n assert(\\\\n typeof typename === 'string',\\\\n details`${q(typename)} must be a string`);\\\\n\\\\n if (optDetails === undefined) {\\\\n /* Like*/\\\\n /* ```js*/\\\\n /* optDetails = details`${specimen} must be ${q(an(typename))}`;*/\\\\n /* ```*/\\\\n /* except it puts the typename into the literal part of the template*/\\\\n /* so it doesn't get quoted.*/\\\\n optDetails = details(['', ` must be ${an(typename)}`], specimen);}\\\\n\\\\n equal(typeof specimen, typename, optDetails);};\\\\n\\\\n\\\\n/**\\\\n * assert that expr is truthy, with an optional details to describe\\\\n * the assertion. It is a tagged template literal like\\\\n * ```js\\\\n * assert(expr, details`....`);`\\\\n * ```\\\\n * If expr is falsy, then the template contents are reported to the\\\\n * console and also in a thrown error.\\\\n *\\\\n * The literal portions of the template are assumed non-sensitive, as\\\\n * are the `typeof` types of the substitution values. These are\\\\n * assembled into the thrown error message. The actual contents of the\\\\n * substitution values are assumed sensitive, to be revealed to the\\\\n * console only. We assume only the virtual platform's owner can read\\\\n * what is written to the console, where the owner is in a privileged\\\\n * position over computation running on that platform.\\\\n *\\\\n * The optional `optDetails` can be a string for backwards compatibility\\\\n * with the nodejs assertion library.\\\\n * @type {typeof assert & { typeof: AssertTypeof, fail: typeof fail, equal: typeof equal }}\\\\n */\\\\nconst assertCombined = Object.assign(assert, {\\\\n equal,\\\\n fail,\\\\n typeof: assertTypeof });\\\\n\\\\nharden(assertCombined);exports.an = an;exports.assert = assertCombined;exports.details = details;exports.q = q;\\\",\\n \\\"node_modules/@agoric/nat/dist/nat.esm.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* Copyright (C) 2011 Google Inc.*/ /* Copyright (C) 2018 Agoric*/ /**/ /* Licensed under the Apache License, Version 2.0 (the \\\\\\\"License\\\\\\\");*/ /* you may not use this file except in compliance with the License.*/ /* You may obtain a copy of the License at*/ /**/ /* http://www.apache.org/licenses/LICENSE-2.0*/ /**/ /* Unless required by applicable law or agreed to in writing, software*/ /* distributed under the License is distributed on an \\\\\\\"AS IS\\\\\\\" BASIS,*/ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*/ /* See the License for the specific language governing permissions and*/ /* limitations under the License.*/ /**\\\\n * Is allegedNum a number in the contiguous range of exactly and\\\\n * unambiguously representable natural numbers (non-negative integers)?\\\\n *\\\\n * <p>See <a href=\\\\n * \\\\\\\"https://code.google.com/p/google-caja/issues/detail?id=1801\\\\\\\"\\\\n * >Issue 1801: Nat must include at most (2**53)-1</a>\\\\n * and <a href=\\\\n * \\\\\\\"https://mail.mozilla.org/pipermail/es-discuss/2013-July/031716.html\\\\\\\"\\\\n * >Allen Wirfs-Brock's suggested phrasing</a> on es-discuss.\\\\n */\\\\n\\\\nfunction Nat(allegedNum) {\\\\n if (!Number.isSafeInteger(allegedNum)) {\\\\n throw new RangeError('not a safe integer');}\\\\n\\\\n\\\\n if (allegedNum < 0) {\\\\n throw new RangeError('negative');}\\\\n\\\\n\\\\n return allegedNum;}exports.default = Nat;\\\",\\n \\\"packages/zoe/src/contractSupport/safeMath.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\nnat_esm = require('../../../../node_modules/@agoric/nat/dist/nat.esm.js'); /* global harden */ /**\\\\n * These operations should be used for calculations with the\\\\n * values of basic fungible tokens.\\\\n */\\\\nconst natSafeMath = harden({\\\\n add: (x, y) => nat_esm.default(x + y),\\\\n subtract: (x, y) => nat_esm.default(x - y),\\\\n multiply: (x, y) => nat_esm.default(x * y),\\\\n floorDivide: (x, y) => nat_esm.default(Math.floor(x / y)) });exports.natSafeMath = natSafeMath;\\\",\\n \\\"packages/zoe/src/contractSupport/bondingCurves.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../../assert/src/assert.js');var safeMath = require('./safeMath.js');\\\\n\\\\n\\\\nconst { add, subtract, multiply, floorDivide } = safeMath.natSafeMath;\\\\n\\\\n/**\\\\n * Contains the logic for calculating how much should be given\\\\n * back to the user in exchange for what they sent in. It also\\\\n * calculates the new amount of the assets in the pool. Reused in\\\\n * several different places, including to check whether an offer\\\\n * is valid, getting the current price for an asset on user\\\\n * request, and to do the actual reallocation after an offer has\\\\n * been made.\\\\n * @param {Object} params\\\\n * @param {number} params.inputValue - the value of the asset sent\\\\n * in to be swapped\\\\n * @param {number} params.inputReserve - the value in the liquidity\\\\n * pool of the kind of asset sent in\\\\n * @param {number} params.outputReserve - the value in the liquidity\\\\n * pool of the kind of asset to be sent out\\\\n * @param {number} params.feeBasisPoints=30 - the fee taken in\\\\n * basis points. The default is 0.3% or 30 basis points. The fee is taken from\\\\n * inputValue\\\\n * @returns {number} outputValue - the current price, in value form\\\\n */\\\\nconst getInputPrice = ({\\\\n inputValue,\\\\n inputReserve,\\\\n outputReserve,\\\\n feeBasisPoints = 30 }) =>\\\\n{\\\\n const oneMinusFeeInTenThousandths = subtract(10000, feeBasisPoints);\\\\n const inputWithFee = multiply(inputValue, oneMinusFeeInTenThousandths);\\\\n const numerator = multiply(inputWithFee, outputReserve);\\\\n const denominator = add(multiply(inputReserve, 10000), inputWithFee);\\\\n\\\\n const outputValue = floorDivide(numerator, denominator);\\\\n return outputValue;};\\\\n\\\\n\\\\nfunction assertDefined(label, value) {\\\\n assert.assert(value !== undefined, assert.details`${label} value required`);}\\\\n\\\\n\\\\n/* Calculate how many liquidity tokens we should be minting to send back to the*/\\\\n/* user when adding liquidity. Calculations are based on the comparing the*/\\\\n/* inputValue to the inputReserve. If the current supply is zero, just return*/\\\\n/* the inputValue.*/\\\\nconst calcLiqValueToMint = ({\\\\n liqTokenSupply,\\\\n inputValue,\\\\n inputReserve }) =>\\\\n{\\\\n assertDefined('liqTokenSupply', liqTokenSupply);\\\\n assertDefined('inputValue', inputValue);\\\\n assertDefined('inputReserve', inputReserve);\\\\n return liqTokenSupply > 0 ?\\\\n floorDivide(multiply(inputValue, liqTokenSupply), inputReserve) :\\\\n inputValue;};\\\\n\\\\n\\\\n/* Calculate how many underlying tokens (in the form of a value) should be*/\\\\n/* returned when removing liquidity.*/\\\\nconst calcValueToRemove = ({\\\\n liqTokenSupply,\\\\n poolValue,\\\\n liquidityValueIn }) =>\\\\n{\\\\n assertDefined('liqTokenSupply', liqTokenSupply);\\\\n assertDefined('liquidityValueIn', liquidityValueIn);\\\\n assertDefined('poolValue', poolValue);\\\\n\\\\n return floorDivide(multiply(liquidityValueIn, poolValue), liqTokenSupply);};exports.calcLiqValueToMint = calcLiqValueToMint;exports.calcValueToRemove = calcValueToRemove;exports.getInputPrice = getInputPrice;\\\",\\n \\\"packages/zoe/src/contractSupport/stateMachine.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\nassert = require('../../../assert/src/assert.js'); /* global harden */ /* allowedTransitions is an array of arrays which gets turned into a\\\\n * map. The map maps string states to an array of potential next\\\\n * states. For example,\\\\n * const allowedTransitions = [\\\\n ['open', ['closed']],\\\\n ['closed', []],\\\\n * ];\\\\n */\\\\nconst makeStateMachine = (initialState, allowedTransitionsArray) => {\\\\n let state = initialState;\\\\n const allowedTransitions = new Map(allowedTransitionsArray);\\\\n return harden({\\\\n canTransitionTo: (nextState) =>\\\\n allowedTransitions.get(state).includes(nextState),\\\\n transitionTo: nextState => {\\\\n assert.assert(allowedTransitions.get(state).includes(nextState));\\\\n state = nextState;},\\\\n\\\\n getStatus: _ => state });};\\\\n\\\\n\\\\nharden(makeStateMachine);exports.makeStateMachine = makeStateMachine;\\\",\\n \\\"packages/marshal/marshal.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var producePromise = require('../produce-promise/src/producePromise.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nnat_esm = require('../../node_modules/@agoric/nat/dist/nat.esm.js'); /* global harden */ /* TODO: Use just 'remote' when we're willing to make a breaking change.*/\\\\nconst REMOTE_STYLE = 'presence';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n/**\\\\n * This is an interface specification.\\\\n * For now, it is just a string, but will eventually become something\\\\n * much richer (anything that pureCopy accepts).\\\\n * @typedef {string} InterfaceSpec\\\\n */\\\\n\\\\n/**\\\\n * @type {WeakMap<Object, InterfaceSpec>}\\\\n */\\\\nconst remotableToInterface = new WeakMap();\\\\n\\\\n/**\\\\n * Simple semantics, just tell what interface (or undefined) a remotable has.\\\\n *\\\\n * @param {*} maybeRemotable the value to check\\\\n * @returns {InterfaceSpec} the interface specification, or undefined if not a Remotable\\\\n */\\\\nfunction getInterfaceOf(maybeRemotable) {\\\\n return remotableToInterface.get(maybeRemotable);}\\\\n\\\\n\\\\n/**\\\\n * Do a deep copy of the object, handling Proxies and recursion.\\\\n * The resulting copy is guaranteed to be pure data, as well as hardened.\\\\n * Such a hardened, pure copy cannot be used as a communications path.\\\\n *\\\\n * @template T\\\\n * @param {T} val input value. NOTE: Must be hardened!\\\\n * @returns {T} pure, hardened copy\\\\n */\\\\nfunction pureCopy(val, already = new WeakMap()) {\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n const passStyle = passStyleOf(val);\\\\n switch (passStyle) {\\\\n case 'bigint':\\\\n case 'boolean':\\\\n case 'null':\\\\n case 'number':\\\\n case 'string':\\\\n case 'undefined':\\\\n return val;\\\\n\\\\n case 'copyArray':\\\\n case 'copyRecord':{\\\\n const obj = /** @type {Object} */val;\\\\n if (already.has(obj)) {\\\\n return already.get(obj);}\\\\n\\\\n\\\\n /* Create a new identity.*/\\\\n const copy = /** @type {T} */passStyle === 'copyArray' ? [] : {};\\\\n\\\\n /* Prevent recursion.*/\\\\n already.set(obj, copy);\\\\n\\\\n /* Make a deep copy on the new identity.*/\\\\n /* Object.entries(obj) takes a snapshot (even if a Proxy).*/\\\\n Object.entries(obj).forEach(([prop, value]) => {\\\\n copy[prop] = pureCopy(value, already);});\\\\n\\\\n return harden(copy);}\\\\n\\\\n\\\\n case 'copyError':{\\\\n const unk = /** @type {unknown} */val;\\\\n const err = /** @type {Error} */unk;\\\\n\\\\n if (already.has(err)) {\\\\n return already.get(err);}\\\\n\\\\n\\\\n const { name, message } = err;\\\\n\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n const EC = getErrorConstructor(`${name}`) || Error;\\\\n const copy = harden(new EC(`${message}`));\\\\n already.set(err, copy);\\\\n\\\\n const unk2 = /** @type {unknown} */harden(copy);\\\\n return (/** @type {T} */unk2);}\\\\n\\\\n\\\\n case REMOTE_STYLE:{\\\\n throw TypeError(\\\\n `Input value ${passStyle} cannot be copied as must be passed by reference`);}\\\\n\\\\n\\\\n\\\\n default:\\\\n throw TypeError(`Input value ${passStyle} is not recognized as data`);}}\\\\n\\\\n\\\\nharden(pureCopy);\\\\n\\\\n\\\\n/* Special property name that indicates an encoding that needs special*/\\\\n/* decoding.*/\\\\nconst QCLASS = '@qclass';\\\\n\\\\n\\\\n/* objects can only be passed in one of two/three forms:*/\\\\n/* 1: pass-by-remote: all properties (own and inherited) are methods,*/\\\\n/* the object itself is of type object, not function*/\\\\n/* 2: pass-by-copy: all string-named own properties are data, not methods*/\\\\n/* the object must inherit from Object.prototype or null*/\\\\n/* 3: the empty object is pass-by-remote, for identity comparison*/\\\\n\\\\n/* all objects must be frozen*/\\\\n\\\\n/* anything else will throw an error if you try to serialize it*/\\\\n\\\\n/* with these restrictions, our remote call/copy protocols expose all useful*/\\\\n/* behavior of these objects: pass-by-remote objects have no other data (so*/\\\\n/* there's nothing else to copy), and pass-by-copy objects have no other*/\\\\n/* behavior (so there's nothing else to invoke)*/\\\\n\\\\nconst errorConstructors = new Map([\\\\n['Error', Error],\\\\n['EvalError', EvalError],\\\\n['RangeError', RangeError],\\\\n['ReferenceError', ReferenceError],\\\\n['SyntaxError', SyntaxError],\\\\n['TypeError', TypeError],\\\\n['URIError', URIError]]);\\\\n\\\\n\\\\nfunction getErrorConstructor(name) {\\\\n return errorConstructors.get(name);}\\\\n\\\\n\\\\nfunction isPassByCopyError(val) {\\\\n /* TODO: Need a better test than instanceof*/\\\\n if (!(val instanceof Error)) {\\\\n return false;}\\\\n\\\\n const proto = Object.getPrototypeOf(val);\\\\n const { name } = val;\\\\n const EC = getErrorConstructor(name);\\\\n if (!EC || EC.prototype !== proto) {\\\\n throw TypeError(`Must inherit from an error class .prototype ${val}`);}\\\\n\\\\n\\\\n const {\\\\n message: { value: messageStr } = { value: '' },\\\\n /* Allow but ignore only extraneous own `stack` property.*/\\\\n /* TODO: I began the variable below with \\\\\\\"_\\\\\\\". Why do I still need*/\\\\n /* to suppress the lint complaint?*/\\\\n /* eslint-disable-next-line no-unused-vars*/\\\\n stack: _optStackDesc,\\\\n ...restDescs } =\\\\n Object.getOwnPropertyDescriptors(val);\\\\n const restNames = Object.keys(restDescs);\\\\n if (restNames.length >= 1) {\\\\n throw new TypeError(`Unexpected own properties in error: ${restNames}`);}\\\\n\\\\n if (typeof messageStr !== 'string') {\\\\n throw new TypeError(`malformed error object: ${val}`);}\\\\n\\\\n return true;}\\\\n\\\\n\\\\nfunction isPassByCopyArray(val) {\\\\n if (!Array.isArray(val)) {\\\\n return false;}\\\\n\\\\n if (Object.getPrototypeOf(val) !== Array.prototype) {\\\\n throw new TypeError(`malformed array: ${val}`);}\\\\n\\\\n const len = val.length;\\\\n const descs = Object.getOwnPropertyDescriptors(val);\\\\n for (let i = 0; i < len; i += 1) {\\\\n const desc = descs[i];\\\\n if (!desc) {\\\\n throw new TypeError(`arrays must not contain holes`);}\\\\n\\\\n if (!('value' in desc)) {\\\\n throw new TypeError(`arrays must not contain accessors`);}\\\\n\\\\n if (typeof desc.value === 'function') {\\\\n throw new TypeError(`arrays must not contain methods`);}}\\\\n\\\\n\\\\n if (Object.keys(descs).length !== len + 1) {\\\\n throw new TypeError(`array must not have non-indexes ${val}`);}\\\\n\\\\n return true;}\\\\n\\\\n\\\\nfunction isPassByCopyRecord(val) {\\\\n if (Object.getPrototypeOf(val) !== Object.prototype) {\\\\n return false;}\\\\n\\\\n const descList = Object.values(Object.getOwnPropertyDescriptors(val));\\\\n if (descList.length === 0) {\\\\n /* empty non-array objects are pass-by-remote, not pass-by-copy*/\\\\n return false;}\\\\n\\\\n for (const desc of descList) {\\\\n if (!('value' in desc)) {\\\\n /* Should we error if we see an accessor here?*/\\\\n return false;}\\\\n\\\\n if (typeof desc.value === 'function') {\\\\n return false;}}\\\\n\\\\n\\\\n return true;}\\\\n\\\\n\\\\n/**\\\\n * Ensure that val could become a legitimate remotable. This is used internally both\\\\n * in the construction of a new remotable and mustPassByRemote.\\\\n *\\\\n * @param {*} val The remotable candidate to check\\\\n */\\\\nfunction assertCanBeRemotable(val) {\\\\n /* throws exception if cannot*/\\\\n if (typeof val !== 'object') {\\\\n throw new Error(`cannot serialize non-objects like ${val}`);}\\\\n\\\\n if (Array.isArray(val)) {\\\\n throw new Error(`Arrays cannot be pass-by-remote`);}\\\\n\\\\n if (val === null) {\\\\n throw new Error(`null cannot be pass-by-remote`);}\\\\n\\\\n\\\\n const names = Object.getOwnPropertyNames(val);\\\\n names.forEach(name => {\\\\n if (typeof val[name] !== 'function') {\\\\n throw new Error(\\\\n `cannot serialize objects with non-methods like the .${name} in ${val}`);\\\\n\\\\n /* return false;*/}});\\\\n\\\\n\\\\n\\\\n /* ok!*/}\\\\n\\\\n\\\\nfunction mustPassByRemote(val) {\\\\n if (!Object.isFrozen(val)) {\\\\n throw new Error(`cannot serialize non-frozen objects like ${val}`);}\\\\n\\\\n\\\\n if (getInterfaceOf(val) === undefined) {\\\\n /* Not a registered Remotable, so check its contents.*/\\\\n assertCanBeRemotable(val);}\\\\n\\\\n\\\\n /* It's not a registered Remotable, so enforce the prototype check.*/\\\\n const p = Object.getPrototypeOf(val);\\\\n if (p !== null && p !== Object.prototype) {\\\\n mustPassByRemote(p);}}\\\\n\\\\n\\\\n\\\\n/* This is the equality comparison used by JavaScript's Map and Set*/\\\\n/* abstractions, where NaN is the same as NaN and -0 is the same as*/\\\\n/* 0. Marshal serializes -0 as zero, so the semantics of our distributed*/\\\\n/* object system does not distinguish 0 from -0.*/\\\\n/**/\\\\n/* `sameValueZero` is the EcmaScript spec name for this equality comparison,*/\\\\n/* but TODO we need a better name for the API.*/\\\\nfunction sameValueZero(x, y) {\\\\n return x === y || Object.is(x, y);}\\\\n\\\\n\\\\n/* How would val be passed? For primitive values, the answer is*/\\\\n/* * 'null' for null*/\\\\n/* * throwing an error for a symbol, whether registered or not.*/\\\\n/* * that value's typeof string for all other primitive values*/\\\\n/* For frozen objects, the possible answers*/\\\\n/* * 'copyRecord' for non-empty records with only data properties*/\\\\n/* * 'copyArray' for arrays with only data properties*/\\\\n/* * 'copyError' for instances of Error with only data properties*/\\\\n/* * REMOTE_STYLE for non-array objects with only method properties*/\\\\n/* * 'promise' for genuine promises only*/\\\\n/* * throwing an error on anything else, including thenables.*/\\\\n/* We export passStyleOf so other algorithms can use this module's*/\\\\n/* classification.*/\\\\nfunction passStyleOf(val) {\\\\n const typestr = typeof val;\\\\n switch (typestr) {\\\\n case 'object':{\\\\n if (getInterfaceOf(val)) {\\\\n return REMOTE_STYLE;}\\\\n\\\\n if (val === null) {\\\\n return 'null';}\\\\n\\\\n if (QCLASS in val) {\\\\n /* TODO Hilbert hotel*/\\\\n throw new Error(`property \\\\\\\"${QCLASS}\\\\\\\" reserved`);}\\\\n\\\\n if (!Object.isFrozen(val)) {\\\\n throw new Error(\\\\n `Cannot pass non-frozen objects like ${val}. Use harden()`);}\\\\n\\\\n\\\\n if (producePromise.isPromise(val)) {\\\\n return 'promise';}\\\\n\\\\n if (typeof val.then === 'function') {\\\\n throw new Error(`Cannot pass non-promise thenables`);}\\\\n\\\\n if (isPassByCopyError(val)) {\\\\n return 'copyError';}\\\\n\\\\n if (isPassByCopyArray(val)) {\\\\n return 'copyArray';}\\\\n\\\\n if (isPassByCopyRecord(val)) {\\\\n return 'copyRecord';}\\\\n\\\\n mustPassByRemote(val);\\\\n return REMOTE_STYLE;}\\\\n\\\\n case 'function':{\\\\n throw new Error(`Bare functions like ${val} are disabled for now`);}\\\\n\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'bigint':{\\\\n return typestr;}\\\\n\\\\n case 'symbol':{\\\\n throw new TypeError('Cannot pass symbols');}\\\\n\\\\n default:{\\\\n throw new TypeError(`Unrecognized typeof ${typestr}`);}}}\\\\n\\\\n\\\\n\\\\n\\\\n/* The ibid logic relies on*/\\\\n/* * JSON.stringify on an array visiting array indexes from 0 to*/\\\\n/* arr.length -1 in order, and not visiting anything else.*/\\\\n/* * JSON.parse of a record (a plain object) creating an object on*/\\\\n/* which a getOwnPropertyNames will enumerate properties in the*/\\\\n/* same order in which they appeared in the parsed JSON string.*/\\\\n\\\\nfunction makeReplacerIbidTable() {\\\\n const ibidMap = new Map();\\\\n let ibidCount = 0;\\\\n\\\\n return harden({\\\\n has(obj) {\\\\n return ibidMap.has(obj);},\\\\n\\\\n get(obj) {\\\\n return ibidMap.get(obj);},\\\\n\\\\n add(obj) {\\\\n ibidMap.set(obj, ibidCount);\\\\n ibidCount += 1;} });}\\\\n\\\\n\\\\n\\\\n\\\\nfunction makeReviverIbidTable(cyclePolicy) {\\\\n const ibids = [];\\\\n const unfinishedIbids = new WeakSet();\\\\n\\\\n return harden({\\\\n get(allegedIndex) {\\\\n const index = nat_esm.default(allegedIndex);\\\\n if (index >= ibids.length) {\\\\n throw new RangeError(`ibid out of range: ${index}`);}\\\\n\\\\n const result = ibids[index];\\\\n if (unfinishedIbids.has(result)) {\\\\n switch (cyclePolicy) {\\\\n case 'allowCycles':{\\\\n break;}\\\\n\\\\n case 'warnOfCycles':{\\\\n console.log(`Warning: ibid cycle at ${index}`);\\\\n break;}\\\\n\\\\n case 'forbidCycles':{\\\\n throw new TypeError(`Ibid cycle at ${index}`);}\\\\n\\\\n default:{\\\\n throw new TypeError(`Unrecognized cycle policy: ${cyclePolicy}`);}}}\\\\n\\\\n\\\\n\\\\n return result;},\\\\n\\\\n register(obj) {\\\\n ibids.push(obj);\\\\n return obj;},\\\\n\\\\n start(obj) {\\\\n ibids.push(obj);\\\\n unfinishedIbids.add(obj);\\\\n return obj;},\\\\n\\\\n finish(obj) {\\\\n unfinishedIbids.delete(obj);\\\\n return obj;} });}\\\\n\\\\n\\\\n\\\\n\\\\nconst identityFn = x => x;\\\\n\\\\nfunction makeMarshal(\\\\nconvertValToSlot = identityFn,\\\\nconvertSlotToVal = identityFn)\\\\n{\\\\n function serializeSlot(val, slots, slotMap) {\\\\n let slotIndex;\\\\n if (slotMap.has(val)) {\\\\n slotIndex = slotMap.get(val);} else\\\\n {\\\\n const slot = convertValToSlot(val);\\\\n\\\\n slotIndex = slots.length;\\\\n slots.push(slot);\\\\n slotMap.set(val, slotIndex);}\\\\n\\\\n\\\\n return harden({\\\\n [QCLASS]: 'slot',\\\\n index: slotIndex });}\\\\n\\\\n\\\\n\\\\n function makeReplacer(slots, slotMap) {\\\\n const ibidTable = makeReplacerIbidTable();\\\\n\\\\n return function replacer(_, val) {\\\\n /* First we handle all primitives. Some can be represented directly as*/\\\\n /* JSON, and some must be encoded as [QCLASS] composites.*/\\\\n const passStyle = passStyleOf(val);\\\\n switch (passStyle) {\\\\n case 'null':{\\\\n return null;}\\\\n\\\\n case 'undefined':{\\\\n return harden({ [QCLASS]: 'undefined' });}\\\\n\\\\n case 'string':\\\\n case 'boolean':{\\\\n return val;}\\\\n\\\\n case 'number':{\\\\n if (Number.isNaN(val)) {\\\\n return harden({ [QCLASS]: 'NaN' });}\\\\n\\\\n if (Object.is(val, -0)) {\\\\n return 0;}\\\\n\\\\n if (val === Infinity) {\\\\n return harden({ [QCLASS]: 'Infinity' });}\\\\n\\\\n if (val === -Infinity) {\\\\n return harden({ [QCLASS]: '-Infinity' });}\\\\n\\\\n return val;}\\\\n\\\\n case 'bigint':{\\\\n return harden({\\\\n [QCLASS]: 'bigint',\\\\n digits: String(val) });}\\\\n\\\\n\\\\n default:{\\\\n /* if we've seen this object before, serialize a backref*/\\\\n if (ibidTable.has(val)) {\\\\n /* Backreference to prior occurrence*/\\\\n return harden({\\\\n [QCLASS]: 'ibid',\\\\n index: ibidTable.get(val) });}\\\\n\\\\n\\\\n ibidTable.add(val);\\\\n\\\\n switch (passStyle) {\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n /* console.log(`canPassByCopy: ${val}`);*/\\\\n /* Purposely in-band for readability, but creates need for*/\\\\n /* Hilbert hotel.*/\\\\n return val;}\\\\n\\\\n case 'copyError':{\\\\n /* We deliberately do not share the stack, but it would*/\\\\n /* be useful to log the stack locally so someone who has*/\\\\n /* privileged access to the throwing Vat can correlate*/\\\\n /* the problem with the remote Vat that gets this*/\\\\n /* summary. If we do that, we could allocate some random*/\\\\n /* identifier and include it in the message, to help*/\\\\n /* with the correlation.*/\\\\n return harden({\\\\n [QCLASS]: 'error',\\\\n name: `${val.name}`,\\\\n message: `${val.message}` });}\\\\n\\\\n\\\\n case REMOTE_STYLE:\\\\n case 'promise':{\\\\n /* console.log(`serializeSlot: ${val}`);*/\\\\n return serializeSlot(val, slots, slotMap);}\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${passStyle}`);}}}}};}\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n /* val might be a primitive, a pass by (shallow) copy object, a*/\\\\n /* remote reference, or other. We treat all other as a local object*/\\\\n /* to be exported as a local webkey.*/\\\\n function serialize(val) {\\\\n const slots = [];\\\\n const slotMap = new Map(); /* maps val (promise or remotable) to*/\\\\n /* index of slots[]*/\\\\n return harden({\\\\n body: JSON.stringify(val, makeReplacer(slots, slotMap)),\\\\n slots });}\\\\n\\\\n\\\\n\\\\n function makeFullRevive(slots, cyclePolicy) {\\\\n /* ibid table is shared across recursive calls to fullRevive.*/\\\\n const ibidTable = makeReviverIbidTable(cyclePolicy);\\\\n\\\\n /* We stay close to the algorith at*/\\\\n /* https://tc39.github.io/ecma262/#sec-json.parse , where*/\\\\n /* fullRevive(JSON.parse(str)) is like JSON.parse(str, revive))*/\\\\n /* for a similar reviver. But with the following differences:*/\\\\n /**/\\\\n /* Rather than pass a reviver to JSON.parse, we first call a plain*/\\\\n /* (one argument) JSON.parse to get rawTree, and then post-process*/\\\\n /* the rawTree with fullRevive. The kind of revive function*/\\\\n /* handled by JSON.parse only does one step in post-order, with*/\\\\n /* JSON.parse doing the recursion. By contrast, fullParse does its*/\\\\n /* own recursion, enabling it to interpret ibids in the same*/\\\\n /* pre-order in which the replacer visited them, and enabling it*/\\\\n /* to break cycles.*/\\\\n /**/\\\\n /* In order to break cycles, the potentially cyclic objects are*/\\\\n /* not frozen during the recursion. Rather, the whole graph is*/\\\\n /* hardened before being returned. Error objects are not*/\\\\n /* potentially recursive, and so may be harmlessly hardened when*/\\\\n /* they are produced.*/\\\\n /**/\\\\n /* fullRevive can produce properties whose value is undefined,*/\\\\n /* which a JSON.parse on a reviver cannot do. If a reviver returns*/\\\\n /* undefined to JSON.parse, JSON.parse will delete the property*/\\\\n /* instead.*/\\\\n /**/\\\\n /* fullRevive creates and returns a new graph, rather than*/\\\\n /* modifying the original tree in place.*/\\\\n /**/\\\\n /* fullRevive may rely on rawTree being the result of a plain call*/\\\\n /* to JSON.parse. However, it *cannot* rely on it having been*/\\\\n /* produced by JSON.stringify on the replacer above, i.e., it*/\\\\n /* cannot rely on it being a valid marshalled*/\\\\n /* representation. Rather, fullRevive must validate that.*/\\\\n return function fullRevive(rawTree) {\\\\n if (Object(rawTree) !== rawTree) {\\\\n /* primitives pass through*/\\\\n return rawTree;}\\\\n\\\\n if (QCLASS in rawTree) {\\\\n const qclass = rawTree[QCLASS];\\\\n if (typeof qclass !== 'string') {\\\\n throw new TypeError(`invalid qclass typeof ${typeof qclass}`);}\\\\n\\\\n switch (qclass) {\\\\n /* Encoding of primitives not handled by JSON*/\\\\n case 'undefined':{\\\\n return undefined;}\\\\n\\\\n case 'NaN':{\\\\n return NaN;}\\\\n\\\\n case 'Infinity':{\\\\n return Infinity;}\\\\n\\\\n case '-Infinity':{\\\\n return -Infinity;}\\\\n\\\\n case 'bigint':{\\\\n if (typeof rawTree.digits !== 'string') {\\\\n throw new TypeError(\\\\n `invalid digits typeof ${typeof rawTree.digits}`);}\\\\n\\\\n\\\\n /* eslint-disable-next-line no-undef */\\\\n return BigInt(rawTree.digits);}\\\\n\\\\n\\\\n case 'ibid':{\\\\n return ibidTable.get(rawTree.index);}\\\\n\\\\n\\\\n case 'error':{\\\\n if (typeof rawTree.name !== 'string') {\\\\n throw new TypeError(\\\\n `invalid error name typeof ${typeof rawTree.name}`);}\\\\n\\\\n\\\\n if (typeof rawTree.message !== 'string') {\\\\n throw new TypeError(\\\\n `invalid error message typeof ${typeof rawTree.message}`);}\\\\n\\\\n\\\\n const EC = getErrorConstructor(`${rawTree.name}`) || Error;\\\\n return ibidTable.register(harden(new EC(`${rawTree.message}`)));}\\\\n\\\\n\\\\n case 'slot':{\\\\n const slot = slots[nat_esm.default(rawTree.index)];\\\\n return ibidTable.register(convertSlotToVal(slot));}\\\\n\\\\n\\\\n default:{\\\\n /* TODO reverse Hilbert hotel*/\\\\n throw new TypeError(`unrecognized ${QCLASS} ${qclass}`);}}} else\\\\n\\\\n\\\\n if (Array.isArray(rawTree)) {\\\\n const result = ibidTable.start([]);\\\\n const len = rawTree.length;\\\\n for (let i = 0; i < len; i += 1) {\\\\n result[i] = fullRevive(rawTree[i]);}\\\\n\\\\n return ibidTable.finish(result);} else\\\\n {\\\\n const result = ibidTable.start({});\\\\n const names = Object.getOwnPropertyNames(rawTree);\\\\n for (const name of names) {\\\\n result[name] = fullRevive(rawTree[name]);}\\\\n\\\\n return ibidTable.finish(result);}};}\\\\n\\\\n\\\\n\\\\n\\\\n function unserialize(data, cyclePolicy = 'forbidCycles') {\\\\n if (data.body !== `${data.body}`) {\\\\n throw new Error(\\\\n `unserialize() given non-capdata (.body is ${data.body}, not string)`);}\\\\n\\\\n\\\\n if (!Array.isArray(data.slots)) {\\\\n throw new Error(`unserialize() given non-capdata (.slots are not Array)`);}\\\\n\\\\n const rawTree = harden(JSON.parse(data.body));\\\\n const fullRevive = makeFullRevive(data.slots, cyclePolicy);\\\\n return harden(fullRevive(rawTree));}\\\\n\\\\n\\\\n return harden({\\\\n serialize,\\\\n unserialize });}\\\\n\\\\n\\\\n\\\\n/**\\\\n * Create and register a Remotable. After this, getInterfaceOf(remotable)\\\\n * returns iface.\\\\n *\\\\n * // https://github.com/Agoric/agoric-sdk/issues/804\\\\n *\\\\n * @param {InterfaceSpec} [iface='Remotable'] The interface specification for the remotable\\\\n * @param {object} [props={}] Own-properties are copied to the remotable\\\\n * @param {object} [remotable={}] The object used as the remotable\\\\n * @returns {object} remotable, modified for debuggability\\\\n */\\\\nfunction Remotable(iface = 'Remotable', props = {}, remotable = {}) {\\\\n iface = pureCopy(harden(iface));\\\\n const ifaceType = typeof iface;\\\\n\\\\n /* Find the alleged name.*/\\\\n if (ifaceType !== 'string') {\\\\n throw Error(`Interface must be a string, not ${ifaceType}; unimplemented`);}\\\\n\\\\n\\\\n /* TODO: When iface is richer than just string, we need to get the allegedName*/\\\\n /* in a different way.*/\\\\n const allegedName = iface;\\\\n\\\\n /* Fail fast: check that the unmodified object is able to become a Remotable.*/\\\\n assertCanBeRemotable(remotable);\\\\n\\\\n /* Ensure that the remotable isn't already registered.*/\\\\n if (remotableToInterface.has(remotable)) {\\\\n throw Error(`Remotable ${remotable} is already mapped to an interface`);}\\\\n\\\\n\\\\n /* A prototype for debuggability.*/\\\\n const oldRemotableProto = harden(Object.getPrototypeOf(remotable));\\\\n\\\\n /* Fail fast: create a fresh empty object with the old*/\\\\n /* prototype in order to check it against our rules.*/\\\\n mustPassByRemote(harden(Object.create(oldRemotableProto)));\\\\n\\\\n /* Assign the arrow function to a variable to set its .name.*/\\\\n const toString = () => `[${allegedName}]`;\\\\n const remotableProto = harden(\\\\n Object.create(oldRemotableProto, {\\\\n toString: {\\\\n value: toString,\\\\n enumerable: false },\\\\n\\\\n [Symbol.toStringTag]: {\\\\n value: allegedName,\\\\n enumerable: false } }));\\\\n\\\\n\\\\n\\\\n\\\\n /* Take a static copy of the properties.*/\\\\n const propEntries = Object.entries(props);\\\\n const mutateHardenAndCheck = target => {\\\\n /* Add the snapshotted properties.*/\\\\n /** @type {PropertyDescriptorMap} */\\\\n const newProps = {};\\\\n propEntries.forEach(([prop, value]) => newProps[prop] = { value });\\\\n Object.defineProperties(target, newProps);\\\\n\\\\n /* Set the prototype for debuggability.*/\\\\n Object.setPrototypeOf(target, remotableProto);\\\\n harden(remotableProto);\\\\n\\\\n harden(target);\\\\n assertCanBeRemotable(target);\\\\n return target;};\\\\n\\\\n\\\\n /* Fail fast: check a fresh remotable to see if our rules fit.*/\\\\n const throwawayRemotable = Object.create(oldRemotableProto);\\\\n mutateHardenAndCheck(throwawayRemotable);\\\\n\\\\n /* Actually finish the new remotable.*/\\\\n mutateHardenAndCheck(remotable);\\\\n\\\\n /* COMMITTED!*/\\\\n /* We're committed, so keep the interface for future reference.*/\\\\n remotableToInterface.set(remotable, iface);\\\\n return remotable;}\\\\n\\\\n\\\\nharden(Remotable);exports.QCLASS = QCLASS;exports.Remotable = Remotable;exports.getErrorConstructor = getErrorConstructor;exports.getInterfaceOf = getInterfaceOf;exports.makeMarshal = makeMarshal;exports.mustPassByPresence = mustPassByRemote;exports.mustPassByRemote = mustPassByRemote;exports.passStyleOf = passStyleOf;exports.pureCopy = pureCopy;exports.sameValueZero = sameValueZero;\\\",\\n \\\"packages/same-structure/src/sameStructure.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../assert/src/assert.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nmarshal = require('../../marshal/marshal.js'); /* global harden */ /* Shim of Object.fromEntries from*/ /* https://github.com/tc39/proposal-object-from-entries/blob/master/polyfill.js*/\\\\nfunction ObjectFromEntries(iter) {\\\\n const obj = {};\\\\n\\\\n for (const pair of iter) {\\\\n if (Object(pair) !== pair) {\\\\n throw new TypeError('iterable for fromEntries should yield objects');}\\\\n\\\\n\\\\n /* Consistency with Map: contract is that entry has \\\\\\\"0\\\\\\\" and \\\\\\\"1\\\\\\\" keys, not*/\\\\n /* that it is an array or iterable.*/\\\\n\\\\n const { '0': key, '1': val } = pair;\\\\n\\\\n Object.defineProperty(obj, key, {\\\\n configurable: true,\\\\n enumerable: true,\\\\n writable: true,\\\\n value: val });}\\\\n\\\\n\\\\n\\\\n return obj;}\\\\n\\\\n\\\\n/* A *passable* is something that may be marshalled. It consists of a*/\\\\n/* graph of pass-by-copy data terminating in leaves of passable*/\\\\n/* non-pass-by-copy data. These leaves may be promises, or*/\\\\n/* pass-by-presence objects. A *comparable* is a passable whose leaves*/\\\\n/* contain no promises. Two comparables can be synchronously compared*/\\\\n/* for structural equivalence.*/\\\\n/**/\\\\n/* TODO: Currently, all algorithms here treat the pass-by-copy*/\\\\n/* superstructure as a tree. This means that dags are unwound at*/\\\\n/* potentially exponential cost, and cycles cause failure to*/\\\\n/* terminate. We must fix both problems, making all these algorithms*/\\\\n/* graph-aware.*/\\\\n\\\\n/* We say that a function *reveals* an X when it returns either an X*/\\\\n/* or a promise for an X.*/\\\\n\\\\n/* Given a passable, reveal a corresponding comparable, where each*/\\\\n/* leaf promise of the passable has been replaced with its*/\\\\n/* corresponding comparable.*/\\\\nfunction allComparable(passable) {\\\\n const passStyle = marshal.passStyleOf(passable);\\\\n switch (passStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':\\\\n case 'copyError':{\\\\n return passable;}\\\\n\\\\n case 'promise':{\\\\n return passable.then(nonp => allComparable(nonp));}\\\\n\\\\n case 'copyArray':{\\\\n const valPs = passable.map(p => allComparable(p));\\\\n return Promise.all(valPs).then(vals => harden(vals));}\\\\n\\\\n case 'copyRecord':{\\\\n const names = Object.getOwnPropertyNames(passable);\\\\n const valPs = names.map(name => allComparable(passable[name]));\\\\n return Promise.all(valPs).then((vals) =>\\\\n harden(ObjectFromEntries(vals.map((val, i) => [names[i], val]))));}\\\\n\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${passStyle}`);}}}\\\\n\\\\n\\\\n\\\\nharden(allComparable);\\\\n\\\\n/* Are left and right structurally equivalent comparables? This*/\\\\n/* compares pass-by-copy data deeply until non-pass-by-copy values are*/\\\\n/* reached. The non-pass-by-copy values at the leaves of the*/\\\\n/* comparison may only be pass-by-presence objects. If they are*/\\\\n/* anything else, including promises, throw an error.*/\\\\n/**/\\\\n/* Pass-by-presence objects compare identities.*/\\\\n\\\\nfunction sameStructure(left, right) {\\\\n const leftStyle = marshal.passStyleOf(left);\\\\n const rightStyle = marshal.passStyleOf(right);\\\\n assert.assert(\\\\n leftStyle !== 'promise',\\\\n assert.details`Cannot structurally compare promises: ${left}`);\\\\n\\\\n assert.assert(\\\\n rightStyle !== 'promise',\\\\n assert.details`Cannot structurally compare promises: ${right}`);\\\\n\\\\n\\\\n if (leftStyle !== rightStyle) {\\\\n return false;}\\\\n\\\\n switch (leftStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':{\\\\n return marshal.sameValueZero(left, right);}\\\\n\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n const leftNames = Object.getOwnPropertyNames(left);\\\\n const rightNames = Object.getOwnPropertyNames(right);\\\\n if (leftNames.length !== rightNames.length) {\\\\n return false;}\\\\n\\\\n for (const name of leftNames) {\\\\n /* TODO: Better hasOwnProperty check*/\\\\n if (!Object.getOwnPropertyDescriptor(right, name)) {\\\\n return false;}\\\\n\\\\n /* TODO: Make cycle tolerant*/\\\\n if (!sameStructure(left[name], right[name])) {\\\\n return false;}}\\\\n\\\\n\\\\n return true;}\\\\n\\\\n case 'copyError':{\\\\n return left.name === right.name && left.message === right.message;}\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${leftStyle}`);}}}\\\\n\\\\n\\\\n\\\\nharden(sameStructure);\\\\n\\\\nfunction pathStr(path) {\\\\n if (path === null) {\\\\n return 'top';}\\\\n\\\\n const [base, index] = path;\\\\n let i = index;\\\\n const baseStr = pathStr(base);\\\\n if (typeof i === 'string' && /^[a-zA-Z]\\\\\\\\w*$/.test(i)) {\\\\n return `${baseStr}.${i}`;}\\\\n\\\\n if (typeof i === 'string' && `${+i}` === i) {\\\\n i = +i;}\\\\n\\\\n return `${baseStr}[${JSON.stringify(i)}]`;}\\\\n\\\\n\\\\n/* TODO: Reduce redundancy between sameStructure and*/\\\\n/* mustBeSameStructureInternal*/\\\\nfunction mustBeSameStructureInternal(left, right, message, path) {\\\\n function complain(problem) {\\\\n assert.assert.fail(\\\\n assert.details`${assert.q(message)}: ${assert.q(problem)} at ${assert.q(\\\\n pathStr(path))\\\\n }: (${left}) vs (${right})`);}\\\\n\\\\n\\\\n\\\\n const leftStyle = marshal.passStyleOf(left);\\\\n const rightStyle = marshal.passStyleOf(right);\\\\n if (leftStyle === 'promise') {\\\\n complain('Promise on left');}\\\\n\\\\n if (rightStyle === 'promise') {\\\\n complain('Promise on right');}\\\\n\\\\n\\\\n if (leftStyle !== rightStyle) {\\\\n complain('different passing style');}\\\\n\\\\n switch (leftStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':{\\\\n if (!marshal.sameValueZero(left, right)) {\\\\n complain('different');}\\\\n\\\\n break;}\\\\n\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n const leftNames = Object.getOwnPropertyNames(left);\\\\n const rightNames = Object.getOwnPropertyNames(right);\\\\n if (leftNames.length !== rightNames.length) {\\\\n complain(`${leftNames.length} vs ${rightNames.length} own properties`);}\\\\n\\\\n for (const name of leftNames) {\\\\n /* TODO: Better hasOwnProperty check*/\\\\n if (!Object.getOwnPropertyDescriptor(right, name)) {\\\\n complain(`${name} not found on right`);}\\\\n\\\\n /* TODO: Make cycle tolerant*/\\\\n mustBeSameStructureInternal(left[name], right[name], message, [\\\\n path,\\\\n name]);}\\\\n\\\\n\\\\n break;}\\\\n\\\\n case 'copyError':{\\\\n if (left.name !== right.name) {\\\\n complain(`different error name: ${left.name} vs ${right.name}`);}\\\\n\\\\n if (left.message !== right.message) {\\\\n complain(\\\\n `different error message: ${left.message} vs ${right.message}`);}\\\\n\\\\n\\\\n break;}\\\\n\\\\n default:{\\\\n complain(`unrecognized passStyle ${leftStyle}`);\\\\n break;}}}\\\\n\\\\n\\\\n\\\\nfunction mustBeSameStructure(left, right, message) {\\\\n mustBeSameStructureInternal(left, right, `${message}`, null);}\\\\n\\\\nharden(mustBeSameStructure);\\\\n\\\\n/* If `val` would be a valid input to `sameStructure`, return*/\\\\n/* normally. Otherwise error.*/\\\\nfunction mustBeComparable(val) {\\\\n mustBeSameStructure(val, val, 'not comparable');}exports.allComparable = allComparable;exports.mustBeComparable = mustBeComparable;exports.mustBeSameStructure = mustBeSameStructure;exports.sameStructure = sameStructure;\\\",\\n \\\"packages/zoe/src/offerSafety.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /**\\\\n * @typedef {Ximport('@agoric/ertp/src/issuer').Brand} Brand\\\\n * @typedef {Ximport('@agoric/ertp/src/issuer').AmountMath} AmountMath\\\\n * @typedef {Ximport('./zoe').Proposal} Proposal\\\\n * @typedef {Ximport('./zoe').AmountKeywordRecord} AmountKeywordRecord\\\\n */ /**\\\\n * Helper to perform satisfiesWant and satisfiesGive. Is\\\\n * allocationAmount greater than or equal to requiredAmount for every\\\\n * keyword of giveOrWant?\\\\n * @param {(Brand) => AmountMath} getAmountMath\\\\n * @param {Proposal[\\\\\\\"give\\\\\\\"] | Proposal[\\\\\\\"want\\\\\\\"]} giveOrWant\\\\n * @param {AmountKeywordRecord} allocation\\\\n */const satisfiesInternal = (getAmountMath, giveOrWant, allocation) => {const isGTEByKeyword = ([keyword, requiredAmount]) => {/* If there is no allocation for a keyword, we know the giveOrWant*/ /* is not satisfied without checking further.*/if (allocation[keyword] === undefined) {\\\\n return false;}\\\\n\\\\n const amountMath = getAmountMath(requiredAmount.brand);\\\\n const allocationAmount = allocation[keyword];\\\\n return amountMath.isGTE(allocationAmount, requiredAmount);};\\\\n\\\\n return Object.entries(giveOrWant).every(isGTEByKeyword);};\\\\n\\\\n\\\\n/**\\\\n * For this allocation to satisfy what the user wanted, their\\\\n * allocated amounts must be greater than or equal to proposal.want.\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.want.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nconst satisfiesWant = (getAmountMath, proposal, allocation) =>\\\\nsatisfiesInternal(getAmountMath, proposal.want, allocation);\\\\n\\\\n/**\\\\n * For this allocation to count as a full refund, the allocated\\\\n * amounts must be greater than or equal to what was originally\\\\n * offered (proposal.give).\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.give.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nconst satisfiesGive = (getAmountMath, proposal, allocation) =>\\\\nsatisfiesInternal(getAmountMath, proposal.give, allocation);\\\\n\\\\n/**\\\\n * `isOfferSafe` checks offer safety for a single offer.\\\\n *\\\\n * Note: This implementation checks whether we fully satisfy\\\\n * `proposal.give` (giving a refund) or whether we fully satisfy\\\\n * `proposal.want`. Both can be fully satisfied.\\\\n *\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.want and\\\\n * proposal.give.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nfunction isOfferSafe(getAmountMath, proposal, allocation) {\\\\n return (\\\\n satisfiesGive(getAmountMath, proposal, allocation) ||\\\\n satisfiesWant(getAmountMath, proposal, allocation));}exports.isOfferSafe = isOfferSafe;exports.satisfiesWant = satisfiesWant;\\\",\\n \\\"packages/zoe/src/contractSupport/zoeHelpers.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var index = require('../../../eventual-send/src/index.js');var assert = require('../../../assert/src/assert.js');var sameStructure = require('../../../same-structure/src/sameStructure.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nofferSafety = require('../offerSafety.js'); /* global harden */ /**\\\\n * @typedef {Ximport('../zoe').OfferHandle} OfferHandle\\\\n * @typedef {Ximport('../zoe').Invite} Invite\\\\n * @typedef {Ximport('../zoe').OfferHook} OfferHook\\\\n * @typedef {Ximport('../zoe').CustomProperties} CustomProperties\\\\n * @typedef {Ximport('../zoe').ContractFacet} ContractFacet\\\\n * @typedef {Ximport('../zoe').Keyword} Keyword\\\\n * @typedef {Ximport('../zoe').AmountKeywordRecord} AmountKeywordRecord\\\\n * @typedef {Ximport('../zoe').Amount} Amount\\\\n * @typedef {Ximport('../zoe').Payment} Payment\\\\n */\\\\n\\\\nconst defaultRejectMsg = `The offer was invalid. Please check your refund.`;\\\\nconst defaultAcceptanceMsg = `The offer has been accepted. Once the contract has been completed, please check your payout`;\\\\n\\\\nconst getKeys = obj => harden(Object.getOwnPropertyNames(obj || {}));\\\\nconst getKeysSorted = (obj) =>\\\\nharden(Object.getOwnPropertyNames(obj || {}).sort());\\\\n/**\\\\n * @function makeZoeHelpers - makes an object with helper functions useful to zoe contracts.\\\\n *\\\\n * @param {ContractFacet} zcf\\\\n */\\\\n/* zcf only picks up the type if the param is in parens, which eslint dislikes*/\\\\n/* eslint-disable-next-line*/\\\\nconst makeZoeHelpers = zcf => {\\\\n const zoeService = zcf.getZoeService();\\\\n\\\\n const rejectOffer = (offerHandle, msg = defaultRejectMsg) => {\\\\n zcf.complete(harden([offerHandle]));\\\\n assert.assert.fail(msg);};\\\\n\\\\n\\\\n /* Compare the keys of actual with expected keys and reject offer if*/\\\\n /* not sameStructure. If expectedKeys is undefined, no comparison occurs.*/\\\\n const rejectKeysIf = (\\\\n offerHandle,\\\\n actual,\\\\n expected,\\\\n msg = defaultRejectMsg) =>\\\\n /* eslint-disable-next-line consistent-return*/\\\\n {\\\\n if (expected !== undefined) {\\\\n if (!sameStructure.sameStructure(getKeysSorted(actual), getKeysSorted(expected))) {\\\\n return rejectOffer(offerHandle, msg);}}};\\\\n\\\\n\\\\n\\\\n /* Compare actual keys to expected keys. If expectedKeys is*/\\\\n /* undefined, return true trivially.*/\\\\n const checkKeys = (actual, expected) => {\\\\n if (expected === undefined) {\\\\n return true;}\\\\n\\\\n return sameStructure.sameStructure(getKeysSorted(actual), getKeysSorted(expected));};\\\\n\\\\n\\\\n /**\\\\n * Given toGains (an AmountKeywordRecord), and allocations (a pair,\\\\n * 'to' and 'from', of AmountKeywordRecords), all the entries in\\\\n * toGains will be added to 'to'. If fromLosses is defined, all the\\\\n * entries in fromLosses are subtracted from 'from'. (If fromLosses\\\\n * is not defined, toGains is subtracted from 'from'.)\\\\n *\\\\n * @param {FromToAllocations} allocations - the 'to' and 'from'\\\\n * allocations\\\\n * @param {AmountKeywordRecord} toGains - what should be gained in\\\\n * the 'to' allocation\\\\n * @param {AmountKeywordRecord} fromLosses - what should be lost in\\\\n * the 'from' allocation. If not defined, fromLosses is equal to\\\\n * toGains. Note that the total amounts should always be equal; it\\\\n * is the keywords that might be different.\\\\n * @returns {FromToAllocations} allocations - new allocations\\\\n *\\\\n * @typedef FromToAllocations\\\\n * @property {AmountKeywordRecord} from\\\\n * @property {AmountKeywordRecord} to\\\\n */\\\\n const calcNewAllocations = (allocations, toGains, fromLosses = undefined) => {\\\\n if (fromLosses === undefined) {\\\\n fromLosses = toGains;}\\\\n\\\\n\\\\n const subtract = (amount, amountToSubtract) => {\\\\n const { brand } = amount;\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n if (amountToSubtract !== undefined) {\\\\n return amountMath.subtract(amount, amountToSubtract);}\\\\n\\\\n return amount;};\\\\n\\\\n\\\\n const add = (amount, amountToAdd) => {\\\\n if (amount && amountToAdd) {\\\\n const { brand } = amount;\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n return amountMath.add(amount, amountToAdd);}\\\\n\\\\n return amount || amountToAdd;};\\\\n\\\\n\\\\n const newFromAllocation = Object.fromEntries(\\\\n Object.entries(allocations.from).map(([keyword, allocAmount]) => {\\\\n return [keyword, subtract(allocAmount, fromLosses[keyword])];}));\\\\n\\\\n\\\\n\\\\n const allToKeywords = [\\\\n ...Object.keys(toGains),\\\\n ...Object.keys(allocations.to)];\\\\n\\\\n\\\\n const newToAllocation = Object.fromEntries(\\\\n allToKeywords.map(keyword => [\\\\n keyword,\\\\n add(allocations.to[keyword], toGains[keyword])]));\\\\n\\\\n\\\\n\\\\n return harden({\\\\n from: newFromAllocation,\\\\n to: newToAllocation });};\\\\n\\\\n\\\\n\\\\n const mergeAllocations = (currentAllocation, allocation) => {\\\\n const newAllocation = {\\\\n ...currentAllocation,\\\\n ...allocation };\\\\n\\\\n return newAllocation;};\\\\n\\\\n\\\\n const helpers = harden({\\\\n getKeys,\\\\n assertKeywords: expected => {\\\\n const { issuerKeywordRecord } = zcf.getInstanceRecord();\\\\n const actual = getKeysSorted(issuerKeywordRecord);\\\\n expected = [...expected]; /* in case hardened*/\\\\n expected.sort();\\\\n assert.assert(\\\\n sameStructure.sameStructure(actual, harden(expected)),\\\\n assert.details`keywords: ${actual} were not as expected: ${expected}`);},\\\\n\\\\n\\\\n rejectIfNotProposal: (offerHandle, expected) => {\\\\n const { proposal: actual } = zcf.getOffer(offerHandle);\\\\n rejectKeysIf(offerHandle, actual.give, expected.give);\\\\n rejectKeysIf(offerHandle, actual.want, expected.want);\\\\n rejectKeysIf(offerHandle, actual.exit, expected.exit);},\\\\n\\\\n checkIfProposal: (offerHandle, expected) => {\\\\n const { proposal: actual } = zcf.getOffer(offerHandle);\\\\n return (\\\\n /* Check that the \\\\\\\"give\\\\\\\" keys match expected keys.*/\\\\n checkKeys(actual.give, expected.give) &&\\\\n /* Check that the \\\\\\\"want\\\\\\\" keys match expected keys.*/\\\\n checkKeys(actual.want, expected.want) &&\\\\n /* Check that the \\\\\\\"exit\\\\\\\" key (i.e. \\\\\\\"onDemand\\\\\\\") matches the expected key.*/\\\\n checkKeys(actual.exit, expected.exit));},\\\\n\\\\n\\\\n getActiveOffers: (handles) =>\\\\n zcf.getOffers(zcf.getOfferStatuses(handles).active),\\\\n rejectOffer,\\\\n\\\\n /**\\\\n * Check whether an update to currentAllocation satisfies\\\\n * proposal.want. Note that this is half of the offer safety\\\\n * check; whether the allocation constitutes a refund is not\\\\n * checked. Allocation is merged with currentAllocation\\\\n * (allocations' values prevailing if the keywords are the same)\\\\n * to produce the newAllocation.\\\\n * @param {OfferHandle} offerHandle\\\\n * @param {allocation} amountKeywordRecord\\\\n * @returns {boolean}\\\\n */\\\\n satisfies: (offerHandle, allocation) => {\\\\n const currentAllocation = zcf.getCurrentAllocation(offerHandle);\\\\n const newAllocation = mergeAllocations(currentAllocation, allocation);\\\\n const { proposal } = zcf.getOffer(offerHandle);\\\\n return offerSafety.satisfiesWant(zcf.getAmountMath, proposal, newAllocation);},\\\\n\\\\n\\\\n /**\\\\n * Check whether an update to currentAllocation satisfies offer\\\\n * safety. Note that this is the equivalent of `satisfiesWant` ||\\\\n * `satisfiesGive`. Allocation is merged with currentAllocation\\\\n * (allocations' values prevailing if the keywords are the same)\\\\n * to produce the newAllocation.\\\\n * @param {OfferHandle} offerHandle\\\\n * @param {AmountKeywordRecord} allocation\\\\n * @returns {boolean}\\\\n */\\\\n\\\\n isOfferSafe: (offerHandle, allocation) => {\\\\n const currentAllocation = zcf.getCurrentAllocation(offerHandle);\\\\n const newAllocation = mergeAllocations(currentAllocation, allocation);\\\\n const { proposal } = zcf.getOffer(offerHandle);\\\\n return offerSafety.isOfferSafe(zcf.getAmountMath, proposal, newAllocation);},\\\\n\\\\n\\\\n /**\\\\n * Trade between left and right so that left and right end up with\\\\n * the declared gains.\\\\n * @param {offerHandleGainsLossesRecord} keepLeft\\\\n * @param {offerHandleGainsLossesRecord} tryRight\\\\n * @returns {undefined | Error}\\\\n *\\\\n * @typedef {object} offerHandleGainsLossesRecord\\\\n * @property {OfferHandle} offerHandle\\\\n * @property {AmountKeywordRecord} gains - what the offer will\\\\n * gain as a result of this trade\\\\n * @property {AmountKeywordRecord=} losses - what the offer will\\\\n * give up as a result of this trade. Losses is optional, but can\\\\n * only be omitted if the keywords for both offers are the same.\\\\n * If losses is not defined, the gains of the other offer is\\\\n * subtracted.\\\\n */\\\\n trade: (keepLeft, tryRight) => {\\\\n assert.assert(\\\\n keepLeft.offerHandle !== tryRight.offerHandle,\\\\n assert.details`an offer cannot trade with itself`);\\\\n\\\\n let leftAllocation = zcf.getCurrentAllocation(keepLeft.offerHandle);\\\\n let rightAllocation = zcf.getCurrentAllocation(tryRight.offerHandle);\\\\n\\\\n try {\\\\n /* for all the keywords and amounts in leftGains, transfer from*/\\\\n /* right to left*/\\\\n ({ from: rightAllocation, to: leftAllocation } = calcNewAllocations(\\\\n { from: rightAllocation, to: leftAllocation },\\\\n keepLeft.gains,\\\\n tryRight.losses));\\\\n\\\\n /* For all the keywords and amounts in rightGains, transfer from*/\\\\n /* left to right*/\\\\n ({ from: leftAllocation, to: rightAllocation } = calcNewAllocations(\\\\n { from: leftAllocation, to: rightAllocation },\\\\n tryRight.gains,\\\\n keepLeft.losses));}\\\\n\\\\n catch (err) {\\\\n return rejectOffer(tryRight.offerHandle);}\\\\n\\\\n\\\\n /* Check whether reallocate would error before calling. If*/\\\\n /* it would error, reject the right offer and return.*/\\\\n const offerSafeForLeft = helpers.isOfferSafe(\\\\n keepLeft.offerHandle,\\\\n leftAllocation);\\\\n\\\\n const offerSafeForRight = helpers.isOfferSafe(\\\\n tryRight.offerHandle,\\\\n rightAllocation);\\\\n\\\\n if (!(offerSafeForLeft && offerSafeForRight)) {\\\\n console.log(\\\\n `currentLeftAllocation`,\\\\n zcf.getCurrentAllocation(keepLeft.offerHandle));\\\\n\\\\n console.log(\\\\n `currentRightAllocation`,\\\\n zcf.getCurrentAllocation(tryRight.offerHandle));\\\\n\\\\n console.log(`proposed left reallocation`, leftAllocation);\\\\n console.log(`proposed right reallocation`, rightAllocation);\\\\n /* show the contraints*/\\\\n console.log(\\\\n `left want`,\\\\n zcf.getOffer(keepLeft.offerHandle).proposal.want);\\\\n\\\\n console.log(\\\\n `right want`,\\\\n zcf.getOffer(tryRight.offerHandle).proposal.want);\\\\n\\\\n\\\\n if (!offerSafeForLeft) {\\\\n console.log(`offer not safe for left`);}\\\\n\\\\n if (!offerSafeForRight) {\\\\n console.log(`offer not safe for right`);}\\\\n\\\\n return rejectOffer(tryRight.offerHandle);}\\\\n\\\\n zcf.reallocate(\\\\n [keepLeft.offerHandle, tryRight.offerHandle],\\\\n [leftAllocation, rightAllocation]);\\\\n\\\\n return undefined;},\\\\n\\\\n\\\\n /**\\\\n * If the two handles can trade, then swap their compatible assets,\\\\n * marking both offers as complete.\\\\n *\\\\n * The surplus remains with the original offer. For example if\\\\n * offer A gives 5 moola and offer B only wants 3 moola, offer A\\\\n * retains 2 moola.\\\\n *\\\\n * If the keep offer is no longer active (it was already completed), the try\\\\n * offer will be rejected with a message (provided by 'keepHandleInactiveMsg').\\\\n *\\\\n * TODO: If the try offer is no longer active, swap() should terminate with\\\\n * a useful error message, like defaultRejectMsg.\\\\n *\\\\n * If the swap fails, no assets are transferred, and the 'try' offer is rejected.\\\\n *\\\\n * @param {OfferHandle} keepHandle\\\\n * @param {OfferHandle} tryHandle\\\\n * @param {String} [keepHandleInactiveMsg]\\\\n */\\\\n swap: (\\\\n keepHandle,\\\\n tryHandle,\\\\n keepHandleInactiveMsg = 'prior offer is unavailable') =>\\\\n {\\\\n if (!zcf.isOfferActive(keepHandle)) {\\\\n throw helpers.rejectOffer(tryHandle, keepHandleInactiveMsg);}\\\\n\\\\n\\\\n helpers.trade(\\\\n {\\\\n offerHandle: keepHandle,\\\\n gains: zcf.getOffer(keepHandle).proposal.want },\\\\n\\\\n {\\\\n offerHandle: tryHandle,\\\\n gains: zcf.getOffer(tryHandle).proposal.want });\\\\n\\\\n\\\\n\\\\n zcf.complete([keepHandle, tryHandle]);\\\\n return defaultAcceptanceMsg;},\\\\n\\\\n\\\\n /**\\\\n * Make an offerHook that wraps the provided `offerHook`, to first\\\\n * check the submitted offer against an `expected` record that says\\\\n * what shape of proposal is acceptable.\\\\n *\\\\n * This ExpectedRecord is like a Proposal, but the amounts in 'want'\\\\n * and 'give' should be null; the exit clause should specify a rule with\\\\n * null contents. If the client submits an Offer which does not match\\\\n * these expectations, that offer will be rejected (and refunded).\\\\n *\\\\n * @param {OfferHook} offerHook\\\\n * @param {ExpectedRecord} expected\\\\n *\\\\n * @typedef ExpectedRecord\\\\n * @property {TODO} [want]\\\\n * @property {TODO} [give]\\\\n * @property {TODO} [exit]\\\\n */\\\\n checkHook: (offerHook, expected) => offerHandle => {\\\\n helpers.rejectIfNotProposal(offerHandle, expected);\\\\n return offerHook(offerHandle);},\\\\n\\\\n\\\\n /**\\\\n * Return a Promise for an OfferHandle.\\\\n *\\\\n * This offer will have an empty 'give' and 'want', making it useful\\\\n * for contracts to use for unrestricted internal asset reallocation.\\\\n * One example is the Autoswap contract, which uses an empty offer\\\\n * to manage internal escrowed assets.\\\\n *\\\\n * @returns {Promise<OfferHandle>}\\\\n */\\\\n makeEmptyOffer: () =>\\\\n new index.HandledPromise(resolve => {\\\\n const invite = zcf.makeInvitation(\\\\n offerHandle => resolve(offerHandle),\\\\n 'empty offer');\\\\n\\\\n index.E(zoeService).offer(invite);}),\\\\n\\\\n\\\\n /**\\\\n * Escrow a payment with Zoe and reallocate the amount of the\\\\n * payment to a recipient.\\\\n *\\\\n * @param {Object} obj\\\\n * @param {Amount} obj.amount\\\\n * @param {Payment} obj.payment\\\\n * @param {String} obj.keyword\\\\n * @param {OfferHandle} obj.recipientHandle\\\\n * @returns {Promise<undefined>}\\\\n */\\\\n escrowAndAllocateTo: ({ amount, payment, keyword, recipientHandle }) => {\\\\n /* We will create a temporary offer to be able to escrow our payment*/\\\\n /* with Zoe.*/\\\\n let tempHandle;\\\\n\\\\n /* We need to make an invite and store the offerHandle of that*/\\\\n /* invite for future use.*/\\\\n const contractSelfInvite = zcf.makeInvitation(\\\\n offerHandle => tempHandle = offerHandle,\\\\n 'self invite');\\\\n\\\\n /* To escrow the payment, we must get the Zoe Service facet and*/\\\\n /* make an offer*/\\\\n const proposal = harden({ give: { Temp: amount } });\\\\n const payments = harden({ Temp: payment });\\\\n\\\\n return index.E(zcf.getZoeService()).\\\\n offer(contractSelfInvite, proposal, payments).\\\\n then(() => {\\\\n /* At this point, the temporary offer has the amount from the*/\\\\n /* payment but nothing else. The recipient offer may have any*/\\\\n /* allocation, so we can't assume the allocation is currently empty for this*/\\\\n /* keyword.*/\\\\n\\\\n helpers.trade(\\\\n {\\\\n offerHandle: tempHandle,\\\\n gains: {},\\\\n losses: { Temp: amount } },\\\\n\\\\n {\\\\n offerHandle: recipientHandle,\\\\n gains: { [keyword]: amount } });\\\\n\\\\n\\\\n\\\\n /* Complete the temporary offerHandle*/\\\\n zcf.complete([tempHandle]);\\\\n\\\\n /* Now, the temporary offer no longer exists, but the recipient*/\\\\n /* offer is allocated the value of the payment.*/});},\\\\n\\\\n\\\\n /* * Given a brand, assert that the mathHelpers for that issuer\\\\n * are 'nat' mathHelpers\\\\n */\\\\n\\\\n assertNatMathHelpers: brand => {\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n assert.assert(\\\\n amountMath.getMathHelpersName() === 'nat',\\\\n assert.details`issuer must have natMathHelpers`);} });\\\\n\\\\n\\\\n\\\\n return helpers;};exports.defaultAcceptanceMsg = defaultAcceptanceMsg;exports.defaultRejectMsg = defaultRejectMsg;exports.makeZoeHelpers = makeZoeHelpers;\\\",\\n \\\"packages/zoe/src/contractSupport/index.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var auctions = require('./auctions.js');var safeMath = require('./safeMath.js');var bondingCurves = require('./bondingCurves.js');var stateMachine = require('./stateMachine.js');var zoeHelpers = require('./zoeHelpers.js');exports.closeAuction = auctions.closeAuction;exports.secondPriceLogic = auctions.secondPriceLogic;exports.natSafeMath = safeMath.natSafeMath;exports.calcLiqValueToMint = bondingCurves.calcLiqValueToMint;exports.calcValueToRemove = bondingCurves.calcValueToRemove;exports.getInputPrice = bondingCurves.getInputPrice;exports.makeStateMachine = stateMachine.makeStateMachine;exports.defaultAcceptanceMsg = zoeHelpers.defaultAcceptanceMsg;exports.defaultRejectMsg = zoeHelpers.defaultRejectMsg;exports.makeZoeHelpers = zoeHelpers.makeZoeHelpers;\\\"\\n};\\n const nsBundle = {};\\n\\n function createEvalString(filename) {\\n const code = sourceBundle[filename];\\n if (!code) {\\n return undefined;\\n }\\n return `\\\\\\n(function getExport(require, exports) { \\\\\\n 'use strict'; \\\\\\n const module = { exports }; \\\\\\n \\\\\\n ${code}\\n return module.exports;\\n})\\n//# sourceURL=${filePrefix}/${filename}\\n`;\\n }\\n\\n function computeExports(filename, exportPowers, exports) {\\n const { require: systemRequire, _log } = exportPowers;\\n // This captures the endowed require.\\n const match = filename.match(/^(.*)\\\\/[^/]+$/);\\n const thisdir = match ? match[1] : '.';\\n const contextRequire = mod => {\\n // Do path algebra to find the actual source.\\n const els = mod.split('/');\\n let prefix;\\n if (els[0][0] === '@') {\\n // Scoped name.\\n prefix = els.splice(0, 2).join('/');\\n } else if (els[0][0] === '.') {\\n // Relative.\\n els.unshift(...thisdir.split('/'));\\n } else {\\n // Bare or absolute.\\n prefix = els.splice(0, 1);\\n }\\n\\n const suffix = [];\\n for (const el of els) {\\n if (el === '.' || el === '') {\\n // Do nothing.\\n } else if (el === '..') {\\n // Traverse upwards.\\n suffix.pop();\\n } else {\\n suffix.push(el);\\n }\\n }\\n\\n // log(mod, prefix, suffix);\\n if (prefix !== undefined) {\\n suffix.unshift(prefix);\\n }\\n let modPath = suffix.join('/');\\n if (modPath.startsWith('./')) {\\n modPath = modPath.slice(2);\\n }\\n // log('requiring', modPath);\\n if (!(modPath in nsBundle)) {\\n // log('evaluating', modPath);\\n // Break cycles, but be tolerant of modules\\n // that completely override their exports object.\\n nsBundle[modPath] = {};\\n nsBundle[modPath] = computeExports(\\n modPath,\\n exportPowers,\\n nsBundle[modPath],\\n );\\n }\\n\\n // log('returning', nsBundle[modPath]);\\n return nsBundle[modPath];\\n };\\n\\n const code = createEvalString(filename);\\n if (!code) {\\n // log('missing code for', filename, sourceBundle);\\n if (systemRequire) {\\n return systemRequire(filename);\\n }\\n throw Error(\\n `require(${JSON.stringify(\\n filename,\\n )}) failed; no toplevel require endowment`,\\n );\\n }\\n\\n // log('evaluating', code);\\n return nestedEvaluate(code)(contextRequire, exports);\\n }\\n\\n // Evaluate the entrypoint recursively, seeding the exports.\\n const systemRequire = typeof require === 'undefined' ? undefined : require;\\n return computeExports(entrypoint, { require: systemRequire }, {});\\n}\\n//# sourceURL=/bundled-source-preamble.js\\n\",\"sourceMap\":\"//# sourceURL=/bundled-source-preamble.js\\n\",\"moduleFormat\":\"nestedEvaluate\"}]","slots":[]},"p-65"],"syscalls":[{"d":["fulfillToPresence","p-65","o+6"],"response":null}],"crankNumber":14}
v5.t.6 :: {"d":["deliver","o+1","install",{"body":"[{\"source\":\"function getExportWithNestedEvaluate(filePrefix) {\\n 'use strict';\\n // Serialised sources.\\n if (filePrefix === undefined) {\\n filePrefix = \\\"/bundled-source\\\";\\n }\\n const moduleFormat = \\\"nestedEvaluate\\\";\\n const entrypoint = \\\"packages/zoe/src/contracts/autoswap.js\\\";\\n const sourceBundle = {\\n \\\"packages/zoe/src/contracts/autoswap.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var issuer = require('../../../ERTP/src/issuer.js');var bondingCurves = require('../contractSupport/bondingCurves.js');var zoeHelpers = require('../contractSupport/zoeHelpers.js');\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nrequire('../contractSupport/index.js'); /* global harden */ /**\\\\n * Autoswap is a rewrite of Uniswap. Please see the documentation for\\\\n * more https://agoric.com/documentation/zoe/guide/contracts/autoswap.html\\\\n *\\\\n * When the contract is instantiated, the two tokens are specified in the\\\\n * issuerKeywordRecord. The party that calls makeInstance gets an invitation\\\\n * to add liquidity. The same invitation is available by calling\\\\n * `await E(publicAPI).makeAddLiquidityInvite()`. Separate invitations are available for\\\\n * adding and removing liquidity, and for doing a swap. Other API operations\\\\n * support monitoring the price and the size of the liquidity pool.\\\\n *\\\\n * @typedef {Ximport('../zoe').ContractFacet} ContractFacet\\\\n * @param {ContractFacet} zcf\\\\n */\\\\nconst makeContract = zcf => {\\\\n /* Create the liquidity mint and issuer.*/\\\\n const {\\\\n mint: liquidityMint,\\\\n issuer: liquidityIssuer,\\\\n amountMath: liquidityAmountMath } =\\\\n issuer.default('liquidity');\\\\n\\\\n let liqTokenSupply = 0;\\\\n\\\\n const {\\\\n makeEmptyOffer,\\\\n checkHook,\\\\n escrowAndAllocateTo,\\\\n assertNatMathHelpers,\\\\n trade } =\\\\n zoeHelpers.makeZoeHelpers(zcf);\\\\n\\\\n return zcf.addNewIssuer(liquidityIssuer, 'Liquidity').then(() => {\\\\n const { brandKeywordRecord } = zcf.getInstanceRecord();\\\\n Object.values(brandKeywordRecord).forEach((brand) =>\\\\n assertNatMathHelpers(brand));\\\\n\\\\n const getPoolKeyword = brandToMatch => {\\\\n const entries = Object.entries(brandKeywordRecord);\\\\n for (const [keyword, brand] of entries) {\\\\n if (brand === brandToMatch) {\\\\n return keyword;}}\\\\n\\\\n\\\\n throw new Error('getPoolKeyword: brand not found');};\\\\n\\\\n\\\\n return makeEmptyOffer().then(poolHandle => {\\\\n const getPoolAmount = brand => {\\\\n const keyword = getPoolKeyword(brand);\\\\n return zcf.getCurrentAllocation(poolHandle)[keyword];};\\\\n\\\\n\\\\n const swapHook = offerHandle => {\\\\n const {\\\\n proposal: {\\\\n give: { In: amountIn },\\\\n want: { Out: wantedAmountOut } } } =\\\\n\\\\n zcf.getOffer(offerHandle);\\\\n const outputValue = bondingCurves.getInputPrice(\\\\n harden({\\\\n inputValue: amountIn.value,\\\\n inputReserve: getPoolAmount(amountIn.brand).value,\\\\n outputReserve: getPoolAmount(wantedAmountOut.brand).value }));\\\\n\\\\n\\\\n const amountOut = zcf.\\\\n getAmountMath(wantedAmountOut.brand).\\\\n make(outputValue);\\\\n\\\\n trade(\\\\n {\\\\n offerHandle: poolHandle,\\\\n gains: {\\\\n [getPoolKeyword(amountIn.brand)]: amountIn },\\\\n\\\\n losses: {\\\\n [getPoolKeyword(amountOut.brand)]: amountOut } },\\\\n\\\\n\\\\n {\\\\n offerHandle,\\\\n gains: { Out: amountOut },\\\\n losses: { In: amountIn } });\\\\n\\\\n\\\\n zcf.complete(harden([offerHandle]));\\\\n return `Swap successfully completed.`;};\\\\n\\\\n\\\\n const addLiquidityHook = offerHandle => {\\\\n const userAllocation = zcf.getCurrentAllocation(offerHandle);\\\\n\\\\n /* Calculate how many liquidity tokens we should be minting.*/\\\\n /* Calculations are based on the values represented by TokenA.*/\\\\n /* If the current supply is zero, start off by just taking the*/\\\\n /* value at TokenA and using it as the value for the*/\\\\n /* liquidity token.*/\\\\n const tokenAPoolAmount = getPoolAmount(userAllocation.TokenA.brand);\\\\n const inputReserve = tokenAPoolAmount ? tokenAPoolAmount.value : 0;\\\\n const liquidityValueOut = bondingCurves.calcLiqValueToMint(\\\\n harden({\\\\n liqTokenSupply,\\\\n inputValue: userAllocation.TokenA.value,\\\\n inputReserve }));\\\\n\\\\n\\\\n const liquidityAmountOut = liquidityAmountMath.make(liquidityValueOut);\\\\n const liquidityPaymentP = liquidityMint.mintPayment(liquidityAmountOut);\\\\n\\\\n return escrowAndAllocateTo({\\\\n amount: liquidityAmountOut,\\\\n payment: liquidityPaymentP,\\\\n keyword: 'Liquidity',\\\\n recipientHandle: offerHandle }).\\\\n then(() => {\\\\n liqTokenSupply += liquidityValueOut;\\\\n\\\\n trade(\\\\n {\\\\n offerHandle: poolHandle,\\\\n gains: {\\\\n TokenA: userAllocation.TokenA,\\\\n TokenB: userAllocation.TokenB } },\\\\n\\\\n\\\\n /* We've already given the user their liquidity using*/\\\\n /* escrowAndAllocateTo*/\\\\n { offerHandle, gains: {} });\\\\n\\\\n\\\\n zcf.complete(harden([offerHandle]));\\\\n return 'Added liquidity.';});};\\\\n\\\\n\\\\n\\\\n const removeLiquidityHook = offerHandle => {\\\\n const userAllocation = zcf.getCurrentAllocation(offerHandle);\\\\n const liquidityValueIn = userAllocation.Liquidity.value;\\\\n\\\\n const newUserTokenAAmount = zcf.\\\\n getAmountMath(userAllocation.TokenA.brand).\\\\n make(\\\\n bondingCurves.calcValueToRemove(\\\\n harden({\\\\n liqTokenSupply,\\\\n poolValue: getPoolAmount(userAllocation.TokenA.brand).value,\\\\n liquidityValueIn })));\\\\n\\\\n\\\\n\\\\n const newUserTokenBAmount = zcf.\\\\n getAmountMath(userAllocation.TokenB.brand).\\\\n make(\\\\n bondingCurves.calcValueToRemove(\\\\n harden({\\\\n liqTokenSupply,\\\\n poolValue: getPoolAmount(userAllocation.TokenB.brand).value,\\\\n liquidityValueIn })));\\\\n\\\\n\\\\n\\\\n\\\\n liqTokenSupply -= liquidityValueIn;\\\\n\\\\n trade(\\\\n {\\\\n offerHandle: poolHandle,\\\\n gains: { Liquidity: userAllocation.Liquidity } },\\\\n\\\\n {\\\\n offerHandle,\\\\n gains: {\\\\n TokenA: newUserTokenAAmount,\\\\n TokenB: newUserTokenBAmount } });\\\\n\\\\n\\\\n\\\\n\\\\n zcf.complete(harden([offerHandle]));\\\\n return 'Liquidity successfully removed.';};\\\\n\\\\n\\\\n const addLiquidityExpected = harden({\\\\n give: { TokenA: null, TokenB: null },\\\\n want: { Liquidity: null } });\\\\n\\\\n\\\\n const removeLiquidityExpected = harden({\\\\n want: { TokenA: null, TokenB: null },\\\\n give: { Liquidity: null } });\\\\n\\\\n\\\\n const swapExpected = {\\\\n want: { Out: null },\\\\n give: { In: null } };\\\\n\\\\n\\\\n const makeAddLiquidityInvite = () =>\\\\n zcf.makeInvitation(\\\\n checkHook(addLiquidityHook, addLiquidityExpected),\\\\n 'autoswap add liquidity');\\\\n\\\\n\\\\n const makeRemoveLiquidityInvite = () =>\\\\n zcf.makeInvitation(\\\\n checkHook(removeLiquidityHook, removeLiquidityExpected),\\\\n 'autoswap remove liquidity');\\\\n\\\\n\\\\n const makeSwapInvite = () =>\\\\n zcf.makeInvitation(checkHook(swapHook, swapExpected), 'autoswap swap');\\\\n\\\\n /**\\\\n * `getCurrentPrice` calculates the result of a trade, given a certain amount\\\\n * of digital assets in.\\\\n * @typedef {Ximport('../zoe').Amount} Amount\\\\n * @param {Amount} amountIn - the amount of digital\\\\n * assets to be sent in\\\\n */\\\\n const getCurrentPrice = (amountIn, brandOut) => {\\\\n const inputReserve = getPoolAmount(amountIn.brand).value;\\\\n const outputReserve = getPoolAmount(brandOut).value;\\\\n const outputValue = bondingCurves.getInputPrice(\\\\n harden({\\\\n inputValue: amountIn.value,\\\\n inputReserve,\\\\n outputReserve }));\\\\n\\\\n\\\\n return zcf.getAmountMath(brandOut).make(outputValue);};\\\\n\\\\n\\\\n const getPoolAllocation = () =>\\\\n zcf.getCurrentAllocation(poolHandle, brandKeywordRecord);\\\\n\\\\n zcf.initPublicAPI(\\\\n harden({\\\\n getCurrentPrice,\\\\n getLiquidityIssuer: () => liquidityIssuer,\\\\n getPoolAllocation,\\\\n makeSwapInvite,\\\\n makeAddLiquidityInvite,\\\\n makeRemoveLiquidityInvite }));\\\\n\\\\n\\\\n\\\\n return makeAddLiquidityInvite();});});};\\\\n\\\\n\\\\n\\\\n\\\\nharden(makeContract);exports.makeContract = makeContract;\\\",\\n \\\"packages/assert/src/assert.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* Copyright (C) 2019 Agoric, under Apache License 2.0*/ /* @ts-check*/ /* This module assumes the de-facto standard `console` host object.*/ /* To the extent that this `console` is considered a resource,*/ /* this module must be considered a resource module.*/ /**\\\\n * Prepend the correct indefinite article onto a noun, typically a typeof result\\\\n * e.g., \\\\\\\"an Object\\\\\\\" vs. \\\\\\\"a Number\\\\\\\"\\\\n *\\\\n * @param {string} str The noun to prepend\\\\n * @returns {string} The noun prepended with a/an\\\\n */\\\\nfunction an(str) {\\\\n str = `${str}`;\\\\n if (str.length >= 1 && 'aeiouAEIOU'.includes(str[0])) {\\\\n return `an ${str}`;}\\\\n\\\\n return `a ${str}`;}\\\\n\\\\nharden(an);\\\\n\\\\n/**\\\\n * Like `JSON.stringify` but does not blow up if given a cycle. This is not\\\\n * intended to be a serialization to support any useful unserialization,\\\\n * or any programmatic use of the resulting string. The string is intended\\\\n * only for showing a human, in order to be informative enough for some\\\\n * logging purposes. As such, this `cycleTolerantStringify` has an\\\\n * imprecise specification and may change over time.\\\\n *\\\\n * The current `cycleTolerantStringify` possibly emits too many \\\\\\\"seen\\\\\\\"\\\\n * markings: Not only for cycles, but also for repeated subtrees by\\\\n * object identity.\\\\n */\\\\nfunction cycleTolerantStringify(payload) {\\\\n const seenSet = new Set();\\\\n const replacer = (_, val) => {\\\\n if (typeof val === 'object' && val !== null) {\\\\n if (seenSet.has(val)) {\\\\n return '<**seen**>';}\\\\n\\\\n seenSet.add(val);}\\\\n\\\\n return val;};\\\\n\\\\n return JSON.stringify(payload, replacer);}\\\\n\\\\n\\\\nconst declassifiers = new WeakSet();\\\\n\\\\n/**\\\\n * To \\\\\\\"declassify\\\\\\\" and quote a substitution value used in a\\\\n * details`...` template literal, enclose that substitution expression\\\\n * in a call to `q`. This states that the argument should appear quoted (with\\\\n * `JSON.stringify`), in the error message of the thrown error. The payload\\\\n * itself is still passed unquoted to the console as it would be without q.\\\\n *\\\\n * Starting from the example in the `details` comment, say instead that the\\\\n * color the sky is supposed to be is also computed. Say that we still don't\\\\n * want to reveal the sky's actual color, but we do want the thrown error's\\\\n * message to reveal what color the sky was supposed to be:\\\\n * ```js\\\\n * assert.equal(\\\\n * sky.color,\\\\n * color,\\\\n * details`${sky.color} should be ${q(color)}`,\\\\n * );\\\\n * ```\\\\n *\\\\n * @typedef {Object} StringablePayload\\\\n * @property {*} payload The original payload\\\\n * @property {() => string} toString How to print the payload\\\\n *\\\\n * @param {*} payload What to declassify\\\\n * @returns {StringablePayload} The declassified payload\\\\n */\\\\nfunction q(payload) {\\\\n /* Don't harden the payload*/\\\\n const result = Object.freeze({\\\\n payload,\\\\n toString: Object.freeze(() => cycleTolerantStringify(payload)) });\\\\n\\\\n declassifiers.add(result);\\\\n return result;}\\\\n\\\\nharden(q);\\\\n\\\\n/**\\\\n * Use the `details` function as a template literal tag to create\\\\n * informative error messages. The assertion functions take such messages\\\\n * as optional arguments:\\\\n * ```js\\\\n * assert(sky.isBlue(), details`${sky.color} should be \\\\\\\"blue\\\\\\\"`);\\\\n * ```\\\\n * The details template tag returns an object that can print itself with the\\\\n * formatted message in two ways. It will report the real details to the\\\\n * console but include only the typeof information in the thrown error\\\\n * to prevent revealing secrets up the exceptional path. In the example\\\\n * above, the thrown error may reveal only that `sky.color` is a string,\\\\n * whereas the same diagnostic printed to the console reveals that the\\\\n * sky was green.\\\\n *\\\\n * WARNING: this function currently returns an unhardened result, as hardening\\\\n * proved to cause significant performance degradation. Consequently, callers\\\\n * should take care to use it only in contexts where this lack of hardening\\\\n * does not present a hazard. In current usage, a `details` template literal\\\\n * may only appear either as an argument to `assert`, where we know hardening\\\\n * won't matter, or inside another hardened object graph, where hardening is\\\\n * already ensured. However, there is currently no means to enfoce these\\\\n * constraints, so users are required to employ this function with caution.\\\\n * Our intent is to eventually have a lint rule that will check for\\\\n * inappropriate uses or find an alternative means of implementing `details`\\\\n * that does not encounter the performance issue. The final disposition of\\\\n * this is being discussed and tracked in issue #679 in the agoric-sdk\\\\n * repository.\\\\n *\\\\n * @typedef {Object} Complainer An object that has custom assert behaviour\\\\n * @property {() => Error} complain Return an Error to throw, and print details to console\\\\n *\\\\n * @typedef {string|Complainer} Details Either a plain string, or made by details``\\\\n *\\\\n * @param {TemplateStringsArray | string[]} template The template to format\\\\n * @param {any[]} args Arguments to the template\\\\n * @returns {Complainer} The complainer for these details\\\\n */\\\\nfunction details(template, ...args) {\\\\n /* const complainer = harden({ // remove harden per above discussion*/\\\\n const complainer = {\\\\n complain() {\\\\n const interleaved = [template[0]];\\\\n const parts = [template[0]];\\\\n for (let i = 0; i < args.length; i += 1) {\\\\n let arg = args[i];\\\\n let argStr;\\\\n if (declassifiers.has(arg)) {\\\\n argStr = `${arg}`;\\\\n arg = arg.payload;} else\\\\n {\\\\n argStr = `(${an(typeof arg)})`;}\\\\n\\\\n\\\\n /* Remove the extra spaces (since console.error puts them*/\\\\n /* between each interleaved).*/\\\\n const priorWithoutSpace = (interleaved.pop() || '').replace(/ $/, '');\\\\n if (priorWithoutSpace !== '') {\\\\n interleaved.push(priorWithoutSpace);}\\\\n\\\\n\\\\n const nextWithoutSpace = template[i + 1].replace(/^ /, '');\\\\n interleaved.push(arg, nextWithoutSpace);\\\\n\\\\n parts.push(argStr, template[i + 1]);}\\\\n\\\\n if (interleaved[interleaved.length - 1] === '') {\\\\n interleaved.pop();}\\\\n\\\\n if (args.length >= 1) {\\\\n parts.push('\\\\\\\\nSee console for error data.');}\\\\n\\\\n const err = new Error(parts.join(''));\\\\n console.error('LOGGED ERROR:', ...interleaved, err);\\\\n /* eslint-disable-next-line no-debugger*/\\\\n debugger;\\\\n return err;} };\\\\n\\\\n\\\\n /* });*/\\\\n return complainer;}\\\\n\\\\nharden(details);\\\\n\\\\n/**\\\\n * Fail an assertion, recording details to the console and\\\\n * raising an exception with just type information.\\\\n *\\\\n * The optional `optDetails` can be a string for backwards compatibility\\\\n * with the nodejs assertion library.\\\\n * @param {Details} [optDetails] The details of what was asserted\\\\n * @returns {never}\\\\n */\\\\nfunction fail(optDetails = details`Assert failed`) {\\\\n if (typeof optDetails === 'string') {\\\\n /* If it is a string, use it as the literal part of the template so*/\\\\n /* it doesn't get quoted.*/\\\\n optDetails = details([optDetails]);}\\\\n\\\\n throw optDetails.complain();}\\\\n\\\\n\\\\n/**\\\\n * @param {*} flag The truthy/falsy value\\\\n * @param {Details} [optDetails] The details to throw\\\\n * @returns {asserts flag}\\\\n */\\\\nfunction assert(flag, optDetails = details`Check failed`) {\\\\n if (!flag) {\\\\n throw fail(optDetails);}}\\\\n\\\\n\\\\n\\\\n/**\\\\n * Assert that two values must be `Object.is`.\\\\n * @param {*} actual The value we received\\\\n * @param {*} expected What we wanted\\\\n * @param {Details} [optDetails] The details to throw\\\\n * @returns {void}\\\\n */\\\\nfunction equal(\\\\nactual,\\\\nexpected,\\\\noptDetails = details`Expected ${actual} is same as ${expected}`)\\\\n{\\\\n assert(Object.is(actual, expected), optDetails);}\\\\n\\\\n\\\\n/**\\\\n * Assert an expected typeof result.\\\\n * @type {AssertTypeof}\\\\n * @param {any} specimen The value to get the typeof\\\\n * @param {string} typename The expected name\\\\n * @param {Details} [optDetails] The details to throw\\\\n */\\\\nconst assertTypeof = (specimen, typename, optDetails) => {\\\\n assert(\\\\n typeof typename === 'string',\\\\n details`${q(typename)} must be a string`);\\\\n\\\\n if (optDetails === undefined) {\\\\n /* Like*/\\\\n /* ```js*/\\\\n /* optDetails = details`${specimen} must be ${q(an(typename))}`;*/\\\\n /* ```*/\\\\n /* except it puts the typename into the literal part of the template*/\\\\n /* so it doesn't get quoted.*/\\\\n optDetails = details(['', ` must be ${an(typename)}`], specimen);}\\\\n\\\\n equal(typeof specimen, typename, optDetails);};\\\\n\\\\n\\\\n/**\\\\n * assert that expr is truthy, with an optional details to describe\\\\n * the assertion. It is a tagged template literal like\\\\n * ```js\\\\n * assert(expr, details`....`);`\\\\n * ```\\\\n * If expr is falsy, then the template contents are reported to the\\\\n * console and also in a thrown error.\\\\n *\\\\n * The literal portions of the template are assumed non-sensitive, as\\\\n * are the `typeof` types of the substitution values. These are\\\\n * assembled into the thrown error message. The actual contents of the\\\\n * substitution values are assumed sensitive, to be revealed to the\\\\n * console only. We assume only the virtual platform's owner can read\\\\n * what is written to the console, where the owner is in a privileged\\\\n * position over computation running on that platform.\\\\n *\\\\n * The optional `optDetails` can be a string for backwards compatibility\\\\n * with the nodejs assertion library.\\\\n * @type {typeof assert & { typeof: AssertTypeof, fail: typeof fail, equal: typeof equal }}\\\\n */\\\\nconst assertCombined = Object.assign(assert, {\\\\n equal,\\\\n fail,\\\\n typeof: assertTypeof });\\\\n\\\\nharden(assertCombined);exports.an = an;exports.assert = assertCombined;exports.details = details;exports.q = q;\\\",\\n \\\"packages/weak-store/src/weakStore.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nassert = require('../../assert/src/assert.js'); /* Copyright (C) 2019 Agoric, under Apache license 2.0*/ /**\\\\n * @template K,V\\\\n * @typedef {Object} WeakStore - A safety wrapper around a WeakMap\\\\n * @property {(key: K) => boolean} has - Check if a key exists\\\\n * @property {(key: K, value: V) => void} init - Initialize the key only if it doesn't already exist\\\\n * @property {(key: K) => V} get - Return a value for the key. Throws\\\\n * if not found.\\\\n * @property {(key: K, value: V) => void} set - Set the key. Throws if not found.\\\\n * @property {(key: K) => void} delete - Remove the key. Throws if not found.\\\\n */ /**\\\\n * Distinguishes between adding a new key (init) and updating or\\\\n * referencing a key (get, set, delete).\\\\n *\\\\n * `init` is only allowed if the key does not already exist. `Get`,\\\\n * `set` and `delete` are only allowed if the key does already exist.\\\\n * @template K,V\\\\n * @param {string} [keyName='key'] - the column name for the key\\\\n * @returns {WeakStore<K,V>}\\\\n */function makeStore(keyName = 'key') {const wm = new WeakMap();const assertKeyDoesNotExist = (key) => assert.assert(!wm.has(key), assert.details`${assert.q(keyName)} already registered: ${key}`);const assertKeyExists = (key) => assert.assert(wm.has(key), assert.details`${assert.q(keyName)} not found: ${key}`);return harden({ has: key => wm.has(key), init: (key, value) => {\\\\n assertKeyDoesNotExist(key);\\\\n wm.set(key, value);},\\\\n\\\\n get: key => {\\\\n assertKeyExists(key);\\\\n return wm.get(key);},\\\\n\\\\n set: (key, value) => {\\\\n assertKeyExists(key);\\\\n wm.set(key, value);},\\\\n\\\\n delete: key => {\\\\n assertKeyExists(key);\\\\n wm.delete(key);} });}\\\\n\\\\n\\\\n\\\\nharden(makeStore);exports.default = makeStore;\\\",\\n \\\"packages/eventual-send/src/E.js\\\": \\\"'use strict';\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* global harden */ /* eslint-disable-next-line spaced-comment*/ /*/ <reference path=\\\\\\\"index.d.ts\\\\\\\" />*/\\\\n\\\\nconst readOnlyProxy = {\\\\n set(_target, _prop, _value) {\\\\n return false;},\\\\n\\\\n isExtensible(_target) {\\\\n return false;},\\\\n\\\\n setPrototypeOf(_target, _value) {\\\\n return false;},\\\\n\\\\n deleteProperty(_target, _prop) {\\\\n return false;} };\\\\n\\\\n\\\\n\\\\n/**\\\\n * A Proxy handler for E(x).\\\\n *\\\\n * @param {*} x Any value passed to E(x)\\\\n * @returns {ProxyHandler} the Proxy handler\\\\n */\\\\nfunction EProxyHandler(x, HandledPromise) {\\\\n return harden({\\\\n ...readOnlyProxy,\\\\n get(_target, p, _receiver) {\\\\n if (`${p}` !== p) {\\\\n return undefined;}\\\\n\\\\n /* Harden this Promise because it's our only opportunity to ensure*/\\\\n /* p1=E(x).foo() is hardened. The Handled Promise API does not (yet)*/\\\\n /* allow the handler to synchronously influence the promise returned*/\\\\n /* by the handled methods, so we must freeze it from the outside. See*/\\\\n /* #95 for details.*/\\\\n return (...args) => harden(HandledPromise.applyMethod(x, p, args));},\\\\n\\\\n apply(_target, _thisArg, argArray = []) {\\\\n return harden(HandledPromise.applyFunction(x, argArray));},\\\\n\\\\n has(_target, _p) {\\\\n /* We just pretend everything exists.*/\\\\n return true;} });}\\\\n\\\\n\\\\n\\\\n\\\\nfunction makeE(HandledPromise) {\\\\n function E(x) {\\\\n const handler = EProxyHandler(x, HandledPromise);\\\\n return harden(new Proxy(() => {}, handler));}\\\\n\\\\n\\\\n const makeEGetterProxy = (x) =>\\\\n new Proxy(Object.create(null), {\\\\n ...readOnlyProxy,\\\\n has(_target, _prop) {\\\\n return true;},\\\\n\\\\n get(_target, prop) {\\\\n return harden(HandledPromise.get(x, prop));} });\\\\n\\\\n\\\\n\\\\n E.G = makeEGetterProxy;\\\\n E.resolve = HandledPromise.resolve;\\\\n E.unwrap = HandledPromise.unwrap;\\\\n\\\\n E.when = (x, onfulfilled = undefined, onrejected = undefined) =>\\\\n HandledPromise.resolve(x).then(onfulfilled, onrejected);\\\\n\\\\n return harden(E);}exports.default = makeE;\\\",\\n \\\"packages/eventual-send/src/index.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var E$1 = require('./E.js'); /* global harden HandledPromise */\\\\n\\\\n\\\\n\\\\nconst {\\\\n defineProperties,\\\\n getOwnPropertyDescriptors,\\\\n getOwnPropertyDescriptor: gopd,\\\\n getPrototypeOf,\\\\n isFrozen } =\\\\nObject;\\\\n\\\\nconst { prototype: promiseProto } = Promise;\\\\nconst { then: originalThen } = promiseProto;\\\\n\\\\n/* 'E' and 'HandledPromise' are exports of the module*/\\\\n\\\\n/* For now:*/\\\\n/* import { HandledPromise, E } from '@agoric/eventual-send';*/\\\\n/* ...*/\\\\n\\\\nconst hp =\\\\ntypeof HandledPromise === 'undefined' ?\\\\n/* eslint-disable-next-line no-use-before-define*/\\\\nmakeHandledPromise(Promise) :\\\\nharden(HandledPromise);\\\\n\\\\n\\\\n\\\\nconst E = E$1.default(hp);\\\\n\\\\n/* the following method (makeHandledPromise) is part*/\\\\n/* of the shim, and will not be exported by the module once the feature*/\\\\n/* becomes a part of standard javascript*/\\\\n\\\\n/**\\\\n * Create a HandledPromise class to have it support eventual send\\\\n * (wavy-dot) operations.\\\\n *\\\\n * Based heavily on nanoq\\\\n * https://github.com/drses/nanoq/blob/master/src/nanoq.js\\\\n *\\\\n * Original spec for the infix-bang (predecessor to wavy-dot) desugaring:\\\\n * https://web.archive.org/web/20161026162206/http://wiki.ecmascript.org/doku.php?id=strawman:concurrency\\\\n *\\\\n * @return {typeof HandledPromise} Handled promise\\\\n */\\\\nfunction makeHandledPromise(Promise) {\\\\n /* xs doesn't support WeakMap in pre-loaded closures*/\\\\n /* aka \\\\\\\"vetted customization code\\\\\\\"*/\\\\n let presenceToHandler;\\\\n let presenceToPromise;\\\\n let promiseToUnsettledHandler;\\\\n let promiseToPresence; /* only for HandledPromise.unwrap*/\\\\n let forwardedPromiseToPromise; /* forwarding, union-find-ish*/\\\\n function ensureMaps() {\\\\n if (!presenceToHandler) {\\\\n presenceToHandler = new WeakMap();\\\\n presenceToPromise = new WeakMap();\\\\n promiseToUnsettledHandler = new WeakMap();\\\\n promiseToPresence = new WeakMap();\\\\n forwardedPromiseToPromise = new WeakMap();}}\\\\n\\\\n\\\\n\\\\n /**\\\\n * You can imagine a forest of trees in which the roots of each tree is an\\\\n * unresolved HandledPromise or a non-Promise, and each node's parent is the\\\\n * HandledPromise to which it was forwarded. We maintain that mapping of\\\\n * forwarded HandledPromise to its resolution in forwardedPromiseToPromise.\\\\n *\\\\n * We use something like the description of \\\\\\\"Find\\\\\\\" with \\\\\\\"Path splitting\\\\\\\"\\\\n * to propagate changes down to the children efficiently:\\\\n * https://en.wikipedia.org/wiki/Disjoint-set_data_structure\\\\n *\\\\n * @param {*} target Any value.\\\\n * @returns {*} If the target was a HandledPromise, the most-resolved parent of it, otherwise the target.\\\\n */\\\\n function shorten(target) {\\\\n let p = target;\\\\n /* Find the most-resolved value for p.*/\\\\n while (forwardedPromiseToPromise.has(p)) {\\\\n p = forwardedPromiseToPromise.get(p);}\\\\n\\\\n const presence = promiseToPresence.get(p);\\\\n if (presence) {\\\\n /* Presences are final, so it is ok to propagate*/\\\\n /* this upstream.*/\\\\n while (target !== p) {\\\\n const parent = forwardedPromiseToPromise.get(target);\\\\n forwardedPromiseToPromise.delete(target);\\\\n promiseToUnsettledHandler.delete(target);\\\\n promiseToPresence.set(target, presence);\\\\n target = parent;}} else\\\\n\\\\n {\\\\n /* We propagate p and remove all other unsettled handlers*/\\\\n /* upstream.*/\\\\n /* Note that everything except presences is covered here.*/\\\\n while (target !== p) {\\\\n const parent = forwardedPromiseToPromise.get(target);\\\\n forwardedPromiseToPromise.set(target, p);\\\\n promiseToUnsettledHandler.delete(target);\\\\n target = parent;}}\\\\n\\\\n\\\\n return target;}\\\\n\\\\n\\\\n /* This special handler accepts Promises, and forwards*/\\\\n /* handled Promises to their corresponding fulfilledHandler.*/\\\\n let forwardingHandler;\\\\n let handle;\\\\n let promiseResolve;\\\\n\\\\n function HandledPromise(executor, unsettledHandler = undefined) {\\\\n if (new.target === undefined) {\\\\n throw new Error('must be invoked with \\\\\\\"new\\\\\\\"');}\\\\n\\\\n let handledResolve;\\\\n let handledReject;\\\\n let resolved = false;\\\\n let resolvedTarget = null;\\\\n let handledP;\\\\n let continueForwarding = () => {};\\\\n const superExecutor = (superResolve, superReject) => {\\\\n handledResolve = value => {\\\\n if (resolved) {\\\\n return resolvedTarget;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n value = shorten(value);\\\\n let targetP;\\\\n if (\\\\n promiseToUnsettledHandler.has(value) ||\\\\n promiseToPresence.has(value))\\\\n {\\\\n targetP = value;} else\\\\n {\\\\n /* We're resolving to a non-promise, so remove our handler.*/\\\\n promiseToUnsettledHandler.delete(handledP);\\\\n targetP = presenceToPromise.get(value);}\\\\n\\\\n /* Ensure our data structure is a propert tree (avoid cycles).*/\\\\n if (targetP && targetP !== handledP) {\\\\n forwardedPromiseToPromise.set(handledP, targetP);} else\\\\n {\\\\n forwardedPromiseToPromise.delete(handledP);}\\\\n\\\\n\\\\n /* Remove stale unsettled handlers, set to canonical form.*/\\\\n shorten(handledP);\\\\n\\\\n /* Ensure our unsettledHandler is cleaned up if not already.*/\\\\n if (promiseToUnsettledHandler.has(handledP)) {\\\\n handledP.then(_ => promiseToUnsettledHandler.delete(handledP));}\\\\n\\\\n\\\\n /* Finish the resolution.*/\\\\n superResolve(value);\\\\n resolved = true;\\\\n resolvedTarget = value;\\\\n\\\\n /* We're resolved, so forward any postponed operations to us.*/\\\\n continueForwarding();\\\\n return resolvedTarget;};\\\\n\\\\n handledReject = err => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n promiseToUnsettledHandler.delete(handledP);\\\\n resolved = true;\\\\n superReject(err);\\\\n continueForwarding();};};\\\\n\\\\n\\\\n handledP = harden(Reflect.construct(Promise, [superExecutor], new.target));\\\\n\\\\n ensureMaps();\\\\n\\\\n const makePostponedHandler = () => {\\\\n /* Create a simple postponedHandler that just postpones until the*/\\\\n /* fulfilledHandler is set.*/\\\\n let donePostponing;\\\\n const interlockP = new Promise(resolve => {\\\\n donePostponing = () => resolve();});\\\\n\\\\n\\\\n const makePostponedOperation = postponedOperation => {\\\\n /* Just wait until the handler is resolved/rejected.*/\\\\n return function postpone(x, ...args) {\\\\n /* console.log(`forwarding ${postponedOperation} ${args[0]}`);*/\\\\n return new HandledPromise((resolve, reject) => {\\\\n interlockP.\\\\n then(_ => {\\\\n /* If targetP is a handled promise, use it, otherwise x.*/\\\\n resolve(HandledPromise[postponedOperation](x, ...args));}).\\\\n\\\\n catch(reject);});};};\\\\n\\\\n\\\\n\\\\n\\\\n const postponedHandler = {\\\\n get: makePostponedOperation('get'),\\\\n applyMethod: makePostponedOperation('applyMethod') };\\\\n\\\\n return [postponedHandler, donePostponing];};\\\\n\\\\n\\\\n if (!unsettledHandler) {\\\\n /* This is insufficient for actual remote handled Promises*/\\\\n /* (too many round-trips), but is an easy way to create a*/\\\\n /* local handled Promise.*/\\\\n [unsettledHandler, continueForwarding] = makePostponedHandler();}\\\\n\\\\n\\\\n const validateHandler = h => {\\\\n if (Object(h) !== h) {\\\\n throw TypeError(`Handler ${h} cannot be a primitive`);}};\\\\n\\\\n\\\\n validateHandler(unsettledHandler);\\\\n\\\\n /* Until the handled promise is resolved, we use the unsettledHandler.*/\\\\n promiseToUnsettledHandler.set(handledP, unsettledHandler);\\\\n\\\\n const rejectHandled = reason => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n handledReject(reason);};\\\\n\\\\n\\\\n const resolveWithPresence = presenceHandler => {\\\\n if (resolved) {\\\\n return resolvedTarget;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n try {\\\\n /* Sanity checks.*/\\\\n validateHandler(presenceHandler);\\\\n\\\\n /* Validate and install our mapped target (i.e. presence).*/\\\\n resolvedTarget = Object.create(null);\\\\n\\\\n /* Create table entries for the presence mapped to the*/\\\\n /* fulfilledHandler.*/\\\\n presenceToPromise.set(resolvedTarget, handledP);\\\\n promiseToPresence.set(handledP, resolvedTarget);\\\\n presenceToHandler.set(resolvedTarget, presenceHandler);\\\\n\\\\n /* We committed to this presence, so resolve.*/\\\\n handledResolve(resolvedTarget);\\\\n return resolvedTarget;}\\\\n catch (e) {\\\\n handledReject(e);\\\\n throw e;}};\\\\n\\\\n\\\\n\\\\n const resolveHandled = async (target, deprecatedPresenceHandler) => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n try {\\\\n if (deprecatedPresenceHandler) {\\\\n throw TypeError(\\\\n `resolveHandled no longer accepts a handler; use resolveWithPresence`);}\\\\n\\\\n\\\\n\\\\n /* Resolve the target.*/\\\\n handledResolve(target);}\\\\n catch (e) {\\\\n handledReject(e);}};\\\\n\\\\n\\\\n\\\\n /* Invoke the callback to let the user resolve/reject.*/\\\\n executor(\\\\n (...args) => {\\\\n resolveHandled(...args);},\\\\n\\\\n rejectHandled,\\\\n resolveWithPresence);\\\\n\\\\n return handledP;}\\\\n\\\\n\\\\n HandledPromise.prototype = promiseProto;\\\\n Object.setPrototypeOf(HandledPromise, Promise);\\\\n\\\\n function isFrozenPromiseThen(p) {\\\\n return (\\\\n isFrozen(p) &&\\\\n getPrototypeOf(p) === promiseProto &&\\\\n promiseResolve(p) === p &&\\\\n gopd(p, 'then') === undefined &&\\\\n gopd(promiseProto, 'then').value === originalThen /* unnecessary under SES*/);}\\\\n\\\\n\\\\n\\\\n const staticMethods = harden({\\\\n get(target, key) {\\\\n return handle(target, 'get', key);},\\\\n\\\\n getSendOnly(target, key) {\\\\n handle(target, 'get', key);},\\\\n\\\\n applyFunction(target, args) {\\\\n return handle(target, 'applyMethod', undefined, args);},\\\\n\\\\n applyFunctionSendOnly(target, args) {\\\\n handle(target, 'applyMethod', undefined, args);},\\\\n\\\\n applyMethod(target, key, args) {\\\\n return handle(target, 'applyMethod', key, args);},\\\\n\\\\n applyMethodSendOnly(target, key, args) {\\\\n handle(target, 'applyMethod', key, args);},\\\\n\\\\n resolve(value) {\\\\n ensureMaps();\\\\n /* Resolving a Presence returns the pre-registered handled promise.*/\\\\n let resolvedPromise = presenceToPromise.get(value);\\\\n if (!resolvedPromise) {\\\\n resolvedPromise = promiseResolve(value);}\\\\n\\\\n /* Prevent any proxy trickery.*/\\\\n harden(resolvedPromise);\\\\n if (isFrozenPromiseThen(resolvedPromise)) {\\\\n return resolvedPromise;}\\\\n\\\\n /* Assimilate the thenable.*/\\\\n const executeThen = (resolve, reject) =>\\\\n resolvedPromise.then(resolve, reject);\\\\n return harden(\\\\n promiseResolve().then(_ => new HandledPromise(executeThen)));},\\\\n\\\\n\\\\n /* TODO verify that this is safe to provide universally, i.e.,*/\\\\n /* that by itself it doesn't provide access to mutable state in*/\\\\n /* ways that violate normal ocap module purity rules. The claim*/\\\\n /* that it does not rests on the handled promise itself being*/\\\\n /* necessary to perceive this mutable state. In that sense, we*/\\\\n /* can think of the right to perceive it, and of access to the*/\\\\n /* target, as being in the handled promise. Note that a .then on*/\\\\n /* the handled promise will already provide async access to the*/\\\\n /* target, so the only additional authorities are: 1)*/\\\\n /* synchronous access for handled promises only, and thus 2) the*/\\\\n /* ability to tell, from the client side, whether a promise is*/\\\\n /* handled. Or, at least, the ability to tell given that the*/\\\\n /* promise is already fulfilled.*/\\\\n unwrap(value) {\\\\n /* This check for Thenable is safe, since in a remote-object*/\\\\n /* environment, our comms system will defend against remote*/\\\\n /* objects being represented as a tricky local Proxy, otherwise*/\\\\n /* it is guaranteed to be local and therefore synchronous enough.*/\\\\n if (Object(value) !== value || !('then' in value)) {\\\\n /* Not a Thenable, so return it.*/\\\\n /* This means that local objects will pass through without error.*/\\\\n return value;}\\\\n\\\\n\\\\n /* Try to look up the HandledPromise.*/\\\\n ensureMaps();\\\\n const pr = presenceToPromise.get(value) || value;\\\\n\\\\n /* Find the fulfilled presence for that HandledPromise.*/\\\\n const presence = promiseToPresence.get(pr);\\\\n if (!presence) {\\\\n throw TypeError(\\\\n `Value is a Thenble but not a HandledPromise fulfilled to a presence`);}\\\\n\\\\n\\\\n return presence;} });\\\\n\\\\n\\\\n\\\\n defineProperties(HandledPromise, getOwnPropertyDescriptors(staticMethods));\\\\n\\\\n function makeForwarder(operation, localImpl) {\\\\n return (o, ...args) => {\\\\n /* We are in another turn already, and have the naked object.*/\\\\n const fulfilledHandler = presenceToHandler.get(o);\\\\n if (\\\\n fulfilledHandler &&\\\\n typeof fulfilledHandler[operation] === 'function')\\\\n {\\\\n /* The handler was resolved, so use it.*/\\\\n return fulfilledHandler[operation](o, ...args);}\\\\n\\\\n\\\\n /* Not handled, so use the local implementation.*/\\\\n return localImpl(o, ...args);};}\\\\n\\\\n\\\\n\\\\n /* eslint-disable-next-line prefer-const*/\\\\n forwardingHandler = {\\\\n get: makeForwarder('get', (o, key) => o[key]),\\\\n applyMethod: makeForwarder('applyMethod', (o, optKey, args) => {\\\\n if (optKey === undefined || optKey === null) {\\\\n return o(...args);}\\\\n\\\\n /* console.log(`sending`, optKey, o[optKey], o);*/\\\\n if (typeof o[optKey] !== 'function') {\\\\n throw TypeError(`o[${JSON.stringify(optKey)}] is not a function`);}\\\\n\\\\n return o[optKey](...args);}) };\\\\n\\\\n\\\\n\\\\n handle = (p, operation, ...opArgs) => {\\\\n ensureMaps();\\\\n const returnedP = new HandledPromise((resolve, reject) => {\\\\n /* We run in a future turn to prevent synchronous attacks,*/\\\\n let raceIsOver = false;\\\\n function win(handlerName, handler, o) {\\\\n if (raceIsOver) {\\\\n return;}\\\\n\\\\n if (typeof handler[operation] !== 'function') {\\\\n throw TypeError(`${handlerName}.${operation} is not a function`);}\\\\n\\\\n try {\\\\n resolve(handler[operation](o, ...opArgs, returnedP));}\\\\n catch (reason) {\\\\n reject(reason);}\\\\n\\\\n raceIsOver = true;}\\\\n\\\\n\\\\n function lose(e) {\\\\n if (raceIsOver) {\\\\n return;}\\\\n\\\\n reject(e);\\\\n raceIsOver = true;}\\\\n\\\\n\\\\n /* This contestant tries to win with the target's resolution.*/\\\\n HandledPromise.resolve(p).\\\\n then(o => win('forwardingHandler', forwardingHandler, o)).\\\\n catch(lose);\\\\n\\\\n /* This contestant sleeps a turn, but then tries to win immediately.*/\\\\n HandledPromise.resolve().\\\\n then(() => {\\\\n p = shorten(p);\\\\n const unsettledHandler = promiseToUnsettledHandler.get(p);\\\\n if (\\\\n unsettledHandler &&\\\\n typeof unsettledHandler[operation] === 'function')\\\\n {\\\\n /* and resolve to the answer from the specific unsettled handler,*/\\\\n /* opArgs are something like [prop] or [method, args],*/\\\\n /* so we don't risk the user's args leaking into this expansion.*/\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n win('unsettledHandler', unsettledHandler, p);} else\\\\n if (Object(p) !== p || !('then' in p)) {\\\\n /* Not a Thenable, so use it.*/\\\\n win('forwardingHandler', forwardingHandler, p);} else\\\\n if (promiseToPresence.has(p)) {\\\\n /* We have the object synchronously, so resolve with it.*/\\\\n const o = promiseToPresence.get(p);\\\\n win('forwardingHandler', forwardingHandler, o);}\\\\n\\\\n /* If we made it here without winning, then we will wait*/\\\\n /* for the other contestant to win instead.*/}).\\\\n\\\\n catch(lose);});\\\\n\\\\n\\\\n /* We return a handled promise with the default unsettled handler.*/\\\\n /* This prevents a race between the above Promise.resolves and*/\\\\n /* pipelining.*/\\\\n return returnedP;};\\\\n\\\\n\\\\n promiseResolve = Promise.resolve.bind(Promise);\\\\n return harden(HandledPromise);}exports.E = E;exports.HandledPromise = hp;exports.makeHandledPromise = makeHandledPromise;\\\",\\n \\\"packages/produce-promise/src/producePromise.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nindex = require('../../eventual-send/src/index.js'); /* global harden */ /**\\\\n * @template U,V\\\\n * @typedef {Object} PromiseRecord A reified Promise\\\\n * @property {(value?: U) => void} resolve\\\\n * @property {(reason?: V) => void} reject\\\\n * @property {Promise.<U, V>} promise\\\\n */ /**\\\\n * producePromise() builds a HandledPromise object, and returns a record\\\\n * containing the promise itself, as well as separate facets for resolving\\\\n * and rejecting it.\\\\n *\\\\n * @template U,V\\\\n * @returns {PromiseRecord.<U,V>}\\\\n */function producePromise() {let res;let rej; /* We use a HandledPromise so that we can run HandledPromise.unwrap(p)*/ /* even if p doesn't travel through a comms system (like SwingSet's).*/const p = new index.HandledPromise((resolve, reject) => {\\\\n res = resolve;\\\\n rej = reject;});\\\\n\\\\n /* Node.js adds the `domain` property which is not a standard*/\\\\n /* property on Promise. Because we do not know it to be ocap-safe,*/\\\\n /* we remove it.*/\\\\n if (p.domain) {\\\\n /* deleting p.domain may break functionality. To retain current*/\\\\n /* functionality at the expense of safety, set unsafe to true.*/\\\\n const unsafe = false;\\\\n if (unsafe) {\\\\n const originalDomain = p.domain;\\\\n Object.defineProperty(p, 'domain', {\\\\n get() {\\\\n return originalDomain;} });} else\\\\n\\\\n\\\\n {\\\\n delete p.domain;}}\\\\n\\\\n\\\\n return harden({ promise: p, resolve: res, reject: rej });}\\\\n\\\\nharden(producePromise);\\\\n\\\\n/**\\\\n * Determine if the argument is a Promise.\\\\n *\\\\n * @param {Promise} maybePromise The value to examine\\\\n * @returns {boolean} Whether it is a promise\\\\n */\\\\nfunction isPromise(maybePromise) {\\\\n return index.HandledPromise.resolve(maybePromise) === maybePromise;}\\\\n\\\\nharden(isPromise);exports.isPromise = isPromise;exports.producePromise = producePromise;\\\",\\n \\\"node_modules/@agoric/nat/dist/nat.esm.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* Copyright (C) 2011 Google Inc.*/ /* Copyright (C) 2018 Agoric*/ /**/ /* Licensed under the Apache License, Version 2.0 (the \\\\\\\"License\\\\\\\");*/ /* you may not use this file except in compliance with the License.*/ /* You may obtain a copy of the License at*/ /**/ /* http://www.apache.org/licenses/LICENSE-2.0*/ /**/ /* Unless required by applicable law or agreed to in writing, software*/ /* distributed under the License is distributed on an \\\\\\\"AS IS\\\\\\\" BASIS,*/ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*/ /* See the License for the specific language governing permissions and*/ /* limitations under the License.*/ /**\\\\n * Is allegedNum a number in the contiguous range of exactly and\\\\n * unambiguously representable natural numbers (non-negative integers)?\\\\n *\\\\n * <p>See <a href=\\\\n * \\\\\\\"https://code.google.com/p/google-caja/issues/detail?id=1801\\\\\\\"\\\\n * >Issue 1801: Nat must include at most (2**53)-1</a>\\\\n * and <a href=\\\\n * \\\\\\\"https://mail.mozilla.org/pipermail/es-discuss/2013-July/031716.html\\\\\\\"\\\\n * >Allen Wirfs-Brock's suggested phrasing</a> on es-discuss.\\\\n */\\\\n\\\\nfunction Nat(allegedNum) {\\\\n if (!Number.isSafeInteger(allegedNum)) {\\\\n throw new RangeError('not a safe integer');}\\\\n\\\\n\\\\n if (allegedNum < 0) {\\\\n throw new RangeError('negative');}\\\\n\\\\n\\\\n return allegedNum;}exports.default = Nat;\\\",\\n \\\"packages/marshal/marshal.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var producePromise = require('../produce-promise/src/producePromise.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nnat_esm = require('../../node_modules/@agoric/nat/dist/nat.esm.js'); /* global harden */ /* TODO: Use just 'remote' when we're willing to make a breaking change.*/\\\\nconst REMOTE_STYLE = 'presence';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n/**\\\\n * This is an interface specification.\\\\n * For now, it is just a string, but will eventually become something\\\\n * much richer (anything that pureCopy accepts).\\\\n * @typedef {string} InterfaceSpec\\\\n */\\\\n\\\\n/**\\\\n * @type {WeakMap<Object, InterfaceSpec>}\\\\n */\\\\nconst remotableToInterface = new WeakMap();\\\\n\\\\n/**\\\\n * Simple semantics, just tell what interface (or undefined) a remotable has.\\\\n *\\\\n * @param {*} maybeRemotable the value to check\\\\n * @returns {InterfaceSpec} the interface specification, or undefined if not a Remotable\\\\n */\\\\nfunction getInterfaceOf(maybeRemotable) {\\\\n return remotableToInterface.get(maybeRemotable);}\\\\n\\\\n\\\\n/**\\\\n * Do a deep copy of the object, handling Proxies and recursion.\\\\n * The resulting copy is guaranteed to be pure data, as well as hardened.\\\\n * Such a hardened, pure copy cannot be used as a communications path.\\\\n *\\\\n * @template T\\\\n * @param {T} val input value. NOTE: Must be hardened!\\\\n * @returns {T} pure, hardened copy\\\\n */\\\\nfunction pureCopy(val, already = new WeakMap()) {\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n const passStyle = passStyleOf(val);\\\\n switch (passStyle) {\\\\n case 'bigint':\\\\n case 'boolean':\\\\n case 'null':\\\\n case 'number':\\\\n case 'string':\\\\n case 'undefined':\\\\n return val;\\\\n\\\\n case 'copyArray':\\\\n case 'copyRecord':{\\\\n const obj = /** @type {Object} */val;\\\\n if (already.has(obj)) {\\\\n return already.get(obj);}\\\\n\\\\n\\\\n /* Create a new identity.*/\\\\n const copy = /** @type {T} */passStyle === 'copyArray' ? [] : {};\\\\n\\\\n /* Prevent recursion.*/\\\\n already.set(obj, copy);\\\\n\\\\n /* Make a deep copy on the new identity.*/\\\\n /* Object.entries(obj) takes a snapshot (even if a Proxy).*/\\\\n Object.entries(obj).forEach(([prop, value]) => {\\\\n copy[prop] = pureCopy(value, already);});\\\\n\\\\n return harden(copy);}\\\\n\\\\n\\\\n case 'copyError':{\\\\n const unk = /** @type {unknown} */val;\\\\n const err = /** @type {Error} */unk;\\\\n\\\\n if (already.has(err)) {\\\\n return already.get(err);}\\\\n\\\\n\\\\n const { name, message } = err;\\\\n\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n const EC = getErrorConstructor(`${name}`) || Error;\\\\n const copy = harden(new EC(`${message}`));\\\\n already.set(err, copy);\\\\n\\\\n const unk2 = /** @type {unknown} */harden(copy);\\\\n return (/** @type {T} */unk2);}\\\\n\\\\n\\\\n case REMOTE_STYLE:{\\\\n throw TypeError(\\\\n `Input value ${passStyle} cannot be copied as must be passed by reference`);}\\\\n\\\\n\\\\n\\\\n default:\\\\n throw TypeError(`Input value ${passStyle} is not recognized as data`);}}\\\\n\\\\n\\\\nharden(pureCopy);\\\\n\\\\n\\\\n/* Special property name that indicates an encoding that needs special*/\\\\n/* decoding.*/\\\\nconst QCLASS = '@qclass';\\\\n\\\\n\\\\n/* objects can only be passed in one of two/three forms:*/\\\\n/* 1: pass-by-remote: all properties (own and inherited) are methods,*/\\\\n/* the object itself is of type object, not function*/\\\\n/* 2: pass-by-copy: all string-named own properties are data, not methods*/\\\\n/* the object must inherit from Object.prototype or null*/\\\\n/* 3: the empty object is pass-by-remote, for identity comparison*/\\\\n\\\\n/* all objects must be frozen*/\\\\n\\\\n/* anything else will throw an error if you try to serialize it*/\\\\n\\\\n/* with these restrictions, our remote call/copy protocols expose all useful*/\\\\n/* behavior of these objects: pass-by-remote objects have no other data (so*/\\\\n/* there's nothing else to copy), and pass-by-copy objects have no other*/\\\\n/* behavior (so there's nothing else to invoke)*/\\\\n\\\\nconst errorConstructors = new Map([\\\\n['Error', Error],\\\\n['EvalError', EvalError],\\\\n['RangeError', RangeError],\\\\n['ReferenceError', ReferenceError],\\\\n['SyntaxError', SyntaxError],\\\\n['TypeError', TypeError],\\\\n['URIError', URIError]]);\\\\n\\\\n\\\\nfunction getErrorConstructor(name) {\\\\n return errorConstructors.get(name);}\\\\n\\\\n\\\\nfunction isPassByCopyError(val) {\\\\n /* TODO: Need a better test than instanceof*/\\\\n if (!(val instanceof Error)) {\\\\n return false;}\\\\n\\\\n const proto = Object.getPrototypeOf(val);\\\\n const { name } = val;\\\\n const EC = getErrorConstructor(name);\\\\n if (!EC || EC.prototype !== proto) {\\\\n throw TypeError(`Must inherit from an error class .prototype ${val}`);}\\\\n\\\\n\\\\n const {\\\\n message: { value: messageStr } = { value: '' },\\\\n /* Allow but ignore only extraneous own `stack` property.*/\\\\n /* TODO: I began the variable below with \\\\\\\"_\\\\\\\". Why do I still need*/\\\\n /* to suppress the lint complaint?*/\\\\n /* eslint-disable-next-line no-unused-vars*/\\\\n stack: _optStackDesc,\\\\n ...restDescs } =\\\\n Object.getOwnPropertyDescriptors(val);\\\\n const restNames = Object.keys(restDescs);\\\\n if (restNames.length >= 1) {\\\\n throw new TypeError(`Unexpected own properties in error: ${restNames}`);}\\\\n\\\\n if (typeof messageStr !== 'string') {\\\\n throw new TypeError(`malformed error object: ${val}`);}\\\\n\\\\n return true;}\\\\n\\\\n\\\\nfunction isPassByCopyArray(val) {\\\\n if (!Array.isArray(val)) {\\\\n return false;}\\\\n\\\\n if (Object.getPrototypeOf(val) !== Array.prototype) {\\\\n throw new TypeError(`malformed array: ${val}`);}\\\\n\\\\n const len = val.length;\\\\n const descs = Object.getOwnPropertyDescriptors(val);\\\\n for (let i = 0; i < len; i += 1) {\\\\n const desc = descs[i];\\\\n if (!desc) {\\\\n throw new TypeError(`arrays must not contain holes`);}\\\\n\\\\n if (!('value' in desc)) {\\\\n throw new TypeError(`arrays must not contain accessors`);}\\\\n\\\\n if (typeof desc.value === 'function') {\\\\n throw new TypeError(`arrays must not contain methods`);}}\\\\n\\\\n\\\\n if (Object.keys(descs).length !== len + 1) {\\\\n throw new TypeError(`array must not have non-indexes ${val}`);}\\\\n\\\\n return true;}\\\\n\\\\n\\\\nfunction isPassByCopyRecord(val) {\\\\n if (Object.getPrototypeOf(val) !== Object.prototype) {\\\\n return false;}\\\\n\\\\n const descList = Object.values(Object.getOwnPropertyDescriptors(val));\\\\n if (descList.length === 0) {\\\\n /* empty non-array objects are pass-by-remote, not pass-by-copy*/\\\\n return false;}\\\\n\\\\n for (const desc of descList) {\\\\n if (!('value' in desc)) {\\\\n /* Should we error if we see an accessor here?*/\\\\n return false;}\\\\n\\\\n if (typeof desc.value === 'function') {\\\\n return false;}}\\\\n\\\\n\\\\n return true;}\\\\n\\\\n\\\\n/**\\\\n * Ensure that val could become a legitimate remotable. This is used internally both\\\\n * in the construction of a new remotable and mustPassByRemote.\\\\n *\\\\n * @param {*} val The remotable candidate to check\\\\n */\\\\nfunction assertCanBeRemotable(val) {\\\\n /* throws exception if cannot*/\\\\n if (typeof val !== 'object') {\\\\n throw new Error(`cannot serialize non-objects like ${val}`);}\\\\n\\\\n if (Array.isArray(val)) {\\\\n throw new Error(`Arrays cannot be pass-by-remote`);}\\\\n\\\\n if (val === null) {\\\\n throw new Error(`null cannot be pass-by-remote`);}\\\\n\\\\n\\\\n const names = Object.getOwnPropertyNames(val);\\\\n names.forEach(name => {\\\\n if (typeof val[name] !== 'function') {\\\\n throw new Error(\\\\n `cannot serialize objects with non-methods like the .${name} in ${val}`);\\\\n\\\\n /* return false;*/}});\\\\n\\\\n\\\\n\\\\n /* ok!*/}\\\\n\\\\n\\\\nfunction mustPassByRemote(val) {\\\\n if (!Object.isFrozen(val)) {\\\\n throw new Error(`cannot serialize non-frozen objects like ${val}`);}\\\\n\\\\n\\\\n if (getInterfaceOf(val) === undefined) {\\\\n /* Not a registered Remotable, so check its contents.*/\\\\n assertCanBeRemotable(val);}\\\\n\\\\n\\\\n /* It's not a registered Remotable, so enforce the prototype check.*/\\\\n const p = Object.getPrototypeOf(val);\\\\n if (p !== null && p !== Object.prototype) {\\\\n mustPassByRemote(p);}}\\\\n\\\\n\\\\n\\\\n/* This is the equality comparison used by JavaScript's Map and Set*/\\\\n/* abstractions, where NaN is the same as NaN and -0 is the same as*/\\\\n/* 0. Marshal serializes -0 as zero, so the semantics of our distributed*/\\\\n/* object system does not distinguish 0 from -0.*/\\\\n/**/\\\\n/* `sameValueZero` is the EcmaScript spec name for this equality comparison,*/\\\\n/* but TODO we need a better name for the API.*/\\\\nfunction sameValueZero(x, y) {\\\\n return x === y || Object.is(x, y);}\\\\n\\\\n\\\\n/* How would val be passed? For primitive values, the answer is*/\\\\n/* * 'null' for null*/\\\\n/* * throwing an error for a symbol, whether registered or not.*/\\\\n/* * that value's typeof string for all other primitive values*/\\\\n/* For frozen objects, the possible answers*/\\\\n/* * 'copyRecord' for non-empty records with only data properties*/\\\\n/* * 'copyArray' for arrays with only data properties*/\\\\n/* * 'copyError' for instances of Error with only data properties*/\\\\n/* * REMOTE_STYLE for non-array objects with only method properties*/\\\\n/* * 'promise' for genuine promises only*/\\\\n/* * throwing an error on anything else, including thenables.*/\\\\n/* We export passStyleOf so other algorithms can use this module's*/\\\\n/* classification.*/\\\\nfunction passStyleOf(val) {\\\\n const typestr = typeof val;\\\\n switch (typestr) {\\\\n case 'object':{\\\\n if (getInterfaceOf(val)) {\\\\n return REMOTE_STYLE;}\\\\n\\\\n if (val === null) {\\\\n return 'null';}\\\\n\\\\n if (QCLASS in val) {\\\\n /* TODO Hilbert hotel*/\\\\n throw new Error(`property \\\\\\\"${QCLASS}\\\\\\\" reserved`);}\\\\n\\\\n if (!Object.isFrozen(val)) {\\\\n throw new Error(\\\\n `Cannot pass non-frozen objects like ${val}. Use harden()`);}\\\\n\\\\n\\\\n if (producePromise.isPromise(val)) {\\\\n return 'promise';}\\\\n\\\\n if (typeof val.then === 'function') {\\\\n throw new Error(`Cannot pass non-promise thenables`);}\\\\n\\\\n if (isPassByCopyError(val)) {\\\\n return 'copyError';}\\\\n\\\\n if (isPassByCopyArray(val)) {\\\\n return 'copyArray';}\\\\n\\\\n if (isPassByCopyRecord(val)) {\\\\n return 'copyRecord';}\\\\n\\\\n mustPassByRemote(val);\\\\n return REMOTE_STYLE;}\\\\n\\\\n case 'function':{\\\\n throw new Error(`Bare functions like ${val} are disabled for now`);}\\\\n\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'bigint':{\\\\n return typestr;}\\\\n\\\\n case 'symbol':{\\\\n throw new TypeError('Cannot pass symbols');}\\\\n\\\\n default:{\\\\n throw new TypeError(`Unrecognized typeof ${typestr}`);}}}\\\\n\\\\n\\\\n\\\\n\\\\n/* The ibid logic relies on*/\\\\n/* * JSON.stringify on an array visiting array indexes from 0 to*/\\\\n/* arr.length -1 in order, and not visiting anything else.*/\\\\n/* * JSON.parse of a record (a plain object) creating an object on*/\\\\n/* which a getOwnPropertyNames will enumerate properties in the*/\\\\n/* same order in which they appeared in the parsed JSON string.*/\\\\n\\\\nfunction makeReplacerIbidTable() {\\\\n const ibidMap = new Map();\\\\n let ibidCount = 0;\\\\n\\\\n return harden({\\\\n has(obj) {\\\\n return ibidMap.has(obj);},\\\\n\\\\n get(obj) {\\\\n return ibidMap.get(obj);},\\\\n\\\\n add(obj) {\\\\n ibidMap.set(obj, ibidCount);\\\\n ibidCount += 1;} });}\\\\n\\\\n\\\\n\\\\n\\\\nfunction makeReviverIbidTable(cyclePolicy) {\\\\n const ibids = [];\\\\n const unfinishedIbids = new WeakSet();\\\\n\\\\n return harden({\\\\n get(allegedIndex) {\\\\n const index = nat_esm.default(allegedIndex);\\\\n if (index >= ibids.length) {\\\\n throw new RangeError(`ibid out of range: ${index}`);}\\\\n\\\\n const result = ibids[index];\\\\n if (unfinishedIbids.has(result)) {\\\\n switch (cyclePolicy) {\\\\n case 'allowCycles':{\\\\n break;}\\\\n\\\\n case 'warnOfCycles':{\\\\n console.log(`Warning: ibid cycle at ${index}`);\\\\n break;}\\\\n\\\\n case 'forbidCycles':{\\\\n throw new TypeError(`Ibid cycle at ${index}`);}\\\\n\\\\n default:{\\\\n throw new TypeError(`Unrecognized cycle policy: ${cyclePolicy}`);}}}\\\\n\\\\n\\\\n\\\\n return result;},\\\\n\\\\n register(obj) {\\\\n ibids.push(obj);\\\\n return obj;},\\\\n\\\\n start(obj) {\\\\n ibids.push(obj);\\\\n unfinishedIbids.add(obj);\\\\n return obj;},\\\\n\\\\n finish(obj) {\\\\n unfinishedIbids.delete(obj);\\\\n return obj;} });}\\\\n\\\\n\\\\n\\\\n\\\\nconst identityFn = x => x;\\\\n\\\\nfunction makeMarshal(\\\\nconvertValToSlot = identityFn,\\\\nconvertSlotToVal = identityFn)\\\\n{\\\\n function serializeSlot(val, slots, slotMap) {\\\\n let slotIndex;\\\\n if (slotMap.has(val)) {\\\\n slotIndex = slotMap.get(val);} else\\\\n {\\\\n const slot = convertValToSlot(val);\\\\n\\\\n slotIndex = slots.length;\\\\n slots.push(slot);\\\\n slotMap.set(val, slotIndex);}\\\\n\\\\n\\\\n return harden({\\\\n [QCLASS]: 'slot',\\\\n index: slotIndex });}\\\\n\\\\n\\\\n\\\\n function makeReplacer(slots, slotMap) {\\\\n const ibidTable = makeReplacerIbidTable();\\\\n\\\\n return function replacer(_, val) {\\\\n /* First we handle all primitives. Some can be represented directly as*/\\\\n /* JSON, and some must be encoded as [QCLASS] composites.*/\\\\n const passStyle = passStyleOf(val);\\\\n switch (passStyle) {\\\\n case 'null':{\\\\n return null;}\\\\n\\\\n case 'undefined':{\\\\n return harden({ [QCLASS]: 'undefined' });}\\\\n\\\\n case 'string':\\\\n case 'boolean':{\\\\n return val;}\\\\n\\\\n case 'number':{\\\\n if (Number.isNaN(val)) {\\\\n return harden({ [QCLASS]: 'NaN' });}\\\\n\\\\n if (Object.is(val, -0)) {\\\\n return 0;}\\\\n\\\\n if (val === Infinity) {\\\\n return harden({ [QCLASS]: 'Infinity' });}\\\\n\\\\n if (val === -Infinity) {\\\\n return harden({ [QCLASS]: '-Infinity' });}\\\\n\\\\n return val;}\\\\n\\\\n case 'bigint':{\\\\n return harden({\\\\n [QCLASS]: 'bigint',\\\\n digits: String(val) });}\\\\n\\\\n\\\\n default:{\\\\n /* if we've seen this object before, serialize a backref*/\\\\n if (ibidTable.has(val)) {\\\\n /* Backreference to prior occurrence*/\\\\n return harden({\\\\n [QCLASS]: 'ibid',\\\\n index: ibidTable.get(val) });}\\\\n\\\\n\\\\n ibidTable.add(val);\\\\n\\\\n switch (passStyle) {\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n /* console.log(`canPassByCopy: ${val}`);*/\\\\n /* Purposely in-band for readability, but creates need for*/\\\\n /* Hilbert hotel.*/\\\\n return val;}\\\\n\\\\n case 'copyError':{\\\\n /* We deliberately do not share the stack, but it would*/\\\\n /* be useful to log the stack locally so someone who has*/\\\\n /* privileged access to the throwing Vat can correlate*/\\\\n /* the problem with the remote Vat that gets this*/\\\\n /* summary. If we do that, we could allocate some random*/\\\\n /* identifier and include it in the message, to help*/\\\\n /* with the correlation.*/\\\\n return harden({\\\\n [QCLASS]: 'error',\\\\n name: `${val.name}`,\\\\n message: `${val.message}` });}\\\\n\\\\n\\\\n case REMOTE_STYLE:\\\\n case 'promise':{\\\\n /* console.log(`serializeSlot: ${val}`);*/\\\\n return serializeSlot(val, slots, slotMap);}\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${passStyle}`);}}}}};}\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n /* val might be a primitive, a pass by (shallow) copy object, a*/\\\\n /* remote reference, or other. We treat all other as a local object*/\\\\n /* to be exported as a local webkey.*/\\\\n function serialize(val) {\\\\n const slots = [];\\\\n const slotMap = new Map(); /* maps val (promise or remotable) to*/\\\\n /* index of slots[]*/\\\\n return harden({\\\\n body: JSON.stringify(val, makeReplacer(slots, slotMap)),\\\\n slots });}\\\\n\\\\n\\\\n\\\\n function makeFullRevive(slots, cyclePolicy) {\\\\n /* ibid table is shared across recursive calls to fullRevive.*/\\\\n const ibidTable = makeReviverIbidTable(cyclePolicy);\\\\n\\\\n /* We stay close to the algorith at*/\\\\n /* https://tc39.github.io/ecma262/#sec-json.parse , where*/\\\\n /* fullRevive(JSON.parse(str)) is like JSON.parse(str, revive))*/\\\\n /* for a similar reviver. But with the following differences:*/\\\\n /**/\\\\n /* Rather than pass a reviver to JSON.parse, we first call a plain*/\\\\n /* (one argument) JSON.parse to get rawTree, and then post-process*/\\\\n /* the rawTree with fullRevive. The kind of revive function*/\\\\n /* handled by JSON.parse only does one step in post-order, with*/\\\\n /* JSON.parse doing the recursion. By contrast, fullParse does its*/\\\\n /* own recursion, enabling it to interpret ibids in the same*/\\\\n /* pre-order in which the replacer visited them, and enabling it*/\\\\n /* to break cycles.*/\\\\n /**/\\\\n /* In order to break cycles, the potentially cyclic objects are*/\\\\n /* not frozen during the recursion. Rather, the whole graph is*/\\\\n /* hardened before being returned. Error objects are not*/\\\\n /* potentially recursive, and so may be harmlessly hardened when*/\\\\n /* they are produced.*/\\\\n /**/\\\\n /* fullRevive can produce properties whose value is undefined,*/\\\\n /* which a JSON.parse on a reviver cannot do. If a reviver returns*/\\\\n /* undefined to JSON.parse, JSON.parse will delete the property*/\\\\n /* instead.*/\\\\n /**/\\\\n /* fullRevive creates and returns a new graph, rather than*/\\\\n /* modifying the original tree in place.*/\\\\n /**/\\\\n /* fullRevive may rely on rawTree being the result of a plain call*/\\\\n /* to JSON.parse. However, it *cannot* rely on it having been*/\\\\n /* produced by JSON.stringify on the replacer above, i.e., it*/\\\\n /* cannot rely on it being a valid marshalled*/\\\\n /* representation. Rather, fullRevive must validate that.*/\\\\n return function fullRevive(rawTree) {\\\\n if (Object(rawTree) !== rawTree) {\\\\n /* primitives pass through*/\\\\n return rawTree;}\\\\n\\\\n if (QCLASS in rawTree) {\\\\n const qclass = rawTree[QCLASS];\\\\n if (typeof qclass !== 'string') {\\\\n throw new TypeError(`invalid qclass typeof ${typeof qclass}`);}\\\\n\\\\n switch (qclass) {\\\\n /* Encoding of primitives not handled by JSON*/\\\\n case 'undefined':{\\\\n return undefined;}\\\\n\\\\n case 'NaN':{\\\\n return NaN;}\\\\n\\\\n case 'Infinity':{\\\\n return Infinity;}\\\\n\\\\n case '-Infinity':{\\\\n return -Infinity;}\\\\n\\\\n case 'bigint':{\\\\n if (typeof rawTree.digits !== 'string') {\\\\n throw new TypeError(\\\\n `invalid digits typeof ${typeof rawTree.digits}`);}\\\\n\\\\n\\\\n /* eslint-disable-next-line no-undef */\\\\n return BigInt(rawTree.digits);}\\\\n\\\\n\\\\n case 'ibid':{\\\\n return ibidTable.get(rawTree.index);}\\\\n\\\\n\\\\n case 'error':{\\\\n if (typeof rawTree.name !== 'string') {\\\\n throw new TypeError(\\\\n `invalid error name typeof ${typeof rawTree.name}`);}\\\\n\\\\n\\\\n if (typeof rawTree.message !== 'string') {\\\\n throw new TypeError(\\\\n `invalid error message typeof ${typeof rawTree.message}`);}\\\\n\\\\n\\\\n const EC = getErrorConstructor(`${rawTree.name}`) || Error;\\\\n return ibidTable.register(harden(new EC(`${rawTree.message}`)));}\\\\n\\\\n\\\\n case 'slot':{\\\\n const slot = slots[nat_esm.default(rawTree.index)];\\\\n return ibidTable.register(convertSlotToVal(slot));}\\\\n\\\\n\\\\n default:{\\\\n /* TODO reverse Hilbert hotel*/\\\\n throw new TypeError(`unrecognized ${QCLASS} ${qclass}`);}}} else\\\\n\\\\n\\\\n if (Array.isArray(rawTree)) {\\\\n const result = ibidTable.start([]);\\\\n const len = rawTree.length;\\\\n for (let i = 0; i < len; i += 1) {\\\\n result[i] = fullRevive(rawTree[i]);}\\\\n\\\\n return ibidTable.finish(result);} else\\\\n {\\\\n const result = ibidTable.start({});\\\\n const names = Object.getOwnPropertyNames(rawTree);\\\\n for (const name of names) {\\\\n result[name] = fullRevive(rawTree[name]);}\\\\n\\\\n return ibidTable.finish(result);}};}\\\\n\\\\n\\\\n\\\\n\\\\n function unserialize(data, cyclePolicy = 'forbidCycles') {\\\\n if (data.body !== `${data.body}`) {\\\\n throw new Error(\\\\n `unserialize() given non-capdata (.body is ${data.body}, not string)`);}\\\\n\\\\n\\\\n if (!Array.isArray(data.slots)) {\\\\n throw new Error(`unserialize() given non-capdata (.slots are not Array)`);}\\\\n\\\\n const rawTree = harden(JSON.parse(data.body));\\\\n const fullRevive = makeFullRevive(data.slots, cyclePolicy);\\\\n return harden(fullRevive(rawTree));}\\\\n\\\\n\\\\n return harden({\\\\n serialize,\\\\n unserialize });}\\\\n\\\\n\\\\n\\\\n/**\\\\n * Create and register a Remotable. After this, getInterfaceOf(remotable)\\\\n * returns iface.\\\\n *\\\\n * // https://github.com/Agoric/agoric-sdk/issues/804\\\\n *\\\\n * @param {InterfaceSpec} [iface='Remotable'] The interface specification for the remotable\\\\n * @param {object} [props={}] Own-properties are copied to the remotable\\\\n * @param {object} [remotable={}] The object used as the remotable\\\\n * @returns {object} remotable, modified for debuggability\\\\n */\\\\nfunction Remotable(iface = 'Remotable', props = {}, remotable = {}) {\\\\n iface = pureCopy(harden(iface));\\\\n const ifaceType = typeof iface;\\\\n\\\\n /* Find the alleged name.*/\\\\n if (ifaceType !== 'string') {\\\\n throw Error(`Interface must be a string, not ${ifaceType}; unimplemented`);}\\\\n\\\\n\\\\n /* TODO: When iface is richer than just string, we need to get the allegedName*/\\\\n /* in a different way.*/\\\\n const allegedName = iface;\\\\n\\\\n /* Fail fast: check that the unmodified object is able to become a Remotable.*/\\\\n assertCanBeRemotable(remotable);\\\\n\\\\n /* Ensure that the remotable isn't already registered.*/\\\\n if (remotableToInterface.has(remotable)) {\\\\n throw Error(`Remotable ${remotable} is already mapped to an interface`);}\\\\n\\\\n\\\\n /* A prototype for debuggability.*/\\\\n const oldRemotableProto = harden(Object.getPrototypeOf(remotable));\\\\n\\\\n /* Fail fast: create a fresh empty object with the old*/\\\\n /* prototype in order to check it against our rules.*/\\\\n mustPassByRemote(harden(Object.create(oldRemotableProto)));\\\\n\\\\n /* Assign the arrow function to a variable to set its .name.*/\\\\n const toString = () => `[${allegedName}]`;\\\\n const remotableProto = harden(\\\\n Object.create(oldRemotableProto, {\\\\n toString: {\\\\n value: toString,\\\\n enumerable: false },\\\\n\\\\n [Symbol.toStringTag]: {\\\\n value: allegedName,\\\\n enumerable: false } }));\\\\n\\\\n\\\\n\\\\n\\\\n /* Take a static copy of the properties.*/\\\\n const propEntries = Object.entries(props);\\\\n const mutateHardenAndCheck = target => {\\\\n /* Add the snapshotted properties.*/\\\\n /** @type {PropertyDescriptorMap} */\\\\n const newProps = {};\\\\n propEntries.forEach(([prop, value]) => newProps[prop] = { value });\\\\n Object.defineProperties(target, newProps);\\\\n\\\\n /* Set the prototype for debuggability.*/\\\\n Object.setPrototypeOf(target, remotableProto);\\\\n harden(remotableProto);\\\\n\\\\n harden(target);\\\\n assertCanBeRemotable(target);\\\\n return target;};\\\\n\\\\n\\\\n /* Fail fast: check a fresh remotable to see if our rules fit.*/\\\\n const throwawayRemotable = Object.create(oldRemotableProto);\\\\n mutateHardenAndCheck(throwawayRemotable);\\\\n\\\\n /* Actually finish the new remotable.*/\\\\n mutateHardenAndCheck(remotable);\\\\n\\\\n /* COMMITTED!*/\\\\n /* We're committed, so keep the interface for future reference.*/\\\\n remotableToInterface.set(remotable, iface);\\\\n return remotable;}\\\\n\\\\n\\\\nharden(Remotable);exports.QCLASS = QCLASS;exports.Remotable = Remotable;exports.getErrorConstructor = getErrorConstructor;exports.getInterfaceOf = getInterfaceOf;exports.makeMarshal = makeMarshal;exports.mustPassByPresence = mustPassByRemote;exports.mustPassByRemote = mustPassByRemote;exports.passStyleOf = passStyleOf;exports.pureCopy = pureCopy;exports.sameValueZero = sameValueZero;\\\",\\n \\\"packages/same-structure/src/sameStructure.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../assert/src/assert.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nmarshal = require('../../marshal/marshal.js'); /* global harden */ /* Shim of Object.fromEntries from*/ /* https://github.com/tc39/proposal-object-from-entries/blob/master/polyfill.js*/\\\\nfunction ObjectFromEntries(iter) {\\\\n const obj = {};\\\\n\\\\n for (const pair of iter) {\\\\n if (Object(pair) !== pair) {\\\\n throw new TypeError('iterable for fromEntries should yield objects');}\\\\n\\\\n\\\\n /* Consistency with Map: contract is that entry has \\\\\\\"0\\\\\\\" and \\\\\\\"1\\\\\\\" keys, not*/\\\\n /* that it is an array or iterable.*/\\\\n\\\\n const { '0': key, '1': val } = pair;\\\\n\\\\n Object.defineProperty(obj, key, {\\\\n configurable: true,\\\\n enumerable: true,\\\\n writable: true,\\\\n value: val });}\\\\n\\\\n\\\\n\\\\n return obj;}\\\\n\\\\n\\\\n/* A *passable* is something that may be marshalled. It consists of a*/\\\\n/* graph of pass-by-copy data terminating in leaves of passable*/\\\\n/* non-pass-by-copy data. These leaves may be promises, or*/\\\\n/* pass-by-presence objects. A *comparable* is a passable whose leaves*/\\\\n/* contain no promises. Two comparables can be synchronously compared*/\\\\n/* for structural equivalence.*/\\\\n/**/\\\\n/* TODO: Currently, all algorithms here treat the pass-by-copy*/\\\\n/* superstructure as a tree. This means that dags are unwound at*/\\\\n/* potentially exponential cost, and cycles cause failure to*/\\\\n/* terminate. We must fix both problems, making all these algorithms*/\\\\n/* graph-aware.*/\\\\n\\\\n/* We say that a function *reveals* an X when it returns either an X*/\\\\n/* or a promise for an X.*/\\\\n\\\\n/* Given a passable, reveal a corresponding comparable, where each*/\\\\n/* leaf promise of the passable has been replaced with its*/\\\\n/* corresponding comparable.*/\\\\nfunction allComparable(passable) {\\\\n const passStyle = marshal.passStyleOf(passable);\\\\n switch (passStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':\\\\n case 'copyError':{\\\\n return passable;}\\\\n\\\\n case 'promise':{\\\\n return passable.then(nonp => allComparable(nonp));}\\\\n\\\\n case 'copyArray':{\\\\n const valPs = passable.map(p => allComparable(p));\\\\n return Promise.all(valPs).then(vals => harden(vals));}\\\\n\\\\n case 'copyRecord':{\\\\n const names = Object.getOwnPropertyNames(passable);\\\\n const valPs = names.map(name => allComparable(passable[name]));\\\\n return Promise.all(valPs).then((vals) =>\\\\n harden(ObjectFromEntries(vals.map((val, i) => [names[i], val]))));}\\\\n\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${passStyle}`);}}}\\\\n\\\\n\\\\n\\\\nharden(allComparable);\\\\n\\\\n/* Are left and right structurally equivalent comparables? This*/\\\\n/* compares pass-by-copy data deeply until non-pass-by-copy values are*/\\\\n/* reached. The non-pass-by-copy values at the leaves of the*/\\\\n/* comparison may only be pass-by-presence objects. If they are*/\\\\n/* anything else, including promises, throw an error.*/\\\\n/**/\\\\n/* Pass-by-presence objects compare identities.*/\\\\n\\\\nfunction sameStructure(left, right) {\\\\n const leftStyle = marshal.passStyleOf(left);\\\\n const rightStyle = marshal.passStyleOf(right);\\\\n assert.assert(\\\\n leftStyle !== 'promise',\\\\n assert.details`Cannot structurally compare promises: ${left}`);\\\\n\\\\n assert.assert(\\\\n rightStyle !== 'promise',\\\\n assert.details`Cannot structurally compare promises: ${right}`);\\\\n\\\\n\\\\n if (leftStyle !== rightStyle) {\\\\n return false;}\\\\n\\\\n switch (leftStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':{\\\\n return marshal.sameValueZero(left, right);}\\\\n\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n const leftNames = Object.getOwnPropertyNames(left);\\\\n const rightNames = Object.getOwnPropertyNames(right);\\\\n if (leftNames.length !== rightNames.length) {\\\\n return false;}\\\\n\\\\n for (const name of leftNames) {\\\\n /* TODO: Better hasOwnProperty check*/\\\\n if (!Object.getOwnPropertyDescriptor(right, name)) {\\\\n return false;}\\\\n\\\\n /* TODO: Make cycle tolerant*/\\\\n if (!sameStructure(left[name], right[name])) {\\\\n return false;}}\\\\n\\\\n\\\\n return true;}\\\\n\\\\n case 'copyError':{\\\\n return left.name === right.name && left.message === right.message;}\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${leftStyle}`);}}}\\\\n\\\\n\\\\n\\\\nharden(sameStructure);\\\\n\\\\nfunction pathStr(path) {\\\\n if (path === null) {\\\\n return 'top';}\\\\n\\\\n const [base, index] = path;\\\\n let i = index;\\\\n const baseStr = pathStr(base);\\\\n if (typeof i === 'string' && /^[a-zA-Z]\\\\\\\\w*$/.test(i)) {\\\\n return `${baseStr}.${i}`;}\\\\n\\\\n if (typeof i === 'string' && `${+i}` === i) {\\\\n i = +i;}\\\\n\\\\n return `${baseStr}[${JSON.stringify(i)}]`;}\\\\n\\\\n\\\\n/* TODO: Reduce redundancy between sameStructure and*/\\\\n/* mustBeSameStructureInternal*/\\\\nfunction mustBeSameStructureInternal(left, right, message, path) {\\\\n function complain(problem) {\\\\n assert.assert.fail(\\\\n assert.details`${assert.q(message)}: ${assert.q(problem)} at ${assert.q(\\\\n pathStr(path))\\\\n }: (${left}) vs (${right})`);}\\\\n\\\\n\\\\n\\\\n const leftStyle = marshal.passStyleOf(left);\\\\n const rightStyle = marshal.passStyleOf(right);\\\\n if (leftStyle === 'promise') {\\\\n complain('Promise on left');}\\\\n\\\\n if (rightStyle === 'promise') {\\\\n complain('Promise on right');}\\\\n\\\\n\\\\n if (leftStyle !== rightStyle) {\\\\n complain('different passing style');}\\\\n\\\\n switch (leftStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':{\\\\n if (!marshal.sameValueZero(left, right)) {\\\\n complain('different');}\\\\n\\\\n break;}\\\\n\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n const leftNames = Object.getOwnPropertyNames(left);\\\\n const rightNames = Object.getOwnPropertyNames(right);\\\\n if (leftNames.length !== rightNames.length) {\\\\n complain(`${leftNames.length} vs ${rightNames.length} own properties`);}\\\\n\\\\n for (const name of leftNames) {\\\\n /* TODO: Better hasOwnProperty check*/\\\\n if (!Object.getOwnPropertyDescriptor(right, name)) {\\\\n complain(`${name} not found on right`);}\\\\n\\\\n /* TODO: Make cycle tolerant*/\\\\n mustBeSameStructureInternal(left[name], right[name], message, [\\\\n path,\\\\n name]);}\\\\n\\\\n\\\\n break;}\\\\n\\\\n case 'copyError':{\\\\n if (left.name !== right.name) {\\\\n complain(`different error name: ${left.name} vs ${right.name}`);}\\\\n\\\\n if (left.message !== right.message) {\\\\n complain(\\\\n `different error message: ${left.message} vs ${right.message}`);}\\\\n\\\\n\\\\n break;}\\\\n\\\\n default:{\\\\n complain(`unrecognized passStyle ${leftStyle}`);\\\\n break;}}}\\\\n\\\\n\\\\n\\\\nfunction mustBeSameStructure(left, right, message) {\\\\n mustBeSameStructureInternal(left, right, `${message}`, null);}\\\\n\\\\nharden(mustBeSameStructure);\\\\n\\\\n/* If `val` would be a valid input to `sameStructure`, return*/\\\\n/* normally. Otherwise error.*/\\\\nfunction mustBeComparable(val) {\\\\n mustBeSameStructure(val, val, 'not comparable');}exports.allComparable = allComparable;exports.mustBeComparable = mustBeComparable;exports.mustBeSameStructure = mustBeSameStructure;exports.sameStructure = sameStructure;\\\",\\n \\\"packages/import-manager/src/importManager.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* Copyright (C) 2019 Agoric, under Apache License 2.0*/ /* global harden */ /* ImportManager allows a package to make some code available that can be run*/ /* locally by a calling vat without requiring a remote round trip to the hosting*/ /* vat. Remote code can indicate what function to run using a key.*/ /**/ /* Long term, we may want to import from a well-known repository, and manage*/ /* version upgrades, but for now, we just import the code from the file system.*/ /**/ /* A package that wanted to export some code for clients to run in their own vat*/ /* would import or define some functions, then call*/ /**/ /* const mgr = importManager();*/ /* return mgr.addExports(*/ /* {*/ /* 'usefulFn', export1,*/ /* 'helpfulFn', export2,*/ /* });*/ /**/ /* then it could pass strings like 'usefulFn' to clients, who could import the*/ /* manager above, then call*/ /**/ /* const genericFn = importer.lookupImport(name);*/ /**/\\\\nfunction importManager() {\\\\n const entries = {};\\\\n\\\\n return harden({\\\\n addExports(obj) {\\\\n for (const name of Object.getOwnPropertyNames(obj)) {\\\\n entries[name] = obj[name];}\\\\n\\\\n return harden(entries);} });}exports.importManager = importManager;\\\",\\n \\\"packages/ERTP/src/mathHelpers/natMathHelpers.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nnat_esm = require('../../../../node_modules/@agoric/nat/dist/nat.esm.js'); /* global harden */ /* Fungible digital assets use the natMathHelpers to manage balances -*/ /* the operations are merely arithmetic on natural, non-negative*/ /* numbers.*/ /* Natural numbers are used for fungible erights such as money because*/ /* rounding issues make floats problematic. All operations should be*/ /* done with the smallest whole unit such that the NatMathHelpers never*/ /* deals with fractional parts.*/\\\\n\\\\nconst identity = 0;\\\\n\\\\nconst natMathHelpers = harden({\\\\n doCoerce: nat_esm.default,\\\\n doGetEmpty: _ => identity,\\\\n doIsEmpty: nat => nat === identity,\\\\n doIsGTE: (left, right) => left >= right,\\\\n doIsEqual: (left, right) => left === right,\\\\n doAdd: (left, right) => nat_esm.default(left + right),\\\\n doSubtract: (left, right) => nat_esm.default(left - right) });\\\\n\\\\n\\\\nvar natMathHelpers$1 = harden(natMathHelpers);exports.default = natMathHelpers$1;\\\",\\n \\\"packages/ERTP/src/mathHelpers/strSetMathHelpers.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../../assert/src/assert.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nmarshal = require('../../../marshal/marshal.js'); /* global harden */ /* Operations for arrays with unique string elements. More information*/ /* about these assets might be provided by some other mechanism, such as*/ /* an off-chain API or physical records. strSetMathHelpers are highly*/ /* efficient, but if the users rely on an external resource to learn*/ /* more about the digital assets (for example, looking up a string ID*/ /* in a database), the administrator of the external resource could*/ /* potentially change the external definition at any time.*/\\\\n\\\\nconst identity = harden([]);\\\\n\\\\nconst checkForDupes = list => {\\\\n const set = new Set(list);\\\\n assert.assert(set.size === list.length, assert.details`value has duplicates: ${list}`);};\\\\n\\\\n\\\\nconst strSetMathHelpers = harden({\\\\n doCoerce: list => {\\\\n assert.assert(marshal.passStyleOf(list) === 'copyArray', 'value must be an array');\\\\n list.forEach(elem => assert.assert.typeof(elem, 'string'));\\\\n checkForDupes(list);\\\\n return list;},\\\\n\\\\n doGetEmpty: _ => identity,\\\\n doIsEmpty: list => marshal.passStyleOf(list) === 'copyArray' && list.length === 0,\\\\n doIsGTE: (left, right) => {\\\\n const leftSet = new Set(left);\\\\n const leftHas = elem => leftSet.has(elem);\\\\n return right.every(leftHas);},\\\\n\\\\n doIsEqual: (left, right) => {\\\\n const leftSet = new Set(left);\\\\n const leftHas = elem => leftSet.has(elem);\\\\n return left.length === right.length && right.every(leftHas);},\\\\n\\\\n doAdd: (left, right) => {\\\\n const union = new Set(left);\\\\n const addToUnion = elem => {\\\\n assert.assert(\\\\n !union.has(elem),\\\\n assert.details`left and right have same element ${elem}`);\\\\n\\\\n union.add(elem);};\\\\n\\\\n right.forEach(addToUnion);\\\\n return harden(Array.from(union));},\\\\n\\\\n doSubtract: (left, right) => {\\\\n const leftSet = new Set(left);\\\\n const remove = elem => leftSet.delete(elem);\\\\n const allRemovedCorrectly = right.every(remove);\\\\n assert.assert(\\\\n allRemovedCorrectly,\\\\n assert.details`some of the elements in right (${right}) were not present in left (${left})`);\\\\n\\\\n return harden(Array.from(leftSet));} });\\\\n\\\\n\\\\n\\\\nharden(strSetMathHelpers);exports.default = strSetMathHelpers;\\\",\\n \\\"packages/ERTP/src/mathHelpers/setMathHelpers.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../../assert/src/assert.js');var marshal = require('../../../marshal/marshal.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nsameStructure = require('../../../same-structure/src/sameStructure.js'); /* global harden */ /* Operations for arrays with unique objects identifying and providing*/ /* information about digital assets. Used for Zoe invites.*/\\\\nconst identity = harden([]);\\\\n\\\\n/* Cut down the number of sameStructure comparisons to only the ones*/\\\\n/* that don't fail basic equality tests*/\\\\n/* TODO: better name?*/\\\\nconst hashBadly = record => {\\\\n const keys = Object.getOwnPropertyNames(record);\\\\n keys.sort();\\\\n const values = Object.values(record).filter(\\\\n value => typeof value === 'string');\\\\n\\\\n values.sort();\\\\n return [...keys, ...values].join();};\\\\n\\\\n\\\\nconst makeBuckets = list => {\\\\n const buckets = new Map();\\\\n list.forEach(elem => {\\\\n const badHash = hashBadly(elem);\\\\n if (!buckets.has(badHash)) {\\\\n buckets.set(badHash, []);}\\\\n\\\\n const soFar = buckets.get(badHash);\\\\n soFar.push(elem);});\\\\n\\\\n return buckets;};\\\\n\\\\n\\\\n/* Based on bucket sort*/\\\\nconst checkForDupes = buckets => {\\\\n for (const maybeMatches of buckets.values()) {\\\\n for (let i = 0; i < maybeMatches.length; i += 1) {\\\\n for (let j = i + 1; j < maybeMatches.length; j += 1) {\\\\n assert.assert(\\\\n !sameStructure.sameStructure(maybeMatches[i], maybeMatches[j]),\\\\n assert.details`value has duplicates: ${maybeMatches[i]} and ${maybeMatches[j]}`);}}}};\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nconst hasElement = (buckets, elem) => {\\\\n const badHash = hashBadly(elem);\\\\n if (!buckets.has(badHash)) {\\\\n return false;}\\\\n\\\\n const maybeMatches = buckets.get(badHash);\\\\n return maybeMatches.some(maybeMatch => sameStructure.sameStructure(maybeMatch, elem));};\\\\n\\\\n\\\\n/* get a string of string keys and string values as a fuzzy hash for*/\\\\n/* bucketing.*/\\\\n/* only use sameStructure within that bucket.*/\\\\n\\\\nconst setMathHelpers = harden({\\\\n doCoerce: list => {\\\\n assert.assert(marshal.passStyleOf(list) === 'copyArray', 'list must be an array');\\\\n checkForDupes(makeBuckets(list));\\\\n return list;},\\\\n\\\\n doGetEmpty: _ => identity,\\\\n doIsEmpty: list => marshal.passStyleOf(list) === 'copyArray' && list.length === 0,\\\\n doIsGTE: (left, right) => {\\\\n const leftBuckets = makeBuckets(left);\\\\n return right.every(rightElem => hasElement(leftBuckets, rightElem));},\\\\n\\\\n doIsEqual: (left, right) => {\\\\n return left.length === right.length && setMathHelpers.doIsGTE(left, right);},\\\\n\\\\n doAdd: (left, right) => {\\\\n const combined = harden([...left, ...right]);\\\\n checkForDupes(makeBuckets(combined));\\\\n return combined;},\\\\n\\\\n doSubtract: (left, right) => {\\\\n const leftBuckets = makeBuckets(left);\\\\n const rightBuckets = makeBuckets(right);\\\\n right.forEach(rightElem => {\\\\n assert.assert(\\\\n hasElement(leftBuckets, rightElem),\\\\n assert.details`right element ${rightElem} was not in left`);});\\\\n\\\\n\\\\n const leftElemNotInRight = leftElem => !hasElement(rightBuckets, leftElem);\\\\n return harden(left.filter(leftElemNotInRight));} });\\\\n\\\\n\\\\n\\\\nharden(setMathHelpers);exports.default = setMathHelpers;\\\",\\n \\\"packages/ERTP/src/mathHelpersLib.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var importManager = require('../../import-manager/src/importManager.js');var natMathHelpers = require('./mathHelpers/natMathHelpers.js');var strSetMathHelpers = require('./mathHelpers/strSetMathHelpers.js');var setMathHelpers = require('./mathHelpers/setMathHelpers.js');\\\\n\\\\n\\\\n\\\\n\\\\nconst manager = importManager.importManager();\\\\nconst mathHelpersLib = manager.addExports({\\\\n nat: natMathHelpers.default,\\\\n strSet: strSetMathHelpers.default,\\\\n set: setMathHelpers.default });exports.default = mathHelpersLib;\\\",\\n \\\"packages/ERTP/src/amountMath.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../assert/src/assert.js');var sameStructure = require('../../same-structure/src/sameStructure.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nmathHelpersLib = require('./mathHelpersLib.js'); /* global harden */ /**\\\\n * @typedef {Object} Amount\\\\n * Amounts are descriptions of digital assets, answering the questions\\\\n * \\\\\\\"how much\\\\\\\" and \\\\\\\"of what kind\\\\\\\". Amounts are values labeled with a brand.\\\\n * AmountMath executes the logic of how amounts are changed when digital\\\\n * assets are merged, separated, or otherwise manipulated. For\\\\n * example, a deposit of 2 bucks into a purse that already has 3 bucks\\\\n * gives a new purse balance of 5 bucks. An empty purse has 0 bucks. AmountMath\\\\n * relies heavily on polymorphic MathHelpers, which manipulate the unbranded\\\\n * portion.\\\\n *\\\\n * @property {Brand} brand\\\\n * @property {Value} value\\\\n */ /**\\\\n * @typedef {Object} Value\\\\n * Values describe the value of something that can be owned or shared.\\\\n * Fungible values are normally represented by natural numbers. Other\\\\n * values may be represented as strings naming a particular right, or\\\\n * an arbitrary object that sensibly represents the rights at issue.\\\\n *\\\\n * Value must be Comparable. (This IDL doesn't yet provide a way to specify\\\\n * subtype relationships for structs.)\\\\n */ /**\\\\n * @typedef {Object} AmountMath\\\\n * Logic for manipulating amounts.\\\\n *\\\\n * Amounts are the canonical description of tradable goods. They are manipulated\\\\n * by issuers and mints, and represent the goods and currency carried by purses and\\\\n * payments. They can be used to represent things like currency, stock, and the\\\\n * abstract right to participate in a particular exchange.\\\\n *\\\\n * @property {() => Brand} getBrand Return the brand.\\\\n * @property {() => string} getMathHelpersName\\\\n * Get the name of the mathHelpers used. This can be used as an\\\\n * argument to `makeAmountMath` to create local amountMath.\\\\n *\\\\n * @property {(allegedValue: Value) => Amount} make\\\\n * Make an amount from a value by adding the brand.\\\\n *\\\\n * @property {(allegedAmount: Amount) => Amount} coerce\\\\n * Make sure this amount is valid and return it if so.\\\\n *\\\\n * @property {(amount: Amount) => Value} getValue\\\\n * Extract and return the value.\\\\n *\\\\n * @property {() => Amount} getEmpty\\\\n * Return the amount representing an empty amount. This is the\\\\n * identity element for MathHelpers.add and MatHelpers.subtract.\\\\n *\\\\n * @property {(amount: Amount) => boolean} isEmpty\\\\n * Return true if the Amount is empty. Otherwise false.\\\\n *\\\\n * @property {(leftAmount: Amount, rightAmount: Amount) => boolean} isGTE\\\\n * Returns true if the leftAmount is greater than or equal to the\\\\n * rightAmount. For non-scalars, \\\\\\\"greater than or equal to\\\\\\\" depends\\\\n * on the kind of amount, as defined by the MathHelpers. For example,\\\\n * whether rectangle A is greater than rectangle B depends on whether rectangle\\\\n * A includes rectangle B as defined by the logic in MathHelpers.\\\\n *\\\\n * @property {(leftAmount: Amount, rightAmount: Amount) => boolean} isEqual\\\\n * Returns true if the leftAmount equals the rightAmount. We assume\\\\n * that if isGTE is true in both directions, isEqual is also true\\\\n *\\\\n * @property {(leftAmount: Amount, rightAmount: Amount) => Amount} add\\\\n * Returns a new amount that is the union of both leftAmount and rightAmount.\\\\n *\\\\n * For fungible amount this means adding the values. For other kinds of\\\\n * amount, it usually means including all of the elements from both\\\\n * left and right.\\\\n *\\\\n * @property {(leftAmount: Amount, rightAmount: Amount) => Amount} subtract\\\\n * Returns a new amount that is the leftAmount minus the rightAmount\\\\n * (i.e. everything in the leftAmount that is not in the\\\\n * rightAmount). If leftAmount doesn't include rightAmount\\\\n * (subtraction results in a negative), throw an error. Because the\\\\n * left amount must include the right amount, this is NOT equivalent\\\\n * to set subtraction.\\\\n */ /**\\\\n * @typedef {Object} Brand\\\\n * The brand identifies the kind of issuer, and has a function to get the\\\\n * alleged name for the kind of asset described. The alleged name (such\\\\n * as 'BTC' or 'moola') is provided by the maker of the issuer and should\\\\n * not be trusted as accurate.\\\\n *\\\\n * Every amount created by AmountMath will have the same brand, but recipients\\\\n * cannot use the brand by itself to verify that a purported amount is\\\\n * authentic, since the brand can be reused by a misbehaving issuer.\\\\n *\\\\n * @property {(issuer: Issuer) => boolean} isMyIssuer\\\\n * @property {() => string} getAllegedName\\\\n */ /* Amounts describe digital assets. From an amount, you can learn the*/ /* kind of digital asset as well as \\\\\\\"how much\\\\\\\" or \\\\\\\"how many\\\\\\\". Amounts*/ /* have two parts: a brand (the kind of digital asset) and the value*/ /* (the answer to \\\\\\\"how much\\\\\\\"). For example, in the phrase \\\\\\\"5 bucks\\\\\\\",*/ /* \\\\\\\"bucks\\\\\\\" takes the role of the brand and the value is 5. Amounts*/ /* can describe fungible and non-fungible digital assets. Amounts are*/ /* pass-by-copy and can be made by and sent to anyone.*/ /* The issuer has an internal table that maps purses and payments to*/ /* amounts. The issuer must be able to do things such as add digital*/ /* assets to a purse and withdraw digital assets from a purse. To do*/ /* so, it must know how to add and subtract digital assets. Rather*/ /* than hard-coding a particular solution, we chose to parameterize*/ /* the issuer with a collection of polymorphic functions, which we*/ /* call `amountMath`. These math functions include concepts like*/ /* addition, subtraction, and greater than or equal to.*/ /* We also want to make sure there is no confusion as to what kind of*/ /* asset we are using. Thus, amountMath includes checks of the*/ /* `brand`, the unique identifier for the type of digital asset. If*/ /* the wrong brand is used in amountMath, an error is thrown and the*/ /* operation does not succeed.*/ /* amountMath uses mathHelpers to do most of the work, but then adds*/ /* the brand to the result. The function `value` gets the value from*/ /* the amount by removing the brand (amount -> value), and the function*/ /* `make` adds the brand to produce an amount (value -> amount). The*/ /* function `coerce` takes an amount and checks it, returning an amount (amount*/ /* -> amount).*/ /* `makeAmount` takes in a brand and the name of the particular*/ /* mathHelpers to use.*/ /* amountMath is unfortunately not pass-by-copy. If you call*/ /* `getAmountMath` on a remote issuer, it will be a remote object and*/ /* each call will incur the costs of calling a remote object. However,*/ /* you can create a local amountMath by importing this module locally*/ /* and recreating by passing in a brand and an mathHelpers name, both*/ /* of which can be passed-by-copy (since there are no calls to brand*/ /* in this module).*/ /* Each issuer of digital assets has an associated brand in a one-to-one*/ /* mapping. In untrusted contexts, such as in analyzing payments and*/ /* amounts, we can get the brand and find the issuer which matches the*/ /* brand. The issuer and the brand mutually validate each other.*/function makeAmountMath(brand, mathHelpersName) {sameStructure.mustBeComparable(brand);assert.assert.typeof(mathHelpersName, 'string');const helpers = mathHelpersLib.default[mathHelpersName];assert.assert(helpers !== undefined, assert.details`unrecognized mathHelpersName: ${mathHelpersName}`); /* Cache the amount if we can.*/const cache = new WeakSet();const amountMath = harden({ getBrand: () => brand, getMathHelpersName: () => mathHelpersName, /* Make an amount from a value by adding the brand.*/make: allegedValue => {const value = helpers.doCoerce(allegedValue);const amount = harden({ brand, value });cache.add(amount);return amount;}, /* Make sure this amount is valid and return it if so.*/coerce: allegedAmount => {/* If the cache already has the allegedAmount, that*/ /* means it is a valid amount.*/if (cache.has(allegedAmount)) {return allegedAmount;}const { brand: allegedBrand, value } = allegedAmount;assert.assert(allegedBrand !== undefined, assert.details`alleged brand is undefined. Did you pass a value rather than an amount?`);assert.assert(brand === allegedBrand, assert.details`the brand in the allegedAmount in 'coerce' didn't match the amountMath brand`); /* Will throw on inappropriate value*/return amountMath.make(value);}, /* Get the value from the amount.*/getValue: amount => amountMath.coerce(amount).value, /* Represents the empty set/mathematical identity.*/ /* eslint-disable-next-line no-use-before-define*/getEmpty: () => empty, /* Is the amount equal to the empty set?*/isEmpty: amount => helpers.doIsEmpty(amountMath.getValue(amount)), /* Is leftAmount greater than or equal to rightAmount? In other*/ /* words, is everything in the rightAmount included in the*/ /* leftAmount?*/isGTE: (leftAmount, rightAmount) => helpers.doIsGTE(amountMath.getValue(leftAmount), amountMath.getValue(rightAmount)), /* Is leftAmount equal to rightAmount?*/isEqual: (leftAmount, rightAmount) => helpers.doIsEqual(amountMath.getValue(leftAmount), amountMath.getValue(rightAmount)), /* Combine leftAmount and rightAmount.*/add: (leftAmount, rightAmount) => amountMath.make(helpers.doAdd(amountMath.getValue(leftAmount), amountMath.getValue(rightAmount))), /* Return the amount included in leftAmount but not included in*/ /* rightAmount. If leftAmount does not include all of rightAmount,*/ /* error.*/subtract: (leftAmount, rightAmount) => amountMath.make(helpers.doSubtract(amountMath.getValue(leftAmount), amountMath.getValue(rightAmount))) });\\\\n\\\\n\\\\n const empty = amountMath.make(helpers.doGetEmpty());\\\\n return amountMath;}\\\\n\\\\n\\\\nvar makeAmountMath$1 = harden(makeAmountMath);exports.default = makeAmountMath$1;\\\",\\n \\\"packages/ERTP/src/issuer.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../assert/src/assert.js');var weakStore = require('../../weak-store/src/weakStore.js');var producePromise = require('../../produce-promise/src/producePromise.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\namountMath = require('./amountMath.js'); /* Copyright (C) 2019 Agoric, under Apache License 2.0*/ /**\\\\n * @typedef {Ximport('./amountMath').Amount} Amount\\\\n * @typedef {Ximport('./amountMath').Value} Value\\\\n * @typedef {Ximport('./amountMath').AmountMath} AmountMath\\\\n * @typedef {Payment|Promise<Payment>} PaymentP\\\\n */ /**\\\\n * @typedef {Object} Issuer\\\\n * The issuer cannot mint a new amount, but it can create empty purses and\\\\n * payments. The issuer can also transform payments (splitting payments,\\\\n * combining payments, burning payments, and claiming payments\\\\n * exclusively). The issuer should be gotten from a trusted source and\\\\n * then relied upon as the decider of whether an untrusted payment is valid.\\\\n *\\\\n * @property {() => Brand} getBrand Get the Brand for this Issuer. The Brand indicates the kind of\\\\n * digital asset and is shared by the mint, the issuer, and any purses\\\\n * and payments of this particular kind. The brand is not closely\\\\n * held, so this function should not be trusted to identify an issuer\\\\n * alone. Fake digital assets and amount can use another issuer's brand.\\\\n *\\\\n * @property {() => string} getAllegedName Get the allegedName for this mint/issuer\\\\n * @property {() => AmountMath} getAmountMath Get the AmountMath for this Issuer.\\\\n * @property {() => string} getMathHelpersName Get the name of the MathHelpers for this Issuer.\\\\n * @property {() => Purse} makeEmptyPurse Make an empty purse of this brand.\\\\n * @property {(payment: PaymentP) => Promise<boolean>} isLive\\\\n * Return true if the payment continues to exist.\\\\n *\\\\n * If the payment is a promise, the operation will proceed upon resolution.\\\\n *\\\\n * @property {(payment: PaymentP) => Promise<Amount>} getAmountOf\\\\n * Get the amount of digital assets in the payment. Because the\\\\n * payment is not trusted, we cannot call a method on it directly,\\\\n * and must use the issuer instead.\\\\n *\\\\n * If the payment is a promise, the operation will proceed upon resolution.\\\\n *\\\\n * @property {(payment: PaymentP, optAmount?: Amount) => Promise<Amount>} burn\\\\n * Burn all of the digital assets in the payment. `optAmount` is optional.\\\\n * If `optAmount` is present, the code will insist that the amount of\\\\n * the digital assets in the payment is equal to `optAmount`, to\\\\n * prevent sending the wrong payment and other confusion.\\\\n *\\\\n * If the payment is a promise, the operation will proceed upon resolution.\\\\n *\\\\n * @property {(payment: PaymentP, optAmount?: Amount) => Promise<Payment>} claim\\\\n * Transfer all digital assets from the payment to a new payment and\\\\n * delete the original. `optAmount` is optional.\\\\n * If `optAmount` is present, the code will insist that the amount of\\\\n * digital assets in the payment is equal to `optAmount`, to prevent\\\\n * sending the wrong payment and other confusion.\\\\n *\\\\n * If the payment is a promise, the operation will proceed upon resolution.\\\\n *\\\\n * @property {(paymentsArray: PaymentP[]) => Promise<Payment>} combine\\\\n * Combine multiple payments into one payment.\\\\n *\\\\n * If any of the payments is a promise, the operation will proceed upon\\\\n * resolution.\\\\n *\\\\n * @property {(payment: PaymentP, paymentAmountA: Amount) => Promise<Payment[]>} split\\\\n * Split a single payment into two payments, A and B, according to the\\\\n * paymentAmountA passed in.\\\\n *\\\\n * If the payment is a promise, the operation will proceed upon resolution.\\\\n *\\\\n * @property {(payment: PaymentP, amounts: Amount[]) => Promise<Payment[]>} splitMany\\\\n * Split a single payment into many payments, according to the\\\\n * amounts passed in.\\\\n *\\\\n * If the payment is a promise, the operation will proceed upon resolution.\\\\n */ /**\\\\n * @typedef {Object} Brand\\\\n * The Brand indicates the kind of digital asset and is shared by\\\\n * the mint, the issuer, and any purses and payments of this\\\\n * particular kind. Fake digital assets and amount can use another\\\\n * issuer's brand.\\\\n *\\\\n * @property {(allegedIssuer: any) => boolean} isMyIssuer Should be used with\\\\n * `issuer.getBrand` to ensure an issuer and brand match.\\\\n * @property {() => string} getAllegedName\\\\n */ /**\\\\n * @typedef {Object} IssuerMaker\\\\n * Makes Issuers.\\\\n *\\\\n * @property {(allegedName: string, mathHelperName: string) => IssuerResults} makeIssuerKit\\\\n * The allegedName becomes part of the brand in asset descriptions. The\\\\n * allegedName doesn't have to be a string, but it will only be used for\\\\n * its value. The allegedName is useful for debugging and double-checking\\\\n * assumptions, but should not be trusted.\\\\n *\\\\n * The mathHelpersName will be used to import a specific mathHelpers\\\\n * from the mathHelpers library. For example, natMathHelpers, the\\\\n * default, is used for basic fungible tokens.\\\\n *\\\\n * @typedef {Object} IssuerResults\\\\n * The return value of makeIssuerKit\\\\n *\\\\n * @property {Mint} mint\\\\n * @property {Issuer} issuer\\\\n * @property {AmountMath} amountMath\\\\n * @property {Brand} brand\\\\n */ /**\\\\n * @typedef {Object} Mint\\\\n * Holding a Mint carries the right to issue new digital assets. These\\\\n * assets all have the same kind, which is called a Brand.\\\\n *\\\\n * @property {() => Issuer} getIssuer Gets the Issuer for this mint.\\\\n * @property {(newAmount: Amount) => Payment} mintPayment\\\\n * Creates a new Payment containing newly minted amount.\\\\n */ /**\\\\n * @typedef {Object} DepositFacet\\\\n * @property {(payment: Payment, optAmount?: Amount) => Amount} receive\\\\n * Deposit all the contents of payment into the purse that made this facet, returning the\\\\n * amount. If the optional argument `optAmount` does not equal the\\\\n * amount of digital assets in the payment, throw an error.\\\\n *\\\\n * If payment is an unresolved promise, throw an error.\\\\n */ /**\\\\n * @typedef {Object} Purse\\\\n * Purses hold amount of digital assets of the same brand, but unlike Payments, they are\\\\n * not meant to be sent to others. To transfer digital assets, a\\\\n * Payment should be withdrawn from a Purse. The amount of digital\\\\n * assets in a purse can change through the action of deposit() and withdraw().\\\\n *\\\\n * The primary use for Purses and Payments is for currency-like and goods-like\\\\n * digital assets, but they can also be used to represent other kinds of rights, such\\\\n * as the right to participate in a particular contract.\\\\n *\\\\n * @property {() => Brand} getAllegedBrand Get the alleged Brand for this Purse\\\\n *\\\\n * @property {() => Amount} getCurrentAmount\\\\n * Get the amount contained in this purse, confirmed by the issuer.\\\\n *\\\\n * @property {(payment: Payment, optAmount?: Amount) => Amount} deposit\\\\n * Deposit all the contents of payment into this purse, returning the\\\\n * amount. If the optional argument `optAmount` does not equal the\\\\n * amount of digital assets in the payment, throw an error.\\\\n *\\\\n * If payment is an unresolved promise, throw an error.\\\\n *\\\\n * @property {() => DepositFacet} makeDepositFacet\\\\n * Create an object whose `deposit` method deposits to the current Purse.\\\\n *\\\\n * @property {(amount: Amount) => Payment} withdraw\\\\n * Withdraw amount from this purse into a new Payment.\\\\n */ /**\\\\n * @typedef {Object} Payment\\\\n * Payments hold amount of digital assets of the same brand in transit. Payments can\\\\n * be deposited in purses, split into multiple payments, combined, and\\\\n * claimed (getting an exclusive payment). Payments are linear, meaning\\\\n * that either a payment has the same amount of digital assets it\\\\n * started with, or it is used up entirely. It is impossible to partially use a payment.\\\\n *\\\\n * Payments are often received from other actors and therefore should\\\\n * not be trusted themselves. To get the amount of digital assets in a payment, use the\\\\n * trusted issuer: issuer.getAmountOf(payment),\\\\n *\\\\n * Payments can be converted to Purses by getting a trusted issuer and\\\\n * calling `issuer.makeEmptyPurse()` to create a purse, then `purse.deposit(payment)`.\\\\n *\\\\n * @property {() => Brand} getAllegedBrand\\\\n * Get the allegedBrand, indicating the kind of digital asset this\\\\n * payment purports to be, and which issuer to use. Because payments\\\\n * are not trusted, any method calls on payments should be treated\\\\n * with suspicion and verified elsewhere.\\\\n */ /**\\\\n * @typedef {Object} MathHelpers\\\\n * All of the difference in how digital asset amount are manipulated can be reduced to\\\\n * the behavior of the math on values. We extract this\\\\n * custom logic into mathHelpers. MathHelpers are about value\\\\n * arithmetic, whereas AmountMath is about amounts, which are the\\\\n * values labeled with a brand. AmountMath use mathHelpers to do their value arithmetic,\\\\n * and then brand the results, making a new amount.\\\\n *\\\\n * @property {(allegedValue: Value) => Value} doCoerce\\\\n * Check the kind of this value and throw if it is not the\\\\n * expected kind.\\\\n *\\\\n * @property {() => Value} doGetEmpty\\\\n * Get the representation for the identity element (often 0 or an\\\\n * empty array)\\\\n *\\\\n * @property {(value: Value) => boolean} doIsEmpty\\\\n * Is the value the identity element?\\\\n *\\\\n * @property {(left: Value, right: Value) => boolean} doIsGTE\\\\n * Is the left greater than or equal to the right?\\\\n *\\\\n * @property {(left: Value, right: Value) => boolean} doIsEqual\\\\n * Does left equal right?\\\\n *\\\\n * @property {(left: Value, right: Value) => Value} doAdd\\\\n * Return the left combined with the right.\\\\n *\\\\n * @property {(left: Value, right: Value) => Value} doSubtract\\\\n * Return what remains after removing the right from the left. If\\\\n * something in the right was not in the left, we throw an error.\\\\n */ /**\\\\n *\\\\n * @param {string} allegedName\\\\n * @param {string} mathHelpersName\\\\n * @returns {IssuerResults}\\\\n */function makeIssuerKit(allegedName, mathHelpersName = 'nat') {assert.assert.typeof(allegedName, 'string');const brand = harden({ /* eslint-disable-next-line no-use-before-define*/isMyIssuer: allegedIssuer => allegedIssuer === issuer, getAllegedName: () => allegedName });const amountMath$1 = amountMath.default(brand, mathHelpersName);const paymentLedger = weakStore.default('payment');const purseLedger = weakStore.default('purse');function assertKnownPayment(payment) {assert.assert(paymentLedger.has(payment), assert.details`payment not found for ${allegedName}`);}const makePayment = () => harden({ getAllegedBrand: () => brand }); /* Methods like deposit() have an optional second parameter `amount`*/ /* which, if present, is supposed to be equal to the balance of the*/ /* payment. This helper function does that check.*/const assertAmountEqual = (paymentBalance, amount) => {if (amount !== undefined) {assert.assert(amountMath$1.isEqual(amount, paymentBalance), assert.details`payment balance ${paymentBalance} must equal amount ${amount}`);}};const makePurse = () => {const purse = harden({ deposit: (srcPayment, optAmount = undefined) => {if (producePromise.isPromise(srcPayment)) {throw new TypeError(`deposit does not accept promises as first argument. Instead of passing the promise (deposit(paymentPromise)), consider unwrapping the promise first: paymentPromise.then(actualPayment => deposit(actualPayment))`);}assertKnownPayment(srcPayment);const srcPaymentBalance = paymentLedger.get(srcPayment); /* Note: this does not guarantee that optAmount itself is a valid stable amount*/assertAmountEqual(srcPaymentBalance, optAmount);const purseBalance = purse.getCurrentAmount();const newPurseBalance = amountMath$1.add(srcPaymentBalance, purseBalance); /* Commit point*/ /* eslint-disable-next-line no-use-before-define*/const payments = reallocate(harden({ payments: [srcPayment], purses: [purse], newPurseBalances: [newPurseBalance] }));assert.assert(payments.length === 0, 'no payments should be returned');return srcPaymentBalance;}, withdraw: amount => {amount = amountMath$1.coerce(amount);const purseBalance = purse.getCurrentAmount();const newPurseBalance = amountMath$1.subtract(purseBalance, amount); /* Commit point*/ /* eslint-disable-next-line no-use-before-define*/const [payment] = reallocate(harden({ purses: [purse], newPurseBalances: [newPurseBalance], newPaymentBalances: [amount] }));return payment;}, getCurrentAmount: () => purseLedger.get(purse), getAllegedBrand: () => brand, makeDepositFacet: () => harden({ receive: purse.deposit }) });return purse;};const { add } = amountMath$1;const empty = amountMath$1.getEmpty(); /* Amount in circulation remains constant with reallocate.*/const reallocate = ({ purses = [], payments = [], newPurseBalances = [], newPaymentBalances = [] }) => {/* There may be zero or one purse and no more. No methods pass in*/ /* more than one purse.*/assert.assert(purses.length === 0 || purses.length === 1, 'purses length must be 0 or 1'); /* There may be zero, one, or many payments as input to*/ /* reallocate. We want to protect against someone passing in*/ /* what appears to be multiple payments that turn out to actually*/ /* be the same payment (an aliasing issue). The `combine` method*/ /* legitimately needs to take in multiple payments, but we don't*/ /* need to pay the costs of protecting against aliasing for the*/ /* other uses.*/if (payments.length > 1) {const paymentSet = new Set();payments.forEach(payment => {if (paymentSet.has(payment)) {throw new Error('same payment seen twice');}paymentSet.add(payment);});}assert.assert(purses.length === newPurseBalances.length, assert.details`purses and newPurseBalances should have same length`);const totalPursesB = purses.map(purseLedger.get).reduce(add, empty);const totalPaymentsB = payments.map(paymentLedger.get).reduce(add, empty);const total = amountMath$1.add(totalPursesB, totalPaymentsB);const newPursesTotal = newPurseBalances.reduce(add, empty);const newPaymentsTotal = newPaymentBalances.reduce(add, empty);const newTotal = amountMath$1.add(newPaymentsTotal, newPursesTotal); /* Invariant check*/assert.assert(amountMath$1.isEqual(total, newTotal), 'rights were not conserved'); /* commit point*/payments.forEach(payment => paymentLedger.delete(payment));purses.forEach((purse, i) => purseLedger.set(purse, newPurseBalances[i]));const newPayments = newPaymentBalances.map(balance => {const newPayment = makePayment();paymentLedger.init(newPayment, balance);return newPayment;});return harden(newPayments);};const issuer = harden({ getBrand: () => brand, getAllegedName: () => allegedName, getAmountMath: () => amountMath$1, getMathHelpersName: () => mathHelpersName, makeEmptyPurse: () => {const purse = makePurse();purseLedger.init(purse, amountMath$1.getEmpty());return purse;}, isLive: paymentP => {return Promise.resolve(paymentP).then(payment => {return paymentLedger.has(payment);});}, getAmountOf: paymentP => {return Promise.resolve(paymentP).then(payment => {assertKnownPayment(payment);return paymentLedger.get(payment);});}, burn: (paymentP, optAmount = undefined) => {return Promise.resolve(paymentP).then(payment => {assertKnownPayment(payment);const paymentBalance = paymentLedger.get(payment);assertAmountEqual(paymentBalance, optAmount); /* Commit point.*/paymentLedger.delete(payment);return paymentBalance;});}, claim: (paymentP, optAmount = undefined) => {return Promise.resolve(paymentP).then(srcPayment => {assertKnownPayment(srcPayment);const srcPaymentBalance = paymentLedger.get(srcPayment);assertAmountEqual(srcPaymentBalance, optAmount); /* Commit point.*/const [payment] = reallocate(harden({ payments: [srcPayment], newPaymentBalances: [srcPaymentBalance] }));return payment;});},\\\\n\\\\n\\\\n /* Payments in `fromPaymentsPArray` must be distinct. Alias*/\\\\n /* checking is delegated to the `reallocate` function.*/\\\\n combine: (fromPaymentsPArray, optTotalAmount = undefined) => {\\\\n return Promise.all(fromPaymentsPArray).then(fromPaymentsArray => {\\\\n fromPaymentsArray.every(assertKnownPayment);\\\\n const totalPaymentsBalance = fromPaymentsArray.\\\\n map(paymentLedger.get).\\\\n reduce(add, empty);\\\\n assertAmountEqual(totalPaymentsBalance, optTotalAmount);\\\\n /* Commit point.*/\\\\n const [payment] = reallocate(\\\\n harden({\\\\n payments: fromPaymentsArray,\\\\n newPaymentBalances: [totalPaymentsBalance] }));\\\\n\\\\n\\\\n return payment;});},\\\\n\\\\n\\\\n /* payment to two payments, A and B*/\\\\n split: (paymentP, paymentAmountA) => {\\\\n return Promise.resolve(paymentP).then(srcPayment => {\\\\n paymentAmountA = amountMath$1.coerce(paymentAmountA);\\\\n assertKnownPayment(srcPayment);\\\\n const srcPaymentBalance = paymentLedger.get(srcPayment);\\\\n const paymentAmountB = amountMath$1.subtract(\\\\n srcPaymentBalance,\\\\n paymentAmountA);\\\\n\\\\n /* Commit point*/\\\\n const newPayments = reallocate(\\\\n harden({\\\\n payments: [srcPayment],\\\\n newPaymentBalances: [paymentAmountA, paymentAmountB] }));\\\\n\\\\n\\\\n return newPayments;});},\\\\n\\\\n\\\\n splitMany: (paymentP, amounts) => {\\\\n return Promise.resolve(paymentP).then(srcPayment => {\\\\n assertKnownPayment(srcPayment);\\\\n amounts = amounts.map(amountMath$1.coerce);\\\\n /* Commit point*/\\\\n const newPayments = reallocate(\\\\n harden({\\\\n payments: [srcPayment],\\\\n newPaymentBalances: amounts }));\\\\n\\\\n\\\\n return newPayments;});} });\\\\n\\\\n\\\\n\\\\n\\\\n const mint = harden({\\\\n getIssuer: () => issuer,\\\\n mintPayment: newAmount => {\\\\n newAmount = amountMath$1.coerce(newAmount);\\\\n const payment = makePayment();\\\\n paymentLedger.init(payment, newAmount);\\\\n return payment;} });\\\\n\\\\n\\\\n\\\\n return harden({\\\\n mint,\\\\n issuer,\\\\n amountMath: amountMath$1,\\\\n brand });}\\\\n\\\\n\\\\n\\\\nharden(makeIssuerKit);exports.default = makeIssuerKit;\\\",\\n \\\"packages/zoe/src/contractSupport/auctions.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true }); /* global harden */\\\\n\\\\nconst secondPriceLogic = (bidAmountMath, bidOfferHandles, bids) => {\\\\n let highestBid = bidAmountMath.getEmpty();\\\\n let secondHighestBid = bidAmountMath.getEmpty();\\\\n let highestBidOfferHandle;\\\\n /* eslint-disable-next-line array-callback-return*/\\\\n bidOfferHandles.map((offerHandle, i) => {\\\\n const bid = bids[i];\\\\n /* If the bid is greater than the highestBid, it's the new highestBid*/\\\\n if (bidAmountMath.isGTE(bid, highestBid)) {\\\\n secondHighestBid = highestBid;\\\\n highestBid = bid;\\\\n highestBidOfferHandle = offerHandle;} else\\\\n if (bidAmountMath.isGTE(bid, secondHighestBid)) {\\\\n /* If the bid is not greater than the highest bid, but is greater*/\\\\n /* than the second highest bid, it is the new second highest bid.*/\\\\n secondHighestBid = bid;}});\\\\n\\\\n\\\\n return harden({\\\\n winnerOfferHandle: highestBidOfferHandle,\\\\n winnerBid: highestBid,\\\\n price: secondHighestBid });};\\\\n\\\\n\\\\n\\\\nconst closeAuction = (\\\\nzcf,\\\\n{ auctionLogicFn, sellerOfferHandle, allBidHandles }) =>\\\\n{\\\\n const { brandKeywordRecord } = zcf.getInstanceRecord();\\\\n const bidAmountMath = zcf.getAmountMath(brandKeywordRecord.Ask);\\\\n const assetAmountMath = zcf.getAmountMath(brandKeywordRecord.Asset);\\\\n\\\\n /* Filter out any inactive bids*/\\\\n const { active: activeBidHandles } = zcf.getOfferStatuses(\\\\n harden(allBidHandles));\\\\n\\\\n\\\\n const getBids = amountsKeywordRecord => amountsKeywordRecord.Bid;\\\\n const bids = zcf.getCurrentAllocations(activeBidHandles).map(getBids);\\\\n const assetAmount = zcf.getOffer(sellerOfferHandle).proposal.give.Asset;\\\\n\\\\n const { winnerOfferHandle, winnerBid, price } = auctionLogicFn(\\\\n bidAmountMath,\\\\n activeBidHandles,\\\\n bids);\\\\n\\\\n\\\\n /* The winner gets to keep the difference between their bid and the*/\\\\n /* price paid.*/\\\\n const winnerRefund = bidAmountMath.subtract(winnerBid, price);\\\\n\\\\n const newSellerAmounts = { Asset: assetAmountMath.getEmpty(), Ask: price };\\\\n const newWinnerAmounts = { Asset: assetAmount, Bid: winnerRefund };\\\\n\\\\n /* Everyone else gets a refund so their values remain the*/\\\\n /* same.*/\\\\n zcf.reallocate(\\\\n harden([sellerOfferHandle, winnerOfferHandle]),\\\\n harden([newSellerAmounts, newWinnerAmounts]));\\\\n\\\\n const allOfferHandles = harden([sellerOfferHandle, ...activeBidHandles]);\\\\n zcf.complete(allOfferHandles);};exports.closeAuction = closeAuction;exports.secondPriceLogic = secondPriceLogic;\\\",\\n \\\"packages/zoe/src/contractSupport/safeMath.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\nnat_esm = require('../../../../node_modules/@agoric/nat/dist/nat.esm.js'); /* global harden */ /**\\\\n * These operations should be used for calculations with the\\\\n * values of basic fungible tokens.\\\\n */\\\\nconst natSafeMath = harden({\\\\n add: (x, y) => nat_esm.default(x + y),\\\\n subtract: (x, y) => nat_esm.default(x - y),\\\\n multiply: (x, y) => nat_esm.default(x * y),\\\\n floorDivide: (x, y) => nat_esm.default(Math.floor(x / y)) });exports.natSafeMath = natSafeMath;\\\",\\n \\\"packages/zoe/src/contractSupport/bondingCurves.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../../assert/src/assert.js');var safeMath = require('./safeMath.js');\\\\n\\\\n\\\\nconst { add, subtract, multiply, floorDivide } = safeMath.natSafeMath;\\\\n\\\\n/**\\\\n * Contains the logic for calculating how much should be given\\\\n * back to the user in exchange for what they sent in. It also\\\\n * calculates the new amount of the assets in the pool. Reused in\\\\n * several different places, including to check whether an offer\\\\n * is valid, getting the current price for an asset on user\\\\n * request, and to do the actual reallocation after an offer has\\\\n * been made.\\\\n * @param {Object} params\\\\n * @param {number} params.inputValue - the value of the asset sent\\\\n * in to be swapped\\\\n * @param {number} params.inputReserve - the value in the liquidity\\\\n * pool of the kind of asset sent in\\\\n * @param {number} params.outputReserve - the value in the liquidity\\\\n * pool of the kind of asset to be sent out\\\\n * @param {number} params.feeBasisPoints=30 - the fee taken in\\\\n * basis points. The default is 0.3% or 30 basis points. The fee is taken from\\\\n * inputValue\\\\n * @returns {number} outputValue - the current price, in value form\\\\n */\\\\nconst getInputPrice = ({\\\\n inputValue,\\\\n inputReserve,\\\\n outputReserve,\\\\n feeBasisPoints = 30 }) =>\\\\n{\\\\n const oneMinusFeeInTenThousandths = subtract(10000, feeBasisPoints);\\\\n const inputWithFee = multiply(inputValue, oneMinusFeeInTenThousandths);\\\\n const numerator = multiply(inputWithFee, outputReserve);\\\\n const denominator = add(multiply(inputReserve, 10000), inputWithFee);\\\\n\\\\n const outputValue = floorDivide(numerator, denominator);\\\\n return outputValue;};\\\\n\\\\n\\\\nfunction assertDefined(label, value) {\\\\n assert.assert(value !== undefined, assert.details`${label} value required`);}\\\\n\\\\n\\\\n/* Calculate how many liquidity tokens we should be minting to send back to the*/\\\\n/* user when adding liquidity. Calculations are based on the comparing the*/\\\\n/* inputValue to the inputReserve. If the current supply is zero, just return*/\\\\n/* the inputValue.*/\\\\nconst calcLiqValueToMint = ({\\\\n liqTokenSupply,\\\\n inputValue,\\\\n inputReserve }) =>\\\\n{\\\\n assertDefined('liqTokenSupply', liqTokenSupply);\\\\n assertDefined('inputValue', inputValue);\\\\n assertDefined('inputReserve', inputReserve);\\\\n return liqTokenSupply > 0 ?\\\\n floorDivide(multiply(inputValue, liqTokenSupply), inputReserve) :\\\\n inputValue;};\\\\n\\\\n\\\\n/* Calculate how many underlying tokens (in the form of a value) should be*/\\\\n/* returned when removing liquidity.*/\\\\nconst calcValueToRemove = ({\\\\n liqTokenSupply,\\\\n poolValue,\\\\n liquidityValueIn }) =>\\\\n{\\\\n assertDefined('liqTokenSupply', liqTokenSupply);\\\\n assertDefined('liquidityValueIn', liquidityValueIn);\\\\n assertDefined('poolValue', poolValue);\\\\n\\\\n return floorDivide(multiply(liquidityValueIn, poolValue), liqTokenSupply);};exports.calcLiqValueToMint = calcLiqValueToMint;exports.calcValueToRemove = calcValueToRemove;exports.getInputPrice = getInputPrice;\\\",\\n \\\"packages/zoe/src/contractSupport/stateMachine.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\nassert = require('../../../assert/src/assert.js'); /* global harden */ /* allowedTransitions is an array of arrays which gets turned into a\\\\n * map. The map maps string states to an array of potential next\\\\n * states. For example,\\\\n * const allowedTransitions = [\\\\n ['open', ['closed']],\\\\n ['closed', []],\\\\n * ];\\\\n */\\\\nconst makeStateMachine = (initialState, allowedTransitionsArray) => {\\\\n let state = initialState;\\\\n const allowedTransitions = new Map(allowedTransitionsArray);\\\\n return harden({\\\\n canTransitionTo: (nextState) =>\\\\n allowedTransitions.get(state).includes(nextState),\\\\n transitionTo: nextState => {\\\\n assert.assert(allowedTransitions.get(state).includes(nextState));\\\\n state = nextState;},\\\\n\\\\n getStatus: _ => state });};\\\\n\\\\n\\\\nharden(makeStateMachine);exports.makeStateMachine = makeStateMachine;\\\",\\n \\\"packages/zoe/src/offerSafety.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /**\\\\n * @typedef {Ximport('@agoric/ertp/src/issuer').Brand} Brand\\\\n * @typedef {Ximport('@agoric/ertp/src/issuer').AmountMath} AmountMath\\\\n * @typedef {Ximport('./zoe').Proposal} Proposal\\\\n * @typedef {Ximport('./zoe').AmountKeywordRecord} AmountKeywordRecord\\\\n */ /**\\\\n * Helper to perform satisfiesWant and satisfiesGive. Is\\\\n * allocationAmount greater than or equal to requiredAmount for every\\\\n * keyword of giveOrWant?\\\\n * @param {(Brand) => AmountMath} getAmountMath\\\\n * @param {Proposal[\\\\\\\"give\\\\\\\"] | Proposal[\\\\\\\"want\\\\\\\"]} giveOrWant\\\\n * @param {AmountKeywordRecord} allocation\\\\n */const satisfiesInternal = (getAmountMath, giveOrWant, allocation) => {const isGTEByKeyword = ([keyword, requiredAmount]) => {/* If there is no allocation for a keyword, we know the giveOrWant*/ /* is not satisfied without checking further.*/if (allocation[keyword] === undefined) {\\\\n return false;}\\\\n\\\\n const amountMath = getAmountMath(requiredAmount.brand);\\\\n const allocationAmount = allocation[keyword];\\\\n return amountMath.isGTE(allocationAmount, requiredAmount);};\\\\n\\\\n return Object.entries(giveOrWant).every(isGTEByKeyword);};\\\\n\\\\n\\\\n/**\\\\n * For this allocation to satisfy what the user wanted, their\\\\n * allocated amounts must be greater than or equal to proposal.want.\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.want.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nconst satisfiesWant = (getAmountMath, proposal, allocation) =>\\\\nsatisfiesInternal(getAmountMath, proposal.want, allocation);\\\\n\\\\n/**\\\\n * For this allocation to count as a full refund, the allocated\\\\n * amounts must be greater than or equal to what was originally\\\\n * offered (proposal.give).\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.give.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nconst satisfiesGive = (getAmountMath, proposal, allocation) =>\\\\nsatisfiesInternal(getAmountMath, proposal.give, allocation);\\\\n\\\\n/**\\\\n * `isOfferSafe` checks offer safety for a single offer.\\\\n *\\\\n * Note: This implementation checks whether we fully satisfy\\\\n * `proposal.give` (giving a refund) or whether we fully satisfy\\\\n * `proposal.want`. Both can be fully satisfied.\\\\n *\\\\n * @param {(Brand) => AmountMath} getAmountMath - a function that\\\\n * takes a brand and returns the appropriate amountMath. The function\\\\n * must have an amountMath for every brand in proposal.want and\\\\n * proposal.give.\\\\n * @param {Proposal} proposal - the rules that accompanied the escrow\\\\n * of payments that dictate what the user expected to get back from\\\\n * Zoe. A proposal is a record with keys `give`, `want`, and `exit`.\\\\n * `give` and `want` are records with keywords as keys and amounts as\\\\n * values. The proposal is a user's understanding of the contract that\\\\n * they are entering when they make an offer.\\\\n * @param {AmountKeywordRecord} allocation - a record with keywords\\\\n * as keys and amounts as values. These amounts are the reallocation\\\\n * to be given to a user.\\\\n */\\\\nfunction isOfferSafe(getAmountMath, proposal, allocation) {\\\\n return (\\\\n satisfiesGive(getAmountMath, proposal, allocation) ||\\\\n satisfiesWant(getAmountMath, proposal, allocation));}exports.isOfferSafe = isOfferSafe;exports.satisfiesWant = satisfiesWant;\\\",\\n \\\"packages/zoe/src/contractSupport/zoeHelpers.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../../assert/src/assert.js');var index = require('../../../eventual-send/src/index.js');var sameStructure = require('../../../same-structure/src/sameStructure.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nofferSafety = require('../offerSafety.js'); /* global harden */ /**\\\\n * @typedef {Ximport('../zoe').OfferHandle} OfferHandle\\\\n * @typedef {Ximport('../zoe').Invite} Invite\\\\n * @typedef {Ximport('../zoe').OfferHook} OfferHook\\\\n * @typedef {Ximport('../zoe').CustomProperties} CustomProperties\\\\n * @typedef {Ximport('../zoe').ContractFacet} ContractFacet\\\\n * @typedef {Ximport('../zoe').Keyword} Keyword\\\\n * @typedef {Ximport('../zoe').AmountKeywordRecord} AmountKeywordRecord\\\\n * @typedef {Ximport('../zoe').Amount} Amount\\\\n * @typedef {Ximport('../zoe').Payment} Payment\\\\n */\\\\n\\\\nconst defaultRejectMsg = `The offer was invalid. Please check your refund.`;\\\\nconst defaultAcceptanceMsg = `The offer has been accepted. Once the contract has been completed, please check your payout`;\\\\n\\\\nconst getKeys = obj => harden(Object.getOwnPropertyNames(obj || {}));\\\\nconst getKeysSorted = (obj) =>\\\\nharden(Object.getOwnPropertyNames(obj || {}).sort());\\\\n/**\\\\n * @function makeZoeHelpers - makes an object with helper functions useful to zoe contracts.\\\\n *\\\\n * @param {ContractFacet} zcf\\\\n */\\\\n/* zcf only picks up the type if the param is in parens, which eslint dislikes*/\\\\n/* eslint-disable-next-line*/\\\\nconst makeZoeHelpers = zcf => {\\\\n const zoeService = zcf.getZoeService();\\\\n\\\\n const rejectOffer = (offerHandle, msg = defaultRejectMsg) => {\\\\n zcf.complete(harden([offerHandle]));\\\\n assert.assert.fail(msg);};\\\\n\\\\n\\\\n /* Compare the keys of actual with expected keys and reject offer if*/\\\\n /* not sameStructure. If expectedKeys is undefined, no comparison occurs.*/\\\\n const rejectKeysIf = (\\\\n offerHandle,\\\\n actual,\\\\n expected,\\\\n msg = defaultRejectMsg) =>\\\\n /* eslint-disable-next-line consistent-return*/\\\\n {\\\\n if (expected !== undefined) {\\\\n if (!sameStructure.sameStructure(getKeysSorted(actual), getKeysSorted(expected))) {\\\\n return rejectOffer(offerHandle, msg);}}};\\\\n\\\\n\\\\n\\\\n /* Compare actual keys to expected keys. If expectedKeys is*/\\\\n /* undefined, return true trivially.*/\\\\n const checkKeys = (actual, expected) => {\\\\n if (expected === undefined) {\\\\n return true;}\\\\n\\\\n return sameStructure.sameStructure(getKeysSorted(actual), getKeysSorted(expected));};\\\\n\\\\n\\\\n /**\\\\n * Given toGains (an AmountKeywordRecord), and allocations (a pair,\\\\n * 'to' and 'from', of AmountKeywordRecords), all the entries in\\\\n * toGains will be added to 'to'. If fromLosses is defined, all the\\\\n * entries in fromLosses are subtracted from 'from'. (If fromLosses\\\\n * is not defined, toGains is subtracted from 'from'.)\\\\n *\\\\n * @param {FromToAllocations} allocations - the 'to' and 'from'\\\\n * allocations\\\\n * @param {AmountKeywordRecord} toGains - what should be gained in\\\\n * the 'to' allocation\\\\n * @param {AmountKeywordRecord} fromLosses - what should be lost in\\\\n * the 'from' allocation. If not defined, fromLosses is equal to\\\\n * toGains. Note that the total amounts should always be equal; it\\\\n * is the keywords that might be different.\\\\n * @returns {FromToAllocations} allocations - new allocations\\\\n *\\\\n * @typedef FromToAllocations\\\\n * @property {AmountKeywordRecord} from\\\\n * @property {AmountKeywordRecord} to\\\\n */\\\\n const calcNewAllocations = (allocations, toGains, fromLosses = undefined) => {\\\\n if (fromLosses === undefined) {\\\\n fromLosses = toGains;}\\\\n\\\\n\\\\n const subtract = (amount, amountToSubtract) => {\\\\n const { brand } = amount;\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n if (amountToSubtract !== undefined) {\\\\n return amountMath.subtract(amount, amountToSubtract);}\\\\n\\\\n return amount;};\\\\n\\\\n\\\\n const add = (amount, amountToAdd) => {\\\\n if (amount && amountToAdd) {\\\\n const { brand } = amount;\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n return amountMath.add(amount, amountToAdd);}\\\\n\\\\n return amount || amountToAdd;};\\\\n\\\\n\\\\n const newFromAllocation = Object.fromEntries(\\\\n Object.entries(allocations.from).map(([keyword, allocAmount]) => {\\\\n return [keyword, subtract(allocAmount, fromLosses[keyword])];}));\\\\n\\\\n\\\\n\\\\n const allToKeywords = [\\\\n ...Object.keys(toGains),\\\\n ...Object.keys(allocations.to)];\\\\n\\\\n\\\\n const newToAllocation = Object.fromEntries(\\\\n allToKeywords.map(keyword => [\\\\n keyword,\\\\n add(allocations.to[keyword], toGains[keyword])]));\\\\n\\\\n\\\\n\\\\n return harden({\\\\n from: newFromAllocation,\\\\n to: newToAllocation });};\\\\n\\\\n\\\\n\\\\n const mergeAllocations = (currentAllocation, allocation) => {\\\\n const newAllocation = {\\\\n ...currentAllocation,\\\\n ...allocation };\\\\n\\\\n return newAllocation;};\\\\n\\\\n\\\\n const helpers = harden({\\\\n getKeys,\\\\n assertKeywords: expected => {\\\\n const { issuerKeywordRecord } = zcf.getInstanceRecord();\\\\n const actual = getKeysSorted(issuerKeywordRecord);\\\\n expected = [...expected]; /* in case hardened*/\\\\n expected.sort();\\\\n assert.assert(\\\\n sameStructure.sameStructure(actual, harden(expected)),\\\\n assert.details`keywords: ${actual} were not as expected: ${expected}`);},\\\\n\\\\n\\\\n rejectIfNotProposal: (offerHandle, expected) => {\\\\n const { proposal: actual } = zcf.getOffer(offerHandle);\\\\n rejectKeysIf(offerHandle, actual.give, expected.give);\\\\n rejectKeysIf(offerHandle, actual.want, expected.want);\\\\n rejectKeysIf(offerHandle, actual.exit, expected.exit);},\\\\n\\\\n checkIfProposal: (offerHandle, expected) => {\\\\n const { proposal: actual } = zcf.getOffer(offerHandle);\\\\n return (\\\\n /* Check that the \\\\\\\"give\\\\\\\" keys match expected keys.*/\\\\n checkKeys(actual.give, expected.give) &&\\\\n /* Check that the \\\\\\\"want\\\\\\\" keys match expected keys.*/\\\\n checkKeys(actual.want, expected.want) &&\\\\n /* Check that the \\\\\\\"exit\\\\\\\" key (i.e. \\\\\\\"onDemand\\\\\\\") matches the expected key.*/\\\\n checkKeys(actual.exit, expected.exit));},\\\\n\\\\n\\\\n getActiveOffers: (handles) =>\\\\n zcf.getOffers(zcf.getOfferStatuses(handles).active),\\\\n rejectOffer,\\\\n\\\\n /**\\\\n * Check whether an update to currentAllocation satisfies\\\\n * proposal.want. Note that this is half of the offer safety\\\\n * check; whether the allocation constitutes a refund is not\\\\n * checked. Allocation is merged with currentAllocation\\\\n * (allocations' values prevailing if the keywords are the same)\\\\n * to produce the newAllocation.\\\\n * @param {OfferHandle} offerHandle\\\\n * @param {allocation} amountKeywordRecord\\\\n * @returns {boolean}\\\\n */\\\\n satisfies: (offerHandle, allocation) => {\\\\n const currentAllocation = zcf.getCurrentAllocation(offerHandle);\\\\n const newAllocation = mergeAllocations(currentAllocation, allocation);\\\\n const { proposal } = zcf.getOffer(offerHandle);\\\\n return offerSafety.satisfiesWant(zcf.getAmountMath, proposal, newAllocation);},\\\\n\\\\n\\\\n /**\\\\n * Check whether an update to currentAllocation satisfies offer\\\\n * safety. Note that this is the equivalent of `satisfiesWant` ||\\\\n * `satisfiesGive`. Allocation is merged with currentAllocation\\\\n * (allocations' values prevailing if the keywords are the same)\\\\n * to produce the newAllocation.\\\\n * @param {OfferHandle} offerHandle\\\\n * @param {AmountKeywordRecord} allocation\\\\n * @returns {boolean}\\\\n */\\\\n\\\\n isOfferSafe: (offerHandle, allocation) => {\\\\n const currentAllocation = zcf.getCurrentAllocation(offerHandle);\\\\n const newAllocation = mergeAllocations(currentAllocation, allocation);\\\\n const { proposal } = zcf.getOffer(offerHandle);\\\\n return offerSafety.isOfferSafe(zcf.getAmountMath, proposal, newAllocation);},\\\\n\\\\n\\\\n /**\\\\n * Trade between left and right so that left and right end up with\\\\n * the declared gains.\\\\n * @param {offerHandleGainsLossesRecord} keepLeft\\\\n * @param {offerHandleGainsLossesRecord} tryRight\\\\n * @returns {undefined | Error}\\\\n *\\\\n * @typedef {object} offerHandleGainsLossesRecord\\\\n * @property {OfferHandle} offerHandle\\\\n * @property {AmountKeywordRecord} gains - what the offer will\\\\n * gain as a result of this trade\\\\n * @property {AmountKeywordRecord=} losses - what the offer will\\\\n * give up as a result of this trade. Losses is optional, but can\\\\n * only be omitted if the keywords for both offers are the same.\\\\n * If losses is not defined, the gains of the other offer is\\\\n * subtracted.\\\\n */\\\\n trade: (keepLeft, tryRight) => {\\\\n assert.assert(\\\\n keepLeft.offerHandle !== tryRight.offerHandle,\\\\n assert.details`an offer cannot trade with itself`);\\\\n\\\\n let leftAllocation = zcf.getCurrentAllocation(keepLeft.offerHandle);\\\\n let rightAllocation = zcf.getCurrentAllocation(tryRight.offerHandle);\\\\n\\\\n try {\\\\n /* for all the keywords and amounts in leftGains, transfer from*/\\\\n /* right to left*/\\\\n ({ from: rightAllocation, to: leftAllocation } = calcNewAllocations(\\\\n { from: rightAllocation, to: leftAllocation },\\\\n keepLeft.gains,\\\\n tryRight.losses));\\\\n\\\\n /* For all the keywords and amounts in rightGains, transfer from*/\\\\n /* left to right*/\\\\n ({ from: leftAllocation, to: rightAllocation } = calcNewAllocations(\\\\n { from: leftAllocation, to: rightAllocation },\\\\n tryRight.gains,\\\\n keepLeft.losses));}\\\\n\\\\n catch (err) {\\\\n return rejectOffer(tryRight.offerHandle);}\\\\n\\\\n\\\\n /* Check whether reallocate would error before calling. If*/\\\\n /* it would error, reject the right offer and return.*/\\\\n const offerSafeForLeft = helpers.isOfferSafe(\\\\n keepLeft.offerHandle,\\\\n leftAllocation);\\\\n\\\\n const offerSafeForRight = helpers.isOfferSafe(\\\\n tryRight.offerHandle,\\\\n rightAllocation);\\\\n\\\\n if (!(offerSafeForLeft && offerSafeForRight)) {\\\\n console.log(\\\\n `currentLeftAllocation`,\\\\n zcf.getCurrentAllocation(keepLeft.offerHandle));\\\\n\\\\n console.log(\\\\n `currentRightAllocation`,\\\\n zcf.getCurrentAllocation(tryRight.offerHandle));\\\\n\\\\n console.log(`proposed left reallocation`, leftAllocation);\\\\n console.log(`proposed right reallocation`, rightAllocation);\\\\n /* show the contraints*/\\\\n console.log(\\\\n `left want`,\\\\n zcf.getOffer(keepLeft.offerHandle).proposal.want);\\\\n\\\\n console.log(\\\\n `right want`,\\\\n zcf.getOffer(tryRight.offerHandle).proposal.want);\\\\n\\\\n\\\\n if (!offerSafeForLeft) {\\\\n console.log(`offer not safe for left`);}\\\\n\\\\n if (!offerSafeForRight) {\\\\n console.log(`offer not safe for right`);}\\\\n\\\\n return rejectOffer(tryRight.offerHandle);}\\\\n\\\\n zcf.reallocate(\\\\n [keepLeft.offerHandle, tryRight.offerHandle],\\\\n [leftAllocation, rightAllocation]);\\\\n\\\\n return undefined;},\\\\n\\\\n\\\\n /**\\\\n * If the two handles can trade, then swap their compatible assets,\\\\n * marking both offers as complete.\\\\n *\\\\n * The surplus remains with the original offer. For example if\\\\n * offer A gives 5 moola and offer B only wants 3 moola, offer A\\\\n * retains 2 moola.\\\\n *\\\\n * If the keep offer is no longer active (it was already completed), the try\\\\n * offer will be rejected with a message (provided by 'keepHandleInactiveMsg').\\\\n *\\\\n * TODO: If the try offer is no longer active, swap() should terminate with\\\\n * a useful error message, like defaultRejectMsg.\\\\n *\\\\n * If the swap fails, no assets are transferred, and the 'try' offer is rejected.\\\\n *\\\\n * @param {OfferHandle} keepHandle\\\\n * @param {OfferHandle} tryHandle\\\\n * @param {String} [keepHandleInactiveMsg]\\\\n */\\\\n swap: (\\\\n keepHandle,\\\\n tryHandle,\\\\n keepHandleInactiveMsg = 'prior offer is unavailable') =>\\\\n {\\\\n if (!zcf.isOfferActive(keepHandle)) {\\\\n throw helpers.rejectOffer(tryHandle, keepHandleInactiveMsg);}\\\\n\\\\n\\\\n helpers.trade(\\\\n {\\\\n offerHandle: keepHandle,\\\\n gains: zcf.getOffer(keepHandle).proposal.want },\\\\n\\\\n {\\\\n offerHandle: tryHandle,\\\\n gains: zcf.getOffer(tryHandle).proposal.want });\\\\n\\\\n\\\\n\\\\n zcf.complete([keepHandle, tryHandle]);\\\\n return defaultAcceptanceMsg;},\\\\n\\\\n\\\\n /**\\\\n * Make an offerHook that wraps the provided `offerHook`, to first\\\\n * check the submitted offer against an `expected` record that says\\\\n * what shape of proposal is acceptable.\\\\n *\\\\n * This ExpectedRecord is like a Proposal, but the amounts in 'want'\\\\n * and 'give' should be null; the exit clause should specify a rule with\\\\n * null contents. If the client submits an Offer which does not match\\\\n * these expectations, that offer will be rejected (and refunded).\\\\n *\\\\n * @param {OfferHook} offerHook\\\\n * @param {ExpectedRecord} expected\\\\n *\\\\n * @typedef ExpectedRecord\\\\n * @property {TODO} [want]\\\\n * @property {TODO} [give]\\\\n * @property {TODO} [exit]\\\\n */\\\\n checkHook: (offerHook, expected) => offerHandle => {\\\\n helpers.rejectIfNotProposal(offerHandle, expected);\\\\n return offerHook(offerHandle);},\\\\n\\\\n\\\\n /**\\\\n * Return a Promise for an OfferHandle.\\\\n *\\\\n * This offer will have an empty 'give' and 'want', making it useful\\\\n * for contracts to use for unrestricted internal asset reallocation.\\\\n * One example is the Autoswap contract, which uses an empty offer\\\\n * to manage internal escrowed assets.\\\\n *\\\\n * @returns {Promise<OfferHandle>}\\\\n */\\\\n makeEmptyOffer: () =>\\\\n new index.HandledPromise(resolve => {\\\\n const invite = zcf.makeInvitation(\\\\n offerHandle => resolve(offerHandle),\\\\n 'empty offer');\\\\n\\\\n index.E(zoeService).offer(invite);}),\\\\n\\\\n\\\\n /**\\\\n * Escrow a payment with Zoe and reallocate the amount of the\\\\n * payment to a recipient.\\\\n *\\\\n * @param {Object} obj\\\\n * @param {Amount} obj.amount\\\\n * @param {Payment} obj.payment\\\\n * @param {String} obj.keyword\\\\n * @param {OfferHandle} obj.recipientHandle\\\\n * @returns {Promise<undefined>}\\\\n */\\\\n escrowAndAllocateTo: ({ amount, payment, keyword, recipientHandle }) => {\\\\n /* We will create a temporary offer to be able to escrow our payment*/\\\\n /* with Zoe.*/\\\\n let tempHandle;\\\\n\\\\n /* We need to make an invite and store the offerHandle of that*/\\\\n /* invite for future use.*/\\\\n const contractSelfInvite = zcf.makeInvitation(\\\\n offerHandle => tempHandle = offerHandle,\\\\n 'self invite');\\\\n\\\\n /* To escrow the payment, we must get the Zoe Service facet and*/\\\\n /* make an offer*/\\\\n const proposal = harden({ give: { Temp: amount } });\\\\n const payments = harden({ Temp: payment });\\\\n\\\\n return index.E(zcf.getZoeService()).\\\\n offer(contractSelfInvite, proposal, payments).\\\\n then(() => {\\\\n /* At this point, the temporary offer has the amount from the*/\\\\n /* payment but nothing else. The recipient offer may have any*/\\\\n /* allocation, so we can't assume the allocation is currently empty for this*/\\\\n /* keyword.*/\\\\n\\\\n helpers.trade(\\\\n {\\\\n offerHandle: tempHandle,\\\\n gains: {},\\\\n losses: { Temp: amount } },\\\\n\\\\n {\\\\n offerHandle: recipientHandle,\\\\n gains: { [keyword]: amount } });\\\\n\\\\n\\\\n\\\\n /* Complete the temporary offerHandle*/\\\\n zcf.complete([tempHandle]);\\\\n\\\\n /* Now, the temporary offer no longer exists, but the recipient*/\\\\n /* offer is allocated the value of the payment.*/});},\\\\n\\\\n\\\\n /* * Given a brand, assert that the mathHelpers for that issuer\\\\n * are 'nat' mathHelpers\\\\n */\\\\n\\\\n assertNatMathHelpers: brand => {\\\\n const amountMath = zcf.getAmountMath(brand);\\\\n assert.assert(\\\\n amountMath.getMathHelpersName() === 'nat',\\\\n assert.details`issuer must have natMathHelpers`);} });\\\\n\\\\n\\\\n\\\\n return helpers;};exports.defaultAcceptanceMsg = defaultAcceptanceMsg;exports.defaultRejectMsg = defaultRejectMsg;exports.makeZoeHelpers = makeZoeHelpers;\\\",\\n \\\"packages/zoe/src/contractSupport/index.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var auctions = require('./auctions.js');var safeMath = require('./safeMath.js');var bondingCurves = require('./bondingCurves.js');var stateMachine = require('./stateMachine.js');var zoeHelpers = require('./zoeHelpers.js');exports.closeAuction = auctions.closeAuction;exports.secondPriceLogic = auctions.secondPriceLogic;exports.natSafeMath = safeMath.natSafeMath;exports.calcLiqValueToMint = bondingCurves.calcLiqValueToMint;exports.calcValueToRemove = bondingCurves.calcValueToRemove;exports.getInputPrice = bondingCurves.getInputPrice;exports.makeStateMachine = stateMachine.makeStateMachine;exports.defaultAcceptanceMsg = zoeHelpers.defaultAcceptanceMsg;exports.defaultRejectMsg = zoeHelpers.defaultRejectMsg;exports.makeZoeHelpers = zoeHelpers.makeZoeHelpers;\\\"\\n};\\n const nsBundle = {};\\n\\n function createEvalString(filename) {\\n const code = sourceBundle[filename];\\n if (!code) {\\n return undefined;\\n }\\n return `\\\\\\n(function getExport(require, exports) { \\\\\\n 'use strict'; \\\\\\n const module = { exports }; \\\\\\n \\\\\\n ${code}\\n return module.exports;\\n})\\n//# sourceURL=${filePrefix}/${filename}\\n`;\\n }\\n\\n function computeExports(filename, exportPowers, exports) {\\n const { require: systemRequire, _log } = exportPowers;\\n // This captures the endowed require.\\n const match = filename.match(/^(.*)\\\\/[^/]+$/);\\n const thisdir = match ? match[1] : '.';\\n const contextRequire = mod => {\\n // Do path algebra to find the actual source.\\n const els = mod.split('/');\\n let prefix;\\n if (els[0][0] === '@') {\\n // Scoped name.\\n prefix = els.splice(0, 2).join('/');\\n } else if (els[0][0] === '.') {\\n // Relative.\\n els.unshift(...thisdir.split('/'));\\n } else {\\n // Bare or absolute.\\n prefix = els.splice(0, 1);\\n }\\n\\n const suffix = [];\\n for (const el of els) {\\n if (el === '.' || el === '') {\\n // Do nothing.\\n } else if (el === '..') {\\n // Traverse upwards.\\n suffix.pop();\\n } else {\\n suffix.push(el);\\n }\\n }\\n\\n // log(mod, prefix, suffix);\\n if (prefix !== undefined) {\\n suffix.unshift(prefix);\\n }\\n let modPath = suffix.join('/');\\n if (modPath.startsWith('./')) {\\n modPath = modPath.slice(2);\\n }\\n // log('requiring', modPath);\\n if (!(modPath in nsBundle)) {\\n // log('evaluating', modPath);\\n // Break cycles, but be tolerant of modules\\n // that completely override their exports object.\\n nsBundle[modPath] = {};\\n nsBundle[modPath] = computeExports(\\n modPath,\\n exportPowers,\\n nsBundle[modPath],\\n );\\n }\\n\\n // log('returning', nsBundle[modPath]);\\n return nsBundle[modPath];\\n };\\n\\n const code = createEvalString(filename);\\n if (!code) {\\n // log('missing code for', filename, sourceBundle);\\n if (systemRequire) {\\n return systemRequire(filename);\\n }\\n throw Error(\\n `require(${JSON.stringify(\\n filename,\\n )}) failed; no toplevel require endowment`,\\n );\\n }\\n\\n // log('evaluating', code);\\n return nestedEvaluate(code)(contextRequire, exports);\\n }\\n\\n // Evaluate the entrypoint recursively, seeding the exports.\\n const systemRequire = typeof require === 'undefined' ? undefined : require;\\n return computeExports(entrypoint, { require: systemRequire }, {});\\n}\\n//# sourceURL=/bundled-source-preamble.js\\n\",\"sourceMap\":\"//# sourceURL=/bundled-source-preamble.js\\n\",\"moduleFormat\":\"nestedEvaluate\"}]","slots":[]},"p-66"],"syscalls":[{"d":["fulfillToPresence","p-66","o+7"],"response":null}],"crankNumber":16}
v5.t.7 :: {"d":["deliver","o+1","install",{"body":"[{\"source\":\"function getExportWithNestedEvaluate(filePrefix) {\\n 'use strict';\\n // Serialised sources.\\n if (filePrefix === undefined) {\\n filePrefix = \\\"/bundled-source\\\";\\n }\\n const moduleFormat = \\\"nestedEvaluate\\\";\\n const entrypoint = \\\"packages/zoe/src/contracts/sellItems.js\\\";\\n const sourceBundle = {\\n \\\"packages/zoe/src/contracts/sellItems.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../../assert/src/assert.js');var zoeHelpers = require('../contractSupport/zoeHelpers.js');\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nrequire('../contractSupport/index.js'); /* global harden */ /** @typedef {Ximport('../zoe').ContractFacet} ContractFacet */ /**\\\\n * Sell items in exchange for money. Items may be fungible or\\\\n * non-fungible and multiple items may be bought at once. Money must\\\\n * be fungible.\\\\n *\\\\n * The `pricePerItem` is to be set in the terms. It is expected that all items\\\\n * are sold for the same uniform price.\\\\n *\\\\n * The initial offer should be { give: { Items: items } }, accompanied by\\\\n * terms as described above.\\\\n * Buyers use offers that match { want: { Items: items } give: { Money: m } }.\\\\n * The items provided should match particular items that the seller still has\\\\n * available to sell, and the money should be pricePerItem times the number of\\\\n * items requested.\\\\n *\\\\n * @typedef {Ximport('../zoe').ContractFacet} ContractFacet\\\\n * @param {ContractFacet} zcf\\\\n */\\\\nconst makeContract = zcf => {\\\\n const allKeywords = ['Items', 'Money'];\\\\n const {\\\\n assertKeywords,\\\\n rejectOffer,\\\\n checkHook,\\\\n assertNatMathHelpers,\\\\n trade } =\\\\n zoeHelpers.makeZoeHelpers(zcf);\\\\n assertKeywords(harden(allKeywords));\\\\n\\\\n const { pricePerItem } = zcf.getInstanceRecord().terms;\\\\n assertNatMathHelpers(pricePerItem.brand);\\\\n let sellerOfferHandle;\\\\n\\\\n const sellerOfferHook = offerHandle => {\\\\n sellerOfferHandle = offerHandle;\\\\n return zoeHelpers.defaultAcceptanceMsg;};\\\\n\\\\n\\\\n const buyerOfferHook = buyerOfferHandle => {\\\\n const { brandKeywordRecord } = zcf.getInstanceRecord();\\\\n const [sellerAllocation, buyerAllocation] = zcf.getCurrentAllocations(\\\\n [sellerOfferHandle, buyerOfferHandle],\\\\n [brandKeywordRecord, brandKeywordRecord]);\\\\n\\\\n const currentItemsForSale = sellerAllocation.Items;\\\\n const providedMoney = buyerAllocation.Money;\\\\n\\\\n const { proposal } = zcf.getOffer(buyerOfferHandle);\\\\n const wantedItems = proposal.want.Items;\\\\n const numItemsWanted = wantedItems.value.length;\\\\n const totalCostValue = pricePerItem.value * numItemsWanted;\\\\n const moneyAmountMaths = zcf.getAmountMath(pricePerItem.brand);\\\\n const itemsAmountMath = zcf.getAmountMath(wantedItems.brand);\\\\n\\\\n const totalCost = moneyAmountMaths.make(totalCostValue);\\\\n\\\\n /* Check that the wanted items are still for sale.*/\\\\n if (!itemsAmountMath.isGTE(currentItemsForSale, wantedItems)) {\\\\n return rejectOffer(\\\\n buyerOfferHandle,\\\\n `Some of the wanted items were not available for sale`);}\\\\n\\\\n\\\\n\\\\n /* Check that the money provided to pay for the items is greater than the totalCost.*/\\\\n if (!moneyAmountMaths.isGTE(providedMoney, totalCost)) {\\\\n return rejectOffer(\\\\n buyerOfferHandle,\\\\n `More money (${totalCost}) is required to buy these items`);}\\\\n\\\\n\\\\n\\\\n /* Reallocate. We are able to trade by only defining the gains*/\\\\n /* (omitting the losses) because the keywords for both offers are*/\\\\n /* the same, so the gains for one offer are the losses for the*/\\\\n /* other.*/\\\\n trade(\\\\n { offerHandle: sellerOfferHandle, gains: { Money: providedMoney } },\\\\n { offerHandle: buyerOfferHandle, gains: { Items: wantedItems } });\\\\n\\\\n\\\\n /* Complete the buyer offer.*/\\\\n zcf.complete([buyerOfferHandle]);\\\\n return zoeHelpers.defaultAcceptanceMsg;};\\\\n\\\\n\\\\n const buyerExpected = harden({\\\\n want: { Items: null },\\\\n give: { Money: null } });\\\\n\\\\n\\\\n zcf.initPublicAPI(\\\\n harden({\\\\n makeBuyerInvite: () => {\\\\n const itemsAmount = zcf.getCurrentAllocation(sellerOfferHandle).Items;\\\\n const itemsAmountMath = zcf.getAmountMath(itemsAmount.brand);\\\\n assert.assert(\\\\n sellerOfferHandle && !itemsAmountMath.isEmpty(itemsAmount),\\\\n assert.details`no items are for sale`);\\\\n\\\\n return zcf.makeInvitation(\\\\n checkHook(buyerOfferHook, buyerExpected),\\\\n 'buyer');},\\\\n\\\\n\\\\n getAvailableItems: () => {\\\\n if (!sellerOfferHandle) {\\\\n throw new Error(`no items have been escrowed`);}\\\\n\\\\n return zcf.getCurrentAllocation(sellerOfferHandle).Items;},\\\\n\\\\n getItemsIssuer: () => zcf.getInstanceRecord().issuerKeywordRecord.Items }));\\\\n\\\\n\\\\n\\\\n return zcf.makeInvitation(sellerOfferHook, 'seller');};\\\\n\\\\n\\\\nharden(makeContract);exports.makeContract = makeContract;\\\",\\n \\\"packages/assert/src/assert.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* Copyright (C) 2019 Agoric, under Apache License 2.0*/ /* @ts-check*/ /* This module assumes the de-facto standard `console` host object.*/ /* To the extent that this `console` is considered a resource,*/ /* this module must be considered a resource module.*/ /**\\\\n * Prepend the correct indefinite article onto a noun, typically a typeof result\\\\n * e.g., \\\\\\\"an Object\\\\\\\" vs. \\\\\\\"a Number\\\\\\\"\\\\n *\\\\n * @param {string} str The noun to prepend\\\\n * @returns {string} The noun prepended with a/an\\\\n */\\\\nfunction an(str) {\\\\n str = `${str}`;\\\\n if (str.length >= 1 && 'aeiouAEIOU'.includes(str[0])) {\\\\n return `an ${str}`;}\\\\n\\\\n return `a ${str}`;}\\\\n\\\\nharden(an);\\\\n\\\\n/**\\\\n * Like `JSON.stringify` but does not blow up if given a cycle. This is not\\\\n * intended to be a serialization to support any useful unserialization,\\\\n * or any programmatic use of the resulting string. The string is intended\\\\n * only for showing a human, in order to be informative enough for some\\\\n * logging purposes. As such, this `cycleTolerantStringify` has an\\\\n * imprecise specification and may change over time.\\\\n *\\\\n * The current `cycleTolerantStringify` possibly emits too many \\\\\\\"seen\\\\\\\"\\\\n * markings: Not only for cycles, but also for repeated subtrees by\\\\n * object identity.\\\\n */\\\\nfunction cycleTolerantStringify(payload) {\\\\n const seenSet = new Set();\\\\n const replacer = (_, val) => {\\\\n if (typeof val === 'object' && val !== null) {\\\\n if (seenSet.has(val)) {\\\\n return '<**seen**>';}\\\\n\\\\n seenSet.add(val);}\\\\n\\\\n return val;};\\\\n\\\\n return JSON.stringify(payload, replacer);}\\\\n\\\\n\\\\nconst declassifiers = new WeakSet();\\\\n\\\\n/**\\\\n * To \\\\\\\"declassify\\\\\\\" and quote a substitution value used in a\\\\n * details`...` template literal, enclose that substitution expression\\\\n * in a call to `q`. This states that the argument should appear quoted (with\\\\n * `JSON.stringify`), in the error message of the thrown error. The payload\\\\n * itself is still passed unquoted to the console as it would be without q.\\\\n *\\\\n * Starting from the example in the `details` comment, say instead that the\\\\n * color the sky is supposed to be is also computed. Say that we still don't\\\\n * want to reveal the sky's actual color, but we do want the thrown error's\\\\n * message to reveal what color the sky was supposed to be:\\\\n * ```js\\\\n * assert.equal(\\\\n * sky.color,\\\\n * color,\\\\n * details`${sky.color} should be ${q(color)}`,\\\\n * );\\\\n * ```\\\\n *\\\\n * @typedef {Object} StringablePayload\\\\n * @property {*} payload The original payload\\\\n * @property {() => string} toString How to print the payload\\\\n *\\\\n * @param {*} payload What to declassify\\\\n * @returns {StringablePayload} The declassified payload\\\\n */\\\\nfunction q(payload) {\\\\n /* Don't harden the payload*/\\\\n const result = Object.freeze({\\\\n payload,\\\\n toString: Object.freeze(() => cycleTolerantStringify(payload)) });\\\\n\\\\n declassifiers.add(result);\\\\n return result;}\\\\n\\\\nharden(q);\\\\n\\\\n/**\\\\n * Use the `details` function as a template literal tag to create\\\\n * informative error messages. The assertion functions take such messages\\\\n * as optional arguments:\\\\n * ```js\\\\n * assert(sky.isBlue(), details`${sky.color} should be \\\\\\\"blue\\\\\\\"`);\\\\n * ```\\\\n * The details template tag returns an object that can print itself with the\\\\n * formatted message in two ways. It will report the real details to the\\\\n * console but include only the typeof information in the thrown error\\\\n * to prevent revealing secrets up the exceptional path. In the example\\\\n * above, the thrown error may reveal only that `sky.color` is a string,\\\\n * whereas the same diagnostic printed to the console reveals that the\\\\n * sky was green.\\\\n *\\\\n * WARNING: this function currently returns an unhardened result, as hardening\\\\n * proved to cause significant performance degradation. Consequently, callers\\\\n * should take care to use it only in contexts where this lack of hardening\\\\n * does not present a hazard. In current usage, a `details` template literal\\\\n * may only appear either as an argument to `assert`, where we know hardening\\\\n * won't matter, or inside another hardened object graph, where hardening is\\\\n * already ensured. However, there is currently no means to enfoce these\\\\n * constraints, so users are required to employ this function with caution.\\\\n * Our intent is to eventually have a lint rule that will check for\\\\n * inappropriate uses or find an alternative means of implementing `details`\\\\n * that does not encounter the performance issue. The final disposition of\\\\n * this is being discussed and tracked in issue #679 in the agoric-sdk\\\\n * repository.\\\\n *\\\\n * @typedef {Object} Complainer An object that has custom assert behaviour\\\\n * @property {() => Error} complain Return an Error to throw, and print details to console\\\\n *\\\\n * @typedef {string|Complainer} Details Either a plain string, or made by details``\\\\n *\\\\n * @param {TemplateStringsArray | string[]} template The template to format\\\\n * @param {any[]} args Arguments to the template\\\\n * @returns {Complainer} The complainer for these details\\\\n */\\\\nfunction details(template, ...args) {\\\\n /* const complainer = harden({ // remove harden per above discussion*/\\\\n const complainer = {\\\\n complain() {\\\\n const interleaved = [template[0]];\\\\n const parts = [template[0]];\\\\n for (let i = 0; i < args.length; i += 1) {\\\\n let arg = args[i];\\\\n let argStr;\\\\n if (declassifiers.has(arg)) {\\\\n argStr = `${arg}`;\\\\n arg = arg.payload;} else\\\\n {\\\\n argStr = `(${an(typeof arg)})`;}\\\\n\\\\n\\\\n /* Remove the extra spaces (since console.error puts them*/\\\\n /* between each interleaved).*/\\\\n const priorWithoutSpace = (interleaved.pop() || '').replace(/ $/, '');\\\\n if (priorWithoutSpace !== '') {\\\\n interleaved.push(priorWithoutSpace);}\\\\n\\\\n\\\\n const nextWithoutSpace = template[i + 1].replace(/^ /, '');\\\\n interleaved.push(arg, nextWithoutSpace);\\\\n\\\\n parts.push(argStr, template[i + 1]);}\\\\n\\\\n if (interleaved[interleaved.length - 1] === '') {\\\\n interleaved.pop();}\\\\n\\\\n if (args.length >= 1) {\\\\n parts.push('\\\\\\\\nSee console for error data.');}\\\\n\\\\n const err = new Error(parts.join(''));\\\\n console.error('LOGGED ERROR:', ...interleaved, err);\\\\n /* eslint-disable-next-line no-debugger*/\\\\n debugger;\\\\n return err;} };\\\\n\\\\n\\\\n /* });*/\\\\n return complainer;}\\\\n\\\\nharden(details);\\\\n\\\\n/**\\\\n * Fail an assertion, recording details to the console and\\\\n * raising an exception with just type information.\\\\n *\\\\n * The optional `optDetails` can be a string for backwards compatibility\\\\n * with the nodejs assertion library.\\\\n * @param {Details} [optDetails] The details of what was asserted\\\\n * @returns {never}\\\\n */\\\\nfunction fail(optDetails = details`Assert failed`) {\\\\n if (typeof optDetails === 'string') {\\\\n /* If it is a string, use it as the literal part of the template so*/\\\\n /* it doesn't get quoted.*/\\\\n optDetails = details([optDetails]);}\\\\n\\\\n throw optDetails.complain();}\\\\n\\\\n\\\\n/**\\\\n * @param {*} flag The truthy/falsy value\\\\n * @param {Details} [optDetails] The details to throw\\\\n * @returns {asserts flag}\\\\n */\\\\nfunction assert(flag, optDetails = details`Check failed`) {\\\\n if (!flag) {\\\\n throw fail(optDetails);}}\\\\n\\\\n\\\\n\\\\n/**\\\\n * Assert that two values must be `Object.is`.\\\\n * @param {*} actual The value we received\\\\n * @param {*} expected What we wanted\\\\n * @param {Details} [optDetails] The details to throw\\\\n * @returns {void}\\\\n */\\\\nfunction equal(\\\\nactual,\\\\nexpected,\\\\noptDetails = details`Expected ${actual} is same as ${expected}`)\\\\n{\\\\n assert(Object.is(actual, expected), optDetails);}\\\\n\\\\n\\\\n/**\\\\n * Assert an expected typeof result.\\\\n * @type {AssertTypeof}\\\\n * @param {any} specimen The value to get the typeof\\\\n * @param {string} typename The expected name\\\\n * @param {Details} [optDetails] The details to throw\\\\n */\\\\nconst assertTypeof = (specimen, typename, optDetails) => {\\\\n assert(\\\\n typeof typename === 'string',\\\\n details`${q(typename)} must be a string`);\\\\n\\\\n if (optDetails === undefined) {\\\\n /* Like*/\\\\n /* ```js*/\\\\n /* optDetails = details`${specimen} must be ${q(an(typename))}`;*/\\\\n /* ```*/\\\\n /* except it puts the typename into the literal part of the template*/\\\\n /* so it doesn't get quoted.*/\\\\n optDetails = details(['', ` must be ${an(typename)}`], specimen);}\\\\n\\\\n equal(typeof specimen, typename, optDetails);};\\\\n\\\\n\\\\n/**\\\\n * assert that expr is truthy, with an optional details to describe\\\\n * the assertion. It is a tagged template literal like\\\\n * ```js\\\\n * assert(expr, details`....`);`\\\\n * ```\\\\n * If expr is falsy, then the template contents are reported to the\\\\n * console and also in a thrown error.\\\\n *\\\\n * The literal portions of the template are assumed non-sensitive, as\\\\n * are the `typeof` types of the substitution values. These are\\\\n * assembled into the thrown error message. The actual contents of the\\\\n * substitution values are assumed sensitive, to be revealed to the\\\\n * console only. We assume only the virtual platform's owner can read\\\\n * what is written to the console, where the owner is in a privileged\\\\n * position over computation running on that platform.\\\\n *\\\\n * The optional `optDetails` can be a string for backwards compatibility\\\\n * with the nodejs assertion library.\\\\n * @type {typeof assert & { typeof: AssertTypeof, fail: typeof fail, equal: typeof equal }}\\\\n */\\\\nconst assertCombined = Object.assign(assert, {\\\\n equal,\\\\n fail,\\\\n typeof: assertTypeof });\\\\n\\\\nharden(assertCombined);exports.an = an;exports.assert = assertCombined;exports.details = details;exports.q = q;\\\",\\n \\\"packages/zoe/src/contractSupport/auctions.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true }); /* global harden */\\\\n\\\\nconst secondPriceLogic = (bidAmountMath, bidOfferHandles, bids) => {\\\\n let highestBid = bidAmountMath.getEmpty();\\\\n let secondHighestBid = bidAmountMath.getEmpty();\\\\n let highestBidOfferHandle;\\\\n /* eslint-disable-next-line array-callback-return*/\\\\n bidOfferHandles.map((offerHandle, i) => {\\\\n const bid = bids[i];\\\\n /* If the bid is greater than the highestBid, it's the new highestBid*/\\\\n if (bidAmountMath.isGTE(bid, highestBid)) {\\\\n secondHighestBid = highestBid;\\\\n highestBid = bid;\\\\n highestBidOfferHandle = offerHandle;} else\\\\n if (bidAmountMath.isGTE(bid, secondHighestBid)) {\\\\n /* If the bid is not greater than the highest bid, but is greater*/\\\\n /* than the second highest bid, it is the new second highest bid.*/\\\\n secondHighestBid = bid;}});\\\\n\\\\n\\\\n return harden({\\\\n winnerOfferHandle: highestBidOfferHandle,\\\\n winnerBid: highestBid,\\\\n price: secondHighestBid });};\\\\n\\\\n\\\\n\\\\nconst closeAuction = (\\\\nzcf,\\\\n{ auctionLogicFn, sellerOfferHandle, allBidHandles }) =>\\\\n{\\\\n const { brandKeywordRecord } = zcf.getInstanceRecord();\\\\n const bidAmountMath = zcf.getAmountMath(brandKeywordRecord.Ask);\\\\n const assetAmountMath = zcf.getAmountMath(brandKeywordRecord.Asset);\\\\n\\\\n /* Filter out any inactive bids*/\\\\n const { active: activeBidHandles } = zcf.getOfferStatuses(\\\\n harden(allBidHandles));\\\\n\\\\n\\\\n const getBids = amountsKeywordRecord => amountsKeywordRecord.Bid;\\\\n const bids = zcf.getCurrentAllocations(activeBidHandles).map(getBids);\\\\n const assetAmount = zcf.getOffer(sellerOfferHandle).proposal.give.Asset;\\\\n\\\\n const { winnerOfferHandle, winnerBid, price } = auctionLogicFn(\\\\n bidAmountMath,\\\\n activeBidHandles,\\\\n bids);\\\\n\\\\n\\\\n /* The winner gets to keep the difference between their bid and the*/\\\\n /* price paid.*/\\\\n const winnerRefund = bidAmountMath.subtract(winnerBid, price);\\\\n\\\\n const newSellerAmounts = { Asset: assetAmountMath.getEmpty(), Ask: price };\\\\n const newWinnerAmounts = { Asset: assetAmount, Bid: winnerRefund };\\\\n\\\\n /* Everyone else gets a refund so their values remain the*/\\\\n /* same.*/\\\\n zcf.reallocate(\\\\n harden([sellerOfferHandle, winnerOfferHandle]),\\\\n harden([newSellerAmounts, newWinnerAmounts]));\\\\n\\\\n const allOfferHandles = harden([sellerOfferHandle, ...activeBidHandles]);\\\\n zcf.complete(allOfferHandles);};exports.closeAuction = closeAuction;exports.secondPriceLogic = secondPriceLogic;\\\",\\n \\\"node_modules/@agoric/nat/dist/nat.esm.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* Copyright (C) 2011 Google Inc.*/ /* Copyright (C) 2018 Agoric*/ /**/ /* Licensed under the Apache License, Version 2.0 (the \\\\\\\"License\\\\\\\");*/ /* you may not use this file except in compliance with the License.*/ /* You may obtain a copy of the License at*/ /**/ /* http://www.apache.org/licenses/LICENSE-2.0*/ /**/ /* Unless required by applicable law or agreed to in writing, software*/ /* distributed under the License is distributed on an \\\\\\\"AS IS\\\\\\\" BASIS,*/ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*/ /* See the License for the specific language governing permissions and*/ /* limitations under the License.*/ /**\\\\n * Is allegedNum a number in the contiguous range of exactly and\\\\n * unambiguously representable natural numbers (non-negative integers)?\\\\n *\\\\n * <p>See <a href=\\\\n * \\\\\\\"https://code.google.com/p/google-caja/issues/detail?id=1801\\\\\\\"\\\\n * >Issue 1801: Nat must include at most (2**53)-1</a>\\\\n * and <a href=\\\\n * \\\\\\\"https://mail.mozilla.org/pipermail/es-discuss/2013-July/031716.html\\\\\\\"\\\\n * >Allen Wirfs-Brock's suggested phrasing</a> on es-discuss.\\\\n */\\\\n\\\\nfunction Nat(allegedNum) {\\\\n if (!Number.isSafeInteger(allegedNum)) {\\\\n throw new RangeError('not a safe integer');}\\\\n\\\\n\\\\n if (allegedNum < 0) {\\\\n throw new RangeError('negative');}\\\\n\\\\n\\\\n return allegedNum;}exports.default = Nat;\\\",\\n \\\"packages/zoe/src/contractSupport/safeMath.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\nnat_esm = require('../../../../node_modules/@agoric/nat/dist/nat.esm.js'); /* global harden */ /**\\\\n * These operations should be used for calculations with the\\\\n * values of basic fungible tokens.\\\\n */\\\\nconst natSafeMath = harden({\\\\n add: (x, y) => nat_esm.default(x + y),\\\\n subtract: (x, y) => nat_esm.default(x - y),\\\\n multiply: (x, y) => nat_esm.default(x * y),\\\\n floorDivide: (x, y) => nat_esm.default(Math.floor(x / y)) });exports.natSafeMath = natSafeMath;\\\",\\n \\\"packages/zoe/src/contractSupport/bondingCurves.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../../assert/src/assert.js');var safeMath = require('./safeMath.js');\\\\n\\\\n\\\\nconst { add, subtract, multiply, floorDivide } = safeMath.natSafeMath;\\\\n\\\\n/**\\\\n * Contains the logic for calculating how much should be given\\\\n * back to the user in exchange for what they sent in. It also\\\\n * calculates the new amount of the assets in the pool. Reused in\\\\n * several different places, including to check whether an offer\\\\n * is valid, getting the current price for an asset on user\\\\n * request, and to do the actual reallocation after an offer has\\\\n * been made.\\\\n * @param {Object} params\\\\n * @param {number} params.inputValue - the value of the asset sent\\\\n * in to be swapped\\\\n * @param {number} params.inputReserve - the value in the liquidity\\\\n * pool of the kind of asset sent in\\\\n * @param {number} params.outputReserve - the value in the liquidity\\\\n * pool of the kind of asset to be sent out\\\\n * @param {number} params.feeBasisPoints=30 - the fee taken in\\\\n * basis points. The default is 0.3% or 30 basis points. The fee is taken from\\\\n * inputValue\\\\n * @returns {number} outputValue - the current price, in value form\\\\n */\\\\nconst getInputPrice = ({\\\\n inputValue,\\\\n inputReserve,\\\\n outputReserve,\\\\n feeBasisPoints = 30 }) =>\\\\n{\\\\n const oneMinusFeeInTenThousandths = subtract(10000, feeBasisPoints);\\\\n const inputWithFee = multiply(inputValue, oneMinusFeeInTenThousandths);\\\\n const numerator = multiply(inputWithFee, outputReserve);\\\\n const denominator = add(multiply(inputReserve, 10000), inputWithFee);\\\\n\\\\n const outputValue = floorDivide(numerator, denominator);\\\\n return outputValue;};\\\\n\\\\n\\\\nfunction assertDefined(label, value) {\\\\n assert.assert(value !== undefined, assert.details`${label} value required`);}\\\\n\\\\n\\\\n/* Calculate how many liquidity tokens we should be minting to send back to the*/\\\\n/* user when adding liquidity. Calculations are based on the comparing the*/\\\\n/* inputValue to the inputReserve. If the current supply is zero, just return*/\\\\n/* the inputValue.*/\\\\nconst calcLiqValueToMint = ({\\\\n liqTokenSupply,\\\\n inputValue,\\\\n inputReserve }) =>\\\\n{\\\\n assertDefined('liqTokenSupply', liqTokenSupply);\\\\n assertDefined('inputValue', inputValue);\\\\n assertDefined('inputReserve', inputReserve);\\\\n return liqTokenSupply > 0 ?\\\\n floorDivide(multiply(inputValue, liqTokenSupply), inputReserve) :\\\\n inputValue;};\\\\n\\\\n\\\\n/* Calculate how many underlying tokens (in the form of a value) should be*/\\\\n/* returned when removing liquidity.*/\\\\nconst calcValueToRemove = ({\\\\n liqTokenSupply,\\\\n poolValue,\\\\n liquidityValueIn }) =>\\\\n{\\\\n assertDefined('liqTokenSupply', liqTokenSupply);\\\\n assertDefined('liquidityValueIn', liquidityValueIn);\\\\n assertDefined('poolValue', poolValue);\\\\n\\\\n return floorDivide(multiply(liquidityValueIn, poolValue), liqTokenSupply);};exports.calcLiqValueToMint = calcLiqValueToMint;exports.calcValueToRemove = calcValueToRemove;exports.getInputPrice = getInputPrice;\\\",\\n \\\"packages/zoe/src/contractSupport/stateMachine.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\nassert = require('../../../assert/src/assert.js'); /* global harden */ /* allowedTransitions is an array of arrays which gets turned into a\\\\n * map. The map maps string states to an array of potential next\\\\n * states. For example,\\\\n * const allowedTransitions = [\\\\n ['open', ['closed']],\\\\n ['closed', []],\\\\n * ];\\\\n */\\\\nconst makeStateMachine = (initialState, allowedTransitionsArray) => {\\\\n let state = initialState;\\\\n const allowedTransitions = new Map(allowedTransitionsArray);\\\\n return harden({\\\\n canTransitionTo: (nextState) =>\\\\n allowedTransitions.get(state).includes(nextState),\\\\n transitionTo: nextState => {\\\\n assert.assert(allowedTransitions.get(state).includes(nextState));\\\\n state = nextState;},\\\\n\\\\n getStatus: _ => state });};\\\\n\\\\n\\\\nharden(makeStateMachine);exports.makeStateMachine = makeStateMachine;\\\",\\n \\\"packages/eventual-send/src/E.js\\\": \\\"'use strict';\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /* global harden */ /* eslint-disable-next-line spaced-comment*/ /*/ <reference path=\\\\\\\"index.d.ts\\\\\\\" />*/\\\\n\\\\nconst readOnlyProxy = {\\\\n set(_target, _prop, _value) {\\\\n return false;},\\\\n\\\\n isExtensible(_target) {\\\\n return false;},\\\\n\\\\n setPrototypeOf(_target, _value) {\\\\n return false;},\\\\n\\\\n deleteProperty(_target, _prop) {\\\\n return false;} };\\\\n\\\\n\\\\n\\\\n/**\\\\n * A Proxy handler for E(x).\\\\n *\\\\n * @param {*} x Any value passed to E(x)\\\\n * @returns {ProxyHandler} the Proxy handler\\\\n */\\\\nfunction EProxyHandler(x, HandledPromise) {\\\\n return harden({\\\\n ...readOnlyProxy,\\\\n get(_target, p, _receiver) {\\\\n if (`${p}` !== p) {\\\\n return undefined;}\\\\n\\\\n /* Harden this Promise because it's our only opportunity to ensure*/\\\\n /* p1=E(x).foo() is hardened. The Handled Promise API does not (yet)*/\\\\n /* allow the handler to synchronously influence the promise returned*/\\\\n /* by the handled methods, so we must freeze it from the outside. See*/\\\\n /* #95 for details.*/\\\\n return (...args) => harden(HandledPromise.applyMethod(x, p, args));},\\\\n\\\\n apply(_target, _thisArg, argArray = []) {\\\\n return harden(HandledPromise.applyFunction(x, argArray));},\\\\n\\\\n has(_target, _p) {\\\\n /* We just pretend everything exists.*/\\\\n return true;} });}\\\\n\\\\n\\\\n\\\\n\\\\nfunction makeE(HandledPromise) {\\\\n function E(x) {\\\\n const handler = EProxyHandler(x, HandledPromise);\\\\n return harden(new Proxy(() => {}, handler));}\\\\n\\\\n\\\\n const makeEGetterProxy = (x) =>\\\\n new Proxy(Object.create(null), {\\\\n ...readOnlyProxy,\\\\n has(_target, _prop) {\\\\n return true;},\\\\n\\\\n get(_target, prop) {\\\\n return harden(HandledPromise.get(x, prop));} });\\\\n\\\\n\\\\n\\\\n E.G = makeEGetterProxy;\\\\n E.resolve = HandledPromise.resolve;\\\\n E.unwrap = HandledPromise.unwrap;\\\\n\\\\n E.when = (x, onfulfilled = undefined, onrejected = undefined) =>\\\\n HandledPromise.resolve(x).then(onfulfilled, onrejected);\\\\n\\\\n return harden(E);}exports.default = makeE;\\\",\\n \\\"packages/eventual-send/src/index.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var E$1 = require('./E.js'); /* global harden HandledPromise */\\\\n\\\\n\\\\n\\\\nconst {\\\\n defineProperties,\\\\n getOwnPropertyDescriptors,\\\\n getOwnPropertyDescriptor: gopd,\\\\n getPrototypeOf,\\\\n isFrozen } =\\\\nObject;\\\\n\\\\nconst { prototype: promiseProto } = Promise;\\\\nconst { then: originalThen } = promiseProto;\\\\n\\\\n/* 'E' and 'HandledPromise' are exports of the module*/\\\\n\\\\n/* For now:*/\\\\n/* import { HandledPromise, E } from '@agoric/eventual-send';*/\\\\n/* ...*/\\\\n\\\\nconst hp =\\\\ntypeof HandledPromise === 'undefined' ?\\\\n/* eslint-disable-next-line no-use-before-define*/\\\\nmakeHandledPromise(Promise) :\\\\nharden(HandledPromise);\\\\n\\\\n\\\\n\\\\nconst E = E$1.default(hp);\\\\n\\\\n/* the following method (makeHandledPromise) is part*/\\\\n/* of the shim, and will not be exported by the module once the feature*/\\\\n/* becomes a part of standard javascript*/\\\\n\\\\n/**\\\\n * Create a HandledPromise class to have it support eventual send\\\\n * (wavy-dot) operations.\\\\n *\\\\n * Based heavily on nanoq\\\\n * https://github.com/drses/nanoq/blob/master/src/nanoq.js\\\\n *\\\\n * Original spec for the infix-bang (predecessor to wavy-dot) desugaring:\\\\n * https://web.archive.org/web/20161026162206/http://wiki.ecmascript.org/doku.php?id=strawman:concurrency\\\\n *\\\\n * @return {typeof HandledPromise} Handled promise\\\\n */\\\\nfunction makeHandledPromise(Promise) {\\\\n /* xs doesn't support WeakMap in pre-loaded closures*/\\\\n /* aka \\\\\\\"vetted customization code\\\\\\\"*/\\\\n let presenceToHandler;\\\\n let presenceToPromise;\\\\n let promiseToUnsettledHandler;\\\\n let promiseToPresence; /* only for HandledPromise.unwrap*/\\\\n let forwardedPromiseToPromise; /* forwarding, union-find-ish*/\\\\n function ensureMaps() {\\\\n if (!presenceToHandler) {\\\\n presenceToHandler = new WeakMap();\\\\n presenceToPromise = new WeakMap();\\\\n promiseToUnsettledHandler = new WeakMap();\\\\n promiseToPresence = new WeakMap();\\\\n forwardedPromiseToPromise = new WeakMap();}}\\\\n\\\\n\\\\n\\\\n /**\\\\n * You can imagine a forest of trees in which the roots of each tree is an\\\\n * unresolved HandledPromise or a non-Promise, and each node's parent is the\\\\n * HandledPromise to which it was forwarded. We maintain that mapping of\\\\n * forwarded HandledPromise to its resolution in forwardedPromiseToPromise.\\\\n *\\\\n * We use something like the description of \\\\\\\"Find\\\\\\\" with \\\\\\\"Path splitting\\\\\\\"\\\\n * to propagate changes down to the children efficiently:\\\\n * https://en.wikipedia.org/wiki/Disjoint-set_data_structure\\\\n *\\\\n * @param {*} target Any value.\\\\n * @returns {*} If the target was a HandledPromise, the most-resolved parent of it, otherwise the target.\\\\n */\\\\n function shorten(target) {\\\\n let p = target;\\\\n /* Find the most-resolved value for p.*/\\\\n while (forwardedPromiseToPromise.has(p)) {\\\\n p = forwardedPromiseToPromise.get(p);}\\\\n\\\\n const presence = promiseToPresence.get(p);\\\\n if (presence) {\\\\n /* Presences are final, so it is ok to propagate*/\\\\n /* this upstream.*/\\\\n while (target !== p) {\\\\n const parent = forwardedPromiseToPromise.get(target);\\\\n forwardedPromiseToPromise.delete(target);\\\\n promiseToUnsettledHandler.delete(target);\\\\n promiseToPresence.set(target, presence);\\\\n target = parent;}} else\\\\n\\\\n {\\\\n /* We propagate p and remove all other unsettled handlers*/\\\\n /* upstream.*/\\\\n /* Note that everything except presences is covered here.*/\\\\n while (target !== p) {\\\\n const parent = forwardedPromiseToPromise.get(target);\\\\n forwardedPromiseToPromise.set(target, p);\\\\n promiseToUnsettledHandler.delete(target);\\\\n target = parent;}}\\\\n\\\\n\\\\n return target;}\\\\n\\\\n\\\\n /* This special handler accepts Promises, and forwards*/\\\\n /* handled Promises to their corresponding fulfilledHandler.*/\\\\n let forwardingHandler;\\\\n let handle;\\\\n let promiseResolve;\\\\n\\\\n function HandledPromise(executor, unsettledHandler = undefined) {\\\\n if (new.target === undefined) {\\\\n throw new Error('must be invoked with \\\\\\\"new\\\\\\\"');}\\\\n\\\\n let handledResolve;\\\\n let handledReject;\\\\n let resolved = false;\\\\n let resolvedTarget = null;\\\\n let handledP;\\\\n let continueForwarding = () => {};\\\\n const superExecutor = (superResolve, superReject) => {\\\\n handledResolve = value => {\\\\n if (resolved) {\\\\n return resolvedTarget;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n value = shorten(value);\\\\n let targetP;\\\\n if (\\\\n promiseToUnsettledHandler.has(value) ||\\\\n promiseToPresence.has(value))\\\\n {\\\\n targetP = value;} else\\\\n {\\\\n /* We're resolving to a non-promise, so remove our handler.*/\\\\n promiseToUnsettledHandler.delete(handledP);\\\\n targetP = presenceToPromise.get(value);}\\\\n\\\\n /* Ensure our data structure is a propert tree (avoid cycles).*/\\\\n if (targetP && targetP !== handledP) {\\\\n forwardedPromiseToPromise.set(handledP, targetP);} else\\\\n {\\\\n forwardedPromiseToPromise.delete(handledP);}\\\\n\\\\n\\\\n /* Remove stale unsettled handlers, set to canonical form.*/\\\\n shorten(handledP);\\\\n\\\\n /* Ensure our unsettledHandler is cleaned up if not already.*/\\\\n if (promiseToUnsettledHandler.has(handledP)) {\\\\n handledP.then(_ => promiseToUnsettledHandler.delete(handledP));}\\\\n\\\\n\\\\n /* Finish the resolution.*/\\\\n superResolve(value);\\\\n resolved = true;\\\\n resolvedTarget = value;\\\\n\\\\n /* We're resolved, so forward any postponed operations to us.*/\\\\n continueForwarding();\\\\n return resolvedTarget;};\\\\n\\\\n handledReject = err => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n promiseToUnsettledHandler.delete(handledP);\\\\n resolved = true;\\\\n superReject(err);\\\\n continueForwarding();};};\\\\n\\\\n\\\\n handledP = harden(Reflect.construct(Promise, [superExecutor], new.target));\\\\n\\\\n ensureMaps();\\\\n\\\\n const makePostponedHandler = () => {\\\\n /* Create a simple postponedHandler that just postpones until the*/\\\\n /* fulfilledHandler is set.*/\\\\n let donePostponing;\\\\n const interlockP = new Promise(resolve => {\\\\n donePostponing = () => resolve();});\\\\n\\\\n\\\\n const makePostponedOperation = postponedOperation => {\\\\n /* Just wait until the handler is resolved/rejected.*/\\\\n return function postpone(x, ...args) {\\\\n /* console.log(`forwarding ${postponedOperation} ${args[0]}`);*/\\\\n return new HandledPromise((resolve, reject) => {\\\\n interlockP.\\\\n then(_ => {\\\\n /* If targetP is a handled promise, use it, otherwise x.*/\\\\n resolve(HandledPromise[postponedOperation](x, ...args));}).\\\\n\\\\n catch(reject);});};};\\\\n\\\\n\\\\n\\\\n\\\\n const postponedHandler = {\\\\n get: makePostponedOperation('get'),\\\\n applyMethod: makePostponedOperation('applyMethod') };\\\\n\\\\n return [postponedHandler, donePostponing];};\\\\n\\\\n\\\\n if (!unsettledHandler) {\\\\n /* This is insufficient for actual remote handled Promises*/\\\\n /* (too many round-trips), but is an easy way to create a*/\\\\n /* local handled Promise.*/\\\\n [unsettledHandler, continueForwarding] = makePostponedHandler();}\\\\n\\\\n\\\\n const validateHandler = h => {\\\\n if (Object(h) !== h) {\\\\n throw TypeError(`Handler ${h} cannot be a primitive`);}};\\\\n\\\\n\\\\n validateHandler(unsettledHandler);\\\\n\\\\n /* Until the handled promise is resolved, we use the unsettledHandler.*/\\\\n promiseToUnsettledHandler.set(handledP, unsettledHandler);\\\\n\\\\n const rejectHandled = reason => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n handledReject(reason);};\\\\n\\\\n\\\\n const resolveWithPresence = presenceHandler => {\\\\n if (resolved) {\\\\n return resolvedTarget;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n try {\\\\n /* Sanity checks.*/\\\\n validateHandler(presenceHandler);\\\\n\\\\n /* Validate and install our mapped target (i.e. presence).*/\\\\n resolvedTarget = Object.create(null);\\\\n\\\\n /* Create table entries for the presence mapped to the*/\\\\n /* fulfilledHandler.*/\\\\n presenceToPromise.set(resolvedTarget, handledP);\\\\n promiseToPresence.set(handledP, resolvedTarget);\\\\n presenceToHandler.set(resolvedTarget, presenceHandler);\\\\n\\\\n /* We committed to this presence, so resolve.*/\\\\n handledResolve(resolvedTarget);\\\\n return resolvedTarget;}\\\\n catch (e) {\\\\n handledReject(e);\\\\n throw e;}};\\\\n\\\\n\\\\n\\\\n const resolveHandled = async (target, deprecatedPresenceHandler) => {\\\\n if (resolved) {\\\\n return;}\\\\n\\\\n if (forwardedPromiseToPromise.has(handledP)) {\\\\n throw new TypeError('internal: already forwarded');}\\\\n\\\\n try {\\\\n if (deprecatedPresenceHandler) {\\\\n throw TypeError(\\\\n `resolveHandled no longer accepts a handler; use resolveWithPresence`);}\\\\n\\\\n\\\\n\\\\n /* Resolve the target.*/\\\\n handledResolve(target);}\\\\n catch (e) {\\\\n handledReject(e);}};\\\\n\\\\n\\\\n\\\\n /* Invoke the callback to let the user resolve/reject.*/\\\\n executor(\\\\n (...args) => {\\\\n resolveHandled(...args);},\\\\n\\\\n rejectHandled,\\\\n resolveWithPresence);\\\\n\\\\n return handledP;}\\\\n\\\\n\\\\n HandledPromise.prototype = promiseProto;\\\\n Object.setPrototypeOf(HandledPromise, Promise);\\\\n\\\\n function isFrozenPromiseThen(p) {\\\\n return (\\\\n isFrozen(p) &&\\\\n getPrototypeOf(p) === promiseProto &&\\\\n promiseResolve(p) === p &&\\\\n gopd(p, 'then') === undefined &&\\\\n gopd(promiseProto, 'then').value === originalThen /* unnecessary under SES*/);}\\\\n\\\\n\\\\n\\\\n const staticMethods = harden({\\\\n get(target, key) {\\\\n return handle(target, 'get', key);},\\\\n\\\\n getSendOnly(target, key) {\\\\n handle(target, 'get', key);},\\\\n\\\\n applyFunction(target, args) {\\\\n return handle(target, 'applyMethod', undefined, args);},\\\\n\\\\n applyFunctionSendOnly(target, args) {\\\\n handle(target, 'applyMethod', undefined, args);},\\\\n\\\\n applyMethod(target, key, args) {\\\\n return handle(target, 'applyMethod', key, args);},\\\\n\\\\n applyMethodSendOnly(target, key, args) {\\\\n handle(target, 'applyMethod', key, args);},\\\\n\\\\n resolve(value) {\\\\n ensureMaps();\\\\n /* Resolving a Presence returns the pre-registered handled promise.*/\\\\n let resolvedPromise = presenceToPromise.get(value);\\\\n if (!resolvedPromise) {\\\\n resolvedPromise = promiseResolve(value);}\\\\n\\\\n /* Prevent any proxy trickery.*/\\\\n harden(resolvedPromise);\\\\n if (isFrozenPromiseThen(resolvedPromise)) {\\\\n return resolvedPromise;}\\\\n\\\\n /* Assimilate the thenable.*/\\\\n const executeThen = (resolve, reject) =>\\\\n resolvedPromise.then(resolve, reject);\\\\n return harden(\\\\n promiseResolve().then(_ => new HandledPromise(executeThen)));},\\\\n\\\\n\\\\n /* TODO verify that this is safe to provide universally, i.e.,*/\\\\n /* that by itself it doesn't provide access to mutable state in*/\\\\n /* ways that violate normal ocap module purity rules. The claim*/\\\\n /* that it does not rests on the handled promise itself being*/\\\\n /* necessary to perceive this mutable state. In that sense, we*/\\\\n /* can think of the right to perceive it, and of access to the*/\\\\n /* target, as being in the handled promise. Note that a .then on*/\\\\n /* the handled promise will already provide async access to the*/\\\\n /* target, so the only additional authorities are: 1)*/\\\\n /* synchronous access for handled promises only, and thus 2) the*/\\\\n /* ability to tell, from the client side, whether a promise is*/\\\\n /* handled. Or, at least, the ability to tell given that the*/\\\\n /* promise is already fulfilled.*/\\\\n unwrap(value) {\\\\n /* This check for Thenable is safe, since in a remote-object*/\\\\n /* environment, our comms system will defend against remote*/\\\\n /* objects being represented as a tricky local Proxy, otherwise*/\\\\n /* it is guaranteed to be local and therefore synchronous enough.*/\\\\n if (Object(value) !== value || !('then' in value)) {\\\\n /* Not a Thenable, so return it.*/\\\\n /* This means that local objects will pass through without error.*/\\\\n return value;}\\\\n\\\\n\\\\n /* Try to look up the HandledPromise.*/\\\\n ensureMaps();\\\\n const pr = presenceToPromise.get(value) || value;\\\\n\\\\n /* Find the fulfilled presence for that HandledPromise.*/\\\\n const presence = promiseToPresence.get(pr);\\\\n if (!presence) {\\\\n throw TypeError(\\\\n `Value is a Thenble but not a HandledPromise fulfilled to a presence`);}\\\\n\\\\n\\\\n return presence;} });\\\\n\\\\n\\\\n\\\\n defineProperties(HandledPromise, getOwnPropertyDescriptors(staticMethods));\\\\n\\\\n function makeForwarder(operation, localImpl) {\\\\n return (o, ...args) => {\\\\n /* We are in another turn already, and have the naked object.*/\\\\n const fulfilledHandler = presenceToHandler.get(o);\\\\n if (\\\\n fulfilledHandler &&\\\\n typeof fulfilledHandler[operation] === 'function')\\\\n {\\\\n /* The handler was resolved, so use it.*/\\\\n return fulfilledHandler[operation](o, ...args);}\\\\n\\\\n\\\\n /* Not handled, so use the local implementation.*/\\\\n return localImpl(o, ...args);};}\\\\n\\\\n\\\\n\\\\n /* eslint-disable-next-line prefer-const*/\\\\n forwardingHandler = {\\\\n get: makeForwarder('get', (o, key) => o[key]),\\\\n applyMethod: makeForwarder('applyMethod', (o, optKey, args) => {\\\\n if (optKey === undefined || optKey === null) {\\\\n return o(...args);}\\\\n\\\\n /* console.log(`sending`, optKey, o[optKey], o);*/\\\\n if (typeof o[optKey] !== 'function') {\\\\n throw TypeError(`o[${JSON.stringify(optKey)}] is not a function`);}\\\\n\\\\n return o[optKey](...args);}) };\\\\n\\\\n\\\\n\\\\n handle = (p, operation, ...opArgs) => {\\\\n ensureMaps();\\\\n const returnedP = new HandledPromise((resolve, reject) => {\\\\n /* We run in a future turn to prevent synchronous attacks,*/\\\\n let raceIsOver = false;\\\\n function win(handlerName, handler, o) {\\\\n if (raceIsOver) {\\\\n return;}\\\\n\\\\n if (typeof handler[operation] !== 'function') {\\\\n throw TypeError(`${handlerName}.${operation} is not a function`);}\\\\n\\\\n try {\\\\n resolve(handler[operation](o, ...opArgs, returnedP));}\\\\n catch (reason) {\\\\n reject(reason);}\\\\n\\\\n raceIsOver = true;}\\\\n\\\\n\\\\n function lose(e) {\\\\n if (raceIsOver) {\\\\n return;}\\\\n\\\\n reject(e);\\\\n raceIsOver = true;}\\\\n\\\\n\\\\n /* This contestant tries to win with the target's resolution.*/\\\\n HandledPromise.resolve(p).\\\\n then(o => win('forwardingHandler', forwardingHandler, o)).\\\\n catch(lose);\\\\n\\\\n /* This contestant sleeps a turn, but then tries to win immediately.*/\\\\n HandledPromise.resolve().\\\\n then(() => {\\\\n p = shorten(p);\\\\n const unsettledHandler = promiseToUnsettledHandler.get(p);\\\\n if (\\\\n unsettledHandler &&\\\\n typeof unsettledHandler[operation] === 'function')\\\\n {\\\\n /* and resolve to the answer from the specific unsettled handler,*/\\\\n /* opArgs are something like [prop] or [method, args],*/\\\\n /* so we don't risk the user's args leaking into this expansion.*/\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n win('unsettledHandler', unsettledHandler, p);} else\\\\n if (Object(p) !== p || !('then' in p)) {\\\\n /* Not a Thenable, so use it.*/\\\\n win('forwardingHandler', forwardingHandler, p);} else\\\\n if (promiseToPresence.has(p)) {\\\\n /* We have the object synchronously, so resolve with it.*/\\\\n const o = promiseToPresence.get(p);\\\\n win('forwardingHandler', forwardingHandler, o);}\\\\n\\\\n /* If we made it here without winning, then we will wait*/\\\\n /* for the other contestant to win instead.*/}).\\\\n\\\\n catch(lose);});\\\\n\\\\n\\\\n /* We return a handled promise with the default unsettled handler.*/\\\\n /* This prevents a race between the above Promise.resolves and*/\\\\n /* pipelining.*/\\\\n return returnedP;};\\\\n\\\\n\\\\n promiseResolve = Promise.resolve.bind(Promise);\\\\n return harden(HandledPromise);}exports.E = E;exports.HandledPromise = hp;exports.makeHandledPromise = makeHandledPromise;\\\",\\n \\\"packages/produce-promise/src/producePromise.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nindex = require('../../eventual-send/src/index.js'); /* global harden */ /**\\\\n * @template U,V\\\\n * @typedef {Object} PromiseRecord A reified Promise\\\\n * @property {(value?: U) => void} resolve\\\\n * @property {(reason?: V) => void} reject\\\\n * @property {Promise.<U, V>} promise\\\\n */ /**\\\\n * producePromise() builds a HandledPromise object, and returns a record\\\\n * containing the promise itself, as well as separate facets for resolving\\\\n * and rejecting it.\\\\n *\\\\n * @template U,V\\\\n * @returns {PromiseRecord.<U,V>}\\\\n */function producePromise() {let res;let rej; /* We use a HandledPromise so that we can run HandledPromise.unwrap(p)*/ /* even if p doesn't travel through a comms system (like SwingSet's).*/const p = new index.HandledPromise((resolve, reject) => {\\\\n res = resolve;\\\\n rej = reject;});\\\\n\\\\n /* Node.js adds the `domain` property which is not a standard*/\\\\n /* property on Promise. Because we do not know it to be ocap-safe,*/\\\\n /* we remove it.*/\\\\n if (p.domain) {\\\\n /* deleting p.domain may break functionality. To retain current*/\\\\n /* functionality at the expense of safety, set unsafe to true.*/\\\\n const unsafe = false;\\\\n if (unsafe) {\\\\n const originalDomain = p.domain;\\\\n Object.defineProperty(p, 'domain', {\\\\n get() {\\\\n return originalDomain;} });} else\\\\n\\\\n\\\\n {\\\\n delete p.domain;}}\\\\n\\\\n\\\\n return harden({ promise: p, resolve: res, reject: rej });}\\\\n\\\\nharden(producePromise);\\\\n\\\\n/**\\\\n * Determine if the argument is a Promise.\\\\n *\\\\n * @param {Promise} maybePromise The value to examine\\\\n * @returns {boolean} Whether it is a promise\\\\n */\\\\nfunction isPromise(maybePromise) {\\\\n return index.HandledPromise.resolve(maybePromise) === maybePromise;}\\\\n\\\\nharden(isPromise);exports.isPromise = isPromise;exports.producePromise = producePromise;\\\",\\n \\\"packages/marshal/marshal.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var nat_esm = require('../../node_modules/@agoric/nat/dist/nat.esm.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nproducePromise = require('../produce-promise/src/producePromise.js'); /* global harden */ /* TODO: Use just 'remote' when we're willing to make a breaking change.*/\\\\nconst REMOTE_STYLE = 'presence';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n/**\\\\n * This is an interface specification.\\\\n * For now, it is just a string, but will eventually become something\\\\n * much richer (anything that pureCopy accepts).\\\\n * @typedef {string} InterfaceSpec\\\\n */\\\\n\\\\n/**\\\\n * @type {WeakMap<Object, InterfaceSpec>}\\\\n */\\\\nconst remotableToInterface = new WeakMap();\\\\n\\\\n/**\\\\n * Simple semantics, just tell what interface (or undefined) a remotable has.\\\\n *\\\\n * @param {*} maybeRemotable the value to check\\\\n * @returns {InterfaceSpec} the interface specification, or undefined if not a Remotable\\\\n */\\\\nfunction getInterfaceOf(maybeRemotable) {\\\\n return remotableToInterface.get(maybeRemotable);}\\\\n\\\\n\\\\n/**\\\\n * Do a deep copy of the object, handling Proxies and recursion.\\\\n * The resulting copy is guaranteed to be pure data, as well as hardened.\\\\n * Such a hardened, pure copy cannot be used as a communications path.\\\\n *\\\\n * @template T\\\\n * @param {T} val input value. NOTE: Must be hardened!\\\\n * @returns {T} pure, hardened copy\\\\n */\\\\nfunction pureCopy(val, already = new WeakMap()) {\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n const passStyle = passStyleOf(val);\\\\n switch (passStyle) {\\\\n case 'bigint':\\\\n case 'boolean':\\\\n case 'null':\\\\n case 'number':\\\\n case 'string':\\\\n case 'undefined':\\\\n return val;\\\\n\\\\n case 'copyArray':\\\\n case 'copyRecord':{\\\\n const obj = /** @type {Object} */val;\\\\n if (already.has(obj)) {\\\\n return already.get(obj);}\\\\n\\\\n\\\\n /* Create a new identity.*/\\\\n const copy = /** @type {T} */passStyle === 'copyArray' ? [] : {};\\\\n\\\\n /* Prevent recursion.*/\\\\n already.set(obj, copy);\\\\n\\\\n /* Make a deep copy on the new identity.*/\\\\n /* Object.entries(obj) takes a snapshot (even if a Proxy).*/\\\\n Object.entries(obj).forEach(([prop, value]) => {\\\\n copy[prop] = pureCopy(value, already);});\\\\n\\\\n return harden(copy);}\\\\n\\\\n\\\\n case 'copyError':{\\\\n const unk = /** @type {unknown} */val;\\\\n const err = /** @type {Error} */unk;\\\\n\\\\n if (already.has(err)) {\\\\n return already.get(err);}\\\\n\\\\n\\\\n const { name, message } = err;\\\\n\\\\n /* eslint-disable-next-line no-use-before-define*/\\\\n const EC = getErrorConstructor(`${name}`) || Error;\\\\n const copy = harden(new EC(`${message}`));\\\\n already.set(err, copy);\\\\n\\\\n const unk2 = /** @type {unknown} */harden(copy);\\\\n return (/** @type {T} */unk2);}\\\\n\\\\n\\\\n case REMOTE_STYLE:{\\\\n throw TypeError(\\\\n `Input value ${passStyle} cannot be copied as must be passed by reference`);}\\\\n\\\\n\\\\n\\\\n default:\\\\n throw TypeError(`Input value ${passStyle} is not recognized as data`);}}\\\\n\\\\n\\\\nharden(pureCopy);\\\\n\\\\n\\\\n/* Special property name that indicates an encoding that needs special*/\\\\n/* decoding.*/\\\\nconst QCLASS = '@qclass';\\\\n\\\\n\\\\n/* objects can only be passed in one of two/three forms:*/\\\\n/* 1: pass-by-remote: all properties (own and inherited) are methods,*/\\\\n/* the object itself is of type object, not function*/\\\\n/* 2: pass-by-copy: all string-named own properties are data, not methods*/\\\\n/* the object must inherit from Object.prototype or null*/\\\\n/* 3: the empty object is pass-by-remote, for identity comparison*/\\\\n\\\\n/* all objects must be frozen*/\\\\n\\\\n/* anything else will throw an error if you try to serialize it*/\\\\n\\\\n/* with these restrictions, our remote call/copy protocols expose all useful*/\\\\n/* behavior of these objects: pass-by-remote objects have no other data (so*/\\\\n/* there's nothing else to copy), and pass-by-copy objects have no other*/\\\\n/* behavior (so there's nothing else to invoke)*/\\\\n\\\\nconst errorConstructors = new Map([\\\\n['Error', Error],\\\\n['EvalError', EvalError],\\\\n['RangeError', RangeError],\\\\n['ReferenceError', ReferenceError],\\\\n['SyntaxError', SyntaxError],\\\\n['TypeError', TypeError],\\\\n['URIError', URIError]]);\\\\n\\\\n\\\\nfunction getErrorConstructor(name) {\\\\n return errorConstructors.get(name);}\\\\n\\\\n\\\\nfunction isPassByCopyError(val) {\\\\n /* TODO: Need a better test than instanceof*/\\\\n if (!(val instanceof Error)) {\\\\n return false;}\\\\n\\\\n const proto = Object.getPrototypeOf(val);\\\\n const { name } = val;\\\\n const EC = getErrorConstructor(name);\\\\n if (!EC || EC.prototype !== proto) {\\\\n throw TypeError(`Must inherit from an error class .prototype ${val}`);}\\\\n\\\\n\\\\n const {\\\\n message: { value: messageStr } = { value: '' },\\\\n /* Allow but ignore only extraneous own `stack` property.*/\\\\n /* TODO: I began the variable below with \\\\\\\"_\\\\\\\". Why do I still need*/\\\\n /* to suppress the lint complaint?*/\\\\n /* eslint-disable-next-line no-unused-vars*/\\\\n stack: _optStackDesc,\\\\n ...restDescs } =\\\\n Object.getOwnPropertyDescriptors(val);\\\\n const restNames = Object.keys(restDescs);\\\\n if (restNames.length >= 1) {\\\\n throw new TypeError(`Unexpected own properties in error: ${restNames}`);}\\\\n\\\\n if (typeof messageStr !== 'string') {\\\\n throw new TypeError(`malformed error object: ${val}`);}\\\\n\\\\n return true;}\\\\n\\\\n\\\\nfunction isPassByCopyArray(val) {\\\\n if (!Array.isArray(val)) {\\\\n return false;}\\\\n\\\\n if (Object.getPrototypeOf(val) !== Array.prototype) {\\\\n throw new TypeError(`malformed array: ${val}`);}\\\\n\\\\n const len = val.length;\\\\n const descs = Object.getOwnPropertyDescriptors(val);\\\\n for (let i = 0; i < len; i += 1) {\\\\n const desc = descs[i];\\\\n if (!desc) {\\\\n throw new TypeError(`arrays must not contain holes`);}\\\\n\\\\n if (!('value' in desc)) {\\\\n throw new TypeError(`arrays must not contain accessors`);}\\\\n\\\\n if (typeof desc.value === 'function') {\\\\n throw new TypeError(`arrays must not contain methods`);}}\\\\n\\\\n\\\\n if (Object.keys(descs).length !== len + 1) {\\\\n throw new TypeError(`array must not have non-indexes ${val}`);}\\\\n\\\\n return true;}\\\\n\\\\n\\\\nfunction isPassByCopyRecord(val) {\\\\n if (Object.getPrototypeOf(val) !== Object.prototype) {\\\\n return false;}\\\\n\\\\n const descList = Object.values(Object.getOwnPropertyDescriptors(val));\\\\n if (descList.length === 0) {\\\\n /* empty non-array objects are pass-by-remote, not pass-by-copy*/\\\\n return false;}\\\\n\\\\n for (const desc of descList) {\\\\n if (!('value' in desc)) {\\\\n /* Should we error if we see an accessor here?*/\\\\n return false;}\\\\n\\\\n if (typeof desc.value === 'function') {\\\\n return false;}}\\\\n\\\\n\\\\n return true;}\\\\n\\\\n\\\\n/**\\\\n * Ensure that val could become a legitimate remotable. This is used internally both\\\\n * in the construction of a new remotable and mustPassByRemote.\\\\n *\\\\n * @param {*} val The remotable candidate to check\\\\n */\\\\nfunction assertCanBeRemotable(val) {\\\\n /* throws exception if cannot*/\\\\n if (typeof val !== 'object') {\\\\n throw new Error(`cannot serialize non-objects like ${val}`);}\\\\n\\\\n if (Array.isArray(val)) {\\\\n throw new Error(`Arrays cannot be pass-by-remote`);}\\\\n\\\\n if (val === null) {\\\\n throw new Error(`null cannot be pass-by-remote`);}\\\\n\\\\n\\\\n const names = Object.getOwnPropertyNames(val);\\\\n names.forEach(name => {\\\\n if (typeof val[name] !== 'function') {\\\\n throw new Error(\\\\n `cannot serialize objects with non-methods like the .${name} in ${val}`);\\\\n\\\\n /* return false;*/}});\\\\n\\\\n\\\\n\\\\n /* ok!*/}\\\\n\\\\n\\\\nfunction mustPassByRemote(val) {\\\\n if (!Object.isFrozen(val)) {\\\\n throw new Error(`cannot serialize non-frozen objects like ${val}`);}\\\\n\\\\n\\\\n if (getInterfaceOf(val) === undefined) {\\\\n /* Not a registered Remotable, so check its contents.*/\\\\n assertCanBeRemotable(val);}\\\\n\\\\n\\\\n /* It's not a registered Remotable, so enforce the prototype check.*/\\\\n const p = Object.getPrototypeOf(val);\\\\n if (p !== null && p !== Object.prototype) {\\\\n mustPassByRemote(p);}}\\\\n\\\\n\\\\n\\\\n/* This is the equality comparison used by JavaScript's Map and Set*/\\\\n/* abstractions, where NaN is the same as NaN and -0 is the same as*/\\\\n/* 0. Marshal serializes -0 as zero, so the semantics of our distributed*/\\\\n/* object system does not distinguish 0 from -0.*/\\\\n/**/\\\\n/* `sameValueZero` is the EcmaScript spec name for this equality comparison,*/\\\\n/* but TODO we need a better name for the API.*/\\\\nfunction sameValueZero(x, y) {\\\\n return x === y || Object.is(x, y);}\\\\n\\\\n\\\\n/* How would val be passed? For primitive values, the answer is*/\\\\n/* * 'null' for null*/\\\\n/* * throwing an error for a symbol, whether registered or not.*/\\\\n/* * that value's typeof string for all other primitive values*/\\\\n/* For frozen objects, the possible answers*/\\\\n/* * 'copyRecord' for non-empty records with only data properties*/\\\\n/* * 'copyArray' for arrays with only data properties*/\\\\n/* * 'copyError' for instances of Error with only data properties*/\\\\n/* * REMOTE_STYLE for non-array objects with only method properties*/\\\\n/* * 'promise' for genuine promises only*/\\\\n/* * throwing an error on anything else, including thenables.*/\\\\n/* We export passStyleOf so other algorithms can use this module's*/\\\\n/* classification.*/\\\\nfunction passStyleOf(val) {\\\\n const typestr = typeof val;\\\\n switch (typestr) {\\\\n case 'object':{\\\\n if (getInterfaceOf(val)) {\\\\n return REMOTE_STYLE;}\\\\n\\\\n if (val === null) {\\\\n return 'null';}\\\\n\\\\n if (QCLASS in val) {\\\\n /* TODO Hilbert hotel*/\\\\n throw new Error(`property \\\\\\\"${QCLASS}\\\\\\\" reserved`);}\\\\n\\\\n if (!Object.isFrozen(val)) {\\\\n throw new Error(\\\\n `Cannot pass non-frozen objects like ${val}. Use harden()`);}\\\\n\\\\n\\\\n if (producePromise.isPromise(val)) {\\\\n return 'promise';}\\\\n\\\\n if (typeof val.then === 'function') {\\\\n throw new Error(`Cannot pass non-promise thenables`);}\\\\n\\\\n if (isPassByCopyError(val)) {\\\\n return 'copyError';}\\\\n\\\\n if (isPassByCopyArray(val)) {\\\\n return 'copyArray';}\\\\n\\\\n if (isPassByCopyRecord(val)) {\\\\n return 'copyRecord';}\\\\n\\\\n mustPassByRemote(val);\\\\n return REMOTE_STYLE;}\\\\n\\\\n case 'function':{\\\\n throw new Error(`Bare functions like ${val} are disabled for now`);}\\\\n\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'bigint':{\\\\n return typestr;}\\\\n\\\\n case 'symbol':{\\\\n throw new TypeError('Cannot pass symbols');}\\\\n\\\\n default:{\\\\n throw new TypeError(`Unrecognized typeof ${typestr}`);}}}\\\\n\\\\n\\\\n\\\\n\\\\n/* The ibid logic relies on*/\\\\n/* * JSON.stringify on an array visiting array indexes from 0 to*/\\\\n/* arr.length -1 in order, and not visiting anything else.*/\\\\n/* * JSON.parse of a record (a plain object) creating an object on*/\\\\n/* which a getOwnPropertyNames will enumerate properties in the*/\\\\n/* same order in which they appeared in the parsed JSON string.*/\\\\n\\\\nfunction makeReplacerIbidTable() {\\\\n const ibidMap = new Map();\\\\n let ibidCount = 0;\\\\n\\\\n return harden({\\\\n has(obj) {\\\\n return ibidMap.has(obj);},\\\\n\\\\n get(obj) {\\\\n return ibidMap.get(obj);},\\\\n\\\\n add(obj) {\\\\n ibidMap.set(obj, ibidCount);\\\\n ibidCount += 1;} });}\\\\n\\\\n\\\\n\\\\n\\\\nfunction makeReviverIbidTable(cyclePolicy) {\\\\n const ibids = [];\\\\n const unfinishedIbids = new WeakSet();\\\\n\\\\n return harden({\\\\n get(allegedIndex) {\\\\n const index = nat_esm.default(allegedIndex);\\\\n if (index >= ibids.length) {\\\\n throw new RangeError(`ibid out of range: ${index}`);}\\\\n\\\\n const result = ibids[index];\\\\n if (unfinishedIbids.has(result)) {\\\\n switch (cyclePolicy) {\\\\n case 'allowCycles':{\\\\n break;}\\\\n\\\\n case 'warnOfCycles':{\\\\n console.log(`Warning: ibid cycle at ${index}`);\\\\n break;}\\\\n\\\\n case 'forbidCycles':{\\\\n throw new TypeError(`Ibid cycle at ${index}`);}\\\\n\\\\n default:{\\\\n throw new TypeError(`Unrecognized cycle policy: ${cyclePolicy}`);}}}\\\\n\\\\n\\\\n\\\\n return result;},\\\\n\\\\n register(obj) {\\\\n ibids.push(obj);\\\\n return obj;},\\\\n\\\\n start(obj) {\\\\n ibids.push(obj);\\\\n unfinishedIbids.add(obj);\\\\n return obj;},\\\\n\\\\n finish(obj) {\\\\n unfinishedIbids.delete(obj);\\\\n return obj;} });}\\\\n\\\\n\\\\n\\\\n\\\\nconst identityFn = x => x;\\\\n\\\\nfunction makeMarshal(\\\\nconvertValToSlot = identityFn,\\\\nconvertSlotToVal = identityFn)\\\\n{\\\\n function serializeSlot(val, slots, slotMap) {\\\\n let slotIndex;\\\\n if (slotMap.has(val)) {\\\\n slotIndex = slotMap.get(val);} else\\\\n {\\\\n const slot = convertValToSlot(val);\\\\n\\\\n slotIndex = slots.length;\\\\n slots.push(slot);\\\\n slotMap.set(val, slotIndex);}\\\\n\\\\n\\\\n return harden({\\\\n [QCLASS]: 'slot',\\\\n index: slotIndex });}\\\\n\\\\n\\\\n\\\\n function makeReplacer(slots, slotMap) {\\\\n const ibidTable = makeReplacerIbidTable();\\\\n\\\\n return function replacer(_, val) {\\\\n /* First we handle all primitives. Some can be represented directly as*/\\\\n /* JSON, and some must be encoded as [QCLASS] composites.*/\\\\n const passStyle = passStyleOf(val);\\\\n switch (passStyle) {\\\\n case 'null':{\\\\n return null;}\\\\n\\\\n case 'undefined':{\\\\n return harden({ [QCLASS]: 'undefined' });}\\\\n\\\\n case 'string':\\\\n case 'boolean':{\\\\n return val;}\\\\n\\\\n case 'number':{\\\\n if (Number.isNaN(val)) {\\\\n return harden({ [QCLASS]: 'NaN' });}\\\\n\\\\n if (Object.is(val, -0)) {\\\\n return 0;}\\\\n\\\\n if (val === Infinity) {\\\\n return harden({ [QCLASS]: 'Infinity' });}\\\\n\\\\n if (val === -Infinity) {\\\\n return harden({ [QCLASS]: '-Infinity' });}\\\\n\\\\n return val;}\\\\n\\\\n case 'bigint':{\\\\n return harden({\\\\n [QCLASS]: 'bigint',\\\\n digits: String(val) });}\\\\n\\\\n\\\\n default:{\\\\n /* if we've seen this object before, serialize a backref*/\\\\n if (ibidTable.has(val)) {\\\\n /* Backreference to prior occurrence*/\\\\n return harden({\\\\n [QCLASS]: 'ibid',\\\\n index: ibidTable.get(val) });}\\\\n\\\\n\\\\n ibidTable.add(val);\\\\n\\\\n switch (passStyle) {\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n /* console.log(`canPassByCopy: ${val}`);*/\\\\n /* Purposely in-band for readability, but creates need for*/\\\\n /* Hilbert hotel.*/\\\\n return val;}\\\\n\\\\n case 'copyError':{\\\\n /* We deliberately do not share the stack, but it would*/\\\\n /* be useful to log the stack locally so someone who has*/\\\\n /* privileged access to the throwing Vat can correlate*/\\\\n /* the problem with the remote Vat that gets this*/\\\\n /* summary. If we do that, we could allocate some random*/\\\\n /* identifier and include it in the message, to help*/\\\\n /* with the correlation.*/\\\\n return harden({\\\\n [QCLASS]: 'error',\\\\n name: `${val.name}`,\\\\n message: `${val.message}` });}\\\\n\\\\n\\\\n case REMOTE_STYLE:\\\\n case 'promise':{\\\\n /* console.log(`serializeSlot: ${val}`);*/\\\\n return serializeSlot(val, slots, slotMap);}\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${passStyle}`);}}}}};}\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n /* val might be a primitive, a pass by (shallow) copy object, a*/\\\\n /* remote reference, or other. We treat all other as a local object*/\\\\n /* to be exported as a local webkey.*/\\\\n function serialize(val) {\\\\n const slots = [];\\\\n const slotMap = new Map(); /* maps val (promise or remotable) to*/\\\\n /* index of slots[]*/\\\\n return harden({\\\\n body: JSON.stringify(val, makeReplacer(slots, slotMap)),\\\\n slots });}\\\\n\\\\n\\\\n\\\\n function makeFullRevive(slots, cyclePolicy) {\\\\n /* ibid table is shared across recursive calls to fullRevive.*/\\\\n const ibidTable = makeReviverIbidTable(cyclePolicy);\\\\n\\\\n /* We stay close to the algorith at*/\\\\n /* https://tc39.github.io/ecma262/#sec-json.parse , where*/\\\\n /* fullRevive(JSON.parse(str)) is like JSON.parse(str, revive))*/\\\\n /* for a similar reviver. But with the following differences:*/\\\\n /**/\\\\n /* Rather than pass a reviver to JSON.parse, we first call a plain*/\\\\n /* (one argument) JSON.parse to get rawTree, and then post-process*/\\\\n /* the rawTree with fullRevive. The kind of revive function*/\\\\n /* handled by JSON.parse only does one step in post-order, with*/\\\\n /* JSON.parse doing the recursion. By contrast, fullParse does its*/\\\\n /* own recursion, enabling it to interpret ibids in the same*/\\\\n /* pre-order in which the replacer visited them, and enabling it*/\\\\n /* to break cycles.*/\\\\n /**/\\\\n /* In order to break cycles, the potentially cyclic objects are*/\\\\n /* not frozen during the recursion. Rather, the whole graph is*/\\\\n /* hardened before being returned. Error objects are not*/\\\\n /* potentially recursive, and so may be harmlessly hardened when*/\\\\n /* they are produced.*/\\\\n /**/\\\\n /* fullRevive can produce properties whose value is undefined,*/\\\\n /* which a JSON.parse on a reviver cannot do. If a reviver returns*/\\\\n /* undefined to JSON.parse, JSON.parse will delete the property*/\\\\n /* instead.*/\\\\n /**/\\\\n /* fullRevive creates and returns a new graph, rather than*/\\\\n /* modifying the original tree in place.*/\\\\n /**/\\\\n /* fullRevive may rely on rawTree being the result of a plain call*/\\\\n /* to JSON.parse. However, it *cannot* rely on it having been*/\\\\n /* produced by JSON.stringify on the replacer above, i.e., it*/\\\\n /* cannot rely on it being a valid marshalled*/\\\\n /* representation. Rather, fullRevive must validate that.*/\\\\n return function fullRevive(rawTree) {\\\\n if (Object(rawTree) !== rawTree) {\\\\n /* primitives pass through*/\\\\n return rawTree;}\\\\n\\\\n if (QCLASS in rawTree) {\\\\n const qclass = rawTree[QCLASS];\\\\n if (typeof qclass !== 'string') {\\\\n throw new TypeError(`invalid qclass typeof ${typeof qclass}`);}\\\\n\\\\n switch (qclass) {\\\\n /* Encoding of primitives not handled by JSON*/\\\\n case 'undefined':{\\\\n return undefined;}\\\\n\\\\n case 'NaN':{\\\\n return NaN;}\\\\n\\\\n case 'Infinity':{\\\\n return Infinity;}\\\\n\\\\n case '-Infinity':{\\\\n return -Infinity;}\\\\n\\\\n case 'bigint':{\\\\n if (typeof rawTree.digits !== 'string') {\\\\n throw new TypeError(\\\\n `invalid digits typeof ${typeof rawTree.digits}`);}\\\\n\\\\n\\\\n /* eslint-disable-next-line no-undef */\\\\n return BigInt(rawTree.digits);}\\\\n\\\\n\\\\n case 'ibid':{\\\\n return ibidTable.get(rawTree.index);}\\\\n\\\\n\\\\n case 'error':{\\\\n if (typeof rawTree.name !== 'string') {\\\\n throw new TypeError(\\\\n `invalid error name typeof ${typeof rawTree.name}`);}\\\\n\\\\n\\\\n if (typeof rawTree.message !== 'string') {\\\\n throw new TypeError(\\\\n `invalid error message typeof ${typeof rawTree.message}`);}\\\\n\\\\n\\\\n const EC = getErrorConstructor(`${rawTree.name}`) || Error;\\\\n return ibidTable.register(harden(new EC(`${rawTree.message}`)));}\\\\n\\\\n\\\\n case 'slot':{\\\\n const slot = slots[nat_esm.default(rawTree.index)];\\\\n return ibidTable.register(convertSlotToVal(slot));}\\\\n\\\\n\\\\n default:{\\\\n /* TODO reverse Hilbert hotel*/\\\\n throw new TypeError(`unrecognized ${QCLASS} ${qclass}`);}}} else\\\\n\\\\n\\\\n if (Array.isArray(rawTree)) {\\\\n const result = ibidTable.start([]);\\\\n const len = rawTree.length;\\\\n for (let i = 0; i < len; i += 1) {\\\\n result[i] = fullRevive(rawTree[i]);}\\\\n\\\\n return ibidTable.finish(result);} else\\\\n {\\\\n const result = ibidTable.start({});\\\\n const names = Object.getOwnPropertyNames(rawTree);\\\\n for (const name of names) {\\\\n result[name] = fullRevive(rawTree[name]);}\\\\n\\\\n return ibidTable.finish(result);}};}\\\\n\\\\n\\\\n\\\\n\\\\n function unserialize(data, cyclePolicy = 'forbidCycles') {\\\\n if (data.body !== `${data.body}`) {\\\\n throw new Error(\\\\n `unserialize() given non-capdata (.body is ${data.body}, not string)`);}\\\\n\\\\n\\\\n if (!Array.isArray(data.slots)) {\\\\n throw new Error(`unserialize() given non-capdata (.slots are not Array)`);}\\\\n\\\\n const rawTree = harden(JSON.parse(data.body));\\\\n const fullRevive = makeFullRevive(data.slots, cyclePolicy);\\\\n return harden(fullRevive(rawTree));}\\\\n\\\\n\\\\n return harden({\\\\n serialize,\\\\n unserialize });}\\\\n\\\\n\\\\n\\\\n/**\\\\n * Create and register a Remotable. After this, getInterfaceOf(remotable)\\\\n * returns iface.\\\\n *\\\\n * // https://github.com/Agoric/agoric-sdk/issues/804\\\\n *\\\\n * @param {InterfaceSpec} [iface='Remotable'] The interface specification for the remotable\\\\n * @param {object} [props={}] Own-properties are copied to the remotable\\\\n * @param {object} [remotable={}] The object used as the remotable\\\\n * @returns {object} remotable, modified for debuggability\\\\n */\\\\nfunction Remotable(iface = 'Remotable', props = {}, remotable = {}) {\\\\n iface = pureCopy(harden(iface));\\\\n const ifaceType = typeof iface;\\\\n\\\\n /* Find the alleged name.*/\\\\n if (ifaceType !== 'string') {\\\\n throw Error(`Interface must be a string, not ${ifaceType}; unimplemented`);}\\\\n\\\\n\\\\n /* TODO: When iface is richer than just string, we need to get the allegedName*/\\\\n /* in a different way.*/\\\\n const allegedName = iface;\\\\n\\\\n /* Fail fast: check that the unmodified object is able to become a Remotable.*/\\\\n assertCanBeRemotable(remotable);\\\\n\\\\n /* Ensure that the remotable isn't already registered.*/\\\\n if (remotableToInterface.has(remotable)) {\\\\n throw Error(`Remotable ${remotable} is already mapped to an interface`);}\\\\n\\\\n\\\\n /* A prototype for debuggability.*/\\\\n const oldRemotableProto = harden(Object.getPrototypeOf(remotable));\\\\n\\\\n /* Fail fast: create a fresh empty object with the old*/\\\\n /* prototype in order to check it against our rules.*/\\\\n mustPassByRemote(harden(Object.create(oldRemotableProto)));\\\\n\\\\n /* Assign the arrow function to a variable to set its .name.*/\\\\n const toString = () => `[${allegedName}]`;\\\\n const remotableProto = harden(\\\\n Object.create(oldRemotableProto, {\\\\n toString: {\\\\n value: toString,\\\\n enumerable: false },\\\\n\\\\n [Symbol.toStringTag]: {\\\\n value: allegedName,\\\\n enumerable: false } }));\\\\n\\\\n\\\\n\\\\n\\\\n /* Take a static copy of the properties.*/\\\\n const propEntries = Object.entries(props);\\\\n const mutateHardenAndCheck = target => {\\\\n /* Add the snapshotted properties.*/\\\\n /** @type {PropertyDescriptorMap} */\\\\n const newProps = {};\\\\n propEntries.forEach(([prop, value]) => newProps[prop] = { value });\\\\n Object.defineProperties(target, newProps);\\\\n\\\\n /* Set the prototype for debuggability.*/\\\\n Object.setPrototypeOf(target, remotableProto);\\\\n harden(remotableProto);\\\\n\\\\n harden(target);\\\\n assertCanBeRemotable(target);\\\\n return target;};\\\\n\\\\n\\\\n /* Fail fast: check a fresh remotable to see if our rules fit.*/\\\\n const throwawayRemotable = Object.create(oldRemotableProto);\\\\n mutateHardenAndCheck(throwawayRemotable);\\\\n\\\\n /* Actually finish the new remotable.*/\\\\n mutateHardenAndCheck(remotable);\\\\n\\\\n /* COMMITTED!*/\\\\n /* We're committed, so keep the interface for future reference.*/\\\\n remotableToInterface.set(remotable, iface);\\\\n return remotable;}\\\\n\\\\n\\\\nharden(Remotable);exports.QCLASS = QCLASS;exports.Remotable = Remotable;exports.getErrorConstructor = getErrorConstructor;exports.getInterfaceOf = getInterfaceOf;exports.makeMarshal = makeMarshal;exports.mustPassByPresence = mustPassByRemote;exports.mustPassByRemote = mustPassByRemote;exports.passStyleOf = passStyleOf;exports.pureCopy = pureCopy;exports.sameValueZero = sameValueZero;\\\",\\n \\\"packages/same-structure/src/sameStructure.js\\\": \\\"'use strict';Object.defineProperty(exports, '__esModule', { value: true });var assert = require('../../assert/src/assert.js');var\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nmarshal = require('../../marshal/marshal.js'); /* global harden */ /* Shim of Object.fromEntries from*/ /* https://github.com/tc39/proposal-object-from-entries/blob/master/polyfill.js*/\\\\nfunction ObjectFromEntries(iter) {\\\\n const obj = {};\\\\n\\\\n for (const pair of iter) {\\\\n if (Object(pair) !== pair) {\\\\n throw new TypeError('iterable for fromEntries should yield objects');}\\\\n\\\\n\\\\n /* Consistency with Map: contract is that entry has \\\\\\\"0\\\\\\\" and \\\\\\\"1\\\\\\\" keys, not*/\\\\n /* that it is an array or iterable.*/\\\\n\\\\n const { '0': key, '1': val } = pair;\\\\n\\\\n Object.defineProperty(obj, key, {\\\\n configurable: true,\\\\n enumerable: true,\\\\n writable: true,\\\\n value: val });}\\\\n\\\\n\\\\n\\\\n return obj;}\\\\n\\\\n\\\\n/* A *passable* is something that may be marshalled. It consists of a*/\\\\n/* graph of pass-by-copy data terminating in leaves of passable*/\\\\n/* non-pass-by-copy data. These leaves may be promises, or*/\\\\n/* pass-by-presence objects. A *comparable* is a passable whose leaves*/\\\\n/* contain no promises. Two comparables can be synchronously compared*/\\\\n/* for structural equivalence.*/\\\\n/**/\\\\n/* TODO: Currently, all algorithms here treat the pass-by-copy*/\\\\n/* superstructure as a tree. This means that dags are unwound at*/\\\\n/* potentially exponential cost, and cycles cause failure to*/\\\\n/* terminate. We must fix both problems, making all these algorithms*/\\\\n/* graph-aware.*/\\\\n\\\\n/* We say that a function *reveals* an X when it returns either an X*/\\\\n/* or a promise for an X.*/\\\\n\\\\n/* Given a passable, reveal a corresponding comparable, where each*/\\\\n/* leaf promise of the passable has been replaced with its*/\\\\n/* corresponding comparable.*/\\\\nfunction allComparable(passable) {\\\\n const passStyle = marshal.passStyleOf(passable);\\\\n switch (passStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':\\\\n case 'copyError':{\\\\n return passable;}\\\\n\\\\n case 'promise':{\\\\n return passable.then(nonp => allComparable(nonp));}\\\\n\\\\n case 'copyArray':{\\\\n const valPs = passable.map(p => allComparable(p));\\\\n return Promise.all(valPs).then(vals => harden(vals));}\\\\n\\\\n case 'copyRecord':{\\\\n const names = Object.getOwnPropertyNames(passable);\\\\n const valPs = names.map(name => allComparable(passable[name]));\\\\n return Promise.all(valPs).then((vals) =>\\\\n harden(ObjectFromEntries(vals.map((val, i) => [names[i], val]))));}\\\\n\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${passStyle}`);}}}\\\\n\\\\n\\\\n\\\\nharden(allComparable);\\\\n\\\\n/* Are left and right structurally equivalent comparables? This*/\\\\n/* compares pass-by-copy data deeply until non-pass-by-copy values are*/\\\\n/* reached. The non-pass-by-copy values at the leaves of the*/\\\\n/* comparison may only be pass-by-presence objects. If they are*/\\\\n/* anything else, including promises, throw an error.*/\\\\n/**/\\\\n/* Pass-by-presence objects compare identities.*/\\\\n\\\\nfunction sameStructure(left, right) {\\\\n const leftStyle = marshal.passStyleOf(left);\\\\n const rightStyle = marshal.passStyleOf(right);\\\\n assert.assert(\\\\n leftStyle !== 'promise',\\\\n assert.details`Cannot structurally compare promises: ${left}`);\\\\n\\\\n assert.assert(\\\\n rightStyle !== 'promise',\\\\n assert.details`Cannot structurally compare promises: ${right}`);\\\\n\\\\n\\\\n if (leftStyle !== rightStyle) {\\\\n return false;}\\\\n\\\\n switch (leftStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':{\\\\n return marshal.sameValueZero(left, right);}\\\\n\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n const leftNames = Object.getOwnPropertyNames(left);\\\\n const rightNames = Object.getOwnPropertyNames(right);\\\\n if (leftNames.length !== rightNames.length) {\\\\n return false;}\\\\n\\\\n for (const name of leftNames) {\\\\n /* TODO: Better hasOwnProperty check*/\\\\n if (!Object.getOwnPropertyDescriptor(right, name)) {\\\\n return false;}\\\\n\\\\n /* TODO: Make cycle tolerant*/\\\\n if (!sameStructure(left[name], right[name])) {\\\\n return false;}}\\\\n\\\\n\\\\n return true;}\\\\n\\\\n case 'copyError':{\\\\n return left.name === right.name && left.message === right.message;}\\\\n\\\\n default:{\\\\n throw new TypeError(`unrecognized passStyle ${leftStyle}`);}}}\\\\n\\\\n\\\\n\\\\nharden(sameStructure);\\\\n\\\\nfunction pathStr(path) {\\\\n if (path === null) {\\\\n return 'top';}\\\\n\\\\n const [base, index] = path;\\\\n let i = index;\\\\n const baseStr = pathStr(base);\\\\n if (typeof i === 'string' && /^[a-zA-Z]\\\\\\\\w*$/.test(i)) {\\\\n return `${baseStr}.${i}`;}\\\\n\\\\n if (typeof i === 'string' && `${+i}` === i) {\\\\n i = +i;}\\\\n\\\\n return `${baseStr}[${JSON.stringify(i)}]`;}\\\\n\\\\n\\\\n/* TODO: Reduce redundancy between sameStructure and*/\\\\n/* mustBeSameStructureInternal*/\\\\nfunction mustBeSameStructureInternal(left, right, message, path) {\\\\n function complain(problem) {\\\\n assert.assert.fail(\\\\n assert.details`${assert.q(message)}: ${assert.q(problem)} at ${assert.q(\\\\n pathStr(path))\\\\n }: (${left}) vs (${right})`);}\\\\n\\\\n\\\\n\\\\n const leftStyle = marshal.passStyleOf(left);\\\\n const rightStyle = marshal.passStyleOf(right);\\\\n if (leftStyle === 'promise') {\\\\n complain('Promise on left');}\\\\n\\\\n if (rightStyle === 'promise') {\\\\n complain('Promise on right');}\\\\n\\\\n\\\\n if (leftStyle !== rightStyle) {\\\\n complain('different passing style');}\\\\n\\\\n switch (leftStyle) {\\\\n case 'null':\\\\n case 'undefined':\\\\n case 'string':\\\\n case 'boolean':\\\\n case 'number':\\\\n case 'symbol':\\\\n case 'bigint':\\\\n case 'presence':{\\\\n if (!marshal.sameValueZero(left, right)) {\\\\n complain('different');}\\\\n\\\\n break;}\\\\n\\\\n case 'copyRecord':\\\\n case 'copyArray':{\\\\n const leftNames = Object.getOwnPropertyNames(left);\\\\n const rightNames = Object.getOwnPropertyNames(right);\\\\n if (leftNames.length !== rightNames.length) {\\\\n complain(`${leftNames.length} vs ${rightNames.length} own properties`);}\\\\n\\\\n for (const name of leftNames) {\\\\n /* TODO: Better hasOwnProperty check*/\\\\n if (!Object.getOwnPropertyDescriptor(right, name)) {\\\\n complain(`${name} not found on right`);}\\\\n\\\\n /* TODO: Make cycle tolerant*/\\\\n mustBeSameStructureInternal(left[name], right[name], message, [\\\\n path,\\\\n name]);}\\\\n\\\\n\\\\n break;}\\\\n\\\\n case 'copyError':{\\\\n if (left.name !== right.name) {\\\\n complain(`different error name: ${left.name} vs ${right.name}`);}\\\\n\\\\n if (left.message !== right.message) {\\\\n complain(\\\\n `different error message: ${left.message} vs ${right.message}`);}\\\\n\\\\n\\\\n break;}\\\\n\\\\n default:{\\\\n complain(`unrecognized passStyle ${leftStyle}`);\\\\n break;}}}\\\\n\\\\n\\\\n\\\\nfunction mustBeSameStructure(left, right, message) {\\\\n mustBeSameStructureInternal(left, right, `${message}`, null);}\\\\n\\\\nharden(mustBeSameStructure);\\\\n\\\\n/* If `val` would be a valid input to `sameStructure`, return*/\\\\n/* normally. Otherwise error.*/\\\\nfunction mustBeComparable(val) {\\\\n mustBeSameStructure(val, val, 'not comparable');}exports.allComparable = allComparable;exports.mustBeComparable = mustBeComparable;exports.mustBeSameStructure = mustBeSameStructure;exports.sameStructure = sameStructure;\\\",\\n \\\"packages/zoe/src/offerSafety.js\\\": \\\"'use strict';\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\nObject.defineProperty(exports, '__esModule', { value: true }); /**\\\\n * @typedef {Ximport('@agoric/
View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment