Chainlink publishes a quickstart for an Automated Portfolio Manager — a portfolio that rebalances itself using three of their services together instead of just one. I built it end to end to understand how those pieces actually fit, not just read about it. This is the architecture, the rebalancing logic, and what's mocked versus real.
The problem: an oracle can't see everything
A price feed tells a contract what an asset is worth right now. It can't tell a contract "crypto sentiment just turned bearish" or "the gold volatility index spiked" — those aren't prices, they're computed signals that live behind ordinary REST APIs. If your rebalancing logic needs to react to them, something has to fetch them, and that something can't be the contract itself — contracts can't make HTTP calls.
That's the gap three Chainlink services close together:
- Functions — runs JavaScript off-chain (on Chainlink's DON) to call an external API and bring the result back on-chain.
- Automation — triggers that fetch on a schedule, then separately watches for "new data is in, time to act" and calls the rebalance.
- Data Feeds — prices the actual assets being held, so a rebalance can be sized correctly.
Architecture
[Time-based upkeep, daily 3 AM UTC]
│
▼
OffchainDataFetcher.sendRequestCBOR() ──▶ Chainlink Functions (DON)
│ runs JS: CryptoCompare sentiment
│ + MarketData GVZ index
▼
fulfillRequest() stores sentimentScore + gvzIndex on-chain
│
▼
[Custom-logic upkeep polls checkUpkeep() continuously]
│ sees fresh data + interval elapsed → true
▼
AutomatedPortfolioManager.performUpkeep()
│ reads sentimentScore + gvzIndex, reads Data Feeds for pricing
▼
rebalances gold / BTC / ETH holdings toward new target weights
Two contracts, two separate responsibilities. OffchainDataFetcher is the only
thing that talks to the outside world; AutomatedPortfolioManager never makes a
Functions call itself, it just reads whatever the fetcher last stored. That
separation matters: it means the portfolio logic can be tested completely
independently of anything network- or DON-related.
The contracts
| Contract | Role |
|---|---|
OffchainDataFetcher.sol |
Chainlink Functions consumer. sendRequestCBOR() (forwarder-gated) builds and sends the request; fulfillRequest() decodes the DON's response into a sentiment score and a GVZ index. |
AutomatedPortfolioManager.sol |
Chainlink Automation-compatible. checkUpkeep() flips true once fresh data exists and the rebalance interval has elapsed; performUpkeep() (forwarder-gated) computes new target weights and rebalances. |
MockAsset.sol |
Mintable/burnable ERC-20 standing in for a real wrapped asset (mXAU/mWBTC/mETH). |
MockFunctionsRouter.sol |
Local stand-in for the real Functions Router — matches the exact sendRequest selector FunctionsClient calls, so the real consumer contract runs completely unmodified against it. |
Both OffchainDataFetcher and AutomatedPortfolioManager extend Chainlink's actual
FunctionsClient and AutomationCompatibleInterface from @chainlink/contracts —
not reimplementations. Price feeds use Chainlink's own MockV3Aggregator, the same
AggregatorV3Interface shape a real Data Feed exposes.
The rebalancing logic
This is the part that made the exercise worth doing — turning two numbers into an allocation decision:
- GVZ (gold volatility index) sets the gold weight. Below a "calm" threshold, gold floors at 20%. Above a "stressed" threshold, it caps at 60% — a flight-to-safety response scaled linearly between the two.
- Sentiment score (-100 to 100) tilts what's left — the "crypto sleeve" — between BTC and ETH. Bullish sentiment shifts weight toward ETH, bearish toward BTC, clamped to a 30/70..70/30 range either direction so one extreme reading can't wipe out an entire side of the portfolio.
function _computeTargetWeights(int256 sentiment, uint256 gvz)
public pure returns (uint256 goldBps, uint256 btcBps, uint256 ethBps)
{
if (gvz >= GVZ_HIGH_THRESHOLD) {
goldBps = GOLD_BPS_CEIL; // 60% — stressed market
} else if (gvz <= GVZ_LOW_THRESHOLD) {
goldBps = GOLD_BPS_FLOOR; // 20% — calm market
} else {
goldBps = GOLD_BPS_FLOOR +
((gvz - GVZ_LOW_THRESHOLD) * (GOLD_BPS_CEIL - GOLD_BPS_FLOOR))
/ (GVZ_HIGH_THRESHOLD - GVZ_LOW_THRESHOLD);
}
uint256 cryptoBps = BPS - goldBps;
int256 clamped = sentiment > 100 ? int256(100) : sentiment < -100 ? int256(-100) : sentiment;
int256 ethShareOfCrypto = int256(5_000) + clamped * 20; // 30%..70% of the sleeve
ethBps = (cryptoBps * uint256(ethShareOfCrypto)) / BPS;
btcBps = cryptoBps - ethBps;
}
Executing the rebalance doesn't route through a DEX — the manager holds the mock assets directly and mints the shortfall / burns the excess against the same price feeds, so it's deterministic and fully testable without needing swap liquidity to exist. A test asserts total portfolio value is conserved across a rebalance to the cent (within integer-division dust) — the whole point is that a rebalance moves allocation, not net worth.
What's real vs. mocked — and why
Same honesty convention I use on every project here: the parts that need a funded wallet, a live Functions subscription, or a real DON are mocked locally so the logic is fully built and tested now, with a documented path to go live.
Real, unmodified: FunctionsClient, AutomationCompatibleInterface,
AggregatorV3Interface/MockV3Aggregator — imported straight from
@chainlink/contracts. Neither of my contracts would need to change to point at
the real Sepolia Functions Router or a real registered Automation upkeep.
Mocked for local dev: the Functions Router + DON itself (MockFunctionsRouter
— a test double, not a reimplementation of Chainlink's infrastructure), the price
feeds (owner-settable instead of live market data), and the automation forwarder
(the deployer's address instead of a real registration).
Verified, not assumed
17 passing
✔ only the automation forwarder can request data
✔ routes a request and stores the DON's fulfilled answer
✔ only the router can call handleOracleFulfillment
✔ records a Functions execution error instead of reverting
✔ shifts to the gold ceiling when GVZ is high (flight to safety)
✔ shifts to the gold floor when GVZ is low (calm market)
✔ tilts the crypto sleeve toward ETH on bullish sentiment / BTC on bearish
✔ clamps sentiment outside [-100, 100]
✔ only the automation forwarder can call performUpkeep
✔ performUpkeep reverts with no fresh data, or before the interval elapses
✔ rebalances toward gold and preserves total portfolio value when GVZ spikes
The access-control tests matter as much as the math ones. performUpkeep and
sendRequestCBOR are both gated to a single forwarder address — exactly the shape
Chainlink's own Automation registry uses, and exactly the kind of check that's easy
to skip when a contract "only" reacts to oracle data instead of holding user funds
directly. It still moves real allocation; it still deserves the same access-control
discipline as anything else on-chain.
Not done yet
Sepolia deploy against the real Functions Router and a registered Automation upkeep, the actual CryptoCompare/MarketData JavaScript Functions would execute, and swapping mint/burn for real DEX trades once this manages a real asset instead of a mock one — all documented as the next concrete steps, not hand-waved.