Skip to content

Commit

Permalink
feat(orchestrator): membrane-friendly timerUtils
Browse files Browse the repository at this point in the history
  • Loading branch information
0xpatrickdev committed Jun 21, 2024
1 parent 52e0339 commit 92292e7
Show file tree
Hide file tree
Showing 10 changed files with 136 additions and 94 deletions.
2 changes: 2 additions & 0 deletions packages/orchestration/src/examples/stakeBld.contract.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { deeplyFulfilled } from '@endo/marshal';
import { M } from '@endo/patterns';
import { prepareLocalOrchestrationAccountKit } from '../exos/local-orchestration-account.js';
import { makeChainHub } from '../exos/chain-hub.js';
import { makeTimeHelper } from '../exos/time-helper.js';

/**
* @import {NameHub} from '@agoric/vats';
Expand Down Expand Up @@ -49,6 +50,7 @@ export const start = async (zcf, privateArgs, baggage) => {
privateArgs.timerService,
vowTools,
makeChainHub(privateArgs.agoricNames),
makeTimeHelper(privateArgs.timerService),
);

// ----------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,12 @@ import {
CoinShape,
DelegationShape,
} from '../typeGuards.js';
import { maxClockSkew, tryDecodeResponse } from '../utils/cosmos.js';
import {
maxClockSkew,
tryDecodeResponse,
dateInSeconds,
} from '../utils/cosmos.js';
import { orchestrationAccountMethods } from '../utils/orchestrationAccount.js';
import { dateInSeconds } from '../utils/time.js';

/**
* @import {AmountArg, IcaAccount, ChainAddress, CosmosValidatorAddress, ICQConnection, StakingAccountActions, DenomAmount, OrchestrationAccountI, DenomArg} from '../types.js';
Expand Down
17 changes: 8 additions & 9 deletions packages/orchestration/src/exos/local-orchestration-account.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@ import {
ChainAmountShape,
IBCTransferOptionsShape,
} from '../typeGuards.js';
import { maxClockSkew } from '../utils/cosmos.js';
import { maxClockSkew, dateInSeconds } from '../utils/cosmos.js';
import { orchestrationAccountMethods } from '../utils/orchestrationAccount.js';
import { dateInSeconds, makeTimestampHelper } from '../utils/time.js';

/**
* @import {LocalChainAccount} from '@agoric/vats/src/localchain.js';
Expand All @@ -27,6 +26,7 @@ import { dateInSeconds, makeTimestampHelper } from '../utils/time.js';
* @import {PromiseVow, VowTools} from '@agoric/vow';
* @import {TypedJson} from '@agoric/cosmic-proto';
* @import {ChainHub} from './chain-hub.js';
* @import {TimeHelper} from './time-helper.js';
*/

