Verified contractExactMIT
DeltaVerifier
Address0x645bfdfd78bea0ec8d3e783e4993c70035761853
- Balance
0 ETH
- Transactions
13
- Compiler
solc 0.8.20
- Same code
Only this contract
Details
- Compiler
- solc 0.8.20+commit.a1b79de6
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,298,910
- Creation transaction
- 0x5dfe5d8b64…50f54a4c42
31 files
- contracts/DeltaVerifier.solmain50.45 KB
- @openzeppelin/contracts/access/AccessControl.sol8.23 KB
- @openzeppelin/contracts/access/IAccessControl.sol2.92 KB
- @openzeppelin/contracts/access/Ownable.sol2.62 KB
- @openzeppelin/contracts/interfaces/IERC5267.sol738 B
- @openzeppelin/contracts/security/Pausable.sol2.55 KB
- @openzeppelin/contracts/security/ReentrancyGuard.sol3.13 KB
- @openzeppelin/contracts/token/ERC20/ERC20.sol12.85 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.74 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- @openzeppelin/contracts/utils/Context.sol962 B
- @openzeppelin/contracts/utils/ShortStrings.sol4.29 KB
- @openzeppelin/contracts/utils/StorageSlot.sol4.11 KB
- @openzeppelin/contracts/utils/Strings.sol2.78 KB
- @openzeppelin/contracts/utils/cryptography/ECDSA.sol9.13 KB
- @openzeppelin/contracts/utils/cryptography/EIP712.sol5.66 KB
- @openzeppelin/contracts/utils/introspection/ERC165.sol987 B
- @openzeppelin/contracts/utils/introspection/IERC165.sol853 B
- @openzeppelin/contracts/utils/math/Math.sol12.79 KB
- @openzeppelin/contracts/utils/math/SignedMath.sol1.26 KB
- contracts/HokusaiParams.sol21.42 KB
- contracts/HokusaiToken.sol11.48 KB
- contracts/TokenManager.sol31.61 KB
- contracts/interfaces/IDataContributionRegistry.sol2.22 KB
- contracts/interfaces/IHokusaiParams.sol11.79 KB
- contracts/interfaces/IManagedHokusaiToken.sol1.35 KB
- contracts/interfaces/IModelRegistry.sol1.35 KB
- contracts/interfaces/IRewardVestingVault.sol1.14 KB
- contracts/libraries/AccessControlBase.sol4.06 KB
- contracts/libraries/RewardSplitLib.sol428 B
- contracts/libraries/ValidationLib.sol6.52 KB
contracts/DeltaVerifier.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./libraries/ValidationLib.sol";
import "./interfaces/IModelRegistry.sol";
import "./TokenManager.sol";
import "./HokusaiToken.sol";
import "./interfaces/IHokusaiParams.sol";
import "./interfaces/IDataContributionRegistry.sol";
contract DeltaVerifier is AccessControl, ReentrancyGuard, Pausable, EIP712 {
using ECDSA for bytes32;
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant SUBMITTER_ROLE = keccak256("SUBMITTER_ROLE");
error ModelTokenMismatch(uint256 modelId, address registryToken, address tokenManagerToken);
// --- Attester registry errors (HOK-2126) ---
error ZeroAttester();
error AttesterAlreadyRegistered(address attester);
error AttesterNotRegistered(address attester);
error InvalidAttesterThreshold(uint256 threshold, uint256 attesterCount);
error AttesterThresholdWouldBeUnmet(uint256 newAttesterCount, uint256 threshold);
// --- Attester signature verification errors (HOK-2132) ---
/// @notice No threshold is set, so no attester can have authorized a mint. Fail-closed: every mint
/// reverts until the admin Safe configures at least a 1-of-1 attester set (addAttester + threshold).
error AttestationThresholdNotConfigured();
error InsufficientAttesterSignatures(uint256 provided, uint256 required);
error SignerNotAttester(address signer);
// Attester-signature expiry (HOK-2170): submission attempted past payload.deadline.
error SignatureExpired(uint256 deadline, uint256 currentTimestamp);
/// @notice Signatures must be ordered by strictly ascending recovered signer address; this both
/// enforces uniqueness (no double-counting one attester toward the threshold) and makes the call
/// deterministic for m-of-n.
error UnorderedOrDuplicateAttesters(address signer);
// --- Per-model mint budget error (HOK-2131) ---
/// @notice A paying mint would exceed the model's remaining budget. The call reverts WITHOUT burning the
/// idempotency key, so the identical attested request succeeds verbatim once the admin Safe tops up.
error MintBudgetExceeded(uint256 modelId, uint256 required, uint256 remaining);
// --- Model-weight lineage errors (HOK-2133) ---
/// @notice The model has no genesis weight commitment set, so its lineage head is undefined. Fail-closed:
/// mint reverts until the registration authority sets the genesis (ModelRegistry.setWeightGenesis).
error LineageNotSeeded(uint256 modelId);
/// @notice The attested baselineCommitment does not equal the model's canonical head. The producer must
/// re-base on the current head and re-evaluate. Reverts without burning the idempotency key.
error LineageParentMismatch(uint256 modelId, bytes32 expectedHead, bytes32 providedBaseline);
error InvalidCandidateCommitment();
error InvalidHeadReset();
/// @notice Thrown by the legacy submitEvaluation* mint entrypoints once legacy mints are disabled.
error LegacyMintEntrypointDisabled();
/// @notice One-way switch. Once true, the legacy submitEvaluation* mint entrypoints revert,
/// leaving submitMintRequest (the canonical path) as the only way to mint. Set on mainnet so a
/// SUBMITTER_ROLE holder cannot bypass the canonical mint path. Cannot be re-enabled. (HOK-2125)
bool public legacyMintsDisabled;
event LegacyMintsDisabled(address indexed by);
struct Metrics {
uint256 accuracy;
uint256 precision;
uint256 recall;
uint256 f1;
uint256 auroc;
}
struct EvaluationData {
string pipelineRunId;
Metrics baselineMetrics;
Metrics newMetrics;
address contributor;
uint256 contributorWeight; // in basis points (10000 = 100%)
uint256 contributedSamples;
uint256 totalSamples;
uint256 maxCostUsd;
uint256 actualCostUsd;
}
struct ContributorInfo {
address walletAddress;
uint256 contributorWeight; // in basis points (10000 = 100%)
uint256 contributedSamples;
uint256 totalSamples;
}
struct Contributor {
address walletAddress;
uint256 weight; // in basis points (10000 = 100%)
}
struct EvaluationDataWithInfo {
string pipelineRunId;
Metrics baselineMetrics;
Metrics newMetrics;
ContributorInfo contributorInfo;
uint256 maxCostUsd;
uint256 actualCostUsd;
}
struct EvaluationDataBase {
string pipelineRunId;
Metrics baselineMetrics;
Metrics newMetrics;
uint256 maxCostUsd;
uint256 actualCostUsd;
uint256 totalSamples;
}
struct BenchmarkAnchors {
bytes32 benchmarkSpecHash;
bytes32 datasetHash;
bytes32 attestationHash;
bytes32 idempotencyKey;
string metricName;
string metricFamily;
}
struct MintRequestPayload {
string pipelineRunId;
uint256 baselineScoreBps;
uint256 candidateScoreBps;
uint256 maxCostUsdMicro;
uint256 actualCostUsdMicro;
uint256 totalSamples;
BenchmarkAnchors anchors;
// Model-weight lineage commitments (HOK-2133). Opaque bytes32 (e.g. 0x + sha256 / Merkle root of the
// weight artifact). baselineCommitment must equal the model's current canonical head; on a paying
// mint candidateCommitment becomes the new head — a hash-linked chain from genesis to head.
bytes32 baselineCommitment;
bytes32 candidateCommitment;
// Attester-signature expiry (HOK-2170). Unix timestamp past which this signed authorization is no
// longer submittable (revert SignatureExpired). Bounds the shelf life of a genuine-but-unsubmitted
// message held in the queue / a compromised relayer. The window is set by the signer (launch policy:
// 5 days); the contract only enforces non-expiry, and `deadline` is NOT part of the idempotency key,
// so an expired-but-unsubmitted request can be re-signed with a fresh deadline over identical content.
uint256 deadline;
}
IModelRegistry public immutable modelRegistry;
TokenManager public immutable tokenManager;
IDataContributionRegistry public immutable contributionRegistry;
uint256 public baseRewardRate; // tokens per 1% improvement
uint256 public minImprovementBps; // minimum improvement in basis points
uint256 public maxReward; // maximum reward cap
uint256 private constant RATE_LIMIT_DURATION = 1 hours;
mapping(address => uint256) private lastSubmissionTime;
mapping(bytes32 => bool) public processedIdempotencyKeys;
// --- Attester registry (HOK-2126) ---
// The set of addresses authorized to attest mints, and how many distinct attester signatures a
// mint must carry (m-of-n). The signature verification that *consumes* these is added in HOK-2132;
// this issue provides only the Safe-governed registry + invariants. Runs 1-of-1 at launch, but the
// set/threshold shape supports m-of-n later with no storage change. Governed by DEFAULT_ADMIN_ROLE
// (the admin Safe / timelock); pause() is the separate fast emergency brake.
mapping(address => bool) public isAttester;
uint256 public attesterCount;
uint256 public attesterThreshold;
// --- Per-model mint budget (HOK-2131) ---
// A deterministic loss ceiling per model: the most tokens submitMintRequest can mint for `modelId`
// before the admin Safe must top it up. Decremented per paying mint; a mint that would exceed it reverts
// (never truncates) without burning the idempotency key, so the exact request retries after a top-up.
// Fail-closed: a model with 0 remaining budget cannot mint a positive reward. Set/refilled only by the
// admin Safe (DEFAULT_ADMIN_ROLE), separate custody from the attester. Per-instance values (e.g. HROUT's
// 1.5M starting budget) are deployment config, not contract constants.
mapping(uint256 => uint256) public mintBudgetRemaining;
// --- Model-weight lineage head (HOK-2133) ---
// The canonical weight commitment per model — the head of a hash-linked chain rooted at the model's
// genesis (ModelRegistry.weightGenesis). Each paying mint must attest a baselineCommitment equal to the
// current head and atomically advances the head to its candidateCommitment, so the full lineage is
// rebuildable from genesis to head and a forged mint cannot invent a baseline. A stored 0 means
// "not yet advanced past genesis" — the effective head falls back to the registry genesis (see
// currentModelHead). The head advances ONLY on paying mints, so the canonical chain never regresses.
mapping(uint256 => bytes32) public modelWeightHead;
// --- EIP-712 typed-data definitions for the attested mint payload (HOK-2132) ---
// The signature binds the FULL economic payload (modelId + every anchor + scores/costs + samples +
// contributors), domain-separated by chainId + this contract's address (via the EIP712 base). The
// typehashes embed the exact schema; adding/removing a field changes the typehash and silently
// invalidates old signatures (cross-schema replay protection). Referenced struct types are listed in
// alphabetical order per EIP-712. Launch is hardware-wallet EOA (ECDSA.recover); the address-keyed
// attester registry is already EIP-1271-ready for a later Safe/threshold signer.
bytes32 private constant BENCHMARK_ANCHORS_TYPEHASH =
keccak256(
"BenchmarkAnchors(bytes32 benchmarkSpecHash,bytes32 datasetHash,bytes32 attestationHash,bytes32 idempotencyKey,string metricName,string metricFamily)"
);
bytes32 private constant CONTRIBUTOR_TYPEHASH = keccak256("Contributor(address walletAddress,uint256 weight)");
bytes32 private constant MINT_REQUEST_PAYLOAD_TYPEHASH =
keccak256(
"MintRequestPayload(string pipelineRunId,uint256 baselineScoreBps,uint256 candidateScoreBps,uint256 maxCostUsdMicro,uint256 actualCostUsdMicro,uint256 totalSamples,BenchmarkAnchors anchors,bytes32 baselineCommitment,bytes32 candidateCommitment,uint256 deadline)BenchmarkAnchors(bytes32 benchmarkSpecHash,bytes32 datasetHash,bytes32 attestationHash,bytes32 idempotencyKey,string metricName,string metricFamily)"
);
bytes32 private constant MINT_REQUEST_TYPEHASH =
keccak256(
"MintRequest(uint256 modelId,MintRequestPayload payload,Contributor[] contributors)BenchmarkAnchors(bytes32 benchmarkSpecHash,bytes32 datasetHash,bytes32 attestationHash,bytes32 idempotencyKey,string metricName,string metricFamily)Contributor(address walletAddress,uint256 weight)MintRequestPayload(string pipelineRunId,uint256 baselineScoreBps,uint256 candidateScoreBps,uint256 maxCostUsdMicro,uint256 actualCostUsdMicro,uint256 totalSamples,BenchmarkAnchors anchors,bytes32 baselineCommitment,bytes32 candidateCommitment,uint256 deadline)"
);
event EvaluationSubmitted(
string indexed pipelineRunId,
uint256 indexed modelId
);
event RewardCalculated(
address indexed contributor,
uint256 deltaInBps,
uint256 rewardAmount
);
event RewardParametersUpdated(
uint256 baseRewardRate,
uint256 minImprovementBps,
uint256 maxReward
);
event BatchRewardsDistributed(
uint256 indexed modelId,
address[] contributors,
uint256[] amounts,
uint256 totalAmount
);
event BudgetConstraintViolated(
string indexed pipelineRunId,
uint256 indexed modelId,
uint256 maxCostUsd,
uint256 actualCostUsd
);
event DeltaOneAccepted(
uint256 indexed modelId,
bytes32 indexed idempotencyKey,
bytes32 indexed benchmarkSpecHash,
bytes32 attestationHash,
bytes32 datasetHash,
string metricName,
string metricFamily,
uint256 baselineScoreBps,
uint256 candidateScoreBps,
uint256 rewardAmount,
string pipelineRunId
);
event AttesterAdded(address indexed attester, uint256 attesterCount);
event AttesterRemoved(address indexed attester, uint256 attesterCount);
event AttesterThresholdUpdated(uint256 threshold);
// --- Per-model mint budget events (HOK-2131) ---
event MintBudgetSet(uint256 indexed modelId, uint256 previousRemaining, uint256 newRemaining);
event MintBudgetToppedUp(uint256 indexed modelId, uint256 addedAmount, uint256 newRemaining);
event MintBudgetConsumed(uint256 indexed modelId, uint256 amount, uint256 remaining);
// --- Model-weight lineage events (HOK-2133) ---
// ModelLineageAdvanced carries parent -> child for every paying mint; rebuild a model's full chain by
// filtering these by modelId from genesis to head. ModelLineageHeadReset is the governed brick-prevention
// correction (e.g. a wrong commitment was accepted and would otherwise strand the model's mint path).
event ModelLineageAdvanced(uint256 indexed modelId, bytes32 parent, bytes32 child);
event ModelLineageHeadReset(uint256 indexed modelId, bytes32 oldHead, bytes32 newHead);
constructor(
address _modelRegistry,
address payable _tokenManager,
address _contributionRegistry,
uint256 _baseRewardRate,
uint256 _minImprovementBps,
uint256 _maxReward
) EIP712("HokusaiDeltaVerifier", "1") {
ValidationLib.requireNonZeroAddress(_modelRegistry, "model registry");
ValidationLib.requireNonZeroAddress(_tokenManager, "token manager");
ValidationLib.requireNonZeroAddress(_contributionRegistry, "contribution registry");
ValidationLib.requirePositiveAmount(_baseRewardRate, "reward rate");
ValidationLib.requirePositiveAmount(_minImprovementBps, "min improvement");
modelRegistry = IModelRegistry(_modelRegistry);
tokenManager = TokenManager(_tokenManager);
contributionRegistry = IDataContributionRegistry(_contributionRegistry);
baseRewardRate = _baseRewardRate;
minImprovementBps = _minImprovementBps;
maxReward = _maxReward;
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(PAUSER_ROLE, msg.sender);
_grantRole(SUBMITTER_ROLE, msg.sender);
}
function submitEvaluation(
uint256 modelId,
EvaluationData calldata data
) external nonReentrant whenNotPaused onlyRole(SUBMITTER_ROLE) returns (uint256) {
if (legacyMintsDisabled) revert LegacyMintEntrypointDisabled();
// Validate model exists
require(modelRegistry.isRegistered(modelId), "Model not registered");
require(modelRegistry.isActive(modelId), "Model is deactivated");
_assertCanonicalTokenMatch(modelId);
return _processEvaluation(modelId, data);
}
function submitEvaluationWithContributorInfo(
uint256 modelId,
EvaluationDataWithInfo calldata data
) external nonReentrant whenNotPaused onlyRole(SUBMITTER_ROLE) returns (uint256) {
if (legacyMintsDisabled) revert LegacyMintEntrypointDisabled();
// Validate model exists
require(modelRegistry.isRegistered(modelId), "Model not registered");
require(modelRegistry.isActive(modelId), "Model is deactivated");
_assertCanonicalTokenMatch(modelId);
// Validate wallet address
ValidationLib.requireNonZeroAddress(data.contributorInfo.walletAddress, "wallet address");
// Create evaluation data from contributor info
EvaluationData memory evalData = EvaluationData({
pipelineRunId: data.pipelineRunId,
baselineMetrics: data.baselineMetrics,
newMetrics: data.newMetrics,
contributor: data.contributorInfo.walletAddress,
contributorWeight: data.contributorInfo.contributorWeight,
contributedSamples: data.contributorInfo.contributedSamples,
totalSamples: data.contributorInfo.totalSamples,
maxCostUsd: data.maxCostUsd,
actualCostUsd: data.actualCostUsd
});
// Process using existing logic
return _processEvaluation(modelId, evalData);
}
function submitEvaluationWithMultipleContributors(
uint256 modelId,
EvaluationDataBase calldata data,
Contributor[] calldata contributors
) external nonReentrant whenNotPaused onlyRole(SUBMITTER_ROLE) returns (uint256) {
if (legacyMintsDisabled) revert LegacyMintEntrypointDisabled();
// Validate model exists
require(modelRegistry.isRegistered(modelId), "Model not registered");
require(modelRegistry.isActive(modelId), "Model is deactivated");
_assertCanonicalTokenMatch(modelId);
(address[] memory contributorAddresses, uint256[] memory rewardAmounts) = _validateContributors(contributors);
require(data.totalSamples > 0, "Total samples must be positive");
if (_isBudgetConstraintViolated(data.maxCostUsd, data.actualCostUsd)) {
emit BudgetConstraintViolated(
data.pipelineRunId,
modelId,
data.maxCostUsd,
data.actualCostUsd
);
return 0;
}
// Calculate delta one score
uint256 deltaInBps = _calculateSingleMetricDelta(data.baselineMetrics.accuracy, data.newMetrics.accuracy);
// Calculate total reward based on full improvement using dynamic parameters
string memory modelIdStr = _uintToString(modelId);
uint256 totalReward = calculateRewardDynamic(modelIdStr, deltaInBps, 10000, 0);
if (totalReward > 0) {
// Distribute rewards proportionally and mint tokens
{
uint256 totalDistributed = 0;
for (uint256 i = 0; i < contributors.length; i++) {
uint256 contributorReward = (totalReward * contributors[i].weight) / 10000;
rewardAmounts[i] = contributorReward;
totalDistributed += contributorReward;
emit RewardCalculated(contributors[i].walletAddress, deltaInBps, contributorReward);
}
// Assign rounding dust to the first contributor to prevent token loss
uint256 dust = totalReward - totalDistributed;
if (dust > 0) {
rewardAmounts[0] += dust;
totalDistributed += dust;
}
// Mint tokens in batch (zero-amount contributors are skipped by TokenManager)
tokenManager.batchMintReward(modelIdStr, contributorAddresses, rewardAmounts);
emit BatchRewardsDistributed(modelId, contributorAddresses, rewardAmounts, totalDistributed);
}
// Record contributions in registry (in separate scope to reduce stack depth)
_recordContributions(
modelIdStr,
contributorAddresses,
contributors,
data.totalSamples,
rewardAmounts,
data.pipelineRunId
);
}
emit EvaluationSubmitted(data.pipelineRunId, modelId);
return totalReward;
}
/**
* @dev Callers must normalize any non-proportion metric to a 0-10000 bps scale before submission.
* @param attesterSignatures EIP-712 signatures over the full (modelId, payload, contributors) tuple,
* ordered by strictly ascending recovered signer address. At least `attesterThreshold` distinct
* registered attesters must sign (1-of-1 at launch). The SUBMITTER relays; the attester authorizes.
*/
function submitMintRequest(
uint256 modelId,
MintRequestPayload calldata payload,
Contributor[] calldata contributors,
bytes[] calldata attesterSignatures
) external nonReentrant whenNotPaused onlyRole(SUBMITTER_ROLE) returns (uint256) {
require(modelRegistry.isRegistered(modelId), "Model not registered");
require(modelRegistry.isActive(modelId), "Model is deactivated");
_assertCanonicalTokenMatch(modelId);
require(payload.anchors.idempotencyKey != bytes32(0), "Idempotency key cannot be empty");
require(!processedIdempotencyKeys[payload.anchors.idempotencyKey], "Idempotency key already processed");
require(bytes(payload.pipelineRunId).length > 0, "Pipeline run ID cannot be empty");
require(bytes(payload.anchors.metricName).length > 0, "Metric name cannot be empty");
require(payload.baselineScoreBps <= 10000, "Baseline score exceeds 10000 bps");
require(payload.candidateScoreBps <= 10000, "Candidate score exceeds 10000 bps");
// HOK-2170: reject expired attester authorizations. deadline is part of the signed digest, so it
// cannot be altered without invalidating the signature; this only enforces the time bound at submit.
if (block.timestamp > payload.deadline) revert SignatureExpired(payload.deadline, block.timestamp);
// Authorization gate (HOK-2132): the mint must be signed by registered attester(s) over this exact
// payload. Fail-closed if no threshold is configured. Verified before any state change or mint.
_verifyAttestation(modelId, payload, contributors, attesterSignatures);
// Lineage parent check (HOK-2133): the attested baselineCommitment must equal the model's canonical
// head (the registry genesis until the first paying mint advances it). Reverts WITHOUT burning the
// idempotency key, so a producer whose baseline went stale (lost a concurrent race) re-bases on the
// new head and re-evaluates. The candidate must be non-zero; on a paying mint it becomes the new head.
bytes32 currentHead = modelWeightHead[modelId];
if (currentHead == bytes32(0)) currentHead = modelRegistry.weightGenesis(modelId);
if (currentHead == bytes32(0)) revert LineageNotSeeded(modelId);
if (payload.candidateCommitment == bytes32(0)) revert InvalidCandidateCommitment();
if (payload.baselineCommitment != currentHead) {
revert LineageParentMismatch(modelId, currentHead, payload.baselineCommitment);
}
(address[] memory contributorAddresses, uint256[] memory rewardAmounts) = _validateContributors(contributors);
uint256 deltaInBps = _calculateSingleMetricDelta(payload.baselineScoreBps, payload.candidateScoreBps);
string memory modelIdStr = _uintToString(modelId);
uint256 totalReward = calculateRewardDynamic(modelIdStr, deltaInBps, 10000, 0);
bool costViolated = _isBudgetConstraintViolated(payload.maxCostUsdMicro, payload.actualCostUsdMicro);
// Per-model mint budget (HOK-2131): a paying mint must fit the model's remaining budget. This is a
// deterministic loss bound on top of the attester check. Revert-not-truncate — and revert BEFORE the
// idempotency-key burn (and before any future lineage-head advance) so the exact attested request
// retries verbatim after a Safe top-up and pays in FULL, never haircut. budget == 0 blocks every
// paying mint for that model (fail-closed). Zero-reward acceptances (no delta) are unaffected.
if (!costViolated && totalReward > mintBudgetRemaining[modelId]) {
revert MintBudgetExceeded(modelId, totalReward, mintBudgetRemaining[modelId]);
}
// Commit point: the request is now resolved (mint or cost-rejection). Burn the idempotency key.
processedIdempotencyKeys[payload.anchors.idempotencyKey] = true;
if (costViolated) {
emit BudgetConstraintViolated(
payload.pipelineRunId,
modelId,
payload.maxCostUsdMicro,
payload.actualCostUsdMicro
);
return 0;
}
if (totalReward > 0) {
// Advance the lineage head atomically (HOK-2133): paying mints only, so the canonical chain never
// regresses to an equal/worse model. parent = currentHead, child = candidateCommitment.
modelWeightHead[modelId] = payload.candidateCommitment;
emit ModelLineageAdvanced(modelId, currentHead, payload.candidateCommitment);
// Decrement before minting (checks-effects-interactions); the budget gate above guarantees no underflow.
uint256 budgetRemaining = mintBudgetRemaining[modelId] - totalReward;
mintBudgetRemaining[modelId] = budgetRemaining;
uint256 totalDistributed = 0;
for (uint256 i = 0; i < contributors.length; i++) {
uint256 contributorReward = (totalReward * contributors[i].weight) / 10000;
rewardAmounts[i] = contributorReward;
totalDistributed += contributorReward;
emit RewardCalculated(contributors[i].walletAddress, deltaInBps, contributorReward);
}
uint256 dust = totalReward - totalDistributed;
if (dust > 0) {
rewardAmounts[0] += dust;
totalDistributed += dust;
}
tokenManager.batchMintReward(modelIdStr, contributorAddresses, rewardAmounts);
emit BatchRewardsDistributed(modelId, contributorAddresses, rewardAmounts, totalDistributed);
emit MintBudgetConsumed(modelId, totalReward, budgetRemaining);
_recordContributions(
modelIdStr,
contributorAddresses,
contributors,
payload.totalSamples,
rewardAmounts,
payload.pipelineRunId
);
}
emit DeltaOneAccepted(
modelId,
payload.anchors.idempotencyKey,
payload.anchors.benchmarkSpecHash,
payload.anchors.attestationHash,
payload.anchors.datasetHash,
payload.anchors.metricName,
payload.anchors.metricFamily,
payload.baselineScoreBps,
payload.candidateScoreBps,
totalReward,
payload.pipelineRunId
);
emit EvaluationSubmitted(payload.pipelineRunId, modelId);
return totalReward;
}
/**
* @notice The EIP-712 digest an attester must sign to authorize a `submitMintRequest`. Off-chain
* signers and tests should sign this exact value (domain = chainId + this contract). Exposed so the
* human-in-the-loop / HSM attester signs precisely the bytes the contract verifies.
*/
function hashMintRequest(
uint256 modelId,
MintRequestPayload calldata payload,
Contributor[] calldata contributors
) external view returns (bytes32) {
return _hashTypedDataV4(_hashMintRequest(modelId, payload, contributors));
}
function _processEvaluation(
uint256 modelId,
EvaluationData memory data
) private returns (uint256) {
// Validate evaluation data
_validateEvaluationDataMemory(data);
// Check rate limit
require(
block.timestamp >= lastSubmissionTime[data.contributor] + RATE_LIMIT_DURATION,
"Rate limit exceeded"
);
if (_isBudgetConstraintViolated(data.maxCostUsd, data.actualCostUsd)) {
emit BudgetConstraintViolated(
data.pipelineRunId,
modelId,
data.maxCostUsd,
data.actualCostUsd
);
return 0;
}
lastSubmissionTime[data.contributor] = block.timestamp;
// Calculate delta one score
uint256 deltaInBps = _calculateSingleMetricDelta(data.baselineMetrics.accuracy, data.newMetrics.accuracy);
// Calculate reward using dynamic parameters
string memory modelIdStr = _uintToString(modelId);
uint256 rewardAmount = calculateRewardDynamic(
modelIdStr,
deltaInBps,
data.contributorWeight,
data.contributedSamples
);
// Emit events
emit EvaluationSubmitted(data.pipelineRunId, modelId);
emit RewardCalculated(data.contributor, deltaInBps, rewardAmount);
// Trigger minting through TokenManager if reward > 0
if (rewardAmount > 0) {
tokenManager.mintReward(modelIdStr, data.contributor, rewardAmount);
// Record contribution in registry
_recordSingleContribution(
modelIdStr,
data.contributor,
data.contributorWeight,
data.contributedSamples,
data.totalSamples,
rewardAmount,
data.pipelineRunId
);
}
return rewardAmount;
}
function calculateDeltaOneForModel(
uint256 /* modelId */,
Metrics memory baseline,
Metrics memory newMetrics
) public pure returns (uint256) {
return _calculateSingleMetricDelta(baseline.accuracy, newMetrics.accuracy);
}
function calculateReward(
uint256 deltaInBps,
uint256 contributorWeight,
uint256 /* contributedSamples */
) public view returns (uint256) {
// Check minimum improvement threshold
if (deltaInBps < minImprovementBps) {
return 0;
}
// Calculate base reward: (improvement % * base rate * contributor weight)
// Note: baseRewardRate is already in wei, so no additional scaling needed
uint256 reward = (deltaInBps * baseRewardRate * contributorWeight) / (100 * 10000);
// Cap at maximum reward
if (reward > maxReward) {
reward = maxReward;
}
return reward;
}
/**
* @dev Calculate reward using dynamic parameters from the token's params contract
* @param modelId The model identifier to get token and parameters for
* @param deltaInBps The improvement delta in basis points
* @param contributorWeight The contributor's weight in basis points
* @return The calculated reward amount
*/
function calculateRewardDynamic(
string memory modelId,
uint256 deltaInBps,
uint256 contributorWeight,
uint256 /* contributedSamples */
) public view returns (uint256) {
address tokenAddress = modelRegistry.getStringToken(modelId);
address tokenManagerAddress = tokenManager.getTokenAddress(modelId);
if (tokenManagerAddress != address(0) && tokenManagerAddress != tokenAddress) {
revert ModelTokenMismatch(_stringToUint(modelId), tokenAddress, tokenManagerAddress);
}
// Get the token's params contract
HokusaiToken token = HokusaiToken(tokenAddress);
IHokusaiParams params = token.params();
// Get dynamic parameters
uint256 tokensPerDeltaOne = params.tokensPerDeltaOne();
// Check minimum improvement threshold
if (deltaInBps < minImprovementBps) {
return 0;
}
// tokensPerDeltaOne is stored in wei-scaled whole tokens, so the reward is already in base units.
// Formula: (improvement % * tokensPerDeltaOne * contributor weight) / (100 * 10000)
uint256 reward = (deltaInBps * tokensPerDeltaOne * contributorWeight) / (100 * 10000);
// Cap at maximum reward
if (reward > maxReward) {
reward = maxReward;
}
return reward;
}
function _calculateSingleMetricDelta(
uint256 baseline,
uint256 newValue
) private pure returns (uint256) {
if (newValue <= baseline) {
return 0;
}
return newValue - baseline;
}
function _validateEvaluationData(EvaluationData calldata data) private pure {
// Validate contributor address
ValidationLib.requireNonZeroAddress(data.contributor, "contributor address");
// Validate contributor weight
ValidationLib.requireMaxValue(data.contributorWeight, 10000);
// Validate metrics are within valid range (0-100%)
_validateMetrics(data.baselineMetrics);
_validateMetrics(data.newMetrics);
// Validate sample counts
ValidationLib.requirePositiveAmount(data.contributedSamples, "contributed samples");
require(data.totalSamples >= data.contributedSamples, "Invalid total samples");
_validateBudgetData(data.maxCostUsd, data.actualCostUsd);
}
function _validateMetrics(Metrics memory metrics) private pure {
ValidationLib.requireMaxValue(metrics.accuracy, 10000);
ValidationLib.requireMaxValue(metrics.precision, 10000);
ValidationLib.requireMaxValue(metrics.recall, 10000);
ValidationLib.requireMaxValue(metrics.f1, 10000);
ValidationLib.requireMaxValue(metrics.auroc, 10000);
}
function _validateEvaluationDataMemory(EvaluationData memory data) private pure {
// Validate contributor address
ValidationLib.requireNonZeroAddress(data.contributor, "contributor address");
// Validate contributor weight
ValidationLib.requireMaxValue(data.contributorWeight, 10000);
// Validate metrics are within valid range (0-100%)
_validateMetrics(data.baselineMetrics);
_validateMetrics(data.newMetrics);
// Validate sample counts
ValidationLib.requirePositiveAmount(data.contributedSamples, "contributed samples");
require(data.totalSamples >= data.contributedSamples, "Invalid total samples");
_validateBudgetData(data.maxCostUsd, data.actualCostUsd);
}
function _validateBudgetData(uint256 maxCostUsd, uint256 actualCostUsd) private pure {
if (maxCostUsd == 0 || actualCostUsd == 0) {
return;
}
ValidationLib.requirePositiveAmount(maxCostUsd, "max cost usd");
ValidationLib.requirePositiveAmount(actualCostUsd, "actual cost usd");
}
function _isBudgetConstraintViolated(uint256 maxCostUsd, uint256 actualCostUsd) private pure returns (bool) {
if (maxCostUsd == 0 || actualCostUsd == 0) {
return false;
}
return actualCostUsd > maxCostUsd;
}
function _validateContributors(
Contributor[] calldata contributors
) private pure returns (address[] memory contributorAddresses, uint256[] memory rewardAmounts) {
ValidationLib.requireNonEmptyArray(contributors.length);
ValidationLib.requireMaxArrayLength(contributors.length, 100);
uint256 totalWeight = 0;
contributorAddresses = new address[](contributors.length);
rewardAmounts = new uint256[](contributors.length);
for (uint256 i = 0; i < contributors.length; i++) {
ValidationLib.requireNonZeroAddress(contributors[i].walletAddress, "wallet address");
for (uint256 j = 0; j < i; j++) {
require(contributors[i].walletAddress != contributorAddresses[j], "Duplicate contributor address");
}
contributorAddresses[i] = contributors[i].walletAddress;
totalWeight += contributors[i].weight;
}
require(totalWeight == 10000, "Weights must sum to 100%");
}
// Admin functions
function setBaseRewardRate(uint256 _baseRewardRate) external onlyRole(DEFAULT_ADMIN_ROLE) {
ValidationLib.requirePositiveAmount(_baseRewardRate, "reward rate");
baseRewardRate = _baseRewardRate;
emit RewardParametersUpdated(baseRewardRate, minImprovementBps, maxReward);
}
function setMinImprovementBps(uint256 _minImprovementBps) external onlyRole(DEFAULT_ADMIN_ROLE) {
ValidationLib.requirePositiveAmount(_minImprovementBps, "min improvement");
minImprovementBps = _minImprovementBps;
emit RewardParametersUpdated(baseRewardRate, minImprovementBps, maxReward);
}
function setMaxReward(uint256 _maxReward) external onlyRole(DEFAULT_ADMIN_ROLE) {
maxReward = _maxReward;
emit RewardParametersUpdated(baseRewardRate, minImprovementBps, maxReward);
}
// --- Per-model mint budget administration (HOK-2131) ---
// Admin Safe only (DEFAULT_ADMIN_ROLE), separate custody from the attester. Setting/refilling the budget
// is the deliberate, governed act that lets a model mint up to the configured loss ceiling.
/// @notice Set a model's remaining mint budget to an absolute value (initialize, correct, or set to 0 to
/// halt that model's paying mints without pausing the whole contract).
function setMintBudget(uint256 modelId, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 previous = mintBudgetRemaining[modelId];
mintBudgetRemaining[modelId] = amount;
emit MintBudgetSet(modelId, previous, amount);
}
/// @notice Increase a model's remaining mint budget (the Safe top-up that releases a budget-deferred mint).
function topUpMintBudget(uint256 modelId, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
ValidationLib.requirePositiveAmount(amount, "top-up amount");
uint256 newRemaining = mintBudgetRemaining[modelId] + amount;
mintBudgetRemaining[modelId] = newRemaining;
emit MintBudgetToppedUp(modelId, amount, newRemaining);
}
// --- Model-weight lineage administration (HOK-2133) ---
/// @notice The model's current canonical weight head — the registry genesis until the first paying mint
/// advances it. Off-chain producers read this to know what baselineCommitment to attest (and to re-base
/// after losing a concurrent race). Returns 0 only if no genesis has been seeded.
function currentModelHead(uint256 modelId) external view returns (bytes32) {
bytes32 head = modelWeightHead[modelId];
return head == bytes32(0) ? modelRegistry.weightGenesis(modelId) : head;
}
/// @notice Governed brick-prevention: reset a model's lineage head to a known-good commitment if a wrong
/// commitment was accepted (which would otherwise strand the model — no future baseline could match).
/// Emergency correction only; routine evolution happens through paying mints. In a generalized protocol
/// this would become per-model-owner controlled; for launch it is DEFAULT_ADMIN_ROLE (the admin Safe).
function resetModelHead(uint256 modelId, bytes32 newHead) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (newHead == bytes32(0)) revert InvalidHeadReset();
bytes32 oldHead = modelWeightHead[modelId];
if (oldHead == bytes32(0)) oldHead = modelRegistry.weightGenesis(modelId);
modelWeightHead[modelId] = newHead;
emit ModelLineageHeadReset(modelId, oldHead, newHead);
}
// --- Attester registry governance (HOK-2126) ---
// Controlled by DEFAULT_ADMIN_ROLE (the admin Safe; non-emergency changes are expected to route
// through the governance timelock). Launch sequence: addAttester(launchAttester) then
// setAttesterThreshold(1). Emergency: pause() halts mints immediately; rotate add-then-remove,
// then unpause(). The signature verification that reads this registry lands in HOK-2132.
/// @notice Register an attester. 1-of-1 at launch; the set/threshold supports m-of-n later.
function addAttester(address attester) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (attester == address(0)) revert ZeroAttester();
if (isAttester[attester]) revert AttesterAlreadyRegistered(attester);
isAttester[attester] = true;
attesterCount += 1;
emit AttesterAdded(attester, attesterCount);
}
/// @notice Remove an attester. Rotation is add-new-then-remove-old (zero-downtime). A removal that
/// would drop the attester count below the current threshold reverts — use pause() for an immediate
/// halt, then rotate.
function removeAttester(address attester) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (!isAttester[attester]) revert AttesterNotRegistered(attester);
uint256 newCount = attesterCount - 1;
if (newCount < attesterThreshold) revert AttesterThresholdWouldBeUnmet(newCount, attesterThreshold);
isAttester[attester] = false;
attesterCount = newCount;
emit AttesterRemoved(attester, attesterCount);
}
/// @notice Set the number of distinct attester signatures a mint must carry (1 <= m <= attesterCount).
function setAttesterThreshold(uint256 threshold) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (threshold == 0 || threshold > attesterCount) {
revert InvalidAttesterThreshold(threshold, attesterCount);
}
attesterThreshold = threshold;
emit AttesterThresholdUpdated(threshold);
}
/// @notice Permanently disable the legacy submitEvaluation* mint entrypoints (one-way; cannot be
/// re-enabled). After this, submitMintRequest is the only mint path. Call on mainnet so a
/// SUBMITTER_ROLE holder cannot bypass the canonical mint path. (HOK-2125)
function disableLegacyMints() external onlyRole(DEFAULT_ADMIN_ROLE) {
legacyMintsDisabled = true;
emit LegacyMintsDisabled(msg.sender);
}
function pause() external onlyRole(PAUSER_ROLE) {
_pause();
}
function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
/**
* @dev Records a single contribution in the DataContributionRegistry
*/
function _recordSingleContribution(
string memory modelId,
address contributor,
uint256 weightBps,
uint256 contributedSamples,
uint256 totalSamples,
uint256 tokensEarned,
string memory pipelineRunId
) private {
address[] memory contributorAddresses = new address[](1);
contributorAddresses[0] = contributor;
bytes32[] memory contributionHashes = new bytes32[](1);
contributionHashes[0] = keccak256(abi.encodePacked(
modelId,
contributor,
pipelineRunId
));
uint256[] memory weightsBps = new uint256[](1);
weightsBps[0] = weightBps;
uint256[] memory samples = new uint256[](1);
samples[0] = contributedSamples;
uint256[] memory rewardAmounts = new uint256[](1);
rewardAmounts[0] = tokensEarned;
contributionRegistry.recordContributionBatch(
modelId,
contributorAddresses,
contributionHashes,
weightsBps,
samples,
totalSamples,
rewardAmounts,
pipelineRunId
);
}
/**
* @dev Records contributions in the DataContributionRegistry
* @param modelId The model identifier (string)
* @param contributorAddresses Array of contributor addresses
* @param contributors Array of Contributor structs with attribution weights
* @param totalSamples Total sample count for the evaluated dataset
* @param rewardAmounts Array of token amounts earned
* @param pipelineRunId ML pipeline execution reference
*/
function _recordContributions(
string memory modelId,
address[] memory contributorAddresses,
Contributor[] calldata contributors,
uint256 totalSamples,
uint256[] memory rewardAmounts,
string memory pipelineRunId
) private {
// Generate contribution hashes (deterministic based on contribution data)
bytes32[] memory contributionHashes = new bytes32[](contributorAddresses.length);
uint256[] memory contributedSamples = new uint256[](contributorAddresses.length);
uint256[] memory weightsBps = new uint256[](contributorAddresses.length);
for (uint256 i = 0; i < contributorAddresses.length; i++) {
// Generate deterministic hash for this contribution
contributionHashes[i] = keccak256(abi.encodePacked(
modelId,
contributorAddresses[i],
pipelineRunId,
i // Include index to ensure uniqueness within batch
));
// Extract weights (already in basis points)
weightsBps[i] = contributors[i].weight;
// Attribute integer samples proportionally; truncation dust stays unassigned.
contributedSamples[i] = (totalSamples * contributors[i].weight) / 10000;
}
// Record contributions in the registry
contributionRegistry.recordContributionBatch(
modelId,
contributorAddresses,
contributionHashes,
weightsBps,
contributedSamples,
totalSamples,
rewardAmounts,
pipelineRunId
);
}
function _assertCanonicalTokenMatch(uint256 modelId) private view {
address registryToken = modelRegistry.getTokenAddress(modelId);
string memory modelIdStr = _uintToString(modelId);
address tokenManagerToken = tokenManager.getTokenAddress(modelIdStr);
if (tokenManagerToken != address(0) && tokenManagerToken != registryToken) {
revert ModelTokenMismatch(modelId, registryToken, tokenManagerToken);
}
}
// --- Attester signature verification (HOK-2132) ---
/**
* @dev Reverts unless at least `attesterThreshold` distinct registered attesters have signed the
* EIP-712 digest of (modelId, payload, contributors). Signatures must be ordered by strictly
* ascending recovered signer address — this rejects duplicate signers (so one attester cannot be
* counted twice toward the threshold) and makes m-of-n deterministic. Fail-closed when unconfigured.
*/
function _verifyAttestation(
uint256 modelId,
MintRequestPayload calldata payload,
Contributor[] calldata contributors,
bytes[] calldata attesterSignatures
) private view {
uint256 threshold = attesterThreshold;
if (threshold == 0) revert AttestationThresholdNotConfigured();
if (attesterSignatures.length < threshold) {
revert InsufficientAttesterSignatures(attesterSignatures.length, threshold);
}
bytes32 digest = _hashTypedDataV4(_hashMintRequest(modelId, payload, contributors));
address last = address(0);
for (uint256 i = 0; i < attesterSignatures.length; i++) {
address signer = digest.recover(attesterSignatures[i]);
if (signer <= last) revert UnorderedOrDuplicateAttesters(signer);
if (!isAttester[signer]) revert SignerNotAttester(signer);
last = signer;
}
}
function _hashMintRequest(
uint256 modelId,
MintRequestPayload calldata payload,
Contributor[] calldata contributors
) private pure returns (bytes32) {
return
keccak256(
abi.encode(
MINT_REQUEST_TYPEHASH,
modelId,
_hashPayload(payload),
_hashContributors(contributors)
)
);
}
function _hashPayload(MintRequestPayload calldata payload) private pure returns (bytes32) {
return
keccak256(
abi.encode(
MINT_REQUEST_PAYLOAD_TYPEHASH,
keccak256(bytes(payload.pipelineRunId)),
payload.baselineScoreBps,
payload.candidateScoreBps,
payload.maxCostUsdMicro,
payload.actualCostUsdMicro,
payload.totalSamples,
_hashAnchors(payload.anchors),
payload.baselineCommitment,
payload.candidateCommitment,
payload.deadline
)
);
}
function _hashAnchors(BenchmarkAnchors calldata anchors) private pure returns (bytes32) {
return
keccak256(
abi.encode(
BENCHMARK_ANCHORS_TYPEHASH,
anchors.benchmarkSpecHash,
anchors.datasetHash,
anchors.attestationHash,
anchors.idempotencyKey,
keccak256(bytes(anchors.metricName)),
keccak256(bytes(anchors.metricFamily))
)
);
}
function _hashContributors(Contributor[] calldata contributors) private pure returns (bytes32) {
bytes32[] memory hashes = new bytes32[](contributors.length);
for (uint256 i = 0; i < contributors.length; i++) {
hashes[i] = keccak256(
abi.encode(CONTRIBUTOR_TYPEHASH, contributors[i].walletAddress, contributors[i].weight)
);
}
return keccak256(abi.encodePacked(hashes));
}
function _stringToUint(string memory value) private pure returns (uint256 parsed) {
bytes memory buffer = bytes(value);
require(buffer.length > 0, "Model not registered");
for (uint256 i = 0; i < buffer.length; i++) {
uint8 charCode = uint8(buffer[i]);
require(charCode >= 48 && charCode <= 57, "Model not registered");
parsed = (parsed * 10) + (charCode - 48);
}
}
/**
* @dev Converts a uint256 to its ASCII string decimal representation.
*/
function _uintToString(uint256 value) private pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
}
@openzeppelin/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(account),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
@openzeppelin/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/contracts/interfaces/IERC5267.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.0;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}
@openzeppelin/contracts/security/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
@openzeppelin/contracts/security/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
}
@openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@openzeppelin/contracts/utils/ShortStrings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)
pragma solidity ^0.8.8;
import "./StorageSlot.sol";
// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
// | length | 0x BB |
type ShortString is bytes32;
/**
* @dev This library provides functions to convert short memory strings
* into a `ShortString` type that can be used as an immutable variable.
*
* Strings of arbitrary length can be optimized using this library if
* they are short enough (up to 31 bytes) by packing them with their
* length (1 byte) in a single EVM word (32 bytes). Additionally, a
* fallback mechanism can be used for every other case.
*
* Usage example:
*
* ```solidity
* contract Named {
* using ShortStrings for *;
*
* ShortString private immutable _name;
* string private _nameFallback;
*
* constructor(string memory contractName) {
* _name = contractName.toShortStringWithFallback(_nameFallback);
* }
*
* function name() external view returns (string memory) {
* return _name.toStringWithFallback(_nameFallback);
* }
* }
* ```
*/
library ShortStrings {
// Used as an identifier for strings longer than 31 bytes.
bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
error StringTooLong(string str);
error InvalidShortString();
/**
* @dev Encode a string of at most 31 chars into a `ShortString`.
*
* This will trigger a `StringTooLong` error is the input string is too long.
*/
function toShortString(string memory str) internal pure returns (ShortString) {
bytes memory bstr = bytes(str);
if (bstr.length > 31) {
revert StringTooLong(str);
}
return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
}
/**
* @dev Decode a `ShortString` back to a "normal" string.
*/
function toString(ShortString sstr) internal pure returns (string memory) {
uint256 len = byteLength(sstr);
// using `new string(len)` would work locally but is not memory safe.
string memory str = new string(32);
/// @solidity memory-safe-assembly
assembly {
mstore(str, len)
mstore(add(str, 0x20), sstr)
}
return str;
}
/**
* @dev Return the length of a `ShortString`.
*/
function byteLength(ShortString sstr) internal pure returns (uint256) {
uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
if (result > 31) {
revert InvalidShortString();
}
return result;
}
/**
* @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
*/
function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
if (bytes(value).length < 32) {
return toShortString(value);
} else {
StorageSlot.getStringSlot(store).value = value;
return ShortString.wrap(_FALLBACK_SENTINEL);
}
}
/**
* @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*/
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
return toString(value);
} else {
return store;
}
}
/**
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
*/
function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
return byteLength(value);
} else {
return bytes(store).length;
}
}
}
@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
* _Available since v4.9 for `string`, `bytes`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
@openzeppelin/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32")
mstore(0x1c, hash)
message := keccak256(0x00, 0x3c)
}
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, "\x19\x01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
data := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns an Ethereum Signed Data with intended validator, created from a
* `validator` and `data` according to the version 0 of EIP-191.
*
* See {recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x00", validator, data));
}
}
@openzeppelin/contracts/utils/cryptography/EIP712.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.8;
import "./ECDSA.sol";
import "../ShortStrings.sol";
import "../../interfaces/IERC5267.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* _Available since v3.4._
*
* @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
*/
abstract contract EIP712 is IERC5267 {
using ShortStrings for *;
bytes32 private constant _TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _cachedDomainSeparator;
uint256 private immutable _cachedChainId;
address private immutable _cachedThis;
bytes32 private immutable _hashedName;
bytes32 private immutable _hashedVersion;
ShortString private immutable _name;
ShortString private immutable _version;
string private _nameFallback;
string private _versionFallback;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_name = name.toShortStringWithFallback(_nameFallback);
_version = version.toShortStringWithFallback(_versionFallback);
_hashedName = keccak256(bytes(name));
_hashedVersion = keccak256(bytes(version));
_cachedChainId = block.chainid;
_cachedDomainSeparator = _buildDomainSeparator();
_cachedThis = address(this);
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
return _cachedDomainSeparator;
} else {
return _buildDomainSeparator();
}
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {EIP-5267}.
*
* _Available since v4.9._
*/
function eip712Domain()
public
view
virtual
override
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
return (
hex"0f", // 01111
_name.toStringWithFallback(_nameFallback),
_version.toStringWithFallback(_versionFallback),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
}
@openzeppelin/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
@openzeppelin/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
contracts/HokusaiParams.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./interfaces/IHokusaiParams.sol";
/**
* @title HokusaiParams
* @dev Implementation of dynamic parameter management for Hokusai tokens
* Allows governance to adjust key operational parameters without contract upgrades
*/
contract HokusaiParams is IHokusaiParams, AccessControl {
string private constant TOKENS_PER_DELTA_ONE_BOUNDS_ERROR =
"tokensPerDeltaOne must be between 100 and 10000000 whole tokens (wei-scaled)";
uint256 private constant TOKEN_UNIT = 1 ether;
uint256 private constant MAX_TOKENS_PER_DELTA_ONE_WHOLE = 10_000_000;
/// @dev Role identifier for governance operations
bytes32 public constant GOV_ROLE = keccak256("GOV_ROLE");
/// @dev Minimum allowed value for tokensPerDeltaOne (100 whole tokens, wei-scaled)
uint256 public constant MIN_TOKENS_PER_DELTA_ONE = 100 ether;
/// @dev Maximum allowed value for tokensPerDeltaOne (10,000,000 whole tokens, wei-scaled)
uint256 public constant MAX_TOKENS_PER_DELTA_ONE = 10_000_000 ether;
/// @dev Minimum allowed value for infrastructureAccrualBps (10% in basis points)
uint16 public constant MIN_INFRASTRUCTURE_ACCRUAL_BPS = 1000;
/// @dev Maximum allowed value for infrastructureAccrualBps (100% in basis points)
uint16 public constant MAX_INFRASTRUCTURE_ACCRUAL_BPS = 10000;
/// @dev Maximum allowed oracle price per 1000 calls, using the platform's 6-decimal USD convention
uint256 public constant MAX_ORACLE_PRICE_PER_THOUSAND_USD = 1_000_000_000_000;
/// @dev Default price epoch duration (30 days in seconds)
uint256 public constant DEFAULT_PRICE_EPOCH_DURATION = 30 days;
bool public constant DEFAULT_VESTING_ENABLED = true;
uint16 public constant DEFAULT_IMMEDIATE_UNLOCK_BPS = 1000;
uint64 public constant DEFAULT_VESTING_DURATION_SECONDS = 365 days;
uint64 public constant DEFAULT_CLIFF_SECONDS = 0;
/// @dev Number of tokens to mint per unit of deltaOne improvement (global default)
uint256 private _tokensPerDeltaOne;
/// @dev Metric evaluation mode for this model's token
IHokusaiParams.MetricType private _metricType;
/// @dev Infrastructure cost accrual percentage in basis points (global default)
uint16 private _infrastructureAccrualBps;
/// @dev Oracle price in USD per 1000 calls (global default)
uint256 private _oraclePricePerThousandUsd;
/// @dev Hash of the license reference
bytes32 private _licenseHash;
/// @dev URI string for the license reference
string private _licenseURI;
/// @dev Vesting policy for contributor rewards minted via TokenManager.
IHokusaiParams.VestingConfig private _vestingConfig;
/// @dev Price epoch duration in seconds
uint256 private _priceEpochDuration;
/// @dev Struct to track pending parameter updates
struct PendingUpdate {
uint256 value;
uint256 queuedAt;
bool exists;
}
/// @dev Mapping of model ID to epoch start timestamp
mapping(string => uint256) private _priceEpochStart;
/// @dev Mapping of model ID to parameter name to pending update
mapping(string => mapping(string => PendingUpdate)) private _pendingParamUpdates;
/// @dev Mapping of model ID to model-specific tokensPerDeltaOne
mapping(string => uint256) private _modelTokensPerDeltaOne;
/// @dev Mapping of model ID to model-specific infrastructureAccrualBps
mapping(string => uint16) private _modelInfrastructureAccrualBps;
/// @dev Mapping to track if a model has been initialized
mapping(string => bool) private _modelInitialized;
/**
* @dev Constructor to initialize the parameter contract
* @param initialTokensPerDeltaOne Initial tokens per deltaOne value in wei (100-10000000 whole tokens)
* @param initialInfrastructureAccrualBps Initial infrastructure accrual in basis points (1000-10000)
* @param initialOraclePricePerThousandUsd Initial oracle price in USD per 1000 calls
* @param initialLicenseHash Initial license reference hash
* @param initialLicenseURI Initial license reference URI
* @param governor Address to grant GOV_ROLE to
*/
constructor(
uint256 initialTokensPerDeltaOne,
uint16 initialInfrastructureAccrualBps,
uint256 initialOraclePricePerThousandUsd,
bytes32 initialLicenseHash,
string memory initialLicenseURI,
address governor,
IHokusaiParams.VestingConfig memory initialVestingConfig
) {
require(governor != address(0), "Governor cannot be zero address");
initialTokensPerDeltaOne = _normalizeTokensPerDeltaOne(initialTokensPerDeltaOne);
_validateTokensPerDeltaOne(initialTokensPerDeltaOne);
require(
initialInfrastructureAccrualBps >= MIN_INFRASTRUCTURE_ACCRUAL_BPS &&
initialInfrastructureAccrualBps <= MAX_INFRASTRUCTURE_ACCRUAL_BPS,
"infrastructureAccrualBps must be between 1000 and 10000"
);
require(
initialOraclePricePerThousandUsd <= MAX_ORACLE_PRICE_PER_THOUSAND_USD,
"oraclePricePerThousandUsd exceeds maximum"
);
// Set initial values
_tokensPerDeltaOne = initialTokensPerDeltaOne;
_metricType = IHokusaiParams.MetricType.SingleMetric;
_infrastructureAccrualBps = initialInfrastructureAccrualBps;
_oraclePricePerThousandUsd = initialOraclePricePerThousandUsd;
_licenseHash = initialLicenseHash;
_licenseURI = initialLicenseURI;
_priceEpochDuration = DEFAULT_PRICE_EPOCH_DURATION;
_vestingConfig = _resolveInitialVestingConfig(initialVestingConfig);
// Setup access control
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(GOV_ROLE, governor);
}
/**
* @inheritdoc IHokusaiParams
*/
function tokensPerDeltaOne() external view override returns (uint256) {
return _tokensPerDeltaOne;
}
/**
* @inheritdoc IHokusaiParams
*/
function metricType() external view override returns (uint8) {
return uint8(_metricType);
}
/**
* @inheritdoc IHokusaiParams
*/
function infrastructureAccrualBps() external view override returns (uint16) {
return _infrastructureAccrualBps;
}
/**
* @inheritdoc IHokusaiParams
*/
function oraclePricePerThousandUsd() external view override returns (uint256) {
return _oraclePricePerThousandUsd;
}
/**
* @inheritdoc IHokusaiParams
*/
function getProfitShareBps() external view override returns (uint16) {
return 10000 - _infrastructureAccrualBps;
}
/**
* @inheritdoc IHokusaiParams
*/
function licenseHash() external view override returns (bytes32) {
return _licenseHash;
}
/**
* @inheritdoc IHokusaiParams
*/
function licenseURI() external view override returns (string memory) {
return _licenseURI;
}
/**
* @inheritdoc IHokusaiParams
*/
function licenseRef() external view override returns (bytes32 hash, string memory uri) {
return (_licenseHash, _licenseURI);
}
/**
* @inheritdoc IHokusaiParams
*/
function vestingEnabled() external view override returns (bool) {
return _vestingConfig.enabled;
}
/**
* @inheritdoc IHokusaiParams
*/
function immediateUnlockBps() external view override returns (uint16) {
return _vestingConfig.immediateUnlockBps;
}
/**
* @inheritdoc IHokusaiParams
*/
function vestingDurationSeconds() external view override returns (uint64) {
return _vestingConfig.vestingDurationSeconds;
}
/**
* @inheritdoc IHokusaiParams
*/
function cliffSeconds() external view override returns (uint64) {
return _vestingConfig.cliffSeconds;
}
/**
* @inheritdoc IHokusaiParams
*/
function vestingConfig() external view override returns (IHokusaiParams.VestingConfig memory) {
return _vestingConfig;
}
/**
* @inheritdoc IHokusaiParams
*/
function setTokensPerDeltaOne(uint256 newValue) external override onlyRole(GOV_ROLE) {
newValue = _normalizeTokensPerDeltaOne(newValue);
_validateTokensPerDeltaOne(newValue);
uint256 oldValue = _tokensPerDeltaOne;
_tokensPerDeltaOne = newValue;
emit TokensPerDeltaOneSet(oldValue, newValue, msg.sender);
}
/**
* @inheritdoc IHokusaiParams
*/
function setMetricType(uint8 newMetricType) external override onlyRole(GOV_ROLE) {
require(newMetricType <= uint8(IHokusaiParams.MetricType.SingleMetric), "Invalid metric type");
uint8 oldMetricType = uint8(_metricType);
_metricType = IHokusaiParams.MetricType(newMetricType);
emit MetricTypeSet(oldMetricType, newMetricType, msg.sender);
}
/**
* @inheritdoc IHokusaiParams
*/
function setInfrastructureAccrualBps(uint16 newBps) external override onlyRole(GOV_ROLE) {
require(
newBps >= MIN_INFRASTRUCTURE_ACCRUAL_BPS && newBps <= MAX_INFRASTRUCTURE_ACCRUAL_BPS,
"infrastructureAccrualBps must be between 1000 and 10000"
);
uint16 oldBps = _infrastructureAccrualBps;
_infrastructureAccrualBps = newBps;
emit InfrastructureAccrualBpsSet(oldBps, newBps, msg.sender);
}
/**
* @inheritdoc IHokusaiParams
*/
function setOraclePricePerThousandUsd(uint256 newValue) external override onlyRole(GOV_ROLE) {
require(
newValue <= MAX_ORACLE_PRICE_PER_THOUSAND_USD,
"oraclePricePerThousandUsd exceeds maximum"
);
uint256 oldValue = _oraclePricePerThousandUsd;
_oraclePricePerThousandUsd = newValue;
emit OraclePricePerThousandUsdSet(oldValue, newValue, msg.sender);
}
/**
* @inheritdoc IHokusaiParams
*/
function setLicenseRef(bytes32 hash, string memory uri) external override onlyRole(GOV_ROLE) {
bytes32 oldHash = _licenseHash;
_licenseHash = hash;
_licenseURI = uri;
emit LicenseRefSet(oldHash, hash, uri, msg.sender);
}
/**
* @inheritdoc IHokusaiParams
*/
function setVestingConfig(IHokusaiParams.VestingConfig calldata cfg) external override onlyRole(GOV_ROLE) {
_setVestingConfig(cfg);
}
// ============================================================
// EPOCH-BASED PRICE LOCKING FUNCTIONS
// ============================================================
/**
* @dev Initializes a model with current global defaults if not already initialized
* @param modelId The model identifier
*/
function _initializeModelIfNeeded(string memory modelId) private {
if (!_modelInitialized[modelId]) {
_modelTokensPerDeltaOne[modelId] = _tokensPerDeltaOne;
_modelInfrastructureAccrualBps[modelId] = _infrastructureAccrualBps;
_priceEpochStart[modelId] = block.timestamp;
_modelInitialized[modelId] = true;
}
}
/**
* @dev Normalizes and validates a parameter value before it is stored.
*/
function _normalizeTokensPerDeltaOne(uint256 value) private pure returns (uint256) {
if (value <= MAX_TOKENS_PER_DELTA_ONE_WHOLE) {
return value * TOKEN_UNIT;
}
return value;
}
function _resolveInitialVestingConfig(
IHokusaiParams.VestingConfig memory cfg
) private pure returns (IHokusaiParams.VestingConfig memory resolved) {
if (_isDefaultVestingSentinel(cfg)) {
return IHokusaiParams.VestingConfig({
enabled: DEFAULT_VESTING_ENABLED,
immediateUnlockBps: DEFAULT_IMMEDIATE_UNLOCK_BPS,
vestingDurationSeconds: DEFAULT_VESTING_DURATION_SECONDS,
cliffSeconds: DEFAULT_CLIFF_SECONDS
});
}
_validateVestingConfig(cfg);
return cfg;
}
function _isDefaultVestingSentinel(IHokusaiParams.VestingConfig memory cfg) private pure returns (bool) {
return
!cfg.enabled &&
cfg.immediateUnlockBps == 0 &&
cfg.vestingDurationSeconds == 0 &&
cfg.cliffSeconds == 0;
}
function _validateVestingConfig(IHokusaiParams.VestingConfig memory cfg) private pure {
require(cfg.immediateUnlockBps <= 10000, "immediateUnlockBps must be <= 10000");
if (cfg.enabled) {
require(cfg.vestingDurationSeconds > 0, "vesting duration must be > 0");
require(cfg.cliffSeconds <= cfg.vestingDurationSeconds, "cliff exceeds vesting duration");
} else {
require(cfg.cliffSeconds == 0, "disabled vesting cliff must be 0");
require(cfg.vestingDurationSeconds == 0, "disabled vesting duration must be 0");
}
}
function _setVestingConfig(IHokusaiParams.VestingConfig memory cfg) private {
_validateVestingConfig(cfg);
_vestingConfig = cfg;
emit VestingConfigSet(
cfg.enabled,
cfg.immediateUnlockBps,
cfg.vestingDurationSeconds,
cfg.cliffSeconds,
msg.sender
);
}
function _validateTokensPerDeltaOne(uint256 value) private pure {
require(
value >= MIN_TOKENS_PER_DELTA_ONE && value <= MAX_TOKENS_PER_DELTA_ONE,
TOKENS_PER_DELTA_ONE_BOUNDS_ERROR
);
}
/**
* @dev Validates parameter name and value and returns the normalized stored value.
* @param paramName The parameter name
* @param newValue The new value to validate
*/
function _validateParam(string memory paramName, uint256 newValue) private pure returns (uint256 normalizedValue) {
bytes32 paramHash = keccak256(bytes(paramName));
if (paramHash == keccak256(bytes("tokensPerDeltaOne"))) {
normalizedValue = _normalizeTokensPerDeltaOne(newValue);
_validateTokensPerDeltaOne(normalizedValue);
} else if (paramHash == keccak256(bytes("infrastructureAccrualBps"))) {
require(
newValue >= MIN_INFRASTRUCTURE_ACCRUAL_BPS && newValue <= MAX_INFRASTRUCTURE_ACCRUAL_BPS,
"infrastructureAccrualBps must be between 1000 and 10000"
);
normalizedValue = newValue;
} else {
revert("Invalid parameter name");
}
}
/**
* @dev Gets the current value of a parameter for a model
* @param modelId The model identifier
* @param paramName The parameter name
* @return The current parameter value
*/
function _getCurrentParamValue(string memory modelId, string memory paramName) private view returns (uint256) {
bytes32 paramHash = keccak256(bytes(paramName));
if (paramHash == keccak256(bytes("tokensPerDeltaOne"))) {
return _modelInitialized[modelId] ? _modelTokensPerDeltaOne[modelId] : _tokensPerDeltaOne;
} else if (paramHash == keccak256(bytes("infrastructureAccrualBps"))) {
return _modelInitialized[modelId] ? _modelInfrastructureAccrualBps[modelId] : _infrastructureAccrualBps;
}
revert("Invalid parameter name");
}
/**
* @dev Sets a parameter value for a model
* @param modelId The model identifier
* @param paramName The parameter name
* @param newValue The new value
*/
function _setParamValue(string memory modelId, string memory paramName, uint256 newValue) private {
bytes32 paramHash = keccak256(bytes(paramName));
if (paramHash == keccak256(bytes("tokensPerDeltaOne"))) {
_modelTokensPerDeltaOne[modelId] = newValue;
} else if (paramHash == keccak256(bytes("infrastructureAccrualBps"))) {
_modelInfrastructureAccrualBps[modelId] = uint16(newValue);
}
}
/**
* @inheritdoc IHokusaiParams
*/
function queueParamUpdate(
string memory modelId,
string memory paramName,
uint256 newValue
) external override onlyRole(GOV_ROLE) {
require(bytes(modelId).length > 0, "Model ID cannot be empty");
_initializeModelIfNeeded(modelId);
uint256 normalizedValue = _validateParam(paramName, newValue);
uint256 currentValue = _getCurrentParamValue(modelId, paramName);
uint256 effectiveAfter = _priceEpochStart[modelId] + _priceEpochDuration;
_pendingParamUpdates[modelId][paramName] = PendingUpdate({
value: normalizedValue,
queuedAt: block.timestamp,
exists: true
});
emit ParamUpdateQueued(modelId, paramName, currentValue, normalizedValue, effectiveAfter);
}
/**
* @inheritdoc IHokusaiParams
*/
function applyPendingUpdates(string memory modelId) external override {
require(bytes(modelId).length > 0, "Model ID cannot be empty");
require(_modelInitialized[modelId], "Model not initialized");
uint256 epochEnd = _priceEpochStart[modelId] + _priceEpochDuration;
require(block.timestamp >= epochEnd, "Epoch has not ended yet");
// Apply tokensPerDeltaOne if pending
string memory tokensParam = "tokensPerDeltaOne";
if (_pendingParamUpdates[modelId][tokensParam].exists) {
uint256 oldValue = _modelTokensPerDeltaOne[modelId];
uint256 newValue = _pendingParamUpdates[modelId][tokensParam].value;
_modelTokensPerDeltaOne[modelId] = newValue;
delete _pendingParamUpdates[modelId][tokensParam];
emit ParamUpdateApplied(modelId, tokensParam, oldValue, newValue);
}
// Apply infrastructureAccrualBps if pending
string memory infraParam = "infrastructureAccrualBps";
if (_pendingParamUpdates[modelId][infraParam].exists) {
uint256 oldValue = _modelInfrastructureAccrualBps[modelId];
uint256 newValue = _pendingParamUpdates[modelId][infraParam].value;
_modelInfrastructureAccrualBps[modelId] = uint16(newValue);
delete _pendingParamUpdates[modelId][infraParam];
emit ParamUpdateApplied(modelId, infraParam, oldValue, newValue);
}
// Start new epoch
_priceEpochStart[modelId] = block.timestamp;
}
/**
* @inheritdoc IHokusaiParams
*/
function getPriceEpochInfo(string memory modelId) external view override returns (
uint256 epochStart,
uint256 epochEnd,
bool hasPendingUpdates
) {
if (!_modelInitialized[modelId]) {
return (0, 0, false);
}
epochStart = _priceEpochStart[modelId];
epochEnd = epochStart + _priceEpochDuration;
hasPendingUpdates =
_pendingParamUpdates[modelId]["tokensPerDeltaOne"].exists ||
_pendingParamUpdates[modelId]["infrastructureAccrualBps"].exists;
return (epochStart, epochEnd, hasPendingUpdates);
}
/**
* @inheritdoc IHokusaiParams
*/
function cancelPendingUpdate(
string memory modelId,
string memory paramName
) external override onlyRole(GOV_ROLE) {
require(bytes(modelId).length > 0, "Model ID cannot be empty");
require(_pendingParamUpdates[modelId][paramName].exists, "No pending update for this parameter");
delete _pendingParamUpdates[modelId][paramName];
}
/**
* @inheritdoc IHokusaiParams
*/
function emergencySetParam(
string memory modelId,
string memory paramName,
uint256 newValue,
string memory reason
) external override onlyRole(DEFAULT_ADMIN_ROLE) {
require(bytes(modelId).length > 0, "Model ID cannot be empty");
require(bytes(reason).length > 0, "Reason cannot be empty");
_initializeModelIfNeeded(modelId);
uint256 normalizedValue = _validateParam(paramName, newValue);
_setParamValue(modelId, paramName, normalizedValue);
// Clear any pending update for this parameter
if (_pendingParamUpdates[modelId][paramName].exists) {
delete _pendingParamUpdates[modelId][paramName];
}
emit EmergencyParamOverride(modelId, paramName, normalizedValue, reason);
}
/**
* @inheritdoc IHokusaiParams
*/
function priceEpochDuration() external view override returns (uint256) {
return _priceEpochDuration;
}
/**
* @inheritdoc IHokusaiParams
*/
function getEpochStart(string memory modelId) external view override returns (uint256) {
return _priceEpochStart[modelId];
}
/**
* @inheritdoc IHokusaiParams
*/
function getModelTokensPerDeltaOne(string memory modelId) external view override returns (uint256) {
if (!_modelInitialized[modelId]) {
return _tokensPerDeltaOne;
}
return _modelTokensPerDeltaOne[modelId];
}
/**
* @inheritdoc IHokusaiParams
*/
function getModelInfrastructureAccrualBps(string memory modelId) external view override returns (uint16) {
if (!_modelInitialized[modelId]) {
return _infrastructureAccrualBps;
}
return _modelInfrastructureAccrualBps[modelId];
}
}
contracts/HokusaiToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./interfaces/IHokusaiParams.sol";
/**
* @title HokusaiToken
* @dev ERC20 token with controller-based minting and burning
* Cap-based launch tokens separate launch allocation accounting from the reward bucket,
* so totalSupply() can exceed maxSupply once reward minting is enabled.
* Each token has an immutable reference to its parameter contract for dynamic configuration
*/
contract HokusaiToken is ERC20, Ownable {
uint256 public constant REWARD_CAP_MULTIPLIER = 100;
address public controller;
/// @dev Immutable reference to the parameter contract for this token
IHokusaiParams public immutable params;
/// @dev Launch allocation cap = supplier allocation + investor allocation, not the total ERC20 supply cap once reward minting is enabled.
/// Reward issuance is tracked by rewardMinted and capped separately by getRewardMintingCap().
uint256 public immutable maxSupply;
/// @dev Model supplier allocation amount (not minted until distributeModelSupplierAllocation is called and split between immediate/vault recipients)
uint256 public immutable modelSupplierAllocation;
/// @dev Investor allocation reserved for AMM-driven mints
uint256 public immutable investorAllocation;
/// @dev Address to receive model supplier allocation
address public immutable modelSupplierRecipient;
/// @dev Flag indicating if model supplier allocation has been distributed through the single-use split-mint path
bool public modelSupplierDistributed;
/// @dev Net investor mints after investor-side burns
uint256 public investorMinted;
/// @dev Total rewards minted across immediate and vested flows
uint256 public rewardMinted;
event ControllerUpdated(address indexed newController);
event Minted(address indexed to, uint256 amount);
event Burned(address indexed from, uint256 amount);
event TokenSupplyConfigured(
uint256 initialSupply,
uint256 maxSupply,
uint256 modelSupplierAllocation,
address indexed modelSupplierRecipient
);
event ModelSupplierAllocationDistributed(address indexed recipient, uint256 amount);
modifier onlyController() {
require(msg.sender == controller, "Only controller can call this function");
_;
}
/**
* @dev Constructor to initialize the token
* @param _name The name of the token (e.g., "Hokusai Model Token")
* @param _symbol The symbol of the token (e.g., "HMT")
* @param _controller The address that will have mint/burn privileges
* @param _params The address of the parameter contract for this token
* @param _initialSupply Initial supply to mint to controller (for legacy deployment), or 0 for cap-based deployment
* @param _maxSupply Launch allocation cap for supplier + investor allocation; not the total ERC20 supply cap once reward minting is enabled (0 for legacy mode = unlimited)
* @param _modelSupplierAllocation Amount allocated for model supplier (0 for legacy mode)
* @param _investorAllocation Amount allocated for investor purchases (0 for legacy mode)
* @param _modelSupplierRecipient Address to receive model supplier allocation (address(0) for legacy mode)
*/
constructor(
string memory _name,
string memory _symbol,
address _controller,
address _params,
uint256 _initialSupply,
uint256 _maxSupply,
uint256 _modelSupplierAllocation,
uint256 _investorAllocation,
address _modelSupplierRecipient
) ERC20(_name, _symbol) Ownable() {
require(bytes(_name).length > 0, "Token name cannot be empty");
require(bytes(_symbol).length > 0, "Token symbol cannot be empty");
require(_controller != address(0), "Controller cannot be zero address");
require(_params != address(0), "Params cannot be zero address");
// Determine mode: cap-based if maxSupply > 0, legacy otherwise
bool isCapBased = _maxSupply > 0;
if (isCapBased) {
require(
_modelSupplierAllocation + _investorAllocation == _maxSupply,
"Max supply must equal supplier + investor allocations"
);
require(_modelSupplierRecipient != address(0), "Model supplier recipient cannot be zero address");
} else {
require(_initialSupply > 0, "Initial supply must be greater than zero");
require(_investorAllocation == 0, "Investor allocation only valid for cap-based tokens");
}
controller = _controller;
params = IHokusaiParams(_params);
// Initialize immutables (must be assigned unconditionally)
maxSupply = isCapBased ? _maxSupply : type(uint256).max;
modelSupplierAllocation = isCapBased ? _modelSupplierAllocation : 0;
investorAllocation = isCapBased ? _investorAllocation : 0;
modelSupplierRecipient = isCapBased ? _modelSupplierRecipient : address(0);
modelSupplierDistributed = !isCapBased; // True for legacy, false for cap-based
// Mint initial supply for legacy mode
if (!isCapBased) {
_mint(_controller, _initialSupply);
emit Minted(_controller, _initialSupply);
}
emit TokenSupplyConfigured(_initialSupply, maxSupply, modelSupplierAllocation, modelSupplierRecipient);
emit ControllerUpdated(_controller);
}
/**
* @dev Sets the controller address that can mint and burn tokens
* @param _controller The address to set as controller
*/
function setController(address _controller) external onlyOwner {
require(_controller != address(0), "Controller cannot be zero address");
controller = _controller;
emit ControllerUpdated(_controller);
}
/**
* @dev Mints tokens to a specified address
* @param to The address to mint tokens to
* @param amount The amount of tokens to mint
*/
function mint(address to, uint256 amount) external onlyController {
require(maxSupply == type(uint256).max, "Use mintInvestor or mintReward on cap-based tokens");
_mint(to, amount);
emit Minted(to, amount);
}
function mintInvestor(address to, uint256 amount) external onlyController {
if (maxSupply < type(uint256).max) {
require(investorMinted + amount <= investorAllocation, "Exceeds investor allocation");
investorMinted += amount;
}
_mint(to, amount);
emit Minted(to, amount);
}
function mintReward(address to, uint256 amount) external onlyController {
if (maxSupply < type(uint256).max) {
uint256 rewardCap = getRewardMintingCap();
require(rewardMinted + amount <= rewardCap, "Exceeds reward mint cap");
rewardMinted += amount;
}
_mint(to, amount);
emit Minted(to, amount);
}
/**
* @dev Distributes model supplier allocation once by minting the immediate portion to
* the supplier recipient and the vested portion to the vesting vault.
* @param vault Vesting vault recipient for the vested portion, or zero when fully immediate
* @param vestedAmount Portion of the supplier allocation to mint to the vesting vault
*/
function distributeModelSupplierAllocation(address vault, uint256 vestedAmount) external onlyController {
require(!modelSupplierDistributed, "Model supplier allocation already distributed");
require(modelSupplierAllocation > 0, "No model supplier allocation set");
require(vestedAmount <= modelSupplierAllocation, "Vested exceeds supplier allocation");
modelSupplierDistributed = true;
uint256 immediateAmount = modelSupplierAllocation - vestedAmount;
if (immediateAmount > 0) {
_mint(modelSupplierRecipient, immediateAmount);
emit Minted(modelSupplierRecipient, immediateAmount);
}
if (vestedAmount > 0) {
require(vault != address(0), "Vault required for vested portion");
_mint(vault, vestedAmount);
emit Minted(vault, vestedAmount);
}
emit ModelSupplierAllocationDistributed(modelSupplierRecipient, modelSupplierAllocation);
}
/**
* @dev Burns tokens from caller's balance
* @param amount The amount of tokens to burn
*/
function burn(uint256 amount) external {
_burn(msg.sender, amount);
emit Burned(msg.sender, amount);
}
/**
* @dev Burns tokens from a specified address using allowance
* @param from The address to burn tokens from
* @param amount The amount of tokens to burn
*/
function burnFrom(address from, uint256 amount) external onlyController {
_burn(from, amount);
emit Burned(from, amount);
}
function burnInvestor(address from, uint256 amount) external onlyController {
if (maxSupply < type(uint256).max) {
require(amount <= investorMinted, "Burn exceeds investor minted");
investorMinted -= amount;
}
_burn(from, amount);
emit Burned(from, amount);
}
/**
* @dev Burns tokens for an AMM sell, reducing investor headroom first, then reward
* accounting. Supplier-distributed tokens have no separate counter so they are
* burned without further tracking — ERC20 _burn guards against insufficient balance.
*/
function burnAMM(address from, uint256 amount) external onlyController {
if (maxSupply < type(uint256).max) {
uint256 investorBurn = amount <= investorMinted ? amount : investorMinted;
investorMinted -= investorBurn;
uint256 remaining = amount - investorBurn;
uint256 rewardBurn = remaining <= rewardMinted ? remaining : rewardMinted;
rewardMinted -= rewardBurn;
}
_burn(from, amount);
emit Burned(from, amount);
}
/**
* @dev Returns the remaining investor allocation for cap-based tokens.
*/
function getRemainingSupply() external view returns (uint256) {
if (maxSupply >= type(uint256).max) {
return type(uint256).max; // Legacy tokens have unlimited supply
}
if (investorMinted >= investorAllocation) {
return 0;
}
return investorAllocation - investorMinted;
}
function getRemainingInvestorAllocation() external view returns (uint256) {
if (maxSupply >= type(uint256).max) {
return type(uint256).max;
}
if (investorMinted >= investorAllocation) {
return 0;
}
return investorAllocation - investorMinted;
}
function getRewardMintingCap() public view returns (uint256) {
if (maxSupply >= type(uint256).max) {
return type(uint256).max;
}
return REWARD_CAP_MULTIPLIER * params.tokensPerDeltaOne();
}
function getRemainingRewardAllocation() external view returns (uint256) {
uint256 rewardCap = getRewardMintingCap();
if (rewardCap == type(uint256).max) {
return type(uint256).max;
}
if (rewardMinted >= rewardCap) {
return 0;
}
return rewardCap - rewardMinted;
}
}
contracts/TokenManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./libraries/AccessControlBase.sol";
import "./libraries/RewardSplitLib.sol";
import "./libraries/ValidationLib.sol";
import "./interfaces/IModelRegistry.sol";
import "./HokusaiToken.sol";
import "./HokusaiParams.sol";
import "./interfaces/IHokusaiParams.sol";
import "./interfaces/IManagedHokusaiToken.sol";
import "./interfaces/IRewardVestingVault.sol";
/**
* @title TokenManager
* @dev Manages token deployment and operations for models
* Users can deploy tokens directly and pay gas fees themselves
*/
contract TokenManager is Ownable, AccessControlBase, ReentrancyGuard {
IModelRegistry public registry;
address public deltaVerifier;
/// @dev Structure for initial parameter values when deploying a token
struct InitialParams {
uint256 tokensPerDeltaOne; // Wei-scaled tokens per deltaOne improvement (100-10,000,000 whole tokens)
uint16 infrastructureAccrualBps; // Infrastructure accrual in basis points (1000-10000, i.e., 10-100%)
uint256 initialOraclePricePerThousandUsd; // Initial oracle price in USD per 1000 calls
bytes32 licenseHash; // Hash of license reference
string licenseURI; // URI for license reference
address governor; // Address to grant GOV_ROLE
IHokusaiParams.VestingConfig vestingConfig; // Contributor reward vesting policy
}
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant DEPLOYER_ROLE = keccak256("DEPLOYER_ROLE");
// Track deployed tokens and their params
mapping(string => address) public modelTokens;
mapping(address => string) public tokenToModel;
mapping(string => address) public modelParams;
// Optional platform fee for deployment
uint256 public deploymentFee = 0;
address public feeRecipient;
IRewardVestingVault public vestingVault;
event TokenDeployed(
string indexed modelId,
address indexed tokenAddress,
address indexed deployer,
string name,
string symbol,
uint256 totalSupply
);
event ParamsDeployed(
string indexed modelId,
address indexed paramsAddress,
address indexed deployer,
uint256 tokensPerDeltaOne,
uint16 infrastructureAccrualBps,
uint256 initialOraclePricePerThousandUsd
);
event TokensMinted(string indexed modelId, address indexed recipient, uint256 amount);
event TokensBurned(string indexed modelId, address indexed account, uint256 amount);
event DeltaVerifierUpdated(address indexed newDeltaVerifier);
event VestingVaultUpdated(address indexed vestingVault);
event BatchMinted(string indexed modelId, address[] recipients, uint256[] amounts, uint256 totalAmount);
event ContributorSkipped(address indexed contributor, uint256 index);
event DeploymentFeeUpdated(uint256 newFee);
event AllocationDistributed(
string indexed modelId,
address indexed modelSupplierRecipient,
uint256 modelSupplierAllocation,
address indexed investorRecipient,
uint256 investorAllocation
);
event ModelSupplierAllocationDistributed(
string indexed modelId,
address indexed recipient,
uint256 amount
);
event DeploymentFeesWithdrawn(address indexed recipient, uint256 amount);
event RewardVestingCreated(
string indexed modelId,
address indexed contributor,
uint256 totalReward,
uint256 immediateAmount,
uint256 vestedAmount,
uint256 vestingStart,
uint256 vestingEnd
);
event SupplierAllocationVested(
string indexed modelId,
address indexed supplierRecipient,
uint256 totalAllocation,
uint256 immediateAmount,
uint256 vestedAmount,
uint256 vestingStart,
uint256 vestingEnd
);
constructor(address registryAddress)
Ownable()
AccessControlBase(msg.sender)
{
ValidationLib.requireNonZeroAddress(registryAddress, "registry address");
registry = IModelRegistry(registryAddress);
feeRecipient = msg.sender;
// Grant additional roles using AccessControlBase
bytes32[] memory roles = new bytes32[](2);
roles[0] = MINTER_ROLE;
roles[1] = DEPLOYER_ROLE;
_grantRoles(roles, msg.sender);
}
/**
* @dev Deploy a new token for a model with custom parameters - USER PAYS GAS
* @param modelId The model identifier (string)
* @param name Token name
* @param symbol Token symbol
* @param totalSupply The total supply to mint initially
* @param initialParams Initial parameter values for the token
* @return tokenAddress The deployed token address
*/
function deployTokenWithParams(
string memory modelId,
string memory name,
string memory symbol,
uint256 totalSupply,
InitialParams memory initialParams
) public payable nonReentrant returns (address tokenAddress) {
// Validate inputs using ValidationLib
ValidationLib.requireNonEmptyString(modelId, "model ID");
ValidationLib.requireNonEmptyString(name, "token name");
ValidationLib.requireNonEmptyString(symbol, "token symbol");
ValidationLib.requirePositiveAmount(totalSupply, "total supply");
ValidationLib.requireNonZeroAddress(initialParams.governor, "governor");
// Check if model already has a token
require(modelTokens[modelId] == address(0), "Token already deployed for this model");
_collectDeploymentFee();
// Deploy HokusaiParams first
HokusaiParams newParams = new HokusaiParams(
initialParams.tokensPerDeltaOne,
initialParams.infrastructureAccrualBps,
initialParams.initialOraclePricePerThousandUsd,
initialParams.licenseHash,
initialParams.licenseURI,
initialParams.governor,
initialParams.vestingConfig
);
address paramsAddress = address(newParams);
// Deploy HokusaiToken with params address (legacy mode: initialSupply > 0, maxSupply = 0)
HokusaiToken newToken = new HokusaiToken(
name,
symbol,
address(this),
paramsAddress,
totalSupply, // initialSupply
0, // maxSupply (0 = legacy mode)
0, // modelSupplierAllocation
0, // investorAllocation
address(0) // modelSupplierRecipient
);
tokenAddress = address(newToken);
// Store token and params mappings
modelTokens[modelId] = tokenAddress;
tokenToModel[tokenAddress] = modelId;
modelParams[modelId] = paramsAddress;
// Note: Registry registration is not attempted as it uses uint256 modelId
// The ModelRegistry can be updated separately to support string modelIds if needed
emit ParamsDeployed(
modelId,
paramsAddress,
msg.sender,
initialParams.tokensPerDeltaOne,
initialParams.infrastructureAccrualBps,
initialParams.initialOraclePricePerThousandUsd
);
emit TokenDeployed(modelId, tokenAddress, msg.sender, name, symbol, totalSupply);
_refundExcess();
return tokenAddress;
}
/**
* @dev Deploy a new token for a model with allocation split - USER PAYS GAS
* Uses cap-based model: investor allocation is a max cap enforced by the contract,
* model supplier allocation is distributed when model is verified
* @param modelId The model identifier (string)
* @param name Token name
* @param symbol Token symbol
* @param modelSupplierAllocation Tokens allocated to model supplier (minted when verified)
* @param modelSupplierRecipient Address to receive model supplier allocation
* @param investorAllocation Maximum tokens that can be minted for investors via AMM
* @param initialParams Initial parameter values for the token
* @return tokenAddress The deployed token address
*/
function deployTokenWithAllocations(
string memory modelId,
string memory name,
string memory symbol,
uint256 modelSupplierAllocation,
address modelSupplierRecipient,
uint256 investorAllocation,
InitialParams memory initialParams
) public payable nonReentrant returns (address tokenAddress) {
// Validate inputs
ValidationLib.requireNonEmptyString(modelId, "model ID");
ValidationLib.requireNonEmptyString(name, "token name");
ValidationLib.requireNonEmptyString(symbol, "token symbol");
ValidationLib.requirePositiveAmount(modelSupplierAllocation, "model supplier allocation");
ValidationLib.requireNonZeroAddress(modelSupplierRecipient, "model supplier recipient");
ValidationLib.requirePositiveAmount(investorAllocation, "investor allocation");
ValidationLib.requireNonZeroAddress(initialParams.governor, "governor");
// Check if model already has a token
require(modelTokens[modelId] == address(0), "Token already deployed for this model");
_collectDeploymentFee();
// Deploy HokusaiParams first
HokusaiParams newParams = new HokusaiParams(
initialParams.tokensPerDeltaOne,
initialParams.infrastructureAccrualBps,
initialParams.initialOraclePricePerThousandUsd,
initialParams.licenseHash,
initialParams.licenseURI,
initialParams.governor,
initialParams.vestingConfig
);
address paramsAddress = address(newParams);
// Calculate launch allocation cap (model supplier + investor allocations)
uint256 maxSupply = modelSupplierAllocation + investorAllocation;
// Deploy HokusaiToken with cap-based model (no initial minting)
HokusaiToken newToken = new HokusaiToken(
name,
symbol,
address(this),
paramsAddress,
0, // initialSupply (0 for cap-based model)
maxSupply, // maxSupply cap
modelSupplierAllocation, // model supplier allocation (not minted yet)
investorAllocation, // investor allocation
modelSupplierRecipient // model supplier recipient
);
tokenAddress = address(newToken);
// Store token and params mappings
modelTokens[modelId] = tokenAddress;
tokenToModel[tokenAddress] = modelId;
modelParams[modelId] = paramsAddress;
emit ParamsDeployed(
modelId,
paramsAddress,
msg.sender,
initialParams.tokensPerDeltaOne,
initialParams.infrastructureAccrualBps,
initialParams.initialOraclePricePerThousandUsd
);
emit TokenDeployed(modelId, tokenAddress, msg.sender, name, symbol, maxSupply);
emit AllocationDistributed(
modelId,
modelSupplierRecipient,
modelSupplierAllocation,
address(0), // No immediate investor recipient (minted via AMM)
investorAllocation
);
_refundExcess();
return tokenAddress;
}
/**
* @dev Distributes model supplier allocation when model is verified
* This should be called after model registration is complete and verified.
* Distribution mints into the supplier wallet, increases redeemable AMM supply,
* and can move spot price and bonding-curve behavior.
* @param modelId The model identifier
*/
function distributeModelSupplierAllocation(string memory modelId) external onlyOwner nonReentrant {
ValidationLib.requireNonEmptyString(modelId, "model ID");
address tokenAddress = modelTokens[modelId];
require(tokenAddress != address(0), "Token not deployed for this model");
_distributeSupplierWithVesting(modelId, tokenAddress);
}
function _distributeSupplierWithVesting(string memory modelId, address tokenAddress) private {
HokusaiToken token = HokusaiToken(tokenAddress);
IHokusaiParams params = token.params();
address supplierRecipient = token.modelSupplierRecipient();
uint256 totalAllocation = token.modelSupplierAllocation();
if (!params.vestingEnabled()) {
token.distributeModelSupplierAllocation(address(0), 0);
emit ModelSupplierAllocationDistributed(modelId, supplierRecipient, totalAllocation);
return;
}
(uint256 immediateAmount, uint256 vestedAmount) =
RewardSplitLib.split(totalAllocation, params.immediateUnlockBps());
if (vestedAmount == 0) {
token.distributeModelSupplierAllocation(address(0), 0);
emit ModelSupplierAllocationDistributed(modelId, supplierRecipient, totalAllocation);
return;
}
require(address(vestingVault) != address(0), "Vesting vault not configured");
uint64 duration = params.vestingDurationSeconds();
token.distributeModelSupplierAllocation(address(vestingVault), vestedAmount);
// slither-disable-next-line unused-return
vestingVault.createSchedule(
modelId,
tokenAddress,
supplierRecipient,
vestedAmount,
params.cliffSeconds(),
duration
);
emit ModelSupplierAllocationDistributed(modelId, supplierRecipient, totalAllocation);
emit SupplierAllocationVested(
modelId,
supplierRecipient,
totalAllocation,
immediateAmount,
vestedAmount,
block.timestamp,
block.timestamp + uint256(duration)
);
}
/**
* @dev Set deployment fee (owner only)
*/
function setDeploymentFee(uint256 _fee) external onlyOwner {
deploymentFee = _fee;
emit DeploymentFeeUpdated(_fee);
}
/**
* @dev Set fee recipient (owner only)
*/
function setFeeRecipient(address _recipient) external onlyOwner {
ValidationLib.requireNonZeroAddress(_recipient, "fee recipient");
feeRecipient = _recipient;
}
/**
* @dev Sets the DeltaVerifier contract address
* @param _deltaVerifier The DeltaVerifier contract address
*/
function setDeltaVerifier(address _deltaVerifier) external onlyOwner {
ValidationLib.requireNonZeroAddress(_deltaVerifier, "delta verifier");
deltaVerifier = _deltaVerifier;
emit DeltaVerifierUpdated(_deltaVerifier);
}
/**
* @dev Sets the reward vesting vault used for contributor reward schedules.
*/
function setVestingVault(address vaultAddress) external onlyOwner {
ValidationLib.requireNonZeroAddress(vaultAddress, "vesting vault");
require(address(vestingVault) == address(0), "Vesting vault already set");
vestingVault = IRewardVestingVault(vaultAddress);
emit VestingVaultUpdated(vaultAddress);
}
/**
* @dev True when the caller is the pool ModelRegistry binds to `modelId`.
* Registry registration is the AMM's only mint/burn authorization: a pool
* can mint or burn its own model's token and nothing else, so one pool's
* upgrade authority cannot reach other models. Pools are never granted
* MINTER_ROLE (which stays model-agnostic for trusted non-AMM minters).
* To cut off a pool, pause it or deactivate its model in the registry.
*/
function _isModelPool(string memory modelId) private view returns (bool) {
return registry.getPool(modelId) == msg.sender;
}
/**
* @dev Returns the redeemable circulating supply used by AMM pricing.
* Excludes balances held in the vesting vault until contributors claim them.
* Supplier-allocation tokens count as redeemable circulating supply once distributed
* because only vesting-vault balances are excluded, so supplier distribution timing
* can affect AMM spot price and bonding-curve behavior.
*/
function getRedeemableSupply(string memory modelId) external view returns (uint256) {
ValidationLib.requireNonEmptyString(modelId, "model ID");
address tokenAddress = modelTokens[modelId];
require(tokenAddress != address(0), "Token not deployed for this model");
uint256 totalSupply = IERC20(tokenAddress).totalSupply();
address vault = address(vestingVault);
if (vault == address(0)) {
return totalSupply;
}
uint256 lockedSupply = IERC20(tokenAddress).balanceOf(vault);
return totalSupply > lockedSupply ? totalSupply - lockedSupply : 0;
}
/**
* @dev Mints tokens for a specific model to a recipient (general-purpose, no vesting)
* @param modelId The model identifier
* @param recipient The address to receive the tokens
* @param amount The amount of tokens to mint
*/
// slither-disable-next-line reentrancy-events
function mintTokens(string memory modelId, address recipient, uint256 amount)
external
{
require(
_isModelPool(modelId) ||
hasRole(MINTER_ROLE, msg.sender) || msg.sender == owner() || msg.sender == deltaVerifier,
"Caller is not authorized to mint"
);
// Use ValidationLib for cleaner validation
ValidationLib.requireNonEmptyString(modelId, "model ID");
ValidationLib.requireNonZeroAddress(recipient, "recipient");
ValidationLib.requirePositiveAmount(amount, "amount");
address tokenAddress = modelTokens[modelId];
require(tokenAddress != address(0), "Token not deployed for this model");
require(
!registry.isStringRegistered(modelId) || registry.isStringActive(modelId),
"Model is deactivated"
);
_mintInvestorToken(tokenAddress, recipient, amount);
emit TokensMinted(modelId, recipient, amount);
}
/**
* @dev Mints tokens to multiple recipients in a single transaction (general-purpose, no vesting)
* @param modelId The model identifier
* @param recipients Array of addresses to receive tokens
* @param amounts Array of token amounts corresponding to each recipient
*/
// slither-disable-next-line reentrancy-events
function batchMintTokens(
string memory modelId,
address[] calldata recipients,
uint256[] calldata amounts
)
external
{
require(
hasRole(MINTER_ROLE, msg.sender) || msg.sender == owner() || msg.sender == deltaVerifier,
"Unauthorized"
);
// Use ValidationLib for batch validation
ValidationLib.requireNonEmptyString(modelId, "model ID");
ValidationLib.requireValidBatch(recipients.length, amounts.length, 100);
address tokenAddress = modelTokens[modelId];
require(tokenAddress != address(0), "Token not deployed for this model");
require(
!registry.isStringRegistered(modelId) || registry.isStringActive(modelId),
"Model is deactivated"
);
uint256 totalAmount = 0;
for (uint256 i = 0; i < recipients.length; i++) {
ValidationLib.requireNonZeroAddress(recipients[i], "recipient");
if (amounts[i] == 0) {
emit ContributorSkipped(recipients[i], i);
continue;
}
_mintInvestorToken(tokenAddress, recipients[i], amounts[i]);
totalAmount += amounts[i];
}
emit BatchMinted(modelId, recipients, amounts, totalAmount);
}
/**
* @dev Mints DeltaOne contributor reward tokens with optional vesting
* @param modelId The model identifier
* @param recipient The contributor address to receive the reward
* @param amount The total reward amount
*/
// slither-disable-next-line reentrancy-events
function mintReward(string memory modelId, address recipient, uint256 amount)
external
{
require(
hasRole(MINTER_ROLE, msg.sender) || msg.sender == owner() || msg.sender == deltaVerifier,
"Caller is not authorized to mint"
);
ValidationLib.requireNonEmptyString(modelId, "model ID");
ValidationLib.requireNonZeroAddress(recipient, "recipient");
ValidationLib.requirePositiveAmount(amount, "amount");
address tokenAddress = modelTokens[modelId];
require(tokenAddress != address(0), "Token not deployed for this model");
require(
!registry.isStringRegistered(modelId) || registry.isStringActive(modelId),
"Model is deactivated"
);
_mintRewardWithVesting(modelId, tokenAddress, recipient, amount);
emit TokensMinted(modelId, recipient, amount);
}
/**
* @dev Mints DeltaOne contributor rewards to multiple recipients with optional vesting
* @param modelId The model identifier
* @param recipients Array of contributor addresses to receive rewards
* @param amounts Array of reward amounts corresponding to each recipient
*/
// slither-disable-next-line reentrancy-events
function batchMintReward(
string memory modelId,
address[] calldata recipients,
uint256[] calldata amounts
)
external
{
require(
hasRole(MINTER_ROLE, msg.sender) || msg.sender == owner() || msg.sender == deltaVerifier,
"Unauthorized"
);
ValidationLib.requireNonEmptyString(modelId, "model ID");
ValidationLib.requireValidBatch(recipients.length, amounts.length, 100);
address tokenAddress = modelTokens[modelId];
require(tokenAddress != address(0), "Token not deployed for this model");
require(
!registry.isStringRegistered(modelId) || registry.isStringActive(modelId),
"Model is deactivated"
);
uint256 totalAmount = 0;
for (uint256 i = 0; i < recipients.length; i++) {
ValidationLib.requireNonZeroAddress(recipients[i], "recipient");
if (amounts[i] == 0) {
emit ContributorSkipped(recipients[i], i);
continue;
}
_mintRewardWithVesting(modelId, tokenAddress, recipients[i], amounts[i]);
totalAmount += amounts[i];
}
emit BatchMinted(modelId, recipients, amounts, totalAmount);
}
/**
* @dev Burns tokens from a specific account for a model
* @param modelId The model identifier
* @param account The address to burn tokens from
* @param amount The amount of tokens to burn
* Note: Can be called by owner, MINTER_ROLE holders, or deltaVerifier (not by AMM pools)
*/
// slither-disable-next-line reentrancy-events
function burnTokens(string memory modelId, address account, uint256 amount)
external
{
require(
hasRole(MINTER_ROLE, msg.sender) || msg.sender == owner() || msg.sender == deltaVerifier,
"Caller is not authorized to burn"
);
// Use ValidationLib for cleaner validation
ValidationLib.requireNonEmptyString(modelId, "model ID");
ValidationLib.requireNonZeroAddress(account, "account");
ValidationLib.requirePositiveAmount(amount, "amount");
address tokenAddress = modelTokens[modelId];
require(tokenAddress != address(0), "Token not deployed for this model");
HokusaiToken(tokenAddress).burnFrom(account, amount);
emit TokensBurned(modelId, account, amount);
}
/**
* @dev Burns investor-minted tokens from a specific account for a model.
* Used by AMM sell flows so investor allocation headroom is restored.
*/
// slither-disable-next-line reentrancy-events
function burnInvestorTokens(string memory modelId, address account, uint256 amount)
external
{
require(
hasRole(MINTER_ROLE, msg.sender) || msg.sender == owner() || msg.sender == deltaVerifier,
"Caller is not authorized to burn"
);
ValidationLib.requireNonEmptyString(modelId, "model ID");
ValidationLib.requireNonZeroAddress(account, "account");
ValidationLib.requirePositiveAmount(amount, "amount");
address tokenAddress = modelTokens[modelId];
require(tokenAddress != address(0), "Token not deployed for this model");
_burnInvestorToken(tokenAddress, account, amount);
emit TokensBurned(modelId, account, amount);
}
/**
* @dev Burns tokens from an AMM sell, restoring investor headroom first then reward.
* Allows both investor and reward token holders to sell into the AMM without reverting.
*/
// slither-disable-next-line reentrancy-events
function burnAMMTokens(string memory modelId, address account, uint256 amount)
external
{
bool isModelPool = _isModelPool(modelId);
require(
isModelPool || hasRole(MINTER_ROLE, msg.sender) || msg.sender == owner() || msg.sender == deltaVerifier,
"Caller is not authorized to burn"
);
// A pool may only burn tokens it holds itself (sold into it).
require(!isModelPool || account == msg.sender, "Pool can only burn own balance");
ValidationLib.requireNonEmptyString(modelId, "model ID");
ValidationLib.requireNonZeroAddress(account, "account");
ValidationLib.requirePositiveAmount(amount, "amount");
address tokenAddress = modelTokens[modelId];
require(tokenAddress != address(0), "Token not deployed for this model");
_burnAMMToken(tokenAddress, account, amount);
emit TokensBurned(modelId, account, amount);
}
/**
* @dev Gets the token address for a specific model
* @param modelId The model identifier
* @return The token contract address
*/
function getTokenAddress(string memory modelId) external view returns (address) {
return modelTokens[modelId];
}
/**
* @dev Checks if a model has a deployed token
* @param modelId The model identifier
* @return True if the model has a token deployed
*/
function hasToken(string memory modelId) external view returns (bool) {
return modelTokens[modelId] != address(0);
}
/**
* @dev Gets the model ID for a specific token address
* @param tokenAddress The token address
* @return The model identifier
*/
function getModelId(address tokenAddress) external view returns (string memory) {
ValidationLib.requireNonZeroAddress(tokenAddress, "token address");
ValidationLib.requireNonEmptyString(tokenToModel[tokenAddress], "token");
return tokenToModel[tokenAddress];
}
/**
* @dev Gets the params address for a specific model
* @param modelId The model identifier
* @return The params contract address
*/
function getParamsAddress(string memory modelId) external view returns (address) {
return modelParams[modelId];
}
/**
* @dev Checks if a model has deployed params
* @param modelId The model identifier
* @return True if the model has params deployed
*/
function hasParams(string memory modelId) external view returns (bool) {
return modelParams[modelId] != address(0);
}
function _collectDeploymentFee() private {
if (deploymentFee > 0) {
require(msg.value >= deploymentFee, "Insufficient deployment fee");
}
}
function _refundExcess() private {
if (msg.value > deploymentFee) {
uint256 excess = msg.value - deploymentFee;
(bool refunded, ) = msg.sender.call{value: excess}("");
require(refunded, "Failed to refund excess payment");
}
}
function withdrawDeploymentFees() external onlyOwner nonReentrant {
uint256 balance = address(this).balance;
require(balance > 0, "No fees to withdraw");
(bool sent, ) = feeRecipient.call{value: balance}("");
require(sent, "Failed to send deployment fees");
emit DeploymentFeesWithdrawn(feeRecipient, balance);
}
receive() external payable {}
// slither-disable-next-line reentrancy-events
function _mintRewardWithVesting(
string memory modelId,
address tokenAddress,
address recipient,
uint256 amount
) private {
HokusaiToken token = HokusaiToken(tokenAddress);
IHokusaiParams params = token.params();
if (!params.vestingEnabled()) {
_mintRewardToken(tokenAddress, recipient, amount);
return;
}
(uint256 immediateAmount, uint256 vestedAmount) =
RewardSplitLib.split(amount, params.immediateUnlockBps());
if (immediateAmount > 0) {
_mintRewardToken(tokenAddress, recipient, immediateAmount);
}
if (vestedAmount == 0) {
return;
}
require(address(vestingVault) != address(0), "Vesting vault not configured");
uint64 duration = params.vestingDurationSeconds();
_mintRewardToken(tokenAddress, address(vestingVault), vestedAmount);
// slither-disable-next-line unused-return
vestingVault.createSchedule(
modelId,
tokenAddress,
recipient,
vestedAmount,
params.cliffSeconds(),
duration
);
emit RewardVestingCreated(
modelId,
recipient,
amount,
immediateAmount,
vestedAmount,
block.timestamp,
block.timestamp + uint256(duration)
);
}
function _mintInvestorToken(address tokenAddress, address recipient, uint256 amount) private {
IManagedHokusaiToken token = IManagedHokusaiToken(tokenAddress);
if (token.maxSupply() == type(uint256).max) {
token.mint(recipient, amount);
return;
}
token.mintInvestor(recipient, amount);
}
function _mintRewardToken(address tokenAddress, address recipient, uint256 amount) private {
IManagedHokusaiToken token = IManagedHokusaiToken(tokenAddress);
if (token.maxSupply() == type(uint256).max) {
token.mint(recipient, amount);
return;
}
token.mintReward(recipient, amount);
}
function _burnInvestorToken(address tokenAddress, address account, uint256 amount) private {
IManagedHokusaiToken token = IManagedHokusaiToken(tokenAddress);
if (token.maxSupply() == type(uint256).max) {
token.burnFrom(account, amount);
return;
}
token.burnInvestor(account, amount);
}
function _burnAMMToken(address tokenAddress, address account, uint256 amount) private {
IManagedHokusaiToken token = IManagedHokusaiToken(tokenAddress);
if (token.maxSupply() == type(uint256).max) {
token.burnFrom(account, amount);
return;
}
token.burnAMM(account, amount);
}
}
contracts/interfaces/IDataContributionRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title IDataContributionRegistry
* @dev Interface for the DataContributionRegistry contract
* @notice Used by DeltaVerifier to record contributions during token minting
*/
interface IDataContributionRegistry {
/**
* @dev Records multiple contributions in a batch
* @param modelId The model identifier
* @param contributors Array of contributor addresses
* @param contributionHashes Array of contribution hashes
* @param weightsBps Array of attribution weights in basis points
* @param contributedSamples Array of contributed samples per contributor
* @param totalSamples Total samples in training set
* @param tokensEarned Array of tokens earned per contributor
* @param pipelineRunId ML pipeline execution reference
* @return contributionIds Array of recorded contribution IDs
*/
function recordContributionBatch(
string memory modelId,
address[] memory contributors,
bytes32[] memory contributionHashes,
uint256[] memory weightsBps,
uint256[] memory contributedSamples,
uint256 totalSamples,
uint256[] memory tokensEarned,
string memory pipelineRunId
) external returns (uint256[] memory contributionIds);
/**
* @dev Checks if an address has contributed to a model
* @param modelId The model identifier
* @param contributor The contributor address
* @return True if the contributor has contributed to the model
*/
function hasContributedToModel(string memory modelId, address contributor) external view returns (bool);
/**
* @dev Gets contributor statistics for a specific model
* @param modelId The model identifier
* @param contributor The contributor address
* @return totalContributions Number of contributions
* @return totalTokens Total tokens earned
* @return totalSamples Total samples contributed
*/
function getContributorStatsForModel(
string memory modelId,
address contributor
) external view returns (
uint256 totalContributions,
uint256 totalTokens,
uint256 totalSamples
);
}
contracts/interfaces/IHokusaiParams.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title IHokusaiParams
* @dev Interface for Hokusai token parameter management
* Provides a standardized way to manage dynamic parameters for token operations
* without requiring contract upgrades.
*/
interface IHokusaiParams {
enum MetricType {
SingleMetric
}
struct VestingConfig {
bool enabled;
uint16 immediateUnlockBps;
uint64 vestingDurationSeconds;
uint64 cliffSeconds;
}
/**
* @dev Returns the metric evaluation mode for the model's token
* @return The metric type enum value (0 = single-metric)
*/
function metricType() external view returns (uint8);
/**
* @dev Returns the number of tokens to mint per unit of deltaOne improvement
* @return The tokens per deltaOne value (replaces hardcoded baseRewardRate)
*/
function tokensPerDeltaOne() external view returns (uint256);
/**
* @dev Returns the infrastructure cost accrual percentage in basis points
* @return The accrual percentage (5000-10000 basis points, where 5000 = 50%, 10000 = 100%)
*/
function infrastructureAccrualBps() external view returns (uint16);
/**
* @dev Returns the oracle price in USD per 1000 calls
* @return The oracle price, using the platform's USD decimal convention
*/
function oraclePricePerThousandUsd() external view returns (uint256);
/**
* @dev Returns the profit share percentage in basis points (residual after infrastructure)
* @return The profit share percentage (calculated as 10000 - infrastructureAccrualBps)
*/
function getProfitShareBps() external view returns (uint16);
/**
* @dev Returns the license reference hash
* @return The bytes32 hash of the license reference
*/
function licenseHash() external view returns (bytes32);
/**
* @dev Returns the license reference URI
* @return The string URI for the license reference
*/
function licenseURI() external view returns (string memory);
/**
* @dev Returns both license hash and URI in a single call for gas efficiency
* @return hash The bytes32 hash of the license reference
* @return uri The string URI for the license reference
*/
function licenseRef() external view returns (bytes32 hash, string memory uri);
/**
* @dev Returns whether reward vesting is enabled for contributor emissions.
*/
function vestingEnabled() external view returns (bool);
/**
* @dev Returns the liquid reward portion in basis points.
*/
function immediateUnlockBps() external view returns (uint16);
/**
* @dev Returns the full vesting duration in seconds.
*/
function vestingDurationSeconds() external view returns (uint64);
/**
* @dev Returns the cliff in seconds before any tokens become claimable.
*/
function cliffSeconds() external view returns (uint64);
/**
* @dev Returns the full vesting configuration.
*/
function vestingConfig() external view returns (VestingConfig memory);
/**
* @dev Sets the tokens per deltaOne parameter
* @param newValue The new tokens per deltaOne value (must be between 100-100000)
* Requirements:
* - Only addresses with GOV_ROLE can call this function
* - newValue must be within valid bounds (100-100000)
*/
function setTokensPerDeltaOne(uint256 newValue) external;
/**
* @dev Sets the metric evaluation mode
* @param newMetricType The metric type enum value (0 = single-metric)
* Requirements:
* - Only addresses with GOV_ROLE can call this function
* - newMetricType must be a supported mode
*/
function setMetricType(uint8 newMetricType) external;
/**
* @dev Sets the infrastructure cost accrual percentage
* @param newBps The new accrual in basis points (must be 5000-10000, i.e., 50-100%)
* Requirements:
* - Only addresses with GOV_ROLE can call this function
* - newBps must be between 5000 and 10000 (50-100%)
*/
function setInfrastructureAccrualBps(uint16 newBps) external;
/**
* @dev Sets the oracle price in USD per 1000 calls
* @param newValue The new oracle price using the platform's USD decimal convention
* Requirements:
* - Only addresses with GOV_ROLE can call this function
* - newValue must not exceed the implementation's sanity bound
*/
function setOraclePricePerThousandUsd(uint256 newValue) external;
/**
* @dev Sets the license reference
* @param hash The bytes32 hash of the license reference
* @param uri The string URI for the license reference
* Requirements:
* - Only addresses with GOV_ROLE can call this function
*/
function setLicenseRef(bytes32 hash, string memory uri) external;
/**
* @dev Sets the vesting configuration for contributor rewards.
*/
function setVestingConfig(VestingConfig calldata cfg) external;
/**
* @dev Emitted when tokensPerDeltaOne is updated
* @param oldValue The previous tokens per deltaOne value
* @param newValue The new tokens per deltaOne value
* @param updatedBy The address that made the update
*/
event TokensPerDeltaOneSet(uint256 indexed oldValue, uint256 indexed newValue, address indexed updatedBy);
/**
* @dev Emitted when metricType is updated
* @param oldMetricType The previous metric type
* @param newMetricType The new metric type
* @param updatedBy The address that made the update
*/
event MetricTypeSet(uint8 indexed oldMetricType, uint8 indexed newMetricType, address indexed updatedBy);
/**
* @dev Emitted when infrastructureAccrualBps is updated
* @param oldBps The previous accrual in basis points
* @param newBps The new accrual in basis points
* @param updatedBy The address that made the update
*/
event InfrastructureAccrualBpsSet(uint16 indexed oldBps, uint16 indexed newBps, address indexed updatedBy);
/**
* @dev Emitted when oraclePricePerThousandUsd is updated
* @param oldValue The previous oracle price value
* @param newValue The new oracle price value
* @param updatedBy The address that made the update
*/
event OraclePricePerThousandUsdSet(
uint256 indexed oldValue,
uint256 indexed newValue,
address indexed updatedBy
);
/**
* @dev Emitted when license reference is updated
* @param oldHash The previous license hash
* @param newHash The new license hash
* @param newUri The new license URI
* @param updatedBy The address that made the update
*/
event LicenseRefSet(bytes32 indexed oldHash, bytes32 indexed newHash, string newUri, address indexed updatedBy);
/**
* @dev Emitted when the vesting configuration is updated.
*/
event VestingConfigSet(
bool enabled,
uint16 immediateUnlockBps,
uint64 vestingDurationSeconds,
uint64 cliffSeconds,
address indexed updatedBy
);
/**
* @dev Emitted when a parameter update is queued for a model
* @param modelId The model identifier
* @param paramName The parameter name being updated
* @param currentValue The current parameter value
* @param newValue The new parameter value
* @param effectiveAfter Timestamp when the update can be applied
*/
event ParamUpdateQueued(
string indexed modelId,
string paramName,
uint256 currentValue,
uint256 newValue,
uint256 effectiveAfter
);
/**
* @dev Emitted when a queued parameter update is applied
* @param modelId The model identifier
* @param paramName The parameter name being updated
* @param oldValue The previous parameter value
* @param newValue The new parameter value
*/
event ParamUpdateApplied(
string indexed modelId,
string paramName,
uint256 oldValue,
uint256 newValue
);
/**
* @dev Emitted when an emergency parameter override is performed
* @param modelId The model identifier
* @param paramName The parameter name being overridden
* @param value The new parameter value
* @param reason The reason for emergency override
*/
event EmergencyParamOverride(
string indexed modelId,
string paramName,
uint256 value,
string reason
);
/**
* @dev Queues a parameter update for a model
* @param modelId The model identifier
* @param paramName The parameter name ("tokensPerDeltaOne" or "infrastructureAccrualBps")
* @param newValue The new parameter value
* Requirements:
* - Only addresses with GOV_ROLE can call this function
* - paramName must be valid
* - newValue must be within valid bounds
*/
function queueParamUpdate(string memory modelId, string memory paramName, uint256 newValue) external;
/**
* @dev Applies all pending parameter updates for a model if epoch boundary has passed
* @param modelId The model identifier
* Requirements:
* - Permissionless function (anyone can call)
* - Can only apply updates after epoch boundary
*/
function applyPendingUpdates(string memory modelId) external;
/**
* @dev Gets the price epoch information for a model
* @param modelId The model identifier
* @return epochStart Timestamp when current epoch started
* @return epochEnd Timestamp when current epoch ends
* @return hasPendingUpdates Whether there are pending parameter updates
*/
function getPriceEpochInfo(string memory modelId) external view returns (
uint256 epochStart,
uint256 epochEnd,
bool hasPendingUpdates
);
/**
* @dev Cancels a pending parameter update for a model
* @param modelId The model identifier
* @param paramName The parameter name to cancel
* Requirements:
* - Only addresses with GOV_ROLE can call this function
*/
function cancelPendingUpdate(string memory modelId, string memory paramName) external;
/**
* @dev Emergency override to force-apply a parameter change bypassing epoch
* @param modelId The model identifier
* @param paramName The parameter name
* @param newValue The new parameter value
* @param reason The reason for emergency override
* Requirements:
* - Only addresses with DEFAULT_ADMIN_ROLE can call this function
* - Should only be used in emergencies
*/
function emergencySetParam(
string memory modelId,
string memory paramName,
uint256 newValue,
string memory reason
) external;
/**
* @dev Gets the price epoch duration
* @return The epoch duration in seconds
*/
function priceEpochDuration() external view returns (uint256);
/**
* @dev Gets the epoch start time for a model
* @param modelId The model identifier
* @return The epoch start timestamp
*/
function getEpochStart(string memory modelId) external view returns (uint256);
/**
* @dev Gets model-specific tokensPerDeltaOne parameter
* @param modelId The model identifier
* @return The tokens per deltaOne value for the model
*/
function getModelTokensPerDeltaOne(string memory modelId) external view returns (uint256);
/**
* @dev Gets model-specific infrastructureAccrualBps parameter
* @param modelId The model identifier
* @return The infrastructure accrual in basis points for the model
*/
function getModelInfrastructureAccrualBps(string memory modelId) external view returns (uint16);
}
contracts/interfaces/IManagedHokusaiToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IHokusaiParams.sol";
interface IManagedHokusaiToken {
function mint(address to, uint256 amount) external;
function mintInvestor(address to, uint256 amount) external;
function mintReward(address to, uint256 amount) external;
function burnFrom(address from, uint256 amount) external;
function burnInvestor(address from, uint256 amount) external;
function burnAMM(address from, uint256 amount) external;
function distributeModelSupplierAllocation(address vault, uint256 vestedAmount) external;
function modelSupplierRecipient() external view returns (address);
function modelSupplierAllocation() external view returns (uint256);
function investorAllocation() external view returns (uint256);
function investorMinted() external view returns (uint256);
function rewardMinted() external view returns (uint256);
/// @dev Launch allocation cap for supplier + investor allocation, not the total ERC20 supply cap once reward minting is enabled.
function maxSupply() external view returns (uint256);
/// @dev Reward-bucket cap that separately bounds reward minting tracked by rewardMinted.
function getRewardMintingCap() external view returns (uint256);
function params() external view returns (IHokusaiParams);
}
contracts/interfaces/IModelRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title IModelRegistry
* @dev Canonical ModelRegistry API for on-chain consumers. ModelRegistry keeps
* older alias names (exists, isModelActive, isStringModelRegistered) for
* off-chain compatibility; they delegate to these functions and are deprecated.
*
* "Registered" means the model exists; "active" means registered AND not
* deactivated. The two are intentionally distinct.
*/
interface IModelRegistry {
// Numeric model IDs
function isRegistered(uint256 modelId) external view returns (bool);
function isActive(uint256 modelId) external view returns (bool);
function getTokenAddress(uint256 modelId) external view returns (address);
function weightGenesis(uint256 modelId) external view returns (bytes32);
// Canonical string model IDs ("1846" etc.)
function isStringRegistered(string memory modelId) external view returns (bool);
function isStringActive(string memory modelId) external view returns (bool);
function getStringToken(string memory modelId) external view returns (address);
// AMM pools
function registerPool(string memory modelId, address pool) external;
function getPool(string memory modelId) external view returns (address);
function hasPool(string memory modelId) external view returns (bool);
}
contracts/interfaces/IRewardVestingVault.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IRewardVestingVault {
struct VestingSchedule {
address token;
address beneficiary;
string modelId;
uint256 totalAmount;
uint256 claimed;
uint64 start;
uint64 cliffSeconds;
uint64 duration;
}
function createSchedule(
string calldata modelId,
address token,
address beneficiary,
uint256 totalAmount,
uint64 cliffSeconds,
uint64 duration
) external returns (uint256 scheduleId);
function claim(uint256 scheduleId) external returns (uint256 claimedAmount);
function claimable(uint256 scheduleId) external view returns (uint256 amount);
function vestedAmount(uint256 scheduleId) external view returns (uint256 amount);
function unvestedAmount(uint256 scheduleId) external view returns (uint256 amount);
function getSchedule(uint256 scheduleId) external view returns (VestingSchedule memory schedule);
function getSchedulesByBeneficiary(address beneficiary) external view returns (uint256[] memory scheduleIds);
}
contracts/libraries/AccessControlBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @title AccessControlBase
* @dev Base contract for standardized role-based access control setup
*
* Reduces boilerplate in contracts using AccessControl by providing:
* - Automatic DEFAULT_ADMIN_ROLE setup in constructor
* - Batch role granting utilities
* - Consistent role management patterns
*
* Benefits:
* - DRY: Eliminates duplicate role setup code across contracts
* - Standardization: All contracts follow same initialization pattern
* - Maintainability: Updates to role management apply to all derived contracts
*
* Usage:
* contract MyContract is AccessControlBase {
* bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
*
* constructor(address admin) AccessControlBase(admin) {
* _grantRole(MINTER_ROLE, admin);
* }
* }
*/
abstract contract AccessControlBase is AccessControl {
// ============================================================
// CONSTRUCTOR
// ============================================================
/**
* @dev Constructor grants DEFAULT_ADMIN_ROLE to specified admin
* @param admin Address to receive admin role (typically msg.sender or owner)
*
* Reverts if admin is zero address to prevent deploying with no admin
*/
constructor(address admin) {
require(admin != address(0), "AccessControlBase: admin cannot be zero");
_grantRole(DEFAULT_ADMIN_ROLE, admin);
}
// ============================================================
// BATCH ROLE MANAGEMENT
// ============================================================
/**
* @dev Grant multiple roles to a single account
* @param roles Array of role identifiers (bytes32)
* @param account Address to grant all roles
*
* Useful for initializing contracts where one address needs multiple roles
*
* Example:
* bytes32[] memory roles = new bytes32[](2);
* roles[0] = MINTER_ROLE;
* roles[1] = BURNER_ROLE;
* _grantRoles(roles, msg.sender);
*/
function _grantRoles(bytes32[] memory roles, address account) internal {
for (uint256 i = 0; i < roles.length; i++) {
_grantRole(roles[i], account);
}
}
/**
* @dev Revoke multiple roles from a single account
* @param roles Array of role identifiers
* @param account Address to revoke roles from
*
* Example:
* bytes32[] memory roles = new bytes32[](2);
* roles[0] = MINTER_ROLE;
* roles[1] = BURNER_ROLE;
* _revokeRoles(roles, oldAddress);
*/
function _revokeRoles(bytes32[] memory roles, address account) internal {
for (uint256 i = 0; i < roles.length; i++) {
_revokeRole(roles[i], account);
}
}
/**
* @dev Grant a role to multiple accounts
* @param role Role identifier to grant
* @param accounts Array of addresses to receive the role
*
* Example:
* address[] memory minters = new address[](3);
* minters[0] = address1;
* minters[1] = address2;
* minters[2] = address3;
* _grantRoleToMany(MINTER_ROLE, minters);
*/
function _grantRoleToMany(bytes32 role, address[] memory accounts) internal {
for (uint256 i = 0; i < accounts.length; i++) {
_grantRole(role, accounts[i]);
}
}
/**
* @dev Revoke a role from multiple accounts
* @param role Role identifier to revoke
* @param accounts Array of addresses to revoke from
*
* Example:
* address[] memory oldMinters = new address[](2);
* oldMinters[0] = address1;
* oldMinters[1] = address2;
* _revokeRoleFromMany(MINTER_ROLE, oldMinters);
*/
function _revokeRoleFromMany(bytes32 role, address[] memory accounts) internal {
for (uint256 i = 0; i < accounts.length; i++) {
_revokeRole(role, accounts[i]);
}
}
}
contracts/libraries/RewardSplitLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library RewardSplitLib {
function split(uint256 amount, uint16 immediateUnlockBps)
internal
pure
returns (uint256 immediateAmount, uint256 vestedAmount)
{
require(immediateUnlockBps <= 10000, "invalid bps");
immediateAmount = (amount * immediateUnlockBps) / 10000;
vestedAmount = amount - immediateAmount;
}
}
contracts/libraries/ValidationLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ValidationLib
* @dev Shared validation utilities to reduce code duplication across contracts
*
* Benefits:
* - Gas optimization: Custom errors save ~50-100 gas per revert vs require strings
* - Code reusability: Single source of truth for validation logic
* - Maintainability: Updates apply to all contracts using the library
* - Auditability: Centralized validation logic is easier to review
*
* Usage:
* import "./libraries/ValidationLib.sol";
*
* ValidationLib.requireNonZeroAddress(someAddress, "token address");
* ValidationLib.requirePositiveAmount(amount, "deposit amount");
*/
library ValidationLib {
// ============================================================
// CUSTOM ERRORS (Gas-efficient vs require strings)
// ============================================================
/**
* @dev Thrown when an address parameter is zero but shouldn't be
* @param context Description of what address was being validated
*/
error ZeroAddress(string context);
/**
* @dev Thrown when an amount is zero but should be positive
* @param context Description of what amount was being validated
*/
error InvalidAmount(string context);
/**
* @dev Thrown when a string parameter is empty but shouldn't be
* @param context Description of what string was being validated
*/
error EmptyString(string context);
/**
* @dev Thrown when two arrays have mismatched lengths
* @param expected Expected array length
* @param actual Actual array length received
*/
error ArrayLengthMismatch(uint256 expected, uint256 actual);
/**
* @dev Thrown when an array is empty but shouldn't be
*/
error ArrayEmpty();
/**
* @dev Thrown when a value is outside allowed bounds
* @param value The value being validated
* @param min Minimum allowed value (inclusive)
* @param max Maximum allowed value (inclusive)
*/
error ValueOutOfBounds(uint256 value, uint256 min, uint256 max);
/**
* @dev Thrown when array length exceeds maximum
* @param length Actual array length
* @param maxLength Maximum allowed length
*/
error ArrayTooLarge(uint256 length, uint256 maxLength);
// ============================================================
// VALIDATION FUNCTIONS
// ============================================================
/**
* @dev Validates that an address is not the zero address
* @param addr Address to validate
* @param context Context string for error message (e.g., "token address")
*
* Example:
* ValidationLib.requireNonZeroAddress(tokenAddress, "token address");
*/
function requireNonZeroAddress(address addr, string memory context) internal pure {
if (addr == address(0)) revert ZeroAddress(context);
}
/**
* @dev Validates that an amount is positive (non-zero)
* @param amount Amount to validate
* @param context Context string for error message (e.g., "deposit amount")
*
* Example:
* ValidationLib.requirePositiveAmount(depositAmount, "deposit amount");
*/
function requirePositiveAmount(uint256 amount, string memory context) internal pure {
if (amount == 0) revert InvalidAmount(context);
}
/**
* @dev Validates that a string is not empty
* @param str String to validate
* @param context Context string for error message (e.g., "model ID")
*
* Example:
* ValidationLib.requireNonEmptyString(modelId, "model ID");
*/
function requireNonEmptyString(string memory str, string memory context) internal pure {
if (bytes(str).length == 0) revert EmptyString(context);
}
/**
* @dev Validates that two array lengths match
* @param length1 First array length
* @param length2 Second array length
*
* Example:
* ValidationLib.requireMatchingArrayLengths(addresses.length, amounts.length);
*/
function requireMatchingArrayLengths(uint256 length1, uint256 length2) internal pure {
if (length1 != length2) revert ArrayLengthMismatch(length1, length2);
}
/**
* @dev Validates that an array is not empty
* @param length Array length
*
* Example:
* ValidationLib.requireNonEmptyArray(recipients.length);
*/
function requireNonEmptyArray(uint256 length) internal pure {
if (length == 0) revert ArrayEmpty();
}
/**
* @dev Validates that a value is within specified bounds (inclusive)
* @param value Value to validate
* @param min Minimum allowed value (inclusive)
* @param max Maximum allowed value (inclusive)
*
* Example:
* ValidationLib.requireInBounds(crr, MIN_CRR, MAX_CRR);
*/
function requireInBounds(uint256 value, uint256 min, uint256 max) internal pure {
if (value < min || value > max) revert ValueOutOfBounds(value, min, max);
}
/**
* @dev Validates that array length doesn't exceed maximum
* @param length Array length
* @param maxLength Maximum allowed length
*
* Example:
* ValidationLib.requireMaxArrayLength(recipients.length, 100);
*/
function requireMaxArrayLength(uint256 length, uint256 maxLength) internal pure {
if (length > maxLength) revert ArrayTooLarge(length, maxLength);
}
/**
* @dev Combined validation for batch operations: non-empty, matching lengths, within limit
* @param length1 First array length
* @param length2 Second array length
* @param maxLength Maximum allowed length
*
* Example:
* ValidationLib.requireValidBatch(addresses.length, amounts.length, 100);
*/
function requireValidBatch(
uint256 length1,
uint256 length2,
uint256 maxLength
) internal pure {
requireNonEmptyArray(length1);
requireMatchingArrayLengths(length1, length2);
requireMaxArrayLength(length1, maxLength);
}
/**
* @dev Validates that a value is less than or equal to a maximum
* @param value The value to check
* @param maxValue The maximum allowed value
*
* Example:
* ValidationLib.requireMaxValue(feeBps, 10000);
*/
function requireMaxValue(uint256 value, uint256 maxValue) internal pure {
if (value > maxValue) revert InvalidAmount("value exceeds maximum");
}
}
Compiler settingsShow
{
"viaIR": true,
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.