Verified contractExactMIT
ORBAgentToken
Address0x00ff8bd242e1bf37b62de0a45fc0c67d3b723868
- Balance
0 ETH
- Transactions
31
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,851,018
- Creation transaction
- 0x3ef79ae2f5…73f233ffc9
6 files
- files/ORBAgentToken.solmain8.24 KB
- files/ORBAgentEcho.sol4.99 KB
- files/ORBAgentGravityWell.sol4.5 KB
- files/ORBAgentOrbit.sol4.64 KB
- files/ORBAgentPrism.sol4.47 KB
- files/ORBAgentResonance.sol5.46 KB
files/ORBAgentToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ORBAgentOrbit} from "./ORBAgentOrbit.sol";
import {ORBAgentGravityWell} from "./ORBAgentGravityWell.sol";
import {ORBAgentPrism} from "./ORBAgentPrism.sol";
import {ORBAgentEcho} from "./ORBAgentEcho.sol";
import {ORBAgentResonance} from "./ORBAgentResonance.sol";
/*
. o . o . o . o .
` / \ `
\ / ORB \ /
. - X - (o)(o) - X - .
/ \ / \
' \ / `
. o . o . o . o .
DISPATCH
FROM: the pool
TO: whoever's reading the source
RE: what ORB actually is
an AI-native token, built on Uniswap v4 hooks. an autonomous agent lives in the swap path
itself - the hook hands it every trade through beforeSwap and afterSwap, the agent reads the
situation and reacts, right there, no off-chain process in the loop. its whole world is its
own pool: how often it gets traded, how big those trades run, how long it's been quiet.
attached to this dispatch: the token you're looking at. fixed supply, ownerless, minted once
at deploy - nothing in this file can create more of it or move it out of anyone's hands
without their say-so. transfer, approve, balance - all standard, none of it touched by
whatever the agent's doing downstream.
also attached, imported above rather than called from here: orbit, gravity well, prism, echo,
and resonance - the rest of the project, filed together for reference.
*/
contract ORBAgentToken {
string public constant name = "ORB (o,o)";
string public constant symbol = "ORB (o,o)";
uint8 public constant decimals = 18;
uint256 public immutable genesisSupply;
uint256 private circulating;
uint256 public immutable deployedBlock;
uint256 public immutable deployedAt;
mapping(address => uint256) private balances;
mapping(address => mapping(address => uint256)) private allowances;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor() {
uint256 supply = 10_000 * 10 ** decimals;
genesisSupply = supply;
circulating = supply;
balances[msg.sender] = supply;
deployedBlock = block.number;
deployedAt = block.timestamp;
emit Transfer(address(0), msg.sender, supply);
}
// ---------------------------------------------------------------
// ORB20 TOKEN CONTRACT
// ---------------------------------------------------------------
function totalSupply() external view returns (uint256) {
return circulating;
}
function balanceOf(address account) public view returns (uint256) {
return balances[account];
}
function allowance(address tokenOwner, address spender) external view returns (uint256) {
return allowances[tokenOwner][spender];
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) external returns (bool) {
_spendAllowance(from, msg.sender, value);
_transfer(from, to, value);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(msg.sender, spender, allowances[msg.sender][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
uint256 current = allowances[msg.sender][spender];
require(current >= subtractedValue, "below zero");
_approve(msg.sender, spender, current - subtractedValue);
return true;
}
function burn(uint256 value) external {
_burn(msg.sender, value);
}
function burnFrom(address account, uint256 value) external {
_spendAllowance(account, msg.sender, value);
_burn(account, value);
}
function _transfer(address from, address to, uint256 value) private {
require(to != address(0), "transfer to zero");
uint256 fromBal = balances[from];
require(fromBal >= value, "balance too low");
unchecked {
balances[from] = fromBal - value;
}
balances[to] += value;
emit Transfer(from, to, value);
}
function _approve(address tokenOwner, address spender, uint256 value) private {
allowances[tokenOwner][spender] = value;
emit Approval(tokenOwner, spender, value);
}
function _spendAllowance(address tokenOwner, address spender, uint256 value) private {
uint256 allowed = allowances[tokenOwner][spender];
if (allowed != type(uint256).max) {
require(allowed >= value, "allowance too low");
unchecked {
allowances[tokenOwner][spender] = allowed - value;
}
}
}
function _burn(address account, uint256 value) private {
uint256 bal = balances[account];
require(bal >= value, "balance too low");
unchecked {
balances[account] = bal - value;
circulating -= value;
}
emit Transfer(account, address(0), value);
}
// ---------------------------------------------------------------
// view functions
// ---------------------------------------------------------------
function liveSupply() external view returns (uint256) {
return circulating;
}
function goneSupply() external view returns (uint256) {
return genesisSupply - circulating;
}
function goneShareBps() external view returns (uint256) {
if (genesisSupply == 0) return 0;
return ((genesisSupply - circulating) * 10000) / genesisSupply;
}
function mintCapacity() external pure returns (uint256) {
return 0;
}
function holdsAny(address account) external view returns (bool) {
return balances[account] > 0;
}
function stakeBps(address account) external view returns (uint256) {
if (circulating == 0) return 0;
return (balances[account] * 10000) / circulating;
}
function grantedTo(address tokenOwner, address spender) external view returns (uint256) {
return allowances[tokenOwner][spender];
}
function isMaxGranted(address tokenOwner, address spender) external view returns (bool) {
return allowances[tokenOwner][spender] == type(uint256).max;
}
function secondsOld() external view returns (uint256) {
return block.timestamp - deployedAt;
}
function blocksOld() external view returns (uint256) {
return block.number - deployedBlock;
}
function originFacts()
external
view
returns (address contractAddress, uint256 atBlock, uint256 atTime, uint256 chainId)
{
return (address(this), deployedBlock, deployedAt, block.chainid);
}
function noGatekeeper() external pure returns (bool) {
return true; // no owner or operator variable exists in this contract, this just says so on-chain
}
function orbFacts() external view returns (string memory, string memory, uint8, uint256) {
return (name, symbol, decimals, circulating);
}
// rough count of whole units held, discarding anything below one
// token - a coarser read than balanceOf for a quick glance.
function wholeOrbsHeld(address account) external view returns (uint256) {
return balances[account] / (10 ** decimals);
}
// a slice small enough to round to zero at current scale - a sense
// of the smallest meaningful holding right now.
function dustLine() external view returns (uint256) {
return circulating / 10000;
}
// purely a self-identifying flag, no functional purpose beyond
// letting a caller confirm this is in fact the ORB token contract.
function isOrb() external pure returns (bool) {
return true;
}
}
files/ORBAgentEcho.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
// ORBAgentEcho -
//
// a shout into a canyon.
// quieter on the way back. later too.
//
// cast(amplitude, delay, decay) - send it out.
// collect() - pick it up once the wait is over, reduced.
// chainFrom() - cast a new one off what an old one returned.
// leave it uncollected forever - costs nothing.
//
// nobody's gated out of any of it.
// call collect() too early, get 0 back. no drama, no revert.
contract ORBAgentEcho {
struct Echo {
uint256 amplitude;
uint256 castAt;
uint256 delaySeconds;
uint256 decayBps; // how much amplitude is lost on collection, in bps
bool collected;
uint256 generation;
}
mapping(address => Echo[]) private echoes;
event Cast(address indexed agent, uint256 indexed echoId, uint256 amplitude, uint256 delaySeconds, uint256 generation);
event Collected(address indexed agent, uint256 indexed echoId, uint256 returnedAmplitude);
event Dampened(address indexed agent, uint256 indexed echoId, uint256 newDecayBps);
function cast(address agent, uint256 amplitude, uint256 delaySeconds, uint256 decayBps)
external
returns (uint256 echoId)
{
uint256 clampedDecay = decayBps > 10000 ? 10000 : decayBps;
echoes[agent].push(
Echo({
amplitude: amplitude,
castAt: block.timestamp,
delaySeconds: delaySeconds,
decayBps: clampedDecay,
collected: false,
generation: 0
})
);
echoId = echoes[agent].length - 1;
emit Cast(agent, echoId, amplitude, delaySeconds, 0);
}
// collects an echo once its delay has elapsed, returning the
// decayed amplitude and marking it collected. calling this early,
// or on an already-collected echo, just returns 0 rather than
// failing.
function collect(address agent, uint256 echoId) external returns (uint256 returnedAmplitude) {
Echo storage e = echoes[agent][echoId];
if (e.collected) return 0;
if (block.timestamp < e.castAt + e.delaySeconds) return 0;
returnedAmplitude = (e.amplitude * (10000 - e.decayBps)) / 10000;
e.collected = true;
emit Collected(agent, echoId, returnedAmplitude);
}
// casts a fresh echo using a previously collected one's returned
// amplitude as the new input - a way to chain reflections that get
// progressively quieter. if the source echo hasn't been collected
// yet, this casts with zero amplitude rather than reverting.
function chainFrom(address agent, uint256 sourceEchoId, uint256 delaySeconds, uint256 decayBps)
external
returns (uint256 newEchoId)
{
Echo storage source = echoes[agent][sourceEchoId];
uint256 carried = source.collected ? (source.amplitude * (10000 - source.decayBps)) / 10000 : 0;
uint256 clampedDecay = decayBps > 10000 ? 10000 : decayBps;
echoes[agent].push(
Echo({
amplitude: carried,
castAt: block.timestamp,
delaySeconds: delaySeconds,
decayBps: clampedDecay,
collected: false,
generation: source.generation + 1
})
);
newEchoId = echoes[agent].length - 1;
emit Cast(agent, newEchoId, carried, delaySeconds, source.generation + 1);
}
// adjusts the decay applied to an echo before it's collected -
// makes it fade faster or slower without changing its amplitude or
// timing.
function dampen(address agent, uint256 echoId, uint256 newDecayBps) external {
Echo storage e = echoes[agent][echoId];
e.decayBps = newDecayBps > 10000 ? 10000 : newDecayBps;
emit Dampened(agent, echoId, e.decayBps);
}
function echoCount(address agent) external view returns (uint256) {
return echoes[agent].length;
}
function getEcho(address agent, uint256 echoId) external view returns (Echo memory) {
return echoes[agent][echoId];
}
function isReady(address agent, uint256 echoId) external view returns (bool) {
Echo memory e = echoes[agent][echoId];
return !e.collected && block.timestamp >= e.castAt + e.delaySeconds;
}
function previewReturn(address agent, uint256 echoId) external view returns (uint256) {
Echo memory e = echoes[agent][echoId];
return (e.amplitude * (10000 - e.decayBps)) / 10000;
}
function timeUntilReady(address agent, uint256 echoId) external view returns (uint256) {
Echo memory e = echoes[agent][echoId];
uint256 readyAt = e.castAt + e.delaySeconds;
if (block.timestamp >= readyAt) return 0;
return readyAt - block.timestamp;
}
function generationOf(address agent, uint256 echoId) external view returns (uint256) {
return echoes[agent][echoId].generation;
}
}
files/ORBAgentGravityWell.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
// Q: what does ORBAgentGravityWell actually do?
// A: mass accumulates per agent, and once one agent's mass is heavy
// enough relative to a smaller one, the smaller can be pulled in
// and consolidated into it - the way a large enough body ends up
// absorbing whatever drifts too close.
//
// Q: what happens if the ratio isn't there yet?
// A: nothing bad. attempting a consolidation before the numbers
// support it is a harmless no-op, not a revert - the smaller agent
// just keeps its mass and stays independent.
//
// Q: is this moving real value?
// A: no. this tracks a nominal mass number, not custody of anything -
// pair it with actual token transfers elsewhere if a consolidation
// needs to move value for real. every write here is permissionless.
contract ORBAgentGravityWell {
uint256 public constant CONSOLIDATION_RATIO = 5; // absorber needs at least 5x the target's mass
mapping(address => uint256) public massOf;
mapping(address => bool) public consumed;
mapping(address => address) public consolidatedInto;
mapping(address => uint256) public consolidationCount;
event MassDeposited(address indexed agent, uint256 amount, uint256 newMass);
event Consolidated(address indexed absorber, address indexed target, uint256 massTransferred);
event MassReleased(address indexed agent, uint256 amount);
// adds to an agent's mass. always succeeds, any amount, any agent.
function depositMass(address agent, uint256 amount) external {
massOf[agent] += amount;
emit MassDeposited(agent, amount, massOf[agent]);
}
// attempts to pull `target`'s mass into `absorber`. only goes
// through if absorber's mass is at least CONSOLIDATION_RATIO times
// target's, target isn't already consumed, and neither is zero
// mass - otherwise this is a no-op and returns false rather than
// reverting.
function attemptConsolidation(address absorber, address target) external returns (bool consolidated) {
if (consumed[target] || absorber == target) return false;
uint256 absorberMass = massOf[absorber];
uint256 targetMass = massOf[target];
if (targetMass == 0 || absorberMass < targetMass * CONSOLIDATION_RATIO) return false;
massOf[absorber] += targetMass;
massOf[target] = 0;
consumed[target] = true;
consolidatedInto[target] = absorber;
unchecked {
consolidationCount[absorber] += 1;
}
emit Consolidated(absorber, target, targetMass);
return true;
}
// releases mass from an agent back down by a given amount, capped
// at whatever it actually holds so this can never go negative or
// revert on an oversized request.
function releaseMass(address agent, uint256 amount) external returns (uint256 released) {
uint256 current = massOf[agent];
released = amount > current ? current : amount;
massOf[agent] = current - released;
emit MassReleased(agent, released);
}
// reverses a consolidation record without moving any mass back -
// just clears the flag so the target can be treated as independent
// again and start accumulating mass fresh.
function reinstateAgent(address agent) external {
consumed[agent] = false;
consolidatedInto[agent] = address(0);
}
function pullStrengthOf(address absorber, address target) external view returns (uint256) {
uint256 targetMass = massOf[target];
if (targetMass == 0) return 0;
return massOf[absorber] / targetMass;
}
function wouldConsolidate(address absorber, address target) external view returns (bool) {
if (consumed[target] || absorber == target) return false;
uint256 targetMass = massOf[target];
if (targetMass == 0) return false;
return massOf[absorber] >= targetMass * CONSOLIDATION_RATIO;
}
function isConsumed(address agent) external view returns (bool) {
return consumed[agent];
}
function absorberOf(address agent) external view returns (address) {
return consolidatedInto[agent];
}
function massRankAbove(address agent, address other) external view returns (bool) {
return massOf[agent] > massOf[other];
}
function totalConsolidationsBy(address absorber) external view returns (uint256) {
return consolidationCount[absorber];
}
}
files/ORBAgentOrbit.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
// MANIFEST : ORBAgentOrbit
// (1) most state machines in this project's lineage move one way - a
// queue empties, a schedule vests, a lock expires.
// (2) this one loops instead. an agent cycles through a fixed sequence
// of phases - Ignition, Ascent, Apex, Descent, Dormant - then back
// to Ignition, each phase carrying its own duration.
// (3) anyone can push a phase forward once its duration has elapsed,
// force a jump to a specific phase, or stretch a phase's duration
// without disturbing where in the cycle the agent currently sits.
// (4) advancing and configuring are both permissionless. this tracks
// where an agent sits in its cycle - it doesn't attach any
// decide.
contract ORBAgentOrbit {
enum Phase {
Ignition,
Ascent,
Apex,
Descent,
Dormant
}
struct OrbitState {
Phase phase;
uint256 enteredAt;
uint256[5] phaseDurations;
uint256 cycleCount;
bool configured;
}
mapping(address => OrbitState) private orbits;
event PhaseAdvanced(address indexed agent, Phase newPhase, uint256 cycleCount);
event PhaseForced(address indexed agent, Phase newPhase);
event DurationSet(address indexed agent, Phase phase, uint256 newDuration);
event OrbitInitialized(address indexed agent);
// sets up an orbit with a duration per phase, defaulting to 1 hour
// each if this is the first time this agent's been configured.
// reconfiguring an existing orbit only updates durations, it doesn't
// reset the current phase.
function initializeOrbit(address agent, uint256[5] calldata durations) external {
OrbitState storage o = orbits[agent];
if (!o.configured) {
o.phase = Phase.Ignition;
o.enteredAt = block.timestamp;
o.configured = true;
emit OrbitInitialized(agent);
}
o.phaseDurations = durations;
}
// moves an agent into its next phase once the current one's duration
// has elapsed. calling this before the duration is up, or on an
// unconfigured agent, is a harmless no-op.
function advancePhase(address agent) external returns (bool advanced) {
OrbitState storage o = orbits[agent];
if (!o.configured) return false;
uint256 duration = o.phaseDurations[uint256(o.phase)];
if (block.timestamp < o.enteredAt + duration) return false;
uint8 nextIndex = uint8(o.phase) + 1;
if (nextIndex > uint8(Phase.Dormant)) {
nextIndex = 0;
unchecked {
o.cycleCount += 1;
}
}
o.phase = Phase(nextIndex);
o.enteredAt = block.timestamp;
emit PhaseAdvanced(agent, o.phase, o.cycleCount);
return true;
}
// jumps straight to a named phase regardless of timing - a manual
// override for when the natural cycle needs to be interrupted.
function forcePhase(address agent, Phase newPhase) external {
OrbitState storage o = orbits[agent];
o.phase = newPhase;
o.enteredAt = block.timestamp;
o.configured = true;
emit PhaseForced(agent, newPhase);
}
// stretches or shrinks how long a specific phase lasts, without
// moving the agent out of whatever phase it's currently in.
function setPhaseDuration(address agent, Phase phase, uint256 newDuration) external {
orbits[agent].phaseDurations[uint256(phase)] = newDuration;
emit DurationSet(agent, phase, newDuration);
}
function currentPhase(address agent) external view returns (Phase) {
return orbits[agent].phase;
}
function timeInPhase(address agent) external view returns (uint256) {
OrbitState storage o = orbits[agent];
if (o.enteredAt == 0) return 0;
return block.timestamp - o.enteredAt;
}
function isPhaseReady(address agent) external view returns (bool) {
OrbitState storage o = orbits[agent];
if (!o.configured) return false;
uint256 duration = o.phaseDurations[uint256(o.phase)];
return block.timestamp >= o.enteredAt + duration;
}
function phaseDuration(address agent, Phase phase) external view returns (uint256) {
return orbits[agent].phaseDurations[uint256(phase)];
}
function cyclesCompleted(address agent) external view returns (uint256) {
return orbits[agent].cycleCount;
}
function isConfigured(address agent) external view returns (bool) {
return orbits[agent].configured;
}
}
files/ORBAgentPrism.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
// [boot] loading ORBAgentPrism...
// [boot] concept: one beam in, several out, each carrying a fixed share
// [boot] up to 8 bands, weights summing to <= 10000 bps
// [boot] refract(amount) -> per-band split, credited to running totals
// [boot] over-budget weights get clamped on configure, not rejected
// [boot] configuring and refracting: open to any caller
// [boot] ready.
contract ORBAgentPrism {
uint256 public constant MAX_BANDS = 8;
mapping(address => uint256[MAX_BANDS]) private bandWeights;
mapping(address => uint256) public bandCount;
mapping(address => uint256[MAX_BANDS]) private bandTotals;
mapping(address => uint256) public refractionCount;
mapping(address => uint256) public totalRefracted;
event BandsConfigured(address indexed agent, uint256 bandCount, uint256 totalWeightBps);
event Refracted(address indexed agent, uint256 amount, uint256 index);
event BandsReset(address indexed agent);
// sets the band weights for an agent's prism. if the weights sum to
// more than 10000 bps, everything past the point where the running
// total hits 10000 gets clamped to zero instead of overshooting.
function configureBands(address agent, uint256[] calldata weightsBps) external returns (uint256 totalBps) {
uint256 count = weightsBps.length > MAX_BANDS ? MAX_BANDS : weightsBps.length;
uint256[MAX_BANDS] memory clamped;
uint256 running;
for (uint256 i = 0; i < count; i++) {
uint256 remaining = running >= 10000 ? 0 : 10000 - running;
uint256 taken = weightsBps[i] > remaining ? remaining : weightsBps[i];
clamped[i] = taken;
running += taken;
}
bandWeights[agent] = clamped;
bandCount[agent] = count;
emit BandsConfigured(agent, count, running);
return running;
}
// splits `amount` across an agent's configured bands according to
// their weights, crediting each band's running total. an agent with
// no bands configured just adds the whole amount to overall totals
// without crediting any individual band.
function refract(address agent, uint256 amount) external returns (uint256 index) {
uint256 count = bandCount[agent];
uint256[MAX_BANDS] storage weights = bandWeights[agent];
uint256[MAX_BANDS] storage totals = bandTotals[agent];
for (uint256 i = 0; i < count; i++) {
uint256 share = (amount * weights[i]) / 10000;
unchecked {
totals[i] += share;
}
}
unchecked {
totalRefracted[agent] += amount;
index = refractionCount[agent];
refractionCount[agent] += 1;
}
emit Refracted(agent, amount, index);
}
// zeroes an agent's accumulated band totals without touching the
// band configuration itself - a fresh start for the running split.
function resetTotals(address agent) external {
delete bandTotals[agent];
emit BandsReset(agent);
}
function weightOf(address agent, uint256 bandIndex) external view returns (uint256) {
if (bandIndex >= MAX_BANDS) return 0;
return bandWeights[agent][bandIndex];
}
function totalOf(address agent, uint256 bandIndex) external view returns (uint256) {
if (bandIndex >= MAX_BANDS) return 0;
return bandTotals[agent][bandIndex];
}
function previewSplit(address agent, uint256 amount) external view returns (uint256[MAX_BANDS] memory shares) {
uint256 count = bandCount[agent];
uint256[MAX_BANDS] storage weights = bandWeights[agent];
for (uint256 i = 0; i < count; i++) {
shares[i] = (amount * weights[i]) / 10000;
}
}
function totalWeightBps(address agent) external view returns (uint256 total) {
uint256 count = bandCount[agent];
uint256[MAX_BANDS] storage weights = bandWeights[agent];
for (uint256 i = 0; i < count; i++) {
total += weights[i];
}
}
function unallocatedBps(address agent) external view returns (uint256) {
uint256 count = bandCount[agent];
uint256[MAX_BANDS] storage weights = bandWeights[agent];
uint256 total;
for (uint256 i = 0; i < count; i++) {
total += weights[i];
}
return total >= 10000 ? 0 : 10000 - total;
}
}
files/ORBAgentResonance.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
// TRANSCRIPT - on ORBAgentResonance
//
// Q: plainly, what's this contract for?
// A: two things resonate when their frequencies land close enough to
// each other. this lets two agents attempt to link on exactly that
// basis - submit a frequency each, and if the gap's inside a given
// tolerance, a bond forms.
//
// Q: and if they're outside tolerance?
// A: no bond, no error. the attempt just doesn't take. nothing reverts,
// nothing breaks - they simply aren't resonating yet.
//
// Q: does a bond last forever once it forms?
// A: no - strength starts full and decays over time unless somebody
// refreshes it. attempting, refreshing, breaking a link: all open
// to anyone. this only records whether two agents are in sync and
// how strongly - what that's used for is somebody else's call.
contract ORBAgentResonance {
uint256 public constant DECAY_PERIOD = 1 days; // strength halves roughly every period without a refresh
struct Bond {
bool active;
uint256 strength;
uint256 lastRefreshedAt;
uint256 formedAt;
}
mapping(bytes32 => Bond) private bonds;
mapping(bytes32 => uint256) public frequencyOf;
event FrequencySet(bytes32 indexed agentKey, uint256 frequency);
event LinkAttempted(address indexed a, address indexed b, bool succeeded);
event LinkFormed(address indexed a, address indexed b, uint256 strength);
event LinkRefreshed(address indexed a, address indexed b, uint256 newStrength);
event LinkBroken(address indexed a, address indexed b);
function _pairKey(address a, address b) internal pure returns (bytes32) {
return a < b ? keccak256(abi.encode(a, b)) : keccak256(abi.encode(b, a));
}
function _agentKey(address a) internal pure returns (bytes32) {
return keccak256(abi.encode(a));
}
function setFrequency(address agent, uint256 frequency) external {
frequencyOf[_agentKey(agent)] = frequency;
emit FrequencySet(_agentKey(agent), frequency);
}
// attempts to link two agents if their frequencies are within
// tolerance of each other. a failed attempt is a no-op that emits
// an event saying so, rather than reverting.
function attemptLink(address a, address b, uint256 toleranceBps) external returns (bool succeeded) {
uint256 freqA = frequencyOf[_agentKey(a)];
uint256 freqB = frequencyOf[_agentKey(b)];
uint256 diff = freqA > freqB ? freqA - freqB : freqB - freqA;
uint256 base = freqA > freqB ? freqA : freqB;
uint256 diffBps = base == 0 ? (diff == 0 ? 0 : 10000) : (diff * 10000) / base;
if (diffBps > toleranceBps) {
emit LinkAttempted(a, b, false);
return false;
}
bytes32 key = _pairKey(a, b);
bonds[key] = Bond({active: true, strength: 10000, lastRefreshedAt: block.timestamp, formedAt: block.timestamp});
emit LinkAttempted(a, b, true);
emit LinkFormed(a, b, 10000);
return true;
}
// restores a bond's strength back to full and resets the decay
// clock. calling this on a pair with no active bond is a no-op.
function refreshLink(address a, address b) external {
bytes32 key = _pairKey(a, b);
Bond storage bond = bonds[key];
if (!bond.active) return;
bond.strength = 10000;
bond.lastRefreshedAt = block.timestamp;
emit LinkRefreshed(a, b, 10000);
}
// deactivates a bond outright, regardless of its current strength.
function breakLink(address a, address b) external {
bytes32 key = _pairKey(a, b);
bonds[key].active = false;
emit LinkBroken(a, b);
}
function _currentStrength(Bond memory bond) internal view returns (uint256) {
if (!bond.active) return 0;
uint256 elapsed = block.timestamp - bond.lastRefreshedAt;
uint256 halvings = elapsed / DECAY_PERIOD;
if (halvings >= 32) return 0;
return bond.strength >> halvings;
}
function frequencyOfAgent(address agent) external view returns (uint256) {
return frequencyOf[_agentKey(agent)];
}
function isLinked(address a, address b) external view returns (bool) {
Bond memory bond = bonds[_pairKey(a, b)];
return _currentStrength(bond) > 0;
}
function linkStrength(address a, address b) external view returns (uint256) {
return _currentStrength(bonds[_pairKey(a, b)]);
}
function linkAge(address a, address b) external view returns (uint256) {
Bond memory bond = bonds[_pairKey(a, b)];
if (bond.formedAt == 0) return 0;
return block.timestamp - bond.formedAt;
}
function timeSinceRefresh(address a, address b) external view returns (uint256) {
Bond memory bond = bonds[_pairKey(a, b)];
if (bond.lastRefreshedAt == 0) return 0;
return block.timestamp - bond.lastRefreshedAt;
}
function wouldLink(address a, address b, uint256 toleranceBps) external view returns (bool) {
uint256 freqA = frequencyOf[_agentKey(a)];
uint256 freqB = frequencyOf[_agentKey(b)];
uint256 diff = freqA > freqB ? freqA - freqB : freqB - freqA;
uint256 base = freqA > freqB ? freqA : freqB;
uint256 diffBps = base == 0 ? (diff == 0 ? 0 : 10000) : (diff * 10000) / base;
return diffBps <= toleranceBps;
}
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.