const trace = makeTracer('LOA');
Expand Down Expand Up @@ -66,6 +66,7 @@ const PUBLIC_TOPICS = {
* @param {Remote<TimerService>} timerService
* @param {VowTools} vowTools
* @param {ChainHub} chainHub
* @param {TimeHelper} timeHelper
*/
export const prepareLocalOrchestrationAccountKit = (
zone,
Expand All @@ -74,11 +75,10 @@ export const prepareLocalOrchestrationAccountKit = (
timerService,
{ watch, when, allVows },
chainHub,
) => {
const timestampHelper = makeTimestampHelper(timerService);

timeHelper,
) =>
/** Make an object wrapping an LCA with Zoe interfaces. */
const makeLocalOrchestrationAccountKit = zone.exoClassKit(
zone.exoClassKit(
'Local Orchestration Account Kit',
{
holder: HolderI,
Expand Down Expand Up @@ -403,7 +403,7 @@ export const prepareLocalOrchestrationAccountKit = (
// TODO #9324 what's a reasonable default? currently 5 minutes
// FIXME: do not call `getTimeoutTimestampNS` if `opts.timeoutTimestamp` or `opts.timeoutHeight` is provided
const timeoutTimestampV = watch(
timestampHelper.getTimeoutTimestampNS(),
timeHelper.getTimeoutTimestampNS(),
this.facets.getTimeoutTimestampWatcher,
{ opts },
);
Expand All @@ -423,7 +423,6 @@ export const prepareLocalOrchestrationAccountKit = (
},
},
);
return makeLocalOrchestrationAccountKit;
};

/** @typedef {ReturnType<typeof prepareLocalOrchestrationAccountKit>} MakeLocalOrchestrationAccountKit */
/** @typedef {ReturnType<MakeLocalOrchestrationAccountKit>} LocalOrchestrationAccountKit */
77 changes: 77 additions & 0 deletions packages/orchestration/src/exos/time-helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { RelativeTimeRecordShape, TimeMath } from '@agoric/time';
import { VowShape } from '@agoric/vow';
import { watch, allVows } from '@agoric/vow/vat.js';
import { makeHeapZone } from '@agoric/zone';
import { E } from '@endo/far';
import { M } from '@endo/patterns';

/**
* @import {Remote} from '@agoric/internal';*
* @import {RelativeTimeRecord, TimerBrand, TimerService, TimestampRecord} from '@agoric/time';
* @import {Vow} from '@agoric/vow';
* @import {Zone} from '@agoric/zone';
*/

export const SECONDS_PER_MINUTE = 60n;
export const NANOSECONDS_PER_SECOND = 1_000_000_000n;

/**
* @param {Remote<TimerService>} timerService
* @param {Zone} [zone]
*/

export const makeTimeHelper = (timerService, zone = makeHeapZone()) => {
/** @type {TimerBrand | undefined} */
let brandCache;
const getBrand = () => {
if (brandCache) return brandCache;
return watch(E(timerService).getTimerBrand(), {
onFulfilled: timerBrand => {
brandCache = timerBrand;
return timerBrand;
},
});
};

return zone.exo(
'Time Helper',
M.interface('TimeHelperI', {
getTimeoutTimestampNS: M.call()
.optional(RelativeTimeRecordShape)
.returns(VowShape),
}),
{
/**
* Takes the current time from ChainTimerService and adds a relative time
* to determine a timeout timestamp in nanoseconds. Useful for
* {@link MsgTransfer.timeoutTimestamp}.
*
* @param {RelativeTimeRecord} [relativeTime] defaults to 5 minutes
* @returns {Vow<bigint>} Timeout timestamp in absolute nanoseconds since
* unix epoch
*/
getTimeoutTimestampNS(relativeTime) {
return watch(
allVows([E(timerService).getCurrentTimestamp(), getBrand()]),
{
/** @param {[TimestampRecord, TimerBrand]} results */
onFulfilled([currentTime, timerBrand]) {
const timeout =
relativeTime ||
TimeMath.coerceRelativeTimeRecord(
SECONDS_PER_MINUTE * 5n,
timerBrand,
);
return (
TimeMath.addAbsRel(currentTime, timeout).absValue *
NANOSECONDS_PER_SECOND
);
},
},
);
},
},
);
};

/** @typedef {Awaited<ReturnType<typeof makeTimeHelper>>} TimeHelper */
9 changes: 9 additions & 0 deletions packages/orchestration/src/utils/cosmos.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,12 @@ export const tryDecodeResponse = (ackStr, fromProtoMsg) => {
throw assert.error(`bad response: ${ackStr}`, undefined, { cause });
}
};

/**
* Convert a Date from a Cosmos message, which has millisecond precision, to a
* BigInt for number of seconds since epoch, for use in a timer.
*
* @param {Date} date
* @returns {bigint}
*/
export const dateInSeconds = date => BigInt(Math.floor(date.getTime() / 1000));
3 changes: 3 additions & 0 deletions packages/orchestration/src/utils/start-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { makeChainHub } from '../exos/chain-hub.js';
import { prepareRemoteChainFacade } from '../exos/remote-chain-facade.js';
import { prepareCosmosOrchestrationAccount } from '../exos/cosmos-orchestration-account.js';
import { prepareLocalChainFacade } from '../exos/local-chain-facade.js';
import { makeTimeHelper } from '../exos/time-helper.js';

/**
* @import {PromiseKit} from '@endo/promise-kit'
Expand Down Expand Up @@ -47,6 +48,7 @@ export const provideOrchestration = (
const zone = makeDurableZone(baggage);

const chainHub = makeChainHub(remotePowers.agoricNames);
const timeHelper = makeTimeHelper(remotePowers.timerService);

const vowTools = prepareVowTools(zone.subZone('vows'));

Expand All @@ -58,6 +60,7 @@ export const provideOrchestration = (
remotePowers.timerService,
vowTools,
chainHub,
timeHelper,
);

const asyncFlowTools = prepareAsyncFlowTools(zone.subZone('asyncFlow'), {
Expand Down
63 changes: 0 additions & 63 deletions packages/orchestration/src/utils/time.js

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ import { Far } from '@endo/far';
import { prepareLocalOrchestrationAccountKit } from '../../src/exos/local-orchestration-account.js';
import { ChainAddress } from '../../src/orchestration-api.js';
import { makeChainHub } from '../../src/exos/chain-hub.js';
import { NANOSECONDS_PER_SECOND } from '../../src/utils/time.js';
import {
makeTimeHelper,
NANOSECONDS_PER_SECOND,
} from '../../src/exos/time-helper.js';
import { commonSetup } from '../supports.js';

test('deposit, withdraw', async t => {
Expand All @@ -34,6 +37,7 @@ test('deposit, withdraw', async t => {
timer,
vowTools,
makeChainHub(bootstrap.agoricNames),
makeTimeHelper(timer),
);

t.log('request account from vat-localchain');
Expand Down Expand Up @@ -105,6 +109,7 @@ test('delegate, undelegate', async t => {
timer,
vowTools,
makeChainHub(bootstrap.agoricNames),
makeTimeHelper(timer),
);

t.log('request account from vat-localchain');
Expand Down Expand Up @@ -157,6 +162,7 @@ test('transfer', async t => {
timer,
vowTools,
makeChainHub(bootstrap.agoricNames),
makeTimeHelper(timer),
);

t.log('request account from vat-localchain');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,29 +1,31 @@
/* eslint-disable @jessie.js/safe-await-separator */
import { test } from '@agoric/zoe/tools/prepare-test-env-ava.js';
import { V } from '@agoric/vow/vat.js';
import { buildZoeManualTimer } from '@agoric/zoe/tools/manualTimer.js';
import { TimeMath } from '@agoric/time';
import {
dateInSeconds,
makeTimestampHelper,
makeTimeHelper,
NANOSECONDS_PER_SECOND,
SECONDS_PER_MINUTE,
} from '../../src/utils/time.js';
} from '../../src/exos/time-helper.js';

test('makeTimestampHelper - getCurrentTimestamp', async t => {
test('makeTimeHelper - getCurrentTimestamp', async t => {
const timer = buildZoeManualTimer(t.log);
const timerBrand = timer.getTimerBrand();
t.is(timer.getCurrentTimestamp().absValue, 0n, 'current time is 0n');

const { getTimeoutTimestampNS } = makeTimestampHelper(timer);
await null;
const timeHelper = makeTimeHelper(timer);
t.is(
await getTimeoutTimestampNS(),
await V.when(timeHelper.getTimeoutTimestampNS()),
5n * SECONDS_PER_MINUTE * NANOSECONDS_PER_SECOND,
'default timestamp is 5 minutes from current time, in nanoseconds',
);

t.is(
await getTimeoutTimestampNS(
TimeMath.coerceRelativeTimeRecord(1n, timerBrand),
await V.when(
timeHelper.getTimeoutTimestampNS(
TimeMath.coerceRelativeTimeRecord(1n, timerBrand),
),
),
1n * NANOSECONDS_PER_SECOND,
'timestamp is 1 second since unix epoch, in nanoseconds',
Expand All @@ -32,18 +34,12 @@ test('makeTimestampHelper - getCurrentTimestamp', async t => {
// advance timer by 3 seconds
await timer.tickN(3);
t.is(
await getTimeoutTimestampNS(
TimeMath.coerceRelativeTimeRecord(1n, timerBrand),
await V.when(
timeHelper.getTimeoutTimestampNS(
TimeMath.coerceRelativeTimeRecord(1n, timerBrand),
),
),
(1n + 3n) * NANOSECONDS_PER_SECOND,
'timestamp is 4 seconds since unix epoch, in nanoseconds',
);
});

test('dateInSeconds', t => {
t.is(dateInSeconds(new Date(1)), 0n);
t.is(dateInSeconds(new Date(999)), 0n);
t.is(dateInSeconds(new Date(1000)), 1n);

t.is(dateInSeconds(new Date('2025-12-17T12:23:45Z')), 1765974225n);
});
10 changes: 10 additions & 0 deletions packages/orchestration/test/utils/cosmos.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { test } from '@agoric/zoe/tools/prepare-test-env-ava.js';
import { dateInSeconds } from '../../src/utils/cosmos.js';

test('dateInSeconds', t => {
t.is(dateInSeconds(new Date(1)), 0n);
t.is(dateInSeconds(new Date(999)), 0n);
t.is(dateInSeconds(new Date(1000)), 1n);

t.is(dateInSeconds(new Date('2025-12-17T12:23:45Z')), 1765974225n);
});

0 comments on commit 92292e7

Please sign in to comment.