@oracle-agent/oracle 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTING.md +98 -0
- package/LICENSE +202 -0
- package/README.md +384 -0
- package/SECURITY.md +89 -0
- package/SETUP.md +235 -0
- package/artifacts/inscription/oracle-was-here-preview.png +0 -0
- package/artifacts/inscription/oracle-was-here.svg +1 -0
- package/artifacts/specialist-packs/oracle-full-crypto.json +273 -0
- package/bin/desk-server.mjs +438 -0
- package/bin/oracle-data-mcp.mjs +603 -0
- package/bin/oracle-init.mjs +423 -0
- package/bin/oracle-public-server.mjs +36 -0
- package/bin/oracle-route.mjs +254 -0
- package/bin/oracle-scan.mjs +192 -0
- package/docs/adding-a-chain.md +229 -0
- package/docs/architecture.md +135 -0
- package/docs/profiles.md +132 -0
- package/examples/add-a-chain.mjs +65 -0
- package/examples/research-a-token.mjs +70 -0
- package/package.json +90 -0
- package/profiles/_template/SOUL.md +47 -0
- package/profiles/_template/profile.json +22 -0
- package/profiles/bitcoin-agent/SOUL.md +31 -0
- package/profiles/bitcoin-agent/profile.json +32 -0
- package/profiles/hyperliquid-agent/SOUL.md +34 -0
- package/profiles/hyperliquid-agent/profile.json +37 -0
- package/profiles/oracle/SOUL.md +65 -0
- package/profiles/oracle/profile.json +35 -0
- package/profiles/polymarket-agent/SOUL.md +35 -0
- package/profiles/polymarket-agent/profile.json +34 -0
- package/profiles/profile.schema.json +90 -0
- package/profiles/protocol-builder/SOUL.md +50 -0
- package/profiles/protocol-builder/profile.json +37 -0
- package/profiles/robinhood-agent/SOUL.md +45 -0
- package/profiles/robinhood-agent/profile.json +39 -0
- package/profiles/solana-agent/SOUL.md +37 -0
- package/profiles/solana-agent/profile.json +37 -0
- package/profiles/stable-agent/SOUL.md +43 -0
- package/profiles/stable-agent/profile.json +37 -0
- package/public/oracle-console/app.js +272 -0
- package/public/oracle-console/bitcoin-wallets.js +206 -0
- package/public/oracle-console/index.html +91 -0
- package/public/oracle-console/styles.css +239 -0
- package/public/oracle-splash/index.html +931 -0
- package/scripts/build-inscription.py +230 -0
- package/scripts/check-test-count.mjs +105 -0
- package/scripts/e2e-hl-markets.mjs +21 -0
- package/scripts/e2e-hl-perps.mjs +48 -0
- package/scripts/e2e-hypercore-staking.mjs +128 -0
- package/scripts/e2e-solana-bitcoin.mjs +183 -0
- package/scripts/public-api-scan.mjs +23 -0
- package/scripts/secret-scan.mjs +181 -0
- package/scripts/verify-v3-venues.mjs +192 -0
- package/skills/oracle-best-execution/SKILL.md +127 -0
- package/skills/oracle-bitcoin/SKILL.md +53 -0
- package/skills/oracle-chain-graphs-telegram-cards/SKILL.md +59 -0
- package/skills/oracle-circuit-breaker/SKILL.md +51 -0
- package/skills/oracle-contract-research/SKILL.md +55 -0
- package/skills/oracle-desk/SKILL.md +58 -0
- package/skills/oracle-dex-launch/SKILL.md +38 -0
- package/skills/oracle-grants/SKILL.md +69 -0
- package/skills/oracle-hypercore-staking/SKILL.md +57 -0
- package/skills/oracle-hyperliquid/SKILL.md +56 -0
- package/skills/oracle-meme-token-sniper/SKILL.md +73 -0
- package/skills/oracle-nft-gacha-launch/SKILL.md +48 -0
- package/skills/oracle-nft-mint-gas-war/SKILL.md +63 -0
- package/skills/oracle-polymarket/SKILL.md +60 -0
- package/skills/oracle-protocol-builder/SKILL.md +38 -0
- package/skills/oracle-protocol-security/SKILL.md +60 -0
- package/skills/oracle-public-product/SKILL.md +44 -0
- package/skills/oracle-receipts/SKILL.md +52 -0
- package/skills/oracle-rfq-tokenized-assets/SKILL.md +69 -0
- package/skills/oracle-smart-wallet-scanner/SKILL.md +49 -0
- package/skills/oracle-solana/SKILL.md +65 -0
- package/skills/oracle-solana-nft/SKILL.md +54 -0
- package/skills/oracle-token-research/SKILL.md +67 -0
- package/src/agent-auth.mjs +191 -0
- package/src/approval-guard.mjs +282 -0
- package/src/attestation-secret.mjs +88 -0
- package/src/audit-log.mjs +196 -0
- package/src/auto-slippage.mjs +378 -0
- package/src/capability-posture.mjs +125 -0
- package/src/chains.mjs +62 -0
- package/src/data/catalog.mjs +495 -0
- package/src/data/desk-data.mjs +623 -0
- package/src/data/http.mjs +200 -0
- package/src/data/provider-endpoint.mjs +94 -0
- package/src/data/providers/aerodrome.mjs +244 -0
- package/src/data/providers/balancer.mjs +208 -0
- package/src/data/providers/bitcoin-esplora.mjs +230 -0
- package/src/data/providers/bitcoin-meta.mjs +378 -0
- package/src/data/providers/blockscout.mjs +14 -0
- package/src/data/providers/bridges.mjs +241 -0
- package/src/data/providers/cowswap.mjs +501 -0
- package/src/data/providers/curve.mjs +200 -0
- package/src/data/providers/defillama.mjs +88 -0
- package/src/data/providers/dexscreener.mjs +43 -0
- package/src/data/providers/evm-rpc.mjs +203 -0
- package/src/data/providers/geckoterminal.mjs +34 -0
- package/src/data/providers/gmx.mjs +495 -0
- package/src/data/providers/hl-info.mjs +102 -0
- package/src/data/providers/hl-markets.mjs +210 -0
- package/src/data/providers/hl-perps.mjs +382 -0
- package/src/data/providers/hl-staking.mjs +352 -0
- package/src/data/providers/hl-ws.mjs +119 -0
- package/src/data/providers/hyperevm-dex.mjs +49 -0
- package/src/data/providers/jupiter.mjs +182 -0
- package/src/data/providers/lifi.mjs +150 -0
- package/src/data/providers/magiceden-sol.mjs +355 -0
- package/src/data/providers/morpho.mjs +173 -0
- package/src/data/providers/odos.mjs +155 -0
- package/src/data/providers/oneinch.mjs +173 -0
- package/src/data/providers/opensea-multichain.mjs +136 -0
- package/src/data/providers/opensea-nft.mjs +99 -0
- package/src/data/providers/paraswap.mjs +117 -0
- package/src/data/providers/pendle.mjs +187 -0
- package/src/data/providers/poly-public.mjs +96 -0
- package/src/data/providers/poly-ws.mjs +103 -0
- package/src/data/providers/rh-agent.mjs +59 -0
- package/src/data/providers/satflow.mjs +336 -0
- package/src/data/providers/solana-rpc.mjs +186 -0
- package/src/data/providers/uniswap-v3.mjs +303 -0
- package/src/data/providers/zerox.mjs +166 -0
- package/src/data/public-api-scan.mjs +61 -0
- package/src/data/quote-placeholder.mjs +31 -0
- package/src/exact-integer.mjs +72 -0
- package/src/exec-policy.mjs +444 -0
- package/src/flags.mjs +15 -0
- package/src/fresh-window.mjs +76 -0
- package/src/gmx-attestation.mjs +175 -0
- package/src/index.mjs +50 -0
- package/src/nft-gas-war-guard.mjs +139 -0
- package/src/onboarding/agent-keys.mjs +157 -0
- package/src/onboarding/index.mjs +18 -0
- package/src/onboarding/tiers.mjs +139 -0
- package/src/oracle-env.mjs +38 -0
- package/src/protocol-execution.mjs +84 -0
- package/src/public-api/buzz-integration.mjs +256 -0
- package/src/public-api/connect-agent.mjs +397 -0
- package/src/public-api/grants.mjs +142 -0
- package/src/public-api/http.mjs +374 -0
- package/src/public-control/aa-adapter.mjs +402 -0
- package/src/public-control/build-registry.mjs +227 -0
- package/src/public-control/bundler-client.mjs +372 -0
- package/src/public-control/grant-indexer.mjs +296 -0
- package/src/public-control/policy-render.mjs +69 -0
- package/src/public-control/policy-schema.mjs +318 -0
- package/src/public-control/runtime-config.mjs +265 -0
- package/src/public-control/session-key-model.mjs +374 -0
- package/src/public-control/session-orchestrator.mjs +412 -0
- package/src/route-attestation.mjs +132 -0
- package/src/router/best-execution.mjs +221 -0
- package/src/router/index.mjs +185 -0
- package/src/router/prepare-bridge.mjs +288 -0
- package/src/router/prepare-route.mjs +341 -0
- package/src/router/proposal.mjs +311 -0
- package/src/router/risk-classifier.mjs +119 -0
- package/src/router/route-sources.mjs +292 -0
- package/src/scanner/chains.config.mjs +381 -0
- package/src/scanner/contract.mjs +270 -0
- package/src/scanner/evm-scanner.mjs +394 -0
- package/src/scanner/index.mjs +9 -0
- package/src/scanner/v2-venue.mjs +335 -0
- package/src/scanner/v3-venue.mjs +290 -0
- package/src/scopes.mjs +44 -0
- package/src/sell-simulation.mjs +167 -0
- package/src/token-transfer-guard.mjs +188 -0
- package/src/vault-attestation.mjs +145 -0
- package/src/venues.mjs +206 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// Sell simulation: can you get OUT of this token before you ape in?
|
|
2
|
+
//
|
|
3
|
+
// The single most expensive failure in memecoin trading is not a bad entry, it
|
|
4
|
+
// is an entry you cannot exit. A honeypot lets you buy and then blocks the
|
|
5
|
+
// sell, or taxes it to zero, or lets only allowlisted wallets out. Every one of
|
|
6
|
+
// those looks identical to a healthy token on a chart and on a buy-side quote.
|
|
7
|
+
//
|
|
8
|
+
// The ONLY reliable test is to simulate the round trip: quote buy, then quote
|
|
9
|
+
// the sell of what that buy would give you, and compare what comes back. This
|
|
10
|
+
// module turns that into a verdict.
|
|
11
|
+
//
|
|
12
|
+
// It is deliberately venue-agnostic: pass in a quote function and it works on
|
|
13
|
+
// any chain and any DEX Oracle supports.
|
|
14
|
+
|
|
15
|
+
export const SELL_SIM = Object.freeze({
|
|
16
|
+
SAFE: "SAFE",
|
|
17
|
+
CAUTION: "CAUTION",
|
|
18
|
+
HONEYPOT: "HONEYPOT",
|
|
19
|
+
UNKNOWN: "UNKNOWN",
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
// Round-trip loss above this is a hard refusal: no honest fee structure eats
|
|
23
|
+
// this much, so it means a sell tax or a rigged curve.
|
|
24
|
+
const HONEYPOT_LOSS_BPS = 5000; // 50%
|
|
25
|
+
// Above this, allow the trade but make the user look at it.
|
|
26
|
+
const CAUTION_LOSS_BPS = 1500; // 15%
|
|
27
|
+
|
|
28
|
+
function bps(part, whole) {
|
|
29
|
+
if (whole === 0n) return null;
|
|
30
|
+
return Number(((whole - part) * 10000n) / whole);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function toBig(value, label) {
|
|
34
|
+
if (value == null || value === "") throw new Error(`sell-sim: ${label} required`);
|
|
35
|
+
if (typeof value === "bigint") return value;
|
|
36
|
+
const text = String(value).trim();
|
|
37
|
+
if (!/^\d+$/.test(text)) throw new Error(`sell-sim: ${label} must be an integer base-unit amount`);
|
|
38
|
+
return BigInt(text);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Simulate the full round trip: base -> token -> base.
|
|
43
|
+
*
|
|
44
|
+
* @param {object} args
|
|
45
|
+
* @param {string} args.token token contract being evaluated
|
|
46
|
+
* @param {string} args.base the asset you pay with (WETH, USDC, SOL...)
|
|
47
|
+
* @param {string|bigint} args.amountIn base amount, in base units
|
|
48
|
+
* @param {number} [args.chainId]
|
|
49
|
+
* @param {object} opts
|
|
50
|
+
* @param {(q:object)=>Promise<{outAmount:string|bigint}>} opts.quote
|
|
51
|
+
* A quote function. Called twice: buy leg, then sell leg.
|
|
52
|
+
*
|
|
53
|
+
* @returns verdict + the numbers behind it. NEVER a bare boolean: the caller
|
|
54
|
+
* must be able to show the user why.
|
|
55
|
+
*/
|
|
56
|
+
export async function simulateSell(args = {}, opts = {}) {
|
|
57
|
+
const { token, base, chainId = null } = args;
|
|
58
|
+
if (!token) throw new Error("sell-sim: token required");
|
|
59
|
+
if (!base) throw new Error("sell-sim: base asset required");
|
|
60
|
+
if (typeof opts.quote !== "function") throw new Error("sell-sim: opts.quote function required");
|
|
61
|
+
|
|
62
|
+
const amountIn = toBig(args.amountIn, "amountIn");
|
|
63
|
+
|
|
64
|
+
let buy;
|
|
65
|
+
try {
|
|
66
|
+
buy = await opts.quote({ chainId, inputMint: base, outputMint: token, amount: amountIn.toString(), side: "buy" });
|
|
67
|
+
} catch (err) {
|
|
68
|
+
return verdict(SELL_SIM.UNKNOWN, `buy leg could not be quoted: ${short(err)}`, { chainId, token, base });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const tokensOut = safeBig(buy?.outAmount);
|
|
72
|
+
if (tokensOut == null || tokensOut === 0n) {
|
|
73
|
+
return verdict(SELL_SIM.UNKNOWN, "buy leg returned no output — no route or no liquidity", { chainId, token, base });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let sell;
|
|
77
|
+
try {
|
|
78
|
+
sell = await opts.quote({ chainId, inputMint: token, outputMint: base, amount: tokensOut.toString(), side: "sell" });
|
|
79
|
+
} catch (err) {
|
|
80
|
+
// A buy that routes and a sell that will not is the classic honeypot shape.
|
|
81
|
+
return verdict(
|
|
82
|
+
SELL_SIM.HONEYPOT,
|
|
83
|
+
`buy routes but the SELL leg fails to quote (${short(err)}) — you would not be able to exit`,
|
|
84
|
+
{ chainId, token, base, tokensOut: tokensOut.toString() }
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const backOut = safeBig(sell?.outAmount);
|
|
89
|
+
if (backOut == null || backOut === 0n) {
|
|
90
|
+
return verdict(SELL_SIM.HONEYPOT, "sell leg returns zero — the position cannot be exited for value", {
|
|
91
|
+
chainId,
|
|
92
|
+
token,
|
|
93
|
+
base,
|
|
94
|
+
tokensOut: tokensOut.toString(),
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const lossBps = bps(backOut, amountIn);
|
|
99
|
+
const detail = {
|
|
100
|
+
chainId,
|
|
101
|
+
token,
|
|
102
|
+
base,
|
|
103
|
+
amountIn: amountIn.toString(),
|
|
104
|
+
tokensOut: tokensOut.toString(),
|
|
105
|
+
roundTripOut: backOut.toString(),
|
|
106
|
+
roundTripLossBps: lossBps,
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
if (lossBps == null) return verdict(SELL_SIM.UNKNOWN, "could not compute round-trip loss", detail);
|
|
110
|
+
if (lossBps >= HONEYPOT_LOSS_BPS) {
|
|
111
|
+
return verdict(
|
|
112
|
+
SELL_SIM.HONEYPOT,
|
|
113
|
+
`round trip loses ${(lossBps / 100).toFixed(1)}% — a sell tax or rigged curve, not normal slippage`,
|
|
114
|
+
detail
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
if (lossBps >= CAUTION_LOSS_BPS) {
|
|
118
|
+
return verdict(SELL_SIM.CAUTION, `round trip loses ${(lossBps / 100).toFixed(1)}% — high tax or thin liquidity`, detail);
|
|
119
|
+
}
|
|
120
|
+
return verdict(SELL_SIM.SAFE, `round trip loses ${(lossBps / 100).toFixed(1)}% — exit path looks normal`, detail);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function verdict(status, reason, detail) {
|
|
124
|
+
return {
|
|
125
|
+
status,
|
|
126
|
+
safe: status === SELL_SIM.SAFE,
|
|
127
|
+
tradable: status === SELL_SIM.SAFE || status === SELL_SIM.CAUTION,
|
|
128
|
+
reason,
|
|
129
|
+
...detail,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function safeBig(v) {
|
|
134
|
+
if (v == null) return null;
|
|
135
|
+
try {
|
|
136
|
+
const text = String(v).trim();
|
|
137
|
+
if (!/^\d+$/.test(text)) return null;
|
|
138
|
+
return BigInt(text);
|
|
139
|
+
} catch {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function short(err) {
|
|
145
|
+
return String(err?.message || err).slice(0, 120);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Refuse to proceed unless the token can actually be sold.
|
|
150
|
+
*
|
|
151
|
+
* Fails CLOSED on UNKNOWN: "we could not verify you can exit" must never read
|
|
152
|
+
* as "safe to ape". Pass allowUnknown only for research surfaces where no money
|
|
153
|
+
* moves.
|
|
154
|
+
*/
|
|
155
|
+
export async function assertSellable(args = {}, opts = {}) {
|
|
156
|
+
const result = await simulateSell(args, opts);
|
|
157
|
+
const acceptable =
|
|
158
|
+
result.status === SELL_SIM.SAFE ||
|
|
159
|
+
(result.status === SELL_SIM.CAUTION && opts.allowCaution !== false) ||
|
|
160
|
+
(result.status === SELL_SIM.UNKNOWN && opts.allowUnknown === true);
|
|
161
|
+
if (!acceptable) {
|
|
162
|
+
const err = new Error(`sell-sim ${result.status}: ${result.reason}`);
|
|
163
|
+
err.sellSim = result;
|
|
164
|
+
throw err;
|
|
165
|
+
}
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { Interface, MaxUint256, isAddress } from "ethers";
|
|
2
|
+
|
|
3
|
+
const TRANSFER_SELECTOR = "0xa9059cbb";
|
|
4
|
+
const TRANSFER_FROM_SELECTOR = "0x23b872dd";
|
|
5
|
+
const DEFAULT_TOKEN_TRANSFER_TTL_MS = 20_000;
|
|
6
|
+
|
|
7
|
+
const ERC20_TRANSFER = new Interface([
|
|
8
|
+
"function transfer(address to,uint256 amount) returns (bool)",
|
|
9
|
+
"function transferFrom(address from,address to,uint256 amount) returns (bool)",
|
|
10
|
+
]);
|
|
11
|
+
|
|
12
|
+
function normalAddress(value, label) {
|
|
13
|
+
const text = String(value || "").trim();
|
|
14
|
+
if (!isAddress(text)) throw new Error(`${label} must be an address`);
|
|
15
|
+
return text.toLowerCase();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function amountString(value, label = "token transfer amount", { allowZero = false } = {}) {
|
|
19
|
+
// A JS number cannot represent every uint256, and above 2^53 it silently
|
|
20
|
+
// rounds — usually UPWARD, which would widen a spending cap past what the
|
|
21
|
+
// user asked for. `9007199254740995` arrives as `...996` and authorizes one
|
|
22
|
+
// more token than intended. Refuse unsafe numbers instead of quietly
|
|
23
|
+
// accepting a different value than the caller wrote.
|
|
24
|
+
if (typeof value === "number") {
|
|
25
|
+
if (!Number.isInteger(value)) {
|
|
26
|
+
throw new Error(`${label} must be an integer`);
|
|
27
|
+
}
|
|
28
|
+
if (!Number.isSafeInteger(value)) {
|
|
29
|
+
throw new Error(
|
|
30
|
+
`${label} exceeds safe integer precision — pass it as a decimal string or BigInt so the exact value is preserved`
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
let amount;
|
|
35
|
+
try {
|
|
36
|
+
amount = BigInt(String(value));
|
|
37
|
+
} catch {
|
|
38
|
+
throw new Error(`${label} must be an integer string`);
|
|
39
|
+
}
|
|
40
|
+
if (allowZero ? amount < 0n : amount <= 0n) throw new Error(`${label} must be positive`);
|
|
41
|
+
if (amount >= MaxUint256) throw new Error("unbounded token transfer amount refused");
|
|
42
|
+
return amount.toString();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function txValue(tx = {}) {
|
|
46
|
+
const raw = tx.value == null ? "0" : String(tx.value);
|
|
47
|
+
return BigInt(raw);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function isTokenTransferCall(data) {
|
|
51
|
+
const hex = String(data || "").toLowerCase();
|
|
52
|
+
return hex.startsWith(TRANSFER_SELECTOR) || hex.startsWith(TRANSFER_FROM_SELECTOR);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function decodeTokenTransferCalldata(data) {
|
|
56
|
+
const hex = String(data || "").toLowerCase();
|
|
57
|
+
try {
|
|
58
|
+
if (hex.startsWith(TRANSFER_SELECTOR)) {
|
|
59
|
+
const [recipient, amount] = ERC20_TRANSFER.decodeFunctionData("transfer", data);
|
|
60
|
+
return {
|
|
61
|
+
kind: "transfer",
|
|
62
|
+
recipient: normalAddress(recipient, "token transfer recipient"),
|
|
63
|
+
amount: amountString(amount),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
if (hex.startsWith(TRANSFER_FROM_SELECTOR)) {
|
|
67
|
+
const [from, recipient, amount] = ERC20_TRANSFER.decodeFunctionData("transferFrom", data);
|
|
68
|
+
return {
|
|
69
|
+
kind: "transferFrom",
|
|
70
|
+
from: normalAddress(from, "token transfer source"),
|
|
71
|
+
recipient: normalAddress(recipient, "token transfer recipient"),
|
|
72
|
+
amount: amountString(amount),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (/token transfer/.test(String(error?.message || error))) throw error;
|
|
77
|
+
throw new Error("invalid token transfer calldata");
|
|
78
|
+
}
|
|
79
|
+
throw new Error("token transfer calldata required");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function createTokenTransferGuard({
|
|
83
|
+
chainId,
|
|
84
|
+
token,
|
|
85
|
+
kind = "transfer",
|
|
86
|
+
from,
|
|
87
|
+
recipient,
|
|
88
|
+
amount,
|
|
89
|
+
maxAmount,
|
|
90
|
+
provider,
|
|
91
|
+
purpose,
|
|
92
|
+
nowMs = Date.now(),
|
|
93
|
+
ttlMs = DEFAULT_TOKEN_TRANSFER_TTL_MS,
|
|
94
|
+
} = {}) {
|
|
95
|
+
const guard = {
|
|
96
|
+
mode: "token-transfer",
|
|
97
|
+
chainId: Number(chainId),
|
|
98
|
+
token: normalAddress(token, "token transfer token"),
|
|
99
|
+
kind: String(kind || "transfer"),
|
|
100
|
+
recipient: normalAddress(recipient, "token transfer recipient"),
|
|
101
|
+
issuedAtMs: Number(nowMs),
|
|
102
|
+
expiresAtMs: Number(nowMs) + Number(ttlMs || DEFAULT_TOKEN_TRANSFER_TTL_MS),
|
|
103
|
+
};
|
|
104
|
+
if (guard.kind !== "transfer" && guard.kind !== "transferFrom") {
|
|
105
|
+
throw new Error("token transfer kind must be transfer or transferFrom");
|
|
106
|
+
}
|
|
107
|
+
if (guard.kind === "transferFrom") guard.from = normalAddress(from, "token transfer source");
|
|
108
|
+
if (amount != null) guard.amount = amountString(amount);
|
|
109
|
+
if (maxAmount != null) guard.maxAmount = amountString(maxAmount);
|
|
110
|
+
if (!guard.amount && !guard.maxAmount) throw new Error("token transfer guard requires exact amount or maxAmount");
|
|
111
|
+
if (provider) guard.provider = String(provider).trim();
|
|
112
|
+
if (purpose) guard.purpose = String(purpose).trim();
|
|
113
|
+
if (!Number.isFinite(guard.chainId)) throw new Error("token transfer chainId required");
|
|
114
|
+
if (!Number.isFinite(guard.issuedAtMs) || !Number.isFinite(guard.expiresAtMs) || guard.expiresAtMs <= guard.issuedAtMs) {
|
|
115
|
+
throw new Error("token transfer guard expiry invalid");
|
|
116
|
+
}
|
|
117
|
+
return guard;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function assertTokenTransferGuard(guard, tx = {}, { chainId, nowMs = Date.now() } = {}) {
|
|
121
|
+
if (!guard || guard.mode !== "token-transfer") throw new Error("token transfer guard required");
|
|
122
|
+
|
|
123
|
+
// Time is a security parameter here, so an unusable clock must fail CLOSED.
|
|
124
|
+
// A NaN/Infinity `nowMs` made every `now > expiresAtMs` comparison false and
|
|
125
|
+
// silently disabled expiry; a guard missing its timestamps skipped the TTL
|
|
126
|
+
// check entirely. Both turn a short-lived authorization into a permanent one.
|
|
127
|
+
const now = Number(nowMs);
|
|
128
|
+
if (!Number.isFinite(now)) {
|
|
129
|
+
throw new Error("token transfer guard: current time must be a finite number");
|
|
130
|
+
}
|
|
131
|
+
const issuedAtMs = Number(guard.issuedAtMs);
|
|
132
|
+
const expiresAtMs = Number(guard.expiresAtMs);
|
|
133
|
+
if (!Number.isFinite(issuedAtMs) || !Number.isFinite(expiresAtMs)) {
|
|
134
|
+
throw new Error("token transfer guard: issuedAtMs and expiresAtMs are required and must be finite");
|
|
135
|
+
}
|
|
136
|
+
if (expiresAtMs <= issuedAtMs) {
|
|
137
|
+
throw new Error("token transfer guard: expiry must be after issuance");
|
|
138
|
+
}
|
|
139
|
+
if (now > expiresAtMs) {
|
|
140
|
+
throw new Error(`token transfer guard expired at ${expiresAtMs}, now ${now}`);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const txChainId = Number(tx.chainId ?? chainId);
|
|
144
|
+
if (Number(guard.chainId) !== txChainId) throw new Error(`token transfer chain mismatch: expected ${txChainId}, got ${guard.chainId}`);
|
|
145
|
+
const token = normalAddress(tx.to, "token transfer token");
|
|
146
|
+
if (normalAddress(guard.token, "token transfer token") !== token) throw new Error("token transfer token mismatch");
|
|
147
|
+
const decoded = decodeTokenTransferCalldata(tx.data);
|
|
148
|
+
if (String(guard.kind) !== decoded.kind) throw new Error("token transfer kind mismatch");
|
|
149
|
+
if (normalAddress(guard.recipient, "token transfer recipient") !== decoded.recipient) throw new Error("token transfer recipient mismatch");
|
|
150
|
+
if (decoded.kind === "transferFrom" && normalAddress(guard.from, "token transfer source") !== decoded.from) {
|
|
151
|
+
throw new Error("token transfer source mismatch");
|
|
152
|
+
}
|
|
153
|
+
// An amount ceiling is MANDATORY. Both checks below were conditional on the
|
|
154
|
+
// field being present, so a guard omitting BOTH `amount` and `maxAmount`
|
|
155
|
+
// skipped every amount check and authorized a transfer of any size — the
|
|
156
|
+
// final ERC-20 gate was effectively unbounded. A guard with no cap is not a
|
|
157
|
+
// guard.
|
|
158
|
+
if (guard.amount == null && guard.maxAmount == null) {
|
|
159
|
+
throw new Error("token transfer guard must bind an amount or a maxAmount — a capless guard authorizes any size");
|
|
160
|
+
}
|
|
161
|
+
// Coherence first: a guard whose own fields contradict each other is
|
|
162
|
+
// malformed, and saying so is more useful than reporting whichever bound
|
|
163
|
+
// happened to trip.
|
|
164
|
+
if (guard.amount != null && guard.maxAmount != null) {
|
|
165
|
+
if (BigInt(amountString(guard.amount)) > BigInt(amountString(guard.maxAmount))) {
|
|
166
|
+
throw new Error("token transfer guard amount exceeds its own maxAmount");
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (guard.amount != null && amountString(guard.amount) !== decoded.amount) {
|
|
170
|
+
throw new Error("token transfer amount mismatch");
|
|
171
|
+
}
|
|
172
|
+
if (guard.maxAmount != null && BigInt(decoded.amount) > BigInt(amountString(guard.maxAmount))) {
|
|
173
|
+
throw new Error("token transfer amount exceeds guard maxAmount");
|
|
174
|
+
}
|
|
175
|
+
if (txValue(tx) !== 0n) throw new Error("token transfer tx value must be zero");
|
|
176
|
+
if (Number(guard.expiresAtMs) <= Number(nowMs)) throw new Error("token transfer guard expired");
|
|
177
|
+
if (Number(guard.issuedAtMs) > Number(nowMs) + 5_000) throw new Error("token transfer guard issued in the future");
|
|
178
|
+
return {
|
|
179
|
+
chainId: txChainId,
|
|
180
|
+
token,
|
|
181
|
+
kind: decoded.kind,
|
|
182
|
+
from: decoded.from || null,
|
|
183
|
+
recipient: decoded.recipient,
|
|
184
|
+
amount: decoded.amount,
|
|
185
|
+
provider: guard.provider || null,
|
|
186
|
+
purpose: guard.purpose || null,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { Interface, isAddress } from "ethers";
|
|
3
|
+
import { routeCalldataHash } from "./route-attestation.mjs";
|
|
4
|
+
import { resolveAttestationSecret } from "./attestation-secret.mjs";
|
|
5
|
+
import { assertFreshWindow } from "./fresh-window.mjs";
|
|
6
|
+
|
|
7
|
+
const DEFAULT_VAULT_ATTESTATION_TTL_MS = 20_000;
|
|
8
|
+
const ERC20 = new Interface(["function approve(address spender,uint256 amount) returns (bool)"]);
|
|
9
|
+
|
|
10
|
+
function canonicalJson(value) {
|
|
11
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
12
|
+
if (value && typeof value === "object") {
|
|
13
|
+
return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(",")}}`;
|
|
14
|
+
}
|
|
15
|
+
return JSON.stringify(value);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function normalAddress(value, label) {
|
|
19
|
+
const text = String(value || "").trim();
|
|
20
|
+
if (!isAddress(text)) throw new Error(`${label} must be an address`);
|
|
21
|
+
return text.toLowerCase();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function amountString(value, label = "vault amount") {
|
|
25
|
+
try {
|
|
26
|
+
const n = BigInt(String(value));
|
|
27
|
+
if (n <= 0n) throw new Error("nonpositive");
|
|
28
|
+
return n.toString();
|
|
29
|
+
} catch {
|
|
30
|
+
throw new Error(`${label} must be a positive integer string`);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function decodeApproveCalldata(data) {
|
|
35
|
+
const hex = String(data || "").toLowerCase();
|
|
36
|
+
if (!hex.startsWith("0x095ea7b3")) throw new Error("approval calldata required");
|
|
37
|
+
const [spender, amount] = ERC20.decodeFunctionData("approve", hex);
|
|
38
|
+
return { spender: normalAddress(spender, "approval spender"), amount: amountString(amount, "approval amount") };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function hmac(secret, payload) {
|
|
42
|
+
return `0x${createHmac("sha256", String(secret)).update(payload).digest("hex")}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function sameSignature(a, b) {
|
|
46
|
+
const left = Buffer.from(String(a || "").replace(/^0x/, ""), "hex");
|
|
47
|
+
const right = Buffer.from(String(b || "").replace(/^0x/, ""), "hex");
|
|
48
|
+
return left.length === right.length && left.length > 0 && timingSafeEqual(left, right);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function attestationSecret(secret) {
|
|
52
|
+
return resolveAttestationSecret(
|
|
53
|
+
secret,
|
|
54
|
+
"ORACLE_ROUTE_ATTESTATION_SECRET",
|
|
55
|
+
"MAD_ROUTE_ATTESTATION_SECRET",
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function unsigned(attestation) {
|
|
60
|
+
const { signature: _signature, ...payload } = attestation;
|
|
61
|
+
return payload;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function createVaultAttestation({
|
|
65
|
+
provider = "morpho",
|
|
66
|
+
chainId,
|
|
67
|
+
action,
|
|
68
|
+
vault,
|
|
69
|
+
asset,
|
|
70
|
+
owner,
|
|
71
|
+
receiver,
|
|
72
|
+
amount,
|
|
73
|
+
data,
|
|
74
|
+
calldataHash,
|
|
75
|
+
minSharesOut,
|
|
76
|
+
maxSharesIn,
|
|
77
|
+
totalAssetsUsd,
|
|
78
|
+
nowMs = Date.now(),
|
|
79
|
+
ttlMs = DEFAULT_VAULT_ATTESTATION_TTL_MS,
|
|
80
|
+
secret,
|
|
81
|
+
} = {}) {
|
|
82
|
+
const normalizedAction = String(action || "").trim().toLowerCase();
|
|
83
|
+
if (!["deposit", "withdraw"].includes(normalizedAction)) throw new Error("vault attestation action must be deposit or withdraw");
|
|
84
|
+
const attestation = {
|
|
85
|
+
mode: "vault-attestation",
|
|
86
|
+
version: 1,
|
|
87
|
+
provider: String(provider || "").trim() || "morpho",
|
|
88
|
+
chainId: Number(chainId),
|
|
89
|
+
action: normalizedAction,
|
|
90
|
+
vault: normalAddress(vault, "vault"),
|
|
91
|
+
asset: normalAddress(asset, "vault asset"),
|
|
92
|
+
owner: normalAddress(owner, "vault owner"),
|
|
93
|
+
receiver: normalAddress(receiver || owner, "vault receiver"),
|
|
94
|
+
amount: amountString(amount),
|
|
95
|
+
calldataHash: data ? routeCalldataHash(data) : calldataHash,
|
|
96
|
+
value: "0",
|
|
97
|
+
issuedAtMs: Number(nowMs),
|
|
98
|
+
expiresAtMs: Number(nowMs) + Number(ttlMs),
|
|
99
|
+
};
|
|
100
|
+
if (!Number.isFinite(attestation.chainId)) throw new Error("vault attestation chainId required");
|
|
101
|
+
if (minSharesOut != null) attestation.minSharesOut = amountString(minSharesOut, "minSharesOut");
|
|
102
|
+
if (maxSharesIn != null) attestation.maxSharesIn = amountString(maxSharesIn, "maxSharesIn");
|
|
103
|
+
if (totalAssetsUsd != null) attestation.totalAssetsUsd = Number(totalAssetsUsd);
|
|
104
|
+
const payload = canonicalJson(attestation);
|
|
105
|
+
return { ...attestation, signature: hmac(attestationSecret(secret), payload) };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function assertVaultAttestation(attestation, tx = {}, { chainId, nowMs = Date.now(), secret } = {}) {
|
|
109
|
+
// Time is a security parameter: an unusable clock must fail CLOSED,
|
|
110
|
+
// otherwise NaN/null/-Infinity silently makes this attestation eternal.
|
|
111
|
+
assertFreshWindow(attestation || {}, nowMs, "vault attestation");
|
|
112
|
+
if (!attestation || attestation.mode !== "vault-attestation") throw new Error("vault attestation required");
|
|
113
|
+
if (Number(attestation.expiresAtMs) <= Number(nowMs)) throw new Error("vault attestation expired");
|
|
114
|
+
const txChainId = Number(chainId ?? tx.chainId);
|
|
115
|
+
if (Number(attestation.chainId) !== txChainId) throw new Error("vault attestation chain mismatch");
|
|
116
|
+
const to = normalAddress(tx.to, "vault tx.to");
|
|
117
|
+
if (normalAddress(attestation.vault, "vault") !== to) throw new Error("vault attestation destination mismatch");
|
|
118
|
+
if (tx.from && normalAddress(attestation.owner, "vault owner") !== normalAddress(tx.from, "vault tx.from")) {
|
|
119
|
+
throw new Error("vault attestation owner mismatch");
|
|
120
|
+
}
|
|
121
|
+
const value = tx.value == null ? "0" : String(BigInt(String(tx.value).startsWith("0x") ? String(tx.value) : String(tx.value)));
|
|
122
|
+
if (value !== "0") throw new Error("vault attestation value mismatch");
|
|
123
|
+
if (attestation.calldataHash !== routeCalldataHash(tx.data || "0x")) throw new Error("vault attestation calldata mismatch");
|
|
124
|
+
const expected = hmac(attestationSecret(secret), canonicalJson(unsigned(attestation)));
|
|
125
|
+
if (!sameSignature(attestation.signature, expected)) throw new Error("vault attestation signature mismatch");
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function assertVaultApprovalAttestation(attestation, tx = {}, guard = {}, { chainId, nowMs = Date.now(), secret } = {}) {
|
|
130
|
+
if (!attestation || attestation.mode !== "vault-attestation") throw new Error("vault attestation required");
|
|
131
|
+
if (String(attestation.action) !== "deposit") throw new Error("vault approval requires deposit attestation");
|
|
132
|
+
if (Number(attestation.expiresAtMs) <= Number(nowMs)) throw new Error("vault attestation expired");
|
|
133
|
+
const expected = hmac(attestationSecret(secret), canonicalJson(unsigned(attestation)));
|
|
134
|
+
if (!sameSignature(attestation.signature, expected)) throw new Error("vault attestation signature mismatch");
|
|
135
|
+
const txChainId = Number(tx.chainId ?? chainId);
|
|
136
|
+
if (Number(attestation.chainId) !== txChainId) throw new Error("vault attestation chain mismatch");
|
|
137
|
+
const decoded = decodeApproveCalldata(tx.data);
|
|
138
|
+
if (normalAddress(attestation.asset, "vault asset") !== normalAddress(tx.to, "approval token")) throw new Error("vault attestation asset mismatch");
|
|
139
|
+
if (normalAddress(attestation.vault, "vault") !== decoded.spender) throw new Error("vault attestation spender mismatch");
|
|
140
|
+
if (String(attestation.amount) !== decoded.amount || String(guard.amount) !== decoded.amount) {
|
|
141
|
+
throw new Error("vault attestation amount mismatch");
|
|
142
|
+
}
|
|
143
|
+
if (guard.provider && String(guard.provider) !== String(attestation.provider)) throw new Error("vault attestation provider mismatch");
|
|
144
|
+
return true;
|
|
145
|
+
}
|