From 1acd85dd9b6d1cfaa7c09bda4a3e9938047e9f92 Mon Sep 17 00:00:00 2001 From: Dan Connolly Date: Thu, 8 Feb 2024 15:25:27 -0600 Subject: [PATCH] chore: durable state snippet w/interface guard - regions for snippets - more concise publicFacet was a poor example of a baggage key --- snippets/zoe/src/02-state.js | 4 ++ snippets/zoe/src/02b-state-durable.js | 57 +++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 snippets/zoe/src/02b-state-durable.js diff --git a/snippets/zoe/src/02-state.js b/snippets/zoe/src/02-state.js index 2c91c5cb5..d94923d5e 100644 --- a/snippets/zoe/src/02-state.js +++ b/snippets/zoe/src/02-state.js @@ -1,13 +1,17 @@ import { Far } from '@endo/far'; // #region startfn +// #region heap-state export const start = () => { let value = 0; + // #endregion heap-state const get = () => value; const set = v => (value = v); + // #region fresh-export return { publicFacet: Far('ValueCell', { get, set }), }; + // #endregion fresh-export }; // #endregion startfn diff --git a/snippets/zoe/src/02b-state-durable.js b/snippets/zoe/src/02b-state-durable.js new file mode 100644 index 000000000..2fba03b5f --- /dev/null +++ b/snippets/zoe/src/02b-state-durable.js @@ -0,0 +1,57 @@ +// @ts-check +// #region contract +import { M } from '@endo/patterns'; +// #region import-zone +import { makeDurableZone } from '@agoric/zone/durable.js'; +// #endregion import-zone + +// #region interface-guard +const RoomI = M.interface('Room', { + getId: M.call().returns(M.number()), + incr: M.call().returns(M.number()), + decr: M.call().returns(M.number()), +}); + +const RoomMakerI = M.interface('RoomMaker', { + makeRoom: M.call().returns(M.remotable()), +}); +// #endregion interface-guard + +// #region export-prepare +export const prepare = (_zcf, _privateArgs, baggage) => { + // #endregion export-prepare + // #region zone1 + const zone = makeDurableZone(baggage); + const rooms = zone.mapStore('rooms'); + // #endregion zone1 + + // #region exoclass + const makeRoom = zone.exoClass('Room', RoomI, (id) => ({ id, count: 0 }), { + getId() { + return this.state.id; + }, + incr() { + this.state.count += 1; + return this.state.count; + }, + decr() { + this.state.count -= 1; + return this.state.count; + }, + }); + // #endregion exoclass + + // #region exo + const publicFacet = zone.exo('RoomMaker', RoomMakerI, { + makeRoom() { + const room = makeRoom(); + const id = rooms.size; + rooms.init(id, room); + return room; + }, + }); + + return { publicFacet }; + // #endregion exo +}; +// #endregion contract