Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(vats): for state upgrade, use single field #9353

Merged
merged 2 commits into from
May 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
185 changes: 68 additions & 117 deletions packages/vats/src/localchain.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,22 @@ import { E } from '@endo/far';
import { M } from '@endo/patterns';
import { AmountShape } from '@agoric/ertp';

const { Fail, bare } = assert;
const { Fail } = assert;

/**
* @import {BankManager} from './vat-bank.js';
* @import {ScopedBridgeManager} from './types.js';
*/

/** @import {TypedJson, ResponseTo} from '@agoric/cosmic-proto'; */

/**
* @typedef {{
* system: import('./types.js').ScopedBridgeManager;
* bankManager: import('./vat-bank.js').BankManager;
* system: ScopedBridgeManager;
* bankManager: BankManager;
* }} LocalChainPowers
*
* @typedef {MapStore<
* keyof LocalChainPowers,
* LocalChainPowers[keyof LocalChainPowers]
* >} PowerStore
*/

/**
* @template {keyof LocalChainPowers} K
* @param {PowerStore} powers
* @param {K} name
*/
const getPower = (powers, name) => {
powers.has(name) || Fail`need powers.${bare(name)} for this method`;
return /** @type {LocalChainPowers[K]} */ (powers.get(name));
};

export const LocalChainAccountI = M.interface('LocalChainAccount', {
getAddress: M.callWhen().returns(M.string()),
deposit: M.callWhen(M.remotable('Payment'))
Expand All @@ -44,9 +34,9 @@ const prepareLocalChainAccount = zone =>
LocalChainAccountI,
/**
* @param {string} address
* @param {PowerStore} powers
* @param {LocalChainPowers} powers
*/
(address, powers) => ({ address, powers }),
(address, powers) => ({ address, ...powers, reserved: undefined }),
{
// Information that the account creator needs.
async getAddress() {
Expand All @@ -60,9 +50,7 @@ const prepareLocalChainAccount = zone =>
* @param {Payment} payment
*/
async deposit(payment) {
const { address, powers } = this.state;

const bankManager = getPower(powers, 'bankManager');
const { address, bankManager } = this.state;

const allegedBrand = await E(payment).getAllegedBrand();
const bankAcct = E(bankManager).getBankForAddress(address);
Expand All @@ -79,7 +67,7 @@ const prepareLocalChainAccount = zone =>
* @returns {Promise<{ [K in keyof MT]: ResponseTo<MT[K]> }>}
*/
async executeTx(messages) {
const { address, powers } = this.state;
const { address, system } = this.state;
messages.length > 0 || Fail`need at least one message to execute`;

const obj = {
Expand All @@ -90,7 +78,6 @@ const prepareLocalChainAccount = zone =>
address,
messages,
};
const system = getPower(powers, 'system');
return E(system).toBridge(obj);
},
},
Expand All @@ -107,105 +94,70 @@ export const LocalChainI = M.interface('LocalChain', {
queryMany: M.callWhen(M.arrayOf(M.record())).returns(M.arrayOf(M.record())),
});

export const LocalChainAdminI = M.interface('LocalChainAdmin', {
setPower: M.callWhen(M.string(), M.await(M.any())).returns(),
});

/**
* @param {import('@agoric/base-zone').Zone} zone
* @param {ReturnType<typeof prepareLocalChainAccount>} makeAccount
*/
const prepareLocalChain = (zone, makeAccount) =>
zone.exoClassKit(
zone.exoClass(
'LocalChain',
{ public: LocalChainI, admin: LocalChainAdminI },
/** @param {Partial<LocalChainPowers>} [initialPowers] */
initialPowers => {
/** @type {PowerStore} */
const powers = zone.detached().mapStore('PowerStore');
if (initialPowers) {
for (const [name, power] of Object.entries(initialPowers)) {
powers.init(/** @type {keyof LocalChainPowers} */ (name), power);
}
}
return { powers };
LocalChainI,
/** @param {LocalChainPowers} powers */
powers => {
return { ...powers };
},
{
admin: {
/**
* @template {keyof LocalChainPowers} K
* @param {K} name
* @param {LocalChainPowers[K]} [power]
*/
setPower(name, power) {
const { powers } = this.state;
if (power === undefined) {
// Remove from powers.
powers.delete(name);
} else if (powers.has(name)) {
// Replace an existing power.
powers.set(name, power);
} else {
// Add a new power.
powers.init(name, power);
}
},
/**
* Allocate a fresh address that doesn't correspond with a public key, and
* follows the ICA guidelines to help reduce collisions. See
* x/vlocalchain/keeper/keeper.go AllocateAddress for the use of the app
* hash and block data hash.
*/
async makeAccount() {
const { system, bankManager } = this.state;
const address = await E(system).toBridge({
type: 'VLOCALCHAIN_ALLOCATE_ADDRESS',
});
return makeAccount(address, { system, bankManager });
},
public: {
/**
* Allocate a fresh address that doesn't correspond with a public key,
* and follows the ICA guidelines to help reduce collisions. See
* x/vlocalchain/keeper/keeper.go AllocateAddress for the use of the app
* hash and block data hash.
*/
async makeAccount() {
const { powers } = this.state;
const system = getPower(powers, 'system');
const address = await E(system).toBridge({
type: 'VLOCALCHAIN_ALLOCATE_ADDRESS',
});
return makeAccount(address, powers);
},
/**
* Make a single query to the local chain. Will reject with an error if
* the query fails. Otherwise, return the response as a JSON-compatible
* object.
*
* @param {import('@agoric/cosmic-proto').TypedJson} request
* @returns {Promise<import('@agoric/cosmic-proto').TypedJson>}
*/
async query(request) {
const requests = harden([request]);
const results = await E(this.facets.public).queryMany(requests);
results.length === 1 ||
Fail`expected exactly one result; got ${results}`;
const { error, reply } = results[0];
if (error) {
throw Fail`query failed: ${error}`;
}
return reply;
},
/**
* Send a batch of query requests to the local chain. Unless there is a
* system error, will return all results to indicate their success or
* failure.
*
* @param {import('@agoric/cosmic-proto').TypedJson[]} requests
* @returns {Promise<
* {
* error?: string;
* reply: import('@agoric/cosmic-proto').TypedJson;
* }[]
* >}
*/
async queryMany(requests) {
const { powers } = this.state;
const system = getPower(powers, 'system');
return E(system).toBridge({
type: 'VLOCALCHAIN_QUERY_MANY',
messages: requests,
});
},
/**
* Make a single query to the local chain. Will reject with an error if
* the query fails. Otherwise, return the response as a JSON-compatible
* object.
*
* @param {import('@agoric/cosmic-proto').TypedJson} request
* @returns {Promise<import('@agoric/cosmic-proto').TypedJson>}
*/
async query(request) {
const requests = harden([request]);
const results = await E(this.self).queryMany(requests);
results.length === 1 ||
Fail`expected exactly one result; got ${results}`;
const { error, reply } = results[0];
if (error) {
throw Fail`query failed: ${error}`;
}
return reply;
},
/**
* Send a batch of query requests to the local chain. Unless there is a
* system error, will return all results to indicate their success or
* failure.
*
* @param {import('@agoric/cosmic-proto').TypedJson[]} requests
* @returns {Promise<
* {
* error?: string;
* reply: import('@agoric/cosmic-proto').TypedJson;
* }[]
* >}
*/
async queryMany(requests) {
const { system } = this.state;
return E(system).toBridge({
type: 'VLOCALCHAIN_QUERY_MANY',
messages: requests,
});
},
},
);
Expand All @@ -220,5 +172,4 @@ export const prepareLocalChainTools = zone => {
harden(prepareLocalChainTools);

/** @typedef {ReturnType<typeof prepareLocalChainTools>} LocalChainTools */
/** @typedef {ReturnType<LocalChainTools['makeLocalChain']>} LocalChainKit */
/** @typedef {LocalChainKit['public']} LocalChain */
/** @typedef {ReturnType<LocalChainTools['makeLocalChain']>} LocalChain */
36 changes: 3 additions & 33 deletions packages/vats/src/proposals/localchain-proposal.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,10 @@ import { BridgeId as BRIDGE_ID } from '@agoric/internal';
* @param {BootstrapPowers & {
* consume: {
* loadCriticalVat: VatLoader<any>;
* bridgeManager: import('../types').BridgeManager;
* localchainBridgeManager: import('../types').ScopedBridgeManager;
* bankManager: Promise<import('../vat-bank.js').BankManager>;
* };
* produce: {
* localchain: Producer<any>;
* localchainAdmin: Producer<any>;
* localchainVat: Producer<any>;
* localchainBridgeManager: Producer<any>;
* };
Expand All @@ -32,12 +29,7 @@ export const setupLocalChainVat = async (
localchainBridgeManager: localchainBridgeManagerP,
bankManager,
},
produce: {
localchainVat,
localchain,
localchainAdmin: localchainAdminP,
localchainBridgeManager,
},
produce: { localchainVat, localchain, localchainBridgeManager },
},
options,
) => {
Expand Down Expand Up @@ -74,34 +66,13 @@ export const setupLocalChainVat = async (
);
}

const { admin: localChainAdmin, public: newLocalChain } = await E(
vats.localchain,
).makeLocalChain({
const newLocalChain = await E(vats.localchain).makeLocalChain({
system: scopedManager,
bankManager: await bankManager,
});

localchain.reset();
localchain.resolve(newLocalChain);
localchainAdminP.reset();
localchainAdminP.resolve(localChainAdmin);

/** @type {Record<string, Promise<void>>} */
const descToPromise = {
'bank manager power': bankManager.then(bm =>
E(localChainAdmin).setPower('bankManager', bm),
),
};
void Promise.all(
Object.entries(descToPromise).map(([desc, p]) =>
p
.then(() =>
console.info(`Completed configuration of localchain with ${desc}`),
)
.catch(e =>
console.error(`Failed to configure localchain with ${desc}:`, e),
),
),
);
};

/**
Expand Down Expand Up @@ -131,7 +102,6 @@ export const getManifestForLocalChain = (_powers, { localchainRef }) => ({
},
produce: {
localchain: 'localchain',
localchainAdmin: 'localchain',
localchainVat: 'localchain',
localchainBridgeManager: 'localchain',
},
Expand Down
6 changes: 3 additions & 3 deletions packages/vats/src/vat-localchain.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ export const buildRootObject = (_vatPowers, _args, baggage) => {
* Create a local chain that allows permissionlessly making fresh local
* chain accounts, then using them to send chain queries and transactions.
*
* @param {Partial<import('./localchain.js').LocalChainPowers>} [initialPowers]
* @param {import('./localchain.js').LocalChainPowers} powers
*/
makeLocalChain(initialPowers = {}) {
return makeLocalChain(initialPowers);
makeLocalChain(powers) {
return makeLocalChain(powers);
},
});
};
Expand Down
Loading