On-chain AI-assisted trading on an Arbitrum vNet fork.
frontend/app/api/cre/stream/route.ts starts cre workflow simulate from a frontend GET /api/cre/stream request and streams execution logs live to the UI via SSE.
Flow summary:
- Spawns a child process (
cre ...) from the project root. - Streams
stdout/stderras SSE events (start,log,operation,error,done). - Auto-answers interactive CLI prompts through
stdin(triggerChoice,httpPayload). - Parses
[OPERATION_LOG]lines into structuredoperationevents. - Sends a final
doneevent with exit status.
-
HTTP trigger enters CRE
- Request is signed and validated against authorized public keys.
- Entry handlers:
positionroute (Aave/Uniswap flow)tradingroute (GMX flow)
-
Runtime options are resolved
reasonis extracted from request payload (or defaulted).actionandminConfidenceare validated/normalized.
-
Market data is fetched (CoinGecko OHLC)
- CRE HTTP capability fetches OHLC data.
- Data is summarized (trend/variation/high-low) for model context.
-
Prompt is built and Gemini is called
- Prompt includes target route, coin, network, forced action rules, and recent candles.
- Model response is parsed as strict JSON.
-
Action resolution and risk gating
- Final action comes from: forced action > model action > text fallback.
- Execution only proceeds if confidence threshold and receiver address checks pass.
-
Intent encoding + onchain writeReport
- For GMX: payload is encoded with GMX action schema and submitted to
GMXExecutor. - For Position: payload is encoded with position schema and submitted to
StrategyExecutor. - Report signature/hashing is performed by CRE before
writeReport.
- For GMX: payload is encoded with GMX action schema and submitted to
-
Structured result output
- Workflow returns recommendation + execution status + tx hash (if available).
my-workflow/main.ts- Bootstraps CRE runner and starts workflow handlers.
my-workflow/httpTriggers.ts- Defines HTTP triggers, key authorization, payload parsing, and mode dispatch (
position/trading).
- Defines HTTP triggers, key authorization, payload parsing, and mode dispatch (
my-workflow/strategyFlow.ts- Core orchestration: secrets, OHLC fetch, Gemini call, action resolution, confidence gating, execution routing, final response shaping.
my-workflow/types.ts- Central schema for config, request payloads, recommendation output, action enums, and OHLC summary types.
my-workflow/shared/data/marketDataClient.ts- CoinGecko fetch client, Gemini request client, OHLC summarization.
my-workflow/shared/prompt/promptBuilder.ts- Deterministic prompt composition with route hints and risk/format constraints.
my-workflow/shared/parsers/valueParsers.ts- Primitive converters/validators (
asNumber,asAddress,parseMinConfidence, etc.) used across modules.
- Primitive converters/validators (
my-workflow/shared/execution/trading/tradingExecutionConfig.ts- Prompt-level execution hints for trading route behavior.
my-workflow/shared/execution/trading/tradingPayloadEncoder.ts- ABI payload encoding for GMX intent.
my-workflow/shared/execution/trading/gmxReportExecution.ts- CRE report creation + EVM
writeReportcall for GMX executor.
- CRE report creation + EVM
my-workflow/shared/execution/trading/executionUtils.ts- Tx hash normalization and simulator-safe handling.
my-workflow/shared/execution/position/positionExecutionConfig.ts- Position defaults (tokens, amounts, chain selector).
my-workflow/shared/execution/position/positionPayloadEncoder.ts- ABI payload encoding for position operations.
my-workflow/shared/execution/position/positionReportExecution.ts- CRE report creation + EVM
writeReportcall for strategy executor.
- CRE report creation + EVM
my-workflow/strategyHelpers.ts- Action inference from model text, switcher resolution, GMX intent building, and strategy report encoding helpers.
my-workflow/config.staging.json/my-workflow/config.production.json- Environment-specific runtime config (secrets ids, chains, execution settings, authorized keys).
my-workflow/workflow.yaml- CRE workflow deployment/definition descriptor.
-
GMX Short Tx
View on Tenderly -
AAVE + UNISWAP Short Tx #1
View on Tenderly -
AAVE + UNISWAP Short Tx #2
View on Tenderly -
GMX Executor - Contract Creation Tx
View on Tenderly -
AAVE + UNISWAP StrategyExecutor - Contract Creation Tx
View on Tenderly
- Makefile: Definition of all targets
- scripts/configure-cre.sh: Automatic CRE configuration for GMX
- src/strategy/: Smart contracts
- script/: Forge scripts for execution
The Makefile organizes two main execution flows:
- Position Strategy: Leveraged trading AAVE + Sushi/Uniswap
- GMX Trading: Direct trading on GMX v2
Each flow has 5 phases: Deploy β Configure β Fund β Execute β Query
Virtual net with forks of mainnet Arbitrum is used for the flows. You need to have one for testing, and fund it from the tap on the Tenderly dashboard. tenderly
# Make sure you have the critical variables set
echo $PRIVATE_KEY
echo $ARB_RPC_URLmake help # Shows all targets# 1οΈβ£ Deploy
make deploy-position-strategy
# 2οΈβ£ Configure (optional, only if using CRE)
make configure-position-strategy
# or for full production setup:
make configure-position-strategy-full
# 3οΈβ£ Fund
make fund-position-strategy
# 4οΈβ£ Check balances
make check-position-strategy-balance
# 5οΈβ£ Execute
make execute-position-strategy
# 6οΈβ£ See results
make query-position-info# Execute with different amounts
make fund-position-strategy COLLATERAL_IN_ETH=2000000000000000000
make execute-position-strategy BORROW_AMOUNT_USDC=5000000000# 1οΈβ£ Deploy
make deploy-gmx-trading
# 2οΈβ£ Configure CRE (automatically integrates configure-cre.sh)
make configure-gmx-trading
# 3οΈβ£ Fund
make fund-gmx-trading
# 4οΈβ£ Execute (Long/Short/Close)
# Long position (default)
make execute-gmx-trading
# Short position
make execute-gmx-trading GMX_OPERATION=short GMX_IS_LONG=false
# Close position (requires GMX_SIZE_DELTA_USD = size to close)
make execute-gmx-trading GMX_OPERATION=close GMX_IS_LONG=false# See open positions
make query-gmx-positions
# See pending orders
make query-gmx-orders
# See details of a specific order
make query-gmx-order-details GMX_ORDER_KEY=0x...# Trading with different amounts
make execute-gmx-trading \
AMOUNT_IN_ETH=2000000000000000000 \
GMX_SIZE_DELTA_USD=2000000000000000000000000000000 \
GMX_OPERATION=long
# Change market
make execute-gmx-trading GMX_MARKET=0x...
# Specify prices
make execute-gmx-trading \
GMX_TRIGGER_PRICE=5000000000000000000000000000000 \
GMX_ACCEPTABLE_PRICE=4900000000000000000000000000000# Current status
make query-position-info# Open positions
make query-gmx-positions
# Pending orders
make query-gmx-orders
# Full order details
make query-gmx-order-details GMX_ORDER_KEY=<key>- Position Strategy:
0x1d315D963d7462F2931dF237B54736F90eE67faA - GMX Executor:
0x2157b12B8841B22A64aF4d049F2914829C8Fdc79 - Customizable via variables
- Position Strategy: Optional, uses
setCreForwarder() - GMX Trading: Automatic via
scripts/configure-cre.sh - CRE values in config variables
- Position Strategy: 10 ETH collateral, 10k USDC borrow
- GMX Trading: 10 ETH size delta in USD, 1 ETH execution
- All configured for Arbitrum
- RPC:
$(ARB_RPC_URL)from.env
Normal if first time. Run the flow first.
export PRIVATE_KEY=0x...
# or add to .env# Verify
echo $ARB_RPC_URL
make query-position-info # Quick test# Wait for block confirmations
sleep 30
make query-gmx-ordersPOSITION STRATEGY
[ ] make deploy-position-strategy
[ ] make fund-position-strategy
[ ] make check-position-strategy-balance
[ ] make execute-position-strategy
[ ] make query-position-info
GMX TRADING
[ ] make deploy-gmx-trading
[ ] make configure-gmx-trading
[ ] make fund-gmx-trading
[ ] make execute-gmx-trading GMX_OPERATION=long
[ ] make query-gmx-positions
[ ] make execute-gmx-trading GMX_OPERATION=close
[ ] make query-gmx-orders
- Main executor for the AAVE + Uniswap/Sushi position flow.
- Supports direct/manual execution through
execute(...). - Supports CRE callback execution through
onReport(...). - Stores CRE security/config values (
creForwarder,creWorkflowId,creWorkflowOwner) and validates sender on report reception.
- Dedicated executor for GMX v2 trading operations (long, short, close).
- Supports manual order creation (
createLongOrder,createShortOrder,createCloseOrder). - Supports CRE callback execution through
onReport(...), decoding report payload and creating the corresponding GMX order. - Uses
CreOrderConfigfor execution-level parameters (vault, execution fee, callback config, referral code, etc.).
- Minimal callback interface used by CRE receiver contracts.
- Standard entrypoint:
onReport(bytes metadata, bytes report).
UniswapBase,SushiBase,AaveBase,ArbitrageCaseprovide reusable DeFi primitives used byStrategyExecutor.- GMX-specific interfaces (
IGMXExecutor,IGMXExchangeRouter) encapsulate GMX request/route structures used byGMXExecutor.