Follow the scenario
Read the deployment, scenario actions and assertions in the Hardhat driver. This local workflow uses demonstration actors and assets.
demo/alpha-agi-mark/scripts/runDemo.ts ↗Agents & applications
Model capital-to-work capacity, draft a USDC job, and inspect the separate launch-gate and refund contract demo.
OPEN THE COMPLETE COMMAND DECKS
Browser-only capital-to-work planning with bounded capacity assumptions, a USDC proposal and an operator-admission task. No wallet, source fetching, provider calls or settlement.
A CLOSER LOOK
For mission owners and reviewers: explore a browser-only work plan, then inspect the separate Alpha Mark bonding-curve, launch-gate and refund demonstration.
Read the deployment, scenario actions and assertions in the Hardhat driver. This local workflow uses demonstration actors and assets.
demo/alpha-agi-mark/scripts/runDemo.ts ↗Inspect transaction-related fields, actors and scenario outcomes. The committed recap is an example; fresh evidence must come from your own run.
demo/alpha-agi-mark/reports/alpha-mark-recap.json ↗Follow the verifier before relying on generated dashboards or narrative briefs. Their presentation should remain traceable to the underlying recap.
demo/alpha-agi-mark/scripts/verifyRecap.ts ↗REAL REPOSITORY MATERIAL
Reading the exact source at revision 5b4cebb3.
This browser inspection does not execute the demo.
demo/alpha-agi-mark/scripts/runDemo.ts
Select a walkthrough step to explore its source.
import { ethers, network as hardhatNetwork } from 'hardhat';
import { mkdir, writeFile } from 'fs/promises';
import path from 'path';
import { createInterface } from 'readline/promises';
import { stdin as input, stdout as output } from 'node:process';
import { createHash } from 'crypto';
import { execSync } from 'child_process';
import { renderDashboard } from './renderDashboard';
import { canonicalStringify } from './utils/canonical';
import { expectRevert } from './utils/expectRevert';
import {
assertDistinctActors,
assertSufficientBalance,
DEMO_CURVE,
DEMO_PURCHASES,
investorMinimumBalances,
MIN_GAS_RESERVE,
resolveExecutionMode,
} from './utils/executionPreflight';
type Address = string;
interface ParticipantSnapshot {
address: Address;
tokens: string;
tokensWei: string;
contributionWei: string;
contributionEth?: string;
}
interface TradeRecord {
kind: 'BUY' | 'SELL';
actor: Address;
label: string;
tokensWhole: bigint;
valueWei: bigint;
}
interface TimelineEntry {
phase: string;
title: string;
description: string;
icon?: string;
actor?: Address;
actorLabel?: string;
}
const OUTPUT_PATH = path.join(
__dirname,
'..',
'reports',
'alpha-mark-recap.json'
);
const ONE_TOKEN = ethers.parseEther('1');
function calculatePurchaseCost(
basePriceWei: bigint,
slopeWei: bigint,
supplyWhole: bigint,
amountWhole: bigint
): bigint {
const baseComponent = basePriceWei * amountWhole;
const slopeComponent =
slopeWei * ((amountWhole * (2n * supplyWhole + amountWhole - 1n)) / 2n);
return baseComponent + slopeComponent;
}
function calculateSaleReturn(
basePriceWei: bigint,
slopeWei: bigint,
supplyWhole: bigint,
amountWhole: bigint
): bigint {
const baseComponent = basePriceWei * amountWhole;
if (amountWhole === 0n || supplyWhole === 0n) {
return baseComponent;
}
const numerator =
amountWhole * (2n * (supplyWhole - 1n) - (amountWhole - 1n));
const slopeComponent = slopeWei * (numerator / 2n);
return baseComponent + slopeComponent;
}
function expectEqual(label: string, actual: bigint, expected: bigint) {
if (actual !== expected) {
throw new Error(
`${label} mismatch: expected ${expected}, received ${actual}`
);
}
console.log(` ✅ ${label}`);
}
function parsePrivateKeys(raw?: string): string[] {
if (!raw) return [];
return raw
.split(',')
.map((value) => value.trim())
.filter((value) => value.length > 0);
}
async function ensureBalance(
label: string,
signer: any,
minimum = MIN_GAS_RESERVE
): Promise<void> {
const address = await signer.getAddress();
const balance = await signer.provider!.getBalance(address);
assertSufficientBalance(label, address, balance, minimum);
}
const HARDHAT_CHAIN_ID = 31337n;
async function requireOperatorConsent(
networkLabel: string,
isDryRun: boolean,
networkChainId: bigint
): Promise<void> {
const flag = process.env.AGIJOBS_DEMO_DRY_RUN ?? 'unset';
if (isDryRun) {
if (
hardhatNetwork.name !== 'hardhat' ||
networkChainId !== HARDHAT_CHAIN_ID
) {
console.log(
'🛑 Dry-run safeguard active – refusing to execute against a live network. ' +
'Set AGIJOBS_DEMO_DRY_RUN=false to opt in to broadcasts.'
);
throw new Error(
'Dry-run requires the in-memory hardhat network; no report was generated.'
);
}
console.log(
`🛡️ Local rehearsal on the Hardhat in-memory network (${networkLabel}; AGIJOBS_DEMO_DRY_RUN=${flag}).`
);
return;
}
const rl = createInterface({ input, output });
const answer = await rl.question(
`⚠️ Real network broadcast detected on ${networkLabel}. Type "launch" to confirm execution: `
);
rl.close();
if (answer.trim().toLowerCase() !== 'launch') {
console.log(
'🛑 Operator declined broadcast – exiting demo without executing transactions.'
);
throw new Error('Operator declined broadcast; no report was generated.');
}
}
async function loadActors() {
const provider = ethers.provider;
const network = await provider.getNetwork();
const isHardhat =
hardhatNetwork.name === 'hardhat' && network.chainId === 31337n;
const ownerKey = process.env.ALPHA_MARK_OWNER_KEY;
const investorKeys = parsePrivateKeys(process.env.ALPHA_MARK_INVESTOR_KEYS);
const validatorKeys = parsePrivateKeys(process.env.ALPHA_MARK_VALIDATOR_KEYS);
if (
isHardhat &&
!ownerKey &&
investorKeys.length === 0 &&
validatorKeys.length === 0
) {
const signers = await ethers.getSigners();
return {
owner: signers[0],
investors: [signers[1], signers[2], signers[3]],
validators: [signers[4], signers[5], signers[6]],
usesExternalKeys: false,
};
}
if (!ownerKey) {
throw new Error(
'ALPHA_MARK_OWNER_KEY must be provided when running outside the Hardhat in-memory network.'
);
}
if (investorKeys.length < 3) {
throw new Error(
'ALPHA_MARK_INVESTOR_KEYS must supply at least three comma-separated private keys.'
);
}
if (validatorKeys.length < 3) {
throw new Error(
'ALPHA_MARK_VALIDATOR_KEYS must supply at least three comma-separated private keys.'
);
}
const makeWallet = (key: string) => new ethers.Wallet(key, provider);
return {
owner: makeWallet(ownerKey),
investors: investorKeys.slice(0, 3).map(makeWallet),
validators: validatorKeys.slice(0, 3).map(makeWallet),
usesExternalKeys: true,
};
}
function describeNetworkName(name: string, chainId: bigint): string {
if (!name || name === 'unknown') {
return `chain-${chainId.toString()}`;
}
return `${name} (chainId ${chainId})`;
}
async function main() {
const network = await ethers.provider.getNetwork();
const dryRun =
resolveExecutionMode(
hardhatNetwork.name,
network.chainId,
process.env.AGIJOBS_DEMO_DRY_RUN
) === 'dry-run';
const networkLabel = describeNetworkName(network.name, network.chainId);
await requireOperatorConsent(networkLabel, dryRun, network.chainId);
const { owner, investors, validators, usesExternalKeys } = await loadActors();
const [investorA, investorB, investorC] = investors;
const [validatorA, validatorB, validatorC] = validators;
const ownerAddress = await owner.getAddress();
const investorAddresses = await Promise.all(
investors.map((signer) => signer.getAddress())
);
const validatorAddresses = await Promise.all(
validators.map((signer) => signer.getAddress())
);
assertDistinctActors([
{ label: 'Owner', address: ownerAddress },
...investorAddresses.map((address, index) => ({
label: DEMO_PURCHASES[index].label,
address,
})),
...validatorAddresses.map((address, index) => ({
label: `Validator ${index + 1}`,
address,
})),
]);
const tradeLedger: TradeRecord[] = [];
const timeline: TimelineEntry[] = [];
const accountState = new Map<
Address,
{
tokens: bigint;
grossContribution: bigint;
netContribution: bigint;
}
>();
let simulatedSupply = 0n;
let simulatedReserve = 0n;
const pushTimeline = (entry: TimelineEntry) => {
timeline.push(entry);
};
const recordTrade = (entry: TradeRecord) => {
tradeLedger.push(entry);
const previous = accountState.get(entry.actor) ?? {
tokens: 0n,
grossContribution: 0n,
netContribution: 0n,
};
const tokensDelta =
entry.kind === 'BUY' ? entry.tokensWhole : -entry.tokensWhole;
const grossDelta = entry.kind === 'BUY' ? entry.valueWei : 0n;
const netDelta = entry.kind === 'BUY' ? entry.valueWei : -entry.valueWei;
accountState.set(entry.actor, {
tokens: previous.tokens + tokensDelta,
grossContribution: previous.grossContribution + grossDelta,
netContribution: previous.netContribution + netDelta,
});
const tokensDisplay = entry.tokensWhole.toString();
const valueEth = ethers.formatEther(entry.valueWei);
const isBuy = entry.kind === 'BUY';
pushTimeline({
phase: isBuy ? 'Market Activation' : 'Liquidity',
title: `${entry.label} ${
isBuy ? 'acquires' : 'redeems'
} ${tokensDisplay} SeedShares`,
description: `${valueEth} ETH ${
isBuy ? 'committed to' : 'released from'
} the reserve`,
icon: isBuy ? '🟢' : '🔄',
actor: entry.actor,
actorLabel: entry.label,
});
};
console.log('🚀 Booting α-AGI MARK foresight exchange demo\n');
console.log(` • Network: ${networkLabel}`);
console.log(` • Dry run mode: ${dryRun ? 'enabled' : 'disabled'}`);
console.log(
` • Actor source: ${
usesExternalKeys ? 'environment-provided keys' : 'Hardhat signers'
}\n`
);
pushTimeline({
phase: 'Orchestration',
title: 'Mission boot sequence',
description: `AGI Jobs orchestrator engaged on ${networkLabel} (${
dryRun ? 'dry-run' : 'broadcast'
} mode)`,
icon: '🚀',
});
await ensureBalance('Owner', owner);
const investorMinimums = investorMinimumBalances();
await Promise.all(
investors.map((signer, idx) =>
ensureBalance(DEMO_PURCHASES[idx].label, signer, investorMinimums[idx])
)
);
await Promise.all(
validators.map((signer, idx) =>
ensureBalance(`Validator ${idx + 1}`, signer)
)
);
console.log(' • All actors funded above operational threshold\n');
pushTimeline({
phase: 'Orchestration',
title: 'Actors cleared for launch',
description: `Distinct actors funded for planned purchases, temporary overpayments, and a ${ethers.formatEther(
MIN_GAS_RESERVE
)} ETH gas reserve each (actual gas costs must be reviewed separately)`,
icon: '💠',
});
const NovaSeed = await ethers.getContractFactory('NovaSeedNFT', owner);
const novaSeed = await NovaSeed.deploy(ownerAddress);
await novaSeed.waitForDeployment();
const seedId = await novaSeed.mintSeed.staticCall(
ownerAddress,
'ipfs://alpha-mark/seed/genesis'
);
await (
await novaSeed.mintSeed(ownerAddress, 'ipfs://alpha-mark/seed/genesis')
).wait();
console.log(
`🌱 Nova-Seed minted with tokenId=${seedId} at ${novaSeed.target}`
);
pushTimeline({
phase: 'Seed Genesis',
title: `Nova-Seed minted (#${seedId})`,
description:
'Operator forges the foresight seed NFT underpinning the launch',
icon: '🌱',
actor: ownerAddress,
actorLabel: 'Owner',
});
const RiskOracle = await ethers.getContractFactory(
'AlphaMarkRiskOracle',
owner
);
const riskOracle = await RiskOracle.deploy(
ownerAddress,
validatorAddresses,
2
);
await riskOracle.waitForDeployment();
console.log(`🛡️ Risk oracle deployed at ${riskOracle.target}`);
pushTimeline({
phase: 'Deployment',
title: 'Risk oracle council activated',
description: 'Validator quorum contract online with 2-of-3 threshold',
icon: '🛡️',
actor: ownerAddress,
actorLabel: 'Owner',
});
const { basePrice, slope, maxSupply } = DEMO_CURVE;
const AlphaMark = await ethers.getContractFactory('AlphaMarkEToken', owner);
const mark = await AlphaMark.deploy(
'α-AGI SeedShares',
'SEED',
ownerAddress,
riskOracle.target,
basePrice,
slope,
maxSupply,
ethers.ZeroAddress
);
await mark.waitForDeployment();
console.log(`🏛️ AlphaMark exchange deployed at ${mark.target}`);
pushTimeline({
phase: 'Deployment',
title: 'Bonding-curve exchange deployed',
description: 'AlphaMarkEToken market-maker ready for capital formation',
icon: '🏛️',
actor: ownerAddress,
actorLabel: 'Owner',
});
const SovereignVault = await ethers.getContractFactory(
'AlphaSovereignVault',
owner
);
const sovereignVault = await SovereignVault.deploy(
ownerAddress,
'ipfs://alpha-mark/sovereign/genesis'
);
await sovereignVault.waitForDeployment();
await (await sovereignVault.designateMarkExchange(mark.target)).wait();
console.log(`👑 Sovereign vault deployed at ${sovereignVault.target}`);
pushTimeline({
phase: 'Deployment',
title: 'Sovereign vault commissioned',
description: 'Vault bound to the exchange for sovereign ignition',
icon: '👑',
actor: ownerAddress,
actorLabel: 'Owner',
});
await (await sovereignVault.pauseVault()).wait();
await (await sovereignVault.unpauseVault()).wait();
console.log(' • Sovereign vault pause/unpause controls verified');
pushTimeline({
phase: 'Safety & Compliance',
title: 'Vault circuit breaker tested',
description:
'Owner pauses and resumes the sovereign vault to verify emergency controls',
icon: '🛡️',
actor: ownerAddress,
actorLabel: 'Owner',
});
const Stable = await ethers.getContractFactory('TestStablecoin', owner);
const stable = await Stable.deploy();
await stable.waitForDeployment();
console.log(
' 🪙 Owner demonstrates base-asset retargeting to a stablecoin and back'
);
await (await mark.setBaseAsset(stable.target)).wait();
await (await mark.setBaseAsset(ethers.ZeroAddress)).wait();
pushTimeline({
phase: 'Configuration',
title: 'Base asset retargeted',
description:
'Funding rail toggled from ETH to stablecoin and back before launch',
icon: '🪙',
actor: ownerAddress,
actorLabel: 'Owner',
});
await (await mark.setTreasury(ownerAddress)).wait();
await (await mark.setFundingCap(ethers.parseEther('1000'))).wait();
await (await mark.setWhitelistEnabled(true)).wait();
await (await mark.setWhitelist(investorAddresses, true)).wait();
pushTimeline({
phase: 'Configuration',
title: 'Owner governance levers calibrated',
description:
'Treasury, funding cap, and whitelist configured for sovereign launch',
icon: '🛠️',
actor: ownerAddress,
actorLabel: 'Owner',
});
console.log('\n📊 Initial bonding curve configuration:');
console.log(` • Base price: ${ethers.formatEther(basePrice)} ETH`);
console.log(` • Slope: ${ethers.formatEther(slope)} ETH per token`);
console.log(` • Max supply: ${maxSupply} SeedShares\n`);
console.log(
' • Base asset: Native ETH (owner can retarget to a stablecoin pre-launch)\n'
);
const buy = async (
signer: any,
purchase: (typeof DEMO_PURCHASES)[number]
) => {
const { label, tokens: tokensWhole, overpayment } = purchase;
const amount = tokensWhole * ONE_TOKEN;
const cost = await mark.previewPurchaseCost(amount);
const manualCost = calculatePurchaseCost(
basePrice,
slope,
simulatedSupply,
tokensWhole
);
expectEqual(
`Bonding curve cost parity for ${label} (${ethers.formatEther(
cost
)} ETH)`,
cost,
manualCost
);
const totalValue = cost + overpayment;
await (
await mark
.connect(signer)
.buyTokensWithLimit(amount, cost, { value: totalValue })
).wait();
simulatedSupply += tokensWhole;
simulatedReserve += cost;
const buyerAddress = await signer.getAddress();
recordTrade({
kind: 'BUY',
actor: buyerAddress,
label,
tokensWhole,
valueWei: cost,
});
console.log(
` ✅ ${label} bought ${tokensWhole} SEED for ${ethers.formatEther(
cost
)} ETH`
);
};
await buy(investorA, DEMO_PURCHASES[0]);
console.log(' 🔒 Owner pauses market to demonstrate compliance gate');
await (await mark.pauseMarket()).wait();
pushTimeline({
phase: 'Safety & Compliance',
title: 'Market paused for compliance review',
description: 'Owner halts trading to showcase real-time control',
icon: '⏸️',
actor: ownerAddress,
actorLabel: 'Owner',
});
await expectRevert(
'Investor C purchase while paused',
mark.interface.encodeErrorResult('EnforcedPause', []),
async () => {
const amount = ethers.parseEther('2');
const cost = await mark.previewPurchaseCost(amount);
await mark
.connect(investorC)
.buyTokens.staticCall(amount, { value: cost });
}
);
{
pushTimeline({
phase: 'Safety & Compliance',
title: 'Pause enforcement confirmed',
description: 'Investor C blocked while the market pause is active',
icon: '🛑',
actor: investorAddresses[2],
actorLabel: 'Investor C',
});
}
console.log(' 🔓 Owner unpauses market\n');
await (await mark.unpauseMarket()).wait();
pushTimeline({
phase: 'Safety & Compliance',
title: 'Market resumed',
description: 'Owner reopens trading after compliance check',
icon: '▶️',
actor: ownerAddress,
actorLabel: 'Owner',
});
await buy(investorB, DEMO_PURCHASES[1]);
await buy(investorC, DEMO_PURCHASES[2]);
console.log('\n💡 Validator council activity:');
await (await riskOracle.connect(validatorA).approveSeed()).wait();
console.log(` • Validator ${validatorAddresses[0]} approved`);
pushTimeline({
phase: 'Governance',
title: 'Validator A casts approval',
description: `Consensus progress: 1/${validatorAddresses.length}`,
icon: '🗳️',
actor: validatorAddresses[0],
actorLabel: 'Validator A',
});
await expectRevert(
'Premature finalize attempt',
ethers.concat([
'0x08c379a0',
ethers.AbiCoder.defaultAbiCoder().encode(['string'], ['Not validated']),
]),
async () => {
const prematureMetadata = ethers.toUtf8Bytes('Attempt before consensus');
await mark.finalizeLaunch.staticCall(
sovereignVault.target,
prematureMetadata
);
}
);
{
pushTimeline({
phase: 'Governance',
title: 'Launch guard rejected premature finalize',
description: 'Owner cannot finalize before oracle quorum',
icon: '⚖️',
actor: ownerAddress,
actorLabel: 'Owner',
});
}
await (await riskOracle.connect(validatorB).approveSeed()).wait();
console.log(` • Validator ${validatorAddresses[1]} approved`);
const approvalsNow = await riskOracle.approvalCount();
const thresholdNow = await riskOracle.approvalThreshold();
pushTimeline({
phase: 'Governance',
title: 'Validator B casts approval',
description: `Consensus secured (${approvalsNow.toString()}/${thresholdNow.toString()})`,
icon: '🗳️',
actor: validatorAddresses[1],
actorLabel: 'Validator B',
});
console.log('\n♻️ Investor B tests liquidity by selling 1 SEED');
const sellAmount = ethers.parseEther('1');
const sellAmountWhole = sellAmount / ONE_TOKEN;
const sellReturn = await mark.previewSaleReturn(sellAmount);
const manualReturn = calculateSaleReturn(
basePrice,
slope,
simulatedSupply,
sellAmountWhole
);
expectEqual(
`Bonding curve redemption parity for Investor B (${ethers.formatEther(
sellReturn
)} ETH)`,
sellReturn,
manualReturn
);
await (
await mark.connect(investorB).sellTokensWithLimit(sellAmount, sellReturn)
).wait();
simulatedSupply -= sellAmountWhole;
simulatedReserve -= sellReturn;
const sellerAddress = await investorB.getAddress();
recordTrade({
kind: 'SELL',
actor: sellerAddress,
label: 'Investor B',
tokensWhole: sellAmountWhole,
valueWei: sellReturn,
});
console.log(
` ✅ Investor B redeemed 1 SEED for ${ethers.formatEther(sellReturn)} ETH`
);
console.log(
'\n🟢 Oracle threshold satisfied, owner finalizes launch to the sovereign vault'
);
const launchMetadata = ethers.toUtf8Bytes(
'α-AGI Sovereign ignition: Nova-Seed ascends'
);
await (
await mark.finalizeLaunch(sovereignVault.target, launchMetadata)
).wait();
console.log(
` • Sovereign vault acknowledged ignition metadata: "${ethers.toUtf8String(
launchMetadata
)}"`
);
pushTimeline({
phase: 'Launch',
title: 'Sovereign ignition finalized',
description:
'Funds transferred to the vault with ignition metadata recorded',
icon: '✨',
actor: ownerAddress,
actorLabel: 'Owner',
});
const [supply, reserve, nextPrice] = await mark.getCurveState();
const approvalCount = await riskOracle.approvalCount();
const threshold = await riskOracle.approvalThreshold();
const ownerControlsRaw = await mark.getOwnerControls();
const ownerControls = {
paused: ownerControlsRaw.isPaused,
whitelistEnabled: ownerControlsRaw.whitelistMode,
emergencyExitEnabled: ownerControlsRaw.emergencyExit,
finalized: ownerControlsRaw.isFinalized,
aborted: ownerControlsRaw.isAborted,
validationOverrideEnabled: ownerControlsRaw.overrideEnabled_,
validationOverrideStatus: ownerControlsRaw.overrideStatus_,
treasury: ownerControlsRaw.treasuryAddr as Address,
riskOracle: ownerControlsRaw.riskOracleAddr as Address,
baseAsset: ownerControlsRaw.baseAssetAddr as Address,
usesNativeAsset: ownerControlsRaw.usesNative,
fundingCapWei: ownerControlsRaw.fundingCapWei.toString(),
fundingCapEth: ethers.formatEther(ownerControlsRaw.fundingCapWei),
maxSupplyWholeTokens: ownerControlsRaw.maxSupplyWholeTokens.toString(),
saleDeadlineTimestamp: ownerControlsRaw.saleDeadlineTimestamp.toString(),
basePriceWei: ownerControlsRaw.basePriceWei.toString(),
basePriceEth: ethers.formatEther(ownerControlsRaw.basePriceWei),
slopeWei: ownerControlsRaw.slopeWei.toString(),
slopeEth: ethers.formatEther(ownerControlsRaw.slopeWei),
};
const participants: ParticipantSnapshot[] = [];
let participantContributionAggregate = 0n;
let participantTokenAggregate = 0n;
for (let i = 0; i < investors.length; i++) {
const address = investorAddresses[i];
const balance = await mark.balanceOf(address);
const balanceWhole = balance / ONE_TOKEN;
const contribution = await mark.participantContribution(address);
const ledgerEntry = accountState.get(address);
if (!ledgerEntry) {
throw new Error(`Missing ledger entry for participant ${address}`);
}
participantContributionAggregate += contribution;
participantTokenAggregate += balanceWhole;
expectEqual(
`Participant ${
i + 1
} token ledger alignment (${balanceWhole.toString()} SeedShares)`,
ledgerEntry.tokens,
balanceWhole
);
expectEqual(
`Participant ${i + 1} gross contribution alignment (${ethers.formatEther(
contribution
)} ETH)`,
ledgerEntry.grossContribution,
contribution
);
participants.push({
address,
tokens: ethers.formatEther(balance),
tokensWei: balance.toString(),
contributionWei: contribution.toString(),
contributionEth: ethers.formatEther(contribution),
});
}
let ledgerSupplyWhole = 0n;
let ledgerGrossWei = 0n;
let ledgerSellWei = 0n;
for (const entry of tradeLedger) {
if (entry.kind === 'BUY') {
ledgerSupplyWhole += entry.tokensWhole;
ledgerGrossWei += entry.valueWei;
} else {
ledgerSupplyWhole -= entry.tokensWhole;
ledgerSellWei += entry.valueWei;
}
}
const ledgerNetWei = ledgerGrossWei - ledgerSellWei;
const simulatedNextPrice = basePrice + slope * simulatedSupply;
const validatorRoster = await riskOracle.getValidators();
const validatorMatrix = [] as Array<{ address: Address; approved: boolean }>;
for (const validator of validatorRoster) {
const approved = await riskOracle.hasApproved(validator);
validatorMatrix.push({ address: validator, approved });
}
const sovereignMetadata = await sovereignVault.lastAcknowledgedMetadata();
const sovereignTotalReceived = await sovereignVault.totalReceived();
const sovereignNativeReceived = await sovereignVault.totalReceivedNative();
const sovereignTokenReceived = await sovereignVault.totalReceivedExternal();
const lastAcknowledgedUsedNative =
await sovereignVault.lastAcknowledgedUsedNative();
const lastAcknowledgedAmount = await sovereignVault.lastAcknowledgedAmount();
const vaultBalance = await sovereignVault.vaultBalance();
const combinedReserve = reserve + sovereignTotalReceived;
console.log('\n🔍 Triple-verification matrix:');
expectEqual(
`Ledger supply matches on-chain total (${ledgerSupplyWhole.toString()} SeedShares)`,
ledgerSupplyWhole,
supply
);
expectEqual(
`Simulation supply matches on-chain total (${simulatedSupply.toString()} SeedShares)`,
simulatedSupply,
supply
);
expectEqual(
`Participant balances sum to supply (${participantTokenAggregate.toString()} SeedShares)`,
participantTokenAggregate,
supply
);
expectEqual(
`Next token price matches first-principles math (${ethers.formatEther(
nextPrice
)} ETH)`,
nextPrice,
simulatedNextPrice
);
expectEqual(
`Vault receipts equal ledger net capital (${ethers.formatEther(
sovereignTotalReceived
)} ETH)`,
sovereignTotalReceived,
ledgerNetWei
);
expectEqual(
`Simulated reserve equals ledger net capital (${ethers.formatEther(
simulatedReserve
)} ETH)`,
simulatedReserve,
ledgerNetWei
);
expectEqual(
`Reserve + vault equals ledger net capital (${ethers.formatEther(
combinedReserve
)} ETH)`,
combinedReserve,
ledgerNetWei
);
expectEqual(
`Participant contributions equal ledger gross capital (${ethers.formatEther(
participantContributionAggregate
)} ETH)`,
participantContributionAggregate,
ledgerGrossWei
);
const recap = {
contracts: {
novaSeed: novaSeed.target,
riskOracle: riskOracle.target,
markExchange: mark.target,
sovereignVault: sovereignVault.target,
},
seed: {
tokenId: seedId.toString(),
holder: ownerAddress,
},
validators: {
approvalCount: approvalCount.toString(),
approvalThreshold: threshold.toString(),
members: validatorRoster,
matrix: validatorMatrix,
},
bondingCurve: {
supplyWholeTokens: supply.toString(),
reserveWei: reserve.toString(),
nextPriceWei: nextPrice.toString(),
basePriceWei: basePrice.toString(),
slopeWei: slope.toString(),
reserveEth: ethers.formatEther(reserve),
nextPriceEth: ethers.formatEther(nextPrice),
basePriceEth: ownerControls.basePriceEth,
slopeEth: ownerControls.slopeEth,
},
ownerControls,
participants,
launch: {
finalized: await mark.finalized(),
aborted: await mark.aborted(),
treasury: await mark.treasury(),
sovereignVault: {
manifestUri: await sovereignVault.manifestUri(),
totalReceivedWei: sovereignTotalReceived.toString(),
totalReceivedEth: ethers.formatEther(sovereignTotalReceived),
totalReceivedNativeWei: sovereignNativeReceived.toString(),
totalReceivedNativeEth: ethers.formatEther(sovereignNativeReceived),
totalReceivedExternalWei: sovereignTokenReceived.toString(),
totalReceivedExternalEth: ethers.formatEther(sovereignTokenReceived),
lastAcknowledgedAmountWei: lastAcknowledgedAmount.toString(),
lastAcknowledgedAmountEth: ethers.formatEther(lastAcknowledgedAmount),
lastAcknowledgedMetadataHex: sovereignMetadata,
decodedMetadata: ethers.toUtf8String(sovereignMetadata),
vaultBalanceWei: vaultBalance.toString(),
vaultBalanceEth: ethers.formatEther(vaultBalance),
lastAcknowledgedUsedNative,
},
},
};
const ownerParameterMatrix = [
{
parameter: 'pauseMarket',
value: ownerControls.paused,
description: 'Master halt switch for all bonding-curve trades',
},
{
parameter: 'whitelistEnabled',
value: ownerControls.whitelistEnabled,
description:
'Compliance gate restricting participation to approved wallets',
},
{
parameter: 'emergencyExitEnabled',
value: ownerControls.emergencyExitEnabled,
description: 'Allow redemptions while paused for orderly unwinding',
},
{
parameter: 'validationOverrideEnabled',
value: ownerControls.validationOverrideEnabled,
description: 'Owner override switch for the risk oracle consensus',
},
{
parameter: 'validationOverrideStatus',
value: ownerControls.validationOverrideStatus,
description: 'Forced validation outcome when override is enabled',
},
{
parameter: 'finalized',
value: ownerControls.finalized,
description: 'Indicates whether sovereign funds have been dispatched',
},
{
parameter: 'aborted',
value: ownerControls.aborted,
description: 'Emergency abort flag preserving participant capital',
},
{
parameter: 'treasury',
value: ownerControls.treasury,
description: 'Address receiving proceeds on finalization',
},
{
parameter: 'riskOracle',
value: ownerControls.riskOracle,
description: 'Validator council contract controlling launch approvals',
},
{
parameter: 'baseAsset',
value: ownerControls.baseAsset,
description: 'Current financing currency (0x0 indicates native ETH)',
},
{
parameter: 'usesNativeAsset',
value: ownerControls.usesNativeAsset,
description: 'True when the market accepts native ETH deposits',
},
{
parameter: 'fundingCap',
value: {
wei: ownerControls.fundingCapWei,
eth: ownerControls.fundingCapEth,
},
description: 'Upper bound on capital accepted before launch',
},
{
parameter: 'maxSupplyWholeTokens',
value: ownerControls.maxSupplyWholeTokens,
description: 'Maximum SeedShares that can ever be minted',
},
{
parameter: 'saleDeadlineTimestamp',
value: ownerControls.saleDeadlineTimestamp,
description: 'Timestamp after which purchases are rejected',
},
{
parameter: 'basePrice',
value: {
wei: ownerControls.basePriceWei,
eth: ownerControls.basePriceEth,
},
description: 'Bonding curve base price component',
},
{
parameter: 'slope',
value: { wei: ownerControls.slopeWei, eth: ownerControls.slopeEth },
description: 'Bonding curve slope component',
},
];
const verificationBase = {
supplyConsensus: {
ledgerWholeTokens: ledgerSupplyWhole.toString(),
contractWholeTokens: supply.toString(),
simulationWholeTokens: simulatedSupply.toString(),
participantAggregateWholeTokens: participantTokenAggregate.toString(),
consistent:
ledgerSupplyWhole === supply &&
simulatedSupply === supply &&
participantTokenAggregate === supply,
},
pricing: {
contractNextPriceWei: nextPrice.toString(),
contractNextPriceEth: ethers.formatEther(nextPrice),
simulatedNextPriceWei: simulatedNextPrice.toString(),
simulatedNextPriceEth: ethers.formatEther(simulatedNextPrice),
consistent: nextPrice === simulatedNextPrice,
},
capitalFlows: {
ledgerGrossWei: ledgerGrossWei.toString(),
ledgerGrossEth: ethers.formatEther(ledgerGrossWei),
ledgerRedemptionsWei: ledgerSellWei.toString(),
ledgerRedemptionsEth: ethers.formatEther(ledgerSellWei),
ledgerNetWei: ledgerNetWei.toString(),
ledgerNetEth: ethers.formatEther(ledgerNetWei),
simulatedReserveWei: simulatedReserve.toString(),
simulatedReserveEth: ethers.formatEther(simulatedReserve),
contractReserveWei: reserve.toString(),
contractReserveEth: ethers.formatEther(reserve),
vaultReceivedWei: sovereignTotalReceived.toString(),
vaultReceivedEth: ethers.formatEther(sovereignTotalReceived),
combinedReserveWei: combinedReserve.toString(),
combinedReserveEth: ethers.formatEther(combinedReserve),
consistent: ledgerNetWei === combinedReserve,
},
contributions: {
participantAggregateWei: participantContributionAggregate.toString(),
participantAggregateEth: ethers.formatEther(
participantContributionAggregate
),
ledgerGrossWei: ledgerGrossWei.toString(),
ledgerGrossEth: ethers.formatEther(ledgerGrossWei),
consistent: participantContributionAggregate === ledgerGrossWei,
},
};
const verificationChecks = [
{
key: 'supplyConsensus',
label: 'Supply consensus alignment',
consistent: verificationBase.supplyConsensus.consistent,
},
{
key: 'pricing',
label: 'Pricing integrity',
consistent: verificationBase.pricing.consistent,
},
{
key: 'capitalFlows',
label: 'Capital flow reconciliation',
consistent: verificationBase.capitalFlows.consistent,
},
{
key: 'contributions',
label: 'Contribution accounting',
consistent: verificationBase.contributions.consistent,
},
];
const passedChecks = verificationChecks.filter(
(check) => check.consistent
).length;
const totalChecks = verificationChecks.length;
const confidenceIndexBps =
totalChecks === 0 ? 0 : Math.round((passedChecks * 10000) / totalChecks);
const confidenceIndexPercent = (confidenceIndexBps / 100).toFixed(2);
const verification = {
...verificationBase,
summary: {
totalChecks,
passedChecks,
failedChecks: totalChecks - passedChecks,
confidenceIndexBps,
confidenceIndexPercent,
verdict: passedChecks === totalChecks ? 'PASS' : 'REVIEW',
checks: verificationChecks,
},
};
pushTimeline({
phase: 'Verification',
title: 'Triple-verification matrix aligned',
description: `Ledger, simulation, and on-chain state reconcile ${passedChecks}/${totalChecks} checks (${confidenceIndexPercent}% check pass rate)`,
icon: '✅',
});
pushTimeline({
phase: 'Mission Control',
title: 'Recap dossier synthesis',
description:
'Preparing sovereign dashboard, owner matrix, and recap digest',
icon: '🧾',
});
const timelineRecap = timeline.map((entry, index) => ({
order: index + 1,
phase: entry.phase,
title: entry.title,
description: entry.description,
icon: entry.icon,
actor: entry.actor,
actorLabel: entry.actorLabel,
}));
const manualCommandsRequired = dryRun ? 1 : 2;
const orchestratedActions = timelineRecap.length;
const automationMultiplier =
manualCommandsRequired === 0
? '0.00'
: (orchestratedActions / manualCommandsRequired).toFixed(2);
const empowerment = {
tagline: `AGI Jobs orchestrated ${orchestratedActions} mission events from ${manualCommandsRequired} command${
manualCommandsRequired === 1 ? '' : 's'
}, sustaining ${confidenceIndexPercent}% check pass rate across ${passedChecks}/${totalChecks} invariants.`,
automation: {
manualCommands: manualCommandsRequired,
orchestratedActions,
automationMultiplier,
},
assurance: {
verificationConfidencePercent: confidenceIndexPercent,
checksPassed: passedChecks,
totalChecks,
validatorApprovals: Number(approvalsNow),
validatorThreshold: Number(thresholdNow),
},
capitalFormation: {
participants: accountState.size,
grossContributionsWei: ledgerGrossWei.toString(),
grossContributionsEth: ethers.formatEther(ledgerGrossWei),
reserveWei: reserve.toString(),
reserveEth: ethers.formatEther(reserve),
},
operatorControls: {
totalControls: ownerParameterMatrix.length,
highlights: ownerParameterMatrix
.slice(0, 4)
.map((entry) => entry.parameter),
},
};
const enrichedRecap = {
...recap,
trades: tradeLedger.map((entry) => ({
kind: entry.kind,
actor: entry.actor,
label: entry.label,
tokensWhole: entry.tokensWhole.toString(),
valueWei: entry.valueWei.toString(),
valueEth: ethers.formatEther(entry.valueWei),
})),
ownerParameterMatrix,
verification,
timeline: timelineRecap,
empowerment,
};
const actors = {
owner: ownerAddress,
investors: investorAddresses,
validators: validatorAddresses,
};
const gitInfo = (command: string): string | undefined => {
try {
return execSync(command, { stdio: ['ignore', 'pipe', 'ignore'] })
.toString()
.trim();
} catch (error) {
return undefined;
}
};
const orchestrationMetadata = {
commit: gitInfo('git rev-parse HEAD'),
branch: gitInfo('git rev-parse --abbrev-ref HEAD'),
workspaceDirty: Boolean(gitInfo('git status --short')),
mode: dryRun ? 'dry-run' : 'broadcast',
};
const generatedAt = new Date().toISOString();
const baseRecap = {
generatedAt,
evidenceScope: {
execution: dryRun
? 'local-hardhat-rehearsal'
: 'operator-authorized-broadcast',
independentReview: false,
buyerAcceptance: false,
productionQualified: false,
note: 'Local invariant checks and seeded model simulations do not establish real-world agent capability, independent review, buyer value, or production readiness.',
},
network: {
label: networkLabel,
name: network.name ?? 'unknown',
chainId: network.chainId.toString(),
blockNumber: (await ethers.provider.getBlockNumber()).toString(),
dryRun,
},
orchestrator: orchestrationMetadata,
actors,
...enrichedRecap,
};
const digest = createHash('sha256')
.update(canonicalStringify(baseRecap))
.digest('hex');
const finalRecap = {
...baseRecap,
checksums: {
algorithm: 'sha256',
canonicalEncoding: 'json-key-sorted',
recapSha256: digest,
},
};
await mkdir(path.dirname(OUTPUT_PATH), { recursive: true });
await writeFile(OUTPUT_PATH, JSON.stringify(finalRecap, null, 2));
const dashboardPath = await renderDashboard(finalRecap);
console.log(
`\n🔍 Verification check pass rate: ${confidenceIndexPercent}% (${passedChecks}/${totalChecks} checks aligned)`
);
console.log('\n🧾 Demo recap written to', OUTPUT_PATH);
console.log('🖥️ Sovereign dashboard rendered to', dashboardPath);
console.log(
`🌌 Empowerment multiplier: ${automationMultiplier}x automation from ${manualCommandsRequired} manual command${
manualCommandsRequired === 1 ? '' : 's'
}`
);
console.log(JSON.stringify(finalRecap, null, 2));
console.log(`🔐 Recap digest (sha256): ${digest}`);
console.log('\n🧭 Owner parameter matrix snapshot:');
console.table(ownerParameterMatrix);
console.log(
`\n✨ α-AGI MARK demo complete. Sovereign vault now safeguards ${ethers.formatEther(
sovereignTotalReceived
)} ETH.`
);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
SHA-256 8bd57984ac952a38f5b4143102640d18cf0b1bc0db0104c8d06dd6d49d42abdb
FROM READING TO A REPRODUCIBLE RUN
Run from the repository root after nvm install, nvm use and npm ci. Use the versions pinned in .nvmrc and package.json. Commands below describe the selected path; optional app/server packages can have their own locked dependencies.
Complete environment setup ↗npm run test:alpha-agi-mark
npm run demo:alpha-agi-mark:fullA disposable local Hardhat run writes demo/alpha-agi-mark/reports/alpha-mark-recap.json and the operator dossier. These demonstrate local capital-market scenarios with test actors, not live agent work or a USDC job settlement.
The source inspector above reads bundled repository material. Local commands run separately on your computer. Recorded examples may contain historical timestamps, placeholders and simulated metrics.
MAKE IT YOUR OWN
In the browser lab, increase workers without increasing review time. Compare the capacity limit, then export a scoped draft for operator review. In the contract demo, trace recap fields to the assertions that establish them.
THE SYSTEM, MADE VISIBLE
```mermaid
flowchart LR
classDef owner fill:#0f0f3d,stroke:#8a7bff,stroke-width:2px,color:#ffffff,font-weight:bold;
classDef contract fill:#111f4d,stroke:#64d7ff,stroke-width:2px,color:#f0f7ff;
classDef process fill:#0a2f33,stroke:#3cf2c9,stroke-width:2px,color:#e5fffb;
classDef outcome fill:#28154b,stroke:#ff7bff,stroke-width:2px,color:#fff2ff,font-weight:bold;
classDef report fill:#1b1b1b,stroke:#f2c94c,stroke-width:2px,color:#fff4d1,font-weight:bold;
classDef checkpoint fill:#2c105a,stroke:#f268b1,stroke-width:2px,color:#ffe3f3,font-weight:bold;
subgraph PREP["Ignition Sphere"]
direction TB
A[Owner launches demo<br/>`npm run demo:alpha-agi-mark`]:::owner --> B{{Dry-run / Broadcast consent}}:::checkpoint
B --> C[Hardhat orchestrator boots deterministic chain]:::process
end
subgraph DEPLOY["Genesis Fabric"]
direction LR
C --> D[NovaSeedNFT deployed<br/>`🌱` Nova-Seed minted]:::contract
D --> E[AlphaMarkRiskOracle instated<br/>Validator quorum configured]:::contract
E --> F[AlphaMarkEToken exchange online<br/>Bonding curve primed]:::contract
F --> G[AlphaSovereignVault fortified<br/>Sovereign receiver handshake]:::contract
end
subgraph MARKET["Resonance Cascade"]
direction TB
G --> H[Investors stream ETH / ERC-20 through bonding curve]:::process
H --> I[Owner toggles whitelist & pause guardians<br/>Compliance envelope proven]:::process
I --> J[Validators vote within oracle council]:::process
J --> K{{Approval threshold met?}}:::checkpoint
K -- "No" --> L[Owner may override, reset, or abort<br/>Emergency exit can be armed]:::process
L --> J
end
K -- "Yes" --> M[Owner finalizes launch<br/>Funds teleported to Sovereign vault]:::outcome
M --> N[Vault acknowledges ignition metadata<br/>`notifyLaunch` handshake sealed]:::outcome
subgraph RECAP["Clairvoyant Dossier"]
direction TB
N --> O[Automated recap dossier minted<br/>`alpha-mark-recap.json`]:::report
O --> P[Owner parameter matrix broadcast<br/>Console + JSON alignment]:::report
P --> Q[Non-technical operator reviews one-page command center]:::owner
end
flowchart TD
classDef contract fill:#1a1f4d,stroke:#60ffcf,color:#f6faff,stroke-width:2px;
classDef actor fill:#113322,stroke:#60ffcf,color:#e8fff6,stroke-dasharray: 5 3;
classDef control fill:#2f2445,stroke:#9d7bff,color:#f6f0ff;
Operator((Operator Console)):::actor -->|Mint & Configure| Seed[NovaSeedNFT — α-AGI Nova-Seed]:::contract
Seed -->|Launch Request| Oracle[AlphaMarkRiskOracle — Validator Council]:::contract
Seed -->|Enables Pricing| Exchange[AlphaMarkEToken — Bonding Curve Exchange]:::contract
Exchange -->|Capital Flow| Reserve((Sovereign Reserve)):::control
Exchange -->|Compliance, Pause, Overrides| ControlDeck{{Owner Control Deck}}:::control
ControlDeck -->|Gates Participation| Exchange
Investors((SeedShare Contributors)):::actor -->|Bonding Curve Buys/Sells| Exchange
Oracle -->|Consensus Signal| Launch{Launch Condition}
Launch -->|Finalized| Vault[AlphaSovereignVault — Treasury]:::contract
Launch -->|Abort Path| Emergency((Emergency Exit Corridor)):::control
Vault -->|Ignition Metadata| Sovereign[[α-AGI Sovereign Manifest]]:::contract
```WHEN SOMETHING DOESN’T MATCH
Start at the first error, confirm the working directory and pinned toolchain, then follow the linked component guide. Optional packages and provider services have separate prerequisites.
Check its source revision, configuration, timestamps and underlying events. Historical fixtures and generated plans do not prove a fresh execution.
TRACE THE CHECKS
8 tracked test source files are available in this directory. Inspect the tests and their environment before choosing a suite; file counts do not establish test results.
For live commissioning, consult the production readiness record.
EVERY VARIANT, PRESERVED
REPRODUCE & INSPECT
Run commands from the repository root after following this demo's guide. Network and owner actions require their documented setup.
npm run demo:alpha-agi-marknpm run demo:alpha-agi-mark:full