bInference Agent
你的 Agent
就在 BNB Smart Chain 上。
调研。交易。质押。跨链。
日夜在你的 Mac 上工作。没有你的点按,什么都不会动。
~ %
- macOSLinux 和 Windows 随后推出
- 开源MIT 许可证
- 不收费用自托管
- 和我对话试试演示
我读
链上数据、K 线图、X 和任何网页。
我查
代币、测试卖出、路由和手续费。
我问
一张卡片,然后等你。
在你所在的地方和我对话。
一张卡片,出现在每块屏幕上。
第一次点按就算数。
每块屏幕同时知道。
你的 Agent机器人
如果 CAKE 看起来安全,就用 0.1 BNB 买入。
已检查:安全,测试卖出也通过了。这是你的卡片:
确认买入
0.1 BNB → 至少 23.41 CAKE
确认取消
已确认0.1 BNB → 23.58 CAKE
消息
binference 控制台
没有等你处理的事。
确认买入
0.1 BNB → 至少 23.41 CAKE
确认取消
已确认0.1 BNB → 23.58 CAKE
等你点按已确认
zsh
~ % binference chat
已检查:安全,测试卖出也通过了。这是你的卡片:
确认买入
0.1 BNB → 至少 23.41 CAKE
⌃Y 确认 · ⌃N 取消
已确认 · 0.1 BNB → 23.58 CAKE
等你点按已确认
Claude Code
binference_intents
1 张卡片等你点按。
已确认 · 0.1 BNB → 23.58 CAKE
等你点按已确认
我的一天。
示例的一天 · 滚动页面转动时钟
读了 214 个新发射,存下了通过检查的 3 个。
你的晨间摘要:持仓、盈亏、行情变化。
CAKE 触发了你的提醒,一笔交易在等你点按。
你在 CAKE 上的止损整个上午都守住了。
读了 40 篇关于 BNB 质押的帖子,回答在你的对话里。
还在这里,还在盯着。
我能做什么。
每一笔交易,我都做成一张卡片。
在你看到之前,已经检查过。
然后,由你点按。
完成。链上可查。
0.1 BNB → 23.58 CAKE
私密发送,机器人无法抢先看到。
在 BscScan 上查看规则由你来定。
即使在你点按之后,它们依然有效。
模式
每笔交易都等你点按。
- 用 0.1 BNB 买入 CAKE问你
- 把 1 BNB 质押给验证者问你
- 把 1 BNB 发送到已保存的地址问你
- 把 50 USDT 跨链到 Base问你
- 买入没人检查过的代币问你
binference approval manual
限额
拖动一个限额。
立即停止所有 Agent。
/freeze
所有资金转到你自己的钱包,只留下网络费用所需的 BNB。
/rescue
先用模拟盘
1 BNB 和 500 USDT 的虚拟资金。真实报价,真实检查。
准备好了再上实盘
只能在你 Mac 的终端里开启。
binference live
现在,和我对话。
选一个请求。我做完事,然后等你点按。这是脚本演示。
/** The policy's answer when every rule passes. */
export interface PolicyPass {
/** The figures the caps passed with; absent for a rescue, which no cap counts. */
readonly figures?: PolicyFigures;
/**
* The intent moves a token on the deny list out of the wallet. It passes, but only the owner's
* tap confirms it: pass this mark to the auto test (decision 0101).
*/
readonly sellsDeniedToken: boolean;
}
/**
* The policy's answer when a rule fails. `error` is the reason the intent stores with
* `rejected_policy`: the first of `reasons`, which lists every rule broken in spec 6's order.
*/
export interface PolicyRefused extends Err<PolicyRejection> {
readonly reasons: readonly [PolicyRejection, ...PolicyRejection[]];
/** The figures behind a cap refusal; absent when an outflow had no price, and for a rescue. */
readonly figures?: PolicyFigures;
}
/** What the policy step decides about one intent. */
export type PolicyVerdict = Ok<PolicyPass> | PolicyRefused;
/**
* The policy step of the money path (ARCHITECTURE.md section 7). It decides and never writes: the
* caller reports the verdict to the state machine as `policy_passed` or `policy_refused`, and runs
* it again as the wallet queue takes the intent.
*/
export interface PolicyCheck {
/**
* Checks a resolved intent against the owner's limits. Every outflow is priced through the
* `PriceSource` and rounded up, so a cap never rounds in the agent's favor. With the trade's own
* `quote`, a token the source cannot price takes its price from the quote, valued at the other
* side's price (decision 0059); without one, that token has no price.
*/
check(
subject: PolicySubject,
facts: PolicyFacts,
options: PolicyCheckCall,
): Promise<PolicyVerdict>;
}
/** What one policy check runs with besides the intent and its facts. */
interface PolicyCheckCall {
readonly signal: AbortSignal;
/** The trade's own quote, when the venue gave one: what it spends and what it expects back. */
readonly quote?: QuotedTrade;
}
/** The ports the policy reads prices and the time from. */
export interface PolicyCheckOptions {
readonly prices: PriceSource;
readonly clock: Clock;
}
const rollingDayMs = 86_400_000;
// An outflow exactly 24 hours old still counts: the window never closes in the agent's favor.
function spentInWindow(outflows: readonly PastOutflow[], nowMs: number): bigint {
return outflows
.filter((outflow) => outflow.atMs >= nowMs - rollingDayMs)
.reduce((sum, outflow) => {
if (outflow.valueUsdMicros < 0n) {
throw new BinferenceError({
code: "policy.negative_outflow",
message: "An earlier outflow must not have a negative USD value.",
});
}
return sum + outflow.valueUsdMicros;
}, 0n);
}
// A zero or malformed price would let any amount through the caps, so it counts as no price.
async function priceOf(
asset: AssetRef,
prices: PriceSource,
signal: AbortSignal,
): Promise<UsdPrice | undefined> {
const price = await prices.usdPrice(asset, { signal });
return price.ok && price.value.numerator > 0n && price.value.denominator > 0n
? price.value
: undefined;
}
// An outflow of nothing is worth nothing at any price, so it needs none: a sale by share of a
// token the wallet does not hold ends as nothing to sell, not as a token without a price.
async function valueOf(
outflows: readonly Amount[],
prices: PriceSource,
/** The policy's answer when every rule passes. */
export interface PolicyPass {
/** The figures the caps passed with; absent for a rescue, which no cap counts. */
readonly figures?: PolicyFigures;
/**
* The intent moves a token on the deny list out of the wallet. It passes, but only the owner's
* tap confirms it: pass this mark to the auto test (decision 0101).
*/
readonly sellsDeniedToken: boolean;
}
/**
* The policy's answer when a rule fails. `error` is the reason the intent stores with
* `rejected_policy`: the first of `reasons`, which lists every rule broken in spec 6's order.
*/
export interface PolicyRefused extends Err<PolicyRejection> {
readonly reasons: readonly [PolicyRejection, ...PolicyRejection[]];
/** The figures behind a cap refusal; absent when an outflow had no price, and for a rescue. */
readonly figures?: PolicyFigures;
}
/** What the policy step decides about one intent. */
export type PolicyVerdict = Ok<PolicyPass> | PolicyRefused;
/**
* The policy step of the money path (ARCHITECTURE.md section 7). It decides and never writes: the
* caller reports the verdict to the state machine as `policy_passed` or `policy_refused`, and runs
* it again as the wallet queue takes the intent.
*/
export interface PolicyCheck {
/**
* Checks a resolved intent against the owner's limits. Every outflow is priced through the
* `PriceSource` and rounded up, so a cap never rounds in the agent's favor. With the trade's own
* `quote`, a token the source cannot price takes its price from the quote, valued at the other
* side's price (decision 0059); without one, that token has no price.
*/
check(
subject: PolicySubject,
facts: PolicyFacts,
options: PolicyCheckCall,
): Promise<PolicyVerdict>;
}
/** What one policy check runs with besides the intent and its facts. */
interface PolicyCheckCall {
readonly signal: AbortSignal;
/** The trade's own quote, when the venue gave one: what it spends and what it expects back. */
readonly quote?: QuotedTrade;
}
/** The ports the policy reads prices and the time from. */
export interface PolicyCheckOptions {
readonly prices: PriceSource;
readonly clock: Clock;
}
const rollingDayMs = 86_400_000;
// An outflow exactly 24 hours old still counts: the window never closes in the agent's favor.
function spentInWindow(outflows: readonly PastOutflow[], nowMs: number): bigint {
return outflows
.filter((outflow) => outflow.atMs >= nowMs - rollingDayMs)
.reduce((sum, outflow) => {
if (outflow.valueUsdMicros < 0n) {
throw new BinferenceError({
code: "policy.negative_outflow",
message: "An earlier outflow must not have a negative USD value.",
});
}
return sum + outflow.valueUsdMicros;
}, 0n);
}
// A zero or malformed price would let any amount through the caps, so it counts as no price.
async function priceOf(
asset: AssetRef,
prices: PriceSource,
signal: AbortSignal,
): Promise<UsdPrice | undefined> {
const price = await prices.usdPrice(asset, { signal });
return price.ok && price.value.numerator > 0n && price.value.denominator > 0n
? price.value
: undefined;
}
// An outflow of nothing is worth nothing at any price, so it needs none: a sale by share of a
// token the wallet does not hold ends as nothing to sell, not as a token without a price.
async function valueOf(
outflows: readonly Amount[],
prices: PriceSource,
import type { NonceGrant } from "./nonce-grant.js";
import type { TransactionState } from "./transaction-record.js";
/** The states in which a transaction may still use its nonce on chain before a block holds it. */
export const holdingStates: readonly TransactionState[] = ["signed", "sent"];
/** The states of a transaction a block holds: its nonce, and every one below, are used on chain. */
export const inBlockStates: readonly TransactionState[] = ["included", "final", "reverted"];
/** What the store knows of one account's nonces, read in the transaction that decides on one. */
export interface AccountNonces {
/**
* One past the highest nonce of the account's transactions a block holds (`included`, `final`
* or `reverted`), or 0 when none does. Every nonce below it is used on chain.
*/
readonly blockFloor: number;
/** The nonces the account's `signed` and `sent` transactions hold, in any order. */
readonly held: readonly number[];
/** One past the highest nonce the queue gave the account, or 0 before the first. */
readonly given: number;
}
/**
* The lowest free nonce rule: the wallet queue gives the lowest nonce at or above both the chain's
* count and the block floor that no `signed` or `sent` transaction of the account holds. A nonce
* given to a step that was never signed (a stop, a refusal, a crash) or held by a transaction that
* was dropped is free again, so the next step takes it and leaves no gap behind.
*/
export function lowestFreeNonce(chainNonce: number, nonces: AccountNonces): NonceGrant {
const start = Math.max(chainNonce, nonces.blockFloor);
const above = [...new Set(nonces.held)]
.filter((nonce) => nonce >= start)
.toSorted((left, right) => left - right);
const gap = above.findIndex((nonce, index) => nonce !== start + index);
const nonce = start + (gap === -1 ? above.length : gap);
return { nonce, refillsGap: nonce < nonces.given };
}
/**
* Whether a transaction may be stored at `nonce`: no block holds it or a later nonce of the
* account, and no `signed` or `sent` transaction of the account holds it.
*/
export function isNonceFree(
nonce: number,
nonces: Pick<AccountNonces, "blockFloor" | "held">,
): boolean {
return nonce >= nonces.blockFloor && !nonces.held.includes(nonce);
}
import type { SendLevelState } from "../agents/send-level-record.js";
import type { SendLevel } from "./policy-rules.js";
/**
* How long a looser setting waits before it takes effect: 24 hours (ARCHITECTURE.md section 11),
* so a hijacked surface cannot quietly loosen what guards the funds.
*/
export const looseningWaitMs = 86_400_000;
/** What a request for a send level does: the state to write, and whether it loosens. */
export interface SendLevelMove {
readonly next: SendLevelState;
/** The level asked is looser than the one in effect: the caller needs the `loosen` scope. */
readonly loosens: boolean;
}
/**
* The send level in effect at `nowMs`: a pending level whose time has come replaces the level,
* and one still waiting stays pending. Every reader of a stored state goes through this.
*/
export function sendLevelAt(state: SendLevelState, nowMs: number): SendLevelState {
const { pending } = state;
return pending !== undefined && pending.atMs <= nowMs ? { level: pending.level } : state;
}
/**
* Moves the send level toward the level asked, judged against the level in effect at `nowMs`.
* A stricter level, or the level in effect, applies at once and drops any looser level that
* waits, failing closed. A looser level waits 24 hours; asking again for the one that already
* waits keeps its time, and asking for another starts the wait again.
*/
export function moveSendLevel(
state: SendLevelState,
asked: SendLevel,
nowMs: number,
): SendLevelMove {
const settled = sendLevelAt(state, nowMs);
if (asked >= settled.level) {
return { next: { level: asked }, loosens: false };
}
const pending =
settled.pending?.level === asked
? settled.pending
: { level: asked, atMs: nowMs + looseningWaitMs };
return { next: { level: settled.level, pending }, loosens: true };
}
import type { NonceGrant } from "./nonce-grant.js";
import type { TransactionState } from "./transaction-record.js";
/** The states in which a transaction may still use its nonce on chain before a block holds it. */
export const holdingStates: readonly TransactionState[] = ["signed", "sent"];
/** The states of a transaction a block holds: its nonce, and every one below, are used on chain. */
export const inBlockStates: readonly TransactionState[] = ["included", "final", "reverted"];
/** What the store knows of one account's nonces, read in the transaction that decides on one. */
export interface AccountNonces {
/**
* One past the highest nonce of the account's transactions a block holds (`included`, `final`
* or `reverted`), or 0 when none does. Every nonce below it is used on chain.
*/
readonly blockFloor: number;
/** The nonces the account's `signed` and `sent` transactions hold, in any order. */
readonly held: readonly number[];
/** One past the highest nonce the queue gave the account, or 0 before the first. */
readonly given: number;
}
/**
* The lowest free nonce rule: the wallet queue gives the lowest nonce at or above both the chain's
* count and the block floor that no `signed` or `sent` transaction of the account holds. A nonce
* given to a step that was never signed (a stop, a refusal, a crash) or held by a transaction that
* was dropped is free again, so the next step takes it and leaves no gap behind.
*/
export function lowestFreeNonce(chainNonce: number, nonces: AccountNonces): NonceGrant {
const start = Math.max(chainNonce, nonces.blockFloor);
const above = [...new Set(nonces.held)]
.filter((nonce) => nonce >= start)
.toSorted((left, right) => left - right);
const gap = above.findIndex((nonce, index) => nonce !== start + index);
const nonce = start + (gap === -1 ? above.length : gap);
return { nonce, refillsGap: nonce < nonces.given };
}
/**
* Whether a transaction may be stored at `nonce`: no block holds it or a later nonce of the
* account, and no `signed` or `sent` transaction of the account holds it.
*/
export function isNonceFree(
nonce: number,
nonces: Pick<AccountNonces, "blockFloor" | "held">,
): boolean {
return nonce >= nonces.blockFloor && !nonces.held.includes(nonce);
}
import type { SendLevelState } from "../agents/send-level-record.js";
import type { SendLevel } from "./policy-rules.js";
/**
* How long a looser setting waits before it takes effect: 24 hours (ARCHITECTURE.md section 11),
* so a hijacked surface cannot quietly loosen what guards the funds.
*/
export const looseningWaitMs = 86_400_000;
/** What a request for a send level does: the state to write, and whether it loosens. */
export interface SendLevelMove {
readonly next: SendLevelState;
/** The level asked is looser than the one in effect: the caller needs the `loosen` scope. */
readonly loosens: boolean;
}
/**
* The send level in effect at `nowMs`: a pending level whose time has come replaces the level,
* and one still waiting stays pending. Every reader of a stored state goes through this.
*/
export function sendLevelAt(state: SendLevelState, nowMs: number): SendLevelState {
const { pending } = state;
return pending !== undefined && pending.atMs <= nowMs ? { level: pending.level } : state;
}
/**
* Moves the send level toward the level asked, judged against the level in effect at `nowMs`.
* A stricter level, or the level in effect, applies at once and drops any looser level that
* waits, failing closed. A looser level waits 24 hours; asking again for the one that already
* waits keeps its time, and asking for another starts the wait again.
*/
export function moveSendLevel(
state: SendLevelState,
asked: SendLevel,
nowMs: number,
): SendLevelMove {
const settled = sendLevelAt(state, nowMs);
if (asked >= settled.level) {
return { next: { level: asked }, loosens: false };
}
const pending =
settled.pending?.level === asked
? settled.pending
: { level: asked, atMs: nowMs + looseningWaitMs };
return { next: { level: settled.level, pending }, loosens: true };
}
import type { AccountRef } from "@binference/chain";
import { looseningWaitMs } from "./send-level-change.js";
/** A new rescue address the owner asked for, and when it takes the place of the one now. */
export interface PendingRescue {
readonly address: AccountRef;
/** Epoch milliseconds from which a rescue pays it: 24 hours after it was asked. */
readonly atMs: number;
}
/**
* The install's rescue address as it was written, and a new one that waits for its time. A
* pending address whose time has come is the rescue address, though the row still names it as
* pending; read the address in effect through `rescueAt`.
*/
export interface RescueState {
readonly rescueAddress?: AccountRef;
readonly pendingRescue?: PendingRescue;
}
/**
* The rescue address in effect at `nowMs`, and nothing else of the state it is given: a pending
* address whose time has come replaces it, and one still waiting stays pending. Every reader of a
* stored state goes through this.
*/
export function rescueAt(state: RescueState, nowMs: number): RescueState {
const { rescueAddress, pendingRescue } = state;
if (pendingRescue !== undefined && pendingRescue.atMs <= nowMs) {
return { rescueAddress: pendingRescue.address };
}
return {
...(rescueAddress === undefined ? {} : { rescueAddress }),
...(pendingRescue === undefined ? {} : { pendingRescue }),
};
}
/**
* Moves the rescue address toward `address`, judged against the address in effect at `nowMs`
* (decision 0044). Any new address waits 24 hours, a first one too, so a hijacked surface cannot
* redirect a rescue before the owner sees the announcement. Asking again for the address that
* already waits keeps its time; asking for the address in effect drops the one that waits.
*/
export function changeRescue(state: RescueState, address: AccountRef, nowMs: number): RescueState {
const { rescueAddress, pendingRescue } = rescueAt(state, nowMs);
const kept = rescueAddress === undefined ? {} : { rescueAddress };
if (address === rescueAddress) {
return kept;
}
return {
...kept,
pendingRescue:
pendingRescue?.address === address
? pendingRescue
: { address, atMs: nowMs + looseningWaitMs },
};
}
/** Drops a new rescue address that still waits at `nowMs`; the address in effect stays. */
export function cancelRescue(state: RescueState, nowMs: number): RescueState {
const { rescueAddress } = rescueAt(state, nowMs);
return rescueAddress === undefined ? {} : { rescueAddress };
}
signal: AbortSignal,
): Promise<bigint | undefined> {
const moving = outflows.filter((outflow) => outflow.base !== 0n);
const assets = [...new Set(moving.map((outflow) => outflow.asset))];
const found = await Promise.all(assets.map(async (asset) => priceOf(asset, prices, signal)));
const byAsset = new Map(assets.map((asset, index) => [asset, found[index]]));
let totalUsdMicros = 0n;
for (const outflow of moving) {
const price = byAsset.get(outflow.asset);
if (price === undefined) {
return undefined;
}
totalUsdMicros += mulDiv(outflow.base, price, "up");
}
return totalUsdMicros;
}
function verdictOf(input: PolicyInput): PolicyVerdict {
const { figures } = input;
const withFigures = figures === undefined ? {} : { figures };
const [first, ...rest] = policyRefusals(input);
return first === undefined
? ok({ ...withFigures, sellsDeniedToken: sellsDeniedToken(input) })
: { ok: false, error: first, reasons: [first, ...rest], ...withFigures };
}
interface CheckCall extends PolicyCheckCall {
readonly subject: PolicySubject;
readonly facts: PolicyFacts;
}
async function checkIntent(
{ subject, facts, signal, quote }: CheckCall,
options: PolicyCheckOptions,
): Promise<PolicyVerdict> {
const nowMs = options.clock.now();
if (subject.kind === "rescue") {
return verdictOf({ subject, facts, nowMs });
}
const prices = quote === undefined ? options.prices : withQuotePrice(options.prices, quote);
import type { AccountRef } from "@binference/chain";
import { looseningWaitMs } from "./send-level-change.js";
/** A new rescue address the owner asked for, and when it takes the place of the one now. */
export interface PendingRescue {
readonly address: AccountRef;
/** Epoch milliseconds from which a rescue pays it: 24 hours after it was asked. */
readonly atMs: number;
}
/**
* The install's rescue address as it was written, and a new one that waits for its time. A
* pending address whose time has come is the rescue address, though the row still names it as
* pending; read the address in effect through `rescueAt`.
*/
export interface RescueState {
readonly rescueAddress?: AccountRef;
readonly pendingRescue?: PendingRescue;
}
/**
* The rescue address in effect at `nowMs`, and nothing else of the state it is given: a pending
* address whose time has come replaces it, and one still waiting stays pending. Every reader of a
* stored state goes through this.
*/
export function rescueAt(state: RescueState, nowMs: number): RescueState {
const { rescueAddress, pendingRescue } = state;
if (pendingRescue !== undefined && pendingRescue.atMs <= nowMs) {
return { rescueAddress: pendingRescue.address };
}
return {
...(rescueAddress === undefined ? {} : { rescueAddress }),
...(pendingRescue === undefined ? {} : { pendingRescue }),
};
}
/**
* Moves the rescue address toward `address`, judged against the address in effect at `nowMs`
* (decision 0044). Any new address waits 24 hours, a first one too, so a hijacked surface cannot
* redirect a rescue before the owner sees the announcement. Asking again for the address that
* already waits keeps its time; asking for the address in effect drops the one that waits.
*/
export function changeRescue(state: RescueState, address: AccountRef, nowMs: number): RescueState {
const { rescueAddress, pendingRescue } = rescueAt(state, nowMs);
const kept = rescueAddress === undefined ? {} : { rescueAddress };
if (address === rescueAddress) {
return kept;
}
return {
...kept,
pendingRescue:
pendingRescue?.address === address
? pendingRescue
: { address, atMs: nowMs + looseningWaitMs },
};
}
/** Drops a new rescue address that still waits at `nowMs`; the address in effect stays. */
export function cancelRescue(state: RescueState, nowMs: number): RescueState {
const { rescueAddress } = rescueAt(state, nowMs);
return rescueAddress === undefined ? {} : { rescueAddress };
}
signal: AbortSignal,
): Promise<bigint | undefined> {
const moving = outflows.filter((outflow) => outflow.base !== 0n);
const assets = [...new Set(moving.map((outflow) => outflow.asset))];
const found = await Promise.all(assets.map(async (asset) => priceOf(asset, prices, signal)));
const byAsset = new Map(assets.map((asset, index) => [asset, found[index]]));
let totalUsdMicros = 0n;
for (const outflow of moving) {
const price = byAsset.get(outflow.asset);
if (price === undefined) {
return undefined;
}
totalUsdMicros += mulDiv(outflow.base, price, "up");
}
return totalUsdMicros;
}
function verdictOf(input: PolicyInput): PolicyVerdict {
const { figures } = input;
const withFigures = figures === undefined ? {} : { figures };
const [first, ...rest] = policyRefusals(input);
return first === undefined
? ok({ ...withFigures, sellsDeniedToken: sellsDeniedToken(input) })
: { ok: false, error: first, reasons: [first, ...rest], ...withFigures };
}
interface CheckCall extends PolicyCheckCall {
readonly subject: PolicySubject;
readonly facts: PolicyFacts;
}
async function checkIntent(
{ subject, facts, signal, quote }: CheckCall,
options: PolicyCheckOptions,
): Promise<PolicyVerdict> {
const nowMs = options.clock.now();
if (subject.kind === "rescue") {
return verdictOf({ subject, facts, nowMs });
}
const prices = quote === undefined ? options.prices : withQuotePrice(options.prices, quote);
/** The policy's answer when every rule passes. */
export interface PolicyPass {
/** The figures the caps passed with; absent for a rescue, which no cap counts. */
readonly figures?: PolicyFigures;
/**
* The intent moves a token on the deny list out of the wallet. It passes, but only the owner's
* tap confirms it: pass this mark to the auto test (decision 0101).
*/
readonly sellsDeniedToken: boolean;
}
/**
* The policy's answer when a rule fails. `error` is the reason the intent stores with
* `rejected_policy`: the first of `reasons`, which lists every rule broken in spec 6's order.
*/
export interface PolicyRefused extends Err<PolicyRejection> {
readonly reasons: readonly [PolicyRejection, ...PolicyRejection[]];
/** The figures behind a cap refusal; absent when an outflow had no price, and for a rescue. */
readonly figures?: PolicyFigures;
}
/** What the policy step decides about one intent. */
export type PolicyVerdict = Ok<PolicyPass> | PolicyRefused;
/**
* The policy step of the money path (ARCHITECTURE.md section 7). It decides and never writes: the
* caller reports the verdict to the state machine as `policy_passed` or `policy_refused`, and runs
* it again as the wallet queue takes the intent.
*/
export interface PolicyCheck {
/**
* Checks a resolved intent against the owner's limits. Every outflow is priced through the
* `PriceSource` and rounded up, so a cap never rounds in the agent's favor. With the trade's own
* `quote`, a token the source cannot price takes its price from the quote, valued at the other
* side's price (decision 0059); without one, that token has no price.
*/
check(
subject: PolicySubject,
facts: PolicyFacts,
options: PolicyCheckCall,
): Promise<PolicyVerdict>;
}
/** What one policy check runs with besides the intent and its facts. */
interface PolicyCheckCall {
readonly signal: AbortSignal;
/** The trade's own quote, when the venue gave one: what it spends and what it expects back. */
readonly quote?: QuotedTrade;
}
/** The ports the policy reads prices and the time from. */
export interface PolicyCheckOptions {
readonly prices: PriceSource;
readonly clock: Clock;
}
const rollingDayMs = 86_400_000;
// An outflow exactly 24 hours old still counts: the window never closes in the agent's favor.
function spentInWindow(outflows: readonly PastOutflow[], nowMs: number): bigint {
return outflows
.filter((outflow) => outflow.atMs >= nowMs - rollingDayMs)
.reduce((sum, outflow) => {
if (outflow.valueUsdMicros < 0n) {
throw new BinferenceError({
code: "policy.negative_outflow",
message: "An earlier outflow must not have a negative USD value.",
});
}
return sum + outflow.valueUsdMicros;
}, 0n);
}
// A zero or malformed price would let any amount through the caps, so it counts as no price.
async function priceOf(
asset: AssetRef,
prices: PriceSource,
signal: AbortSignal,
): Promise<UsdPrice | undefined> {
const price = await prices.usdPrice(asset, { signal });
return price.ok && price.value.numerator > 0n && price.value.denominator > 0n
? price.value
: undefined;
}
// An outflow of nothing is worth nothing at any price, so it needs none: a sale by share of a
// token the wallet does not hold ends as nothing to sell, not as a token without a price.
async function valueOf(
outflows: readonly Amount[],
prices: PriceSource,
/** The policy's answer when every rule passes. */
export interface PolicyPass {
/** The figures the caps passed with; absent for a rescue, which no cap counts. */
readonly figures?: PolicyFigures;
/**
* The intent moves a token on the deny list out of the wallet. It passes, but only the owner's
* tap confirms it: pass this mark to the auto test (decision 0101).
*/
readonly sellsDeniedToken: boolean;
}
/**
* The policy's answer when a rule fails. `error` is the reason the intent stores with
* `rejected_policy`: the first of `reasons`, which lists every rule broken in spec 6's order.
*/
export interface PolicyRefused extends Err<PolicyRejection> {
readonly reasons: readonly [PolicyRejection, ...PolicyRejection[]];
/** The figures behind a cap refusal; absent when an outflow had no price, and for a rescue. */
readonly figures?: PolicyFigures;
}
/** What the policy step decides about one intent. */
export type PolicyVerdict = Ok<PolicyPass> | PolicyRefused;
/**
* The policy step of the money path (ARCHITECTURE.md section 7). It decides and never writes: the
* caller reports the verdict to the state machine as `policy_passed` or `policy_refused`, and runs
* it again as the wallet queue takes the intent.
*/
export interface PolicyCheck {
/**
* Checks a resolved intent against the owner's limits. Every outflow is priced through the
* `PriceSource` and rounded up, so a cap never rounds in the agent's favor. With the trade's own
* `quote`, a token the source cannot price takes its price from the quote, valued at the other
* side's price (decision 0059); without one, that token has no price.
*/
check(
subject: PolicySubject,
facts: PolicyFacts,
options: PolicyCheckCall,
): Promise<PolicyVerdict>;
}
/** What one policy check runs with besides the intent and its facts. */
interface PolicyCheckCall {
readonly signal: AbortSignal;
/** The trade's own quote, when the venue gave one: what it spends and what it expects back. */
readonly quote?: QuotedTrade;
}
/** The ports the policy reads prices and the time from. */
export interface PolicyCheckOptions {
readonly prices: PriceSource;
readonly clock: Clock;
}
const rollingDayMs = 86_400_000;
// An outflow exactly 24 hours old still counts: the window never closes in the agent's favor.
function spentInWindow(outflows: readonly PastOutflow[], nowMs: number): bigint {
return outflows
.filter((outflow) => outflow.atMs >= nowMs - rollingDayMs)
.reduce((sum, outflow) => {
if (outflow.valueUsdMicros < 0n) {
throw new BinferenceError({
code: "policy.negative_outflow",
message: "An earlier outflow must not have a negative USD value.",
});
}
return sum + outflow.valueUsdMicros;
}, 0n);
}
// A zero or malformed price would let any amount through the caps, so it counts as no price.
async function priceOf(
asset: AssetRef,
prices: PriceSource,
signal: AbortSignal,
): Promise<UsdPrice | undefined> {
const price = await prices.usdPrice(asset, { signal });
return price.ok && price.value.numerator > 0n && price.value.denominator > 0n
? price.value
: undefined;
}
// An outflow of nothing is worth nothing at any price, so it needs none: a sale by share of a
// token the wallet does not hold ends as nothing to sell, not as a token without a price.
async function valueOf(
outflows: readonly Amount[],
prices: PriceSource,
import type { NonceGrant } from "./nonce-grant.js";
import type { TransactionState } from "./transaction-record.js";
/** The states in which a transaction may still use its nonce on chain before a block holds it. */
export const holdingStates: readonly TransactionState[] = ["signed", "sent"];
/** The states of a transaction a block holds: its nonce, and every one below, are used on chain. */
export const inBlockStates: readonly TransactionState[] = ["included", "final", "reverted"];
/** What the store knows of one account's nonces, read in the transaction that decides on one. */
export interface AccountNonces {
/**
* One past the highest nonce of the account's transactions a block holds (`included`, `final`
* or `reverted`), or 0 when none does. Every nonce below it is used on chain.
*/
readonly blockFloor: number;
/** The nonces the account's `signed` and `sent` transactions hold, in any order. */
readonly held: readonly number[];
/** One past the highest nonce the queue gave the account, or 0 before the first. */
readonly given: number;
}
/**
* The lowest free nonce rule: the wallet queue gives the lowest nonce at or above both the chain's
* count and the block floor that no `signed` or `sent` transaction of the account holds. A nonce
* given to a step that was never signed (a stop, a refusal, a crash) or held by a transaction that
* was dropped is free again, so the next step takes it and leaves no gap behind.
*/
export function lowestFreeNonce(chainNonce: number, nonces: AccountNonces): NonceGrant {
const start = Math.max(chainNonce, nonces.blockFloor);
const above = [...new Set(nonces.held)]
.filter((nonce) => nonce >= start)
.toSorted((left, right) => left - right);
const gap = above.findIndex((nonce, index) => nonce !== start + index);
const nonce = start + (gap === -1 ? above.length : gap);
return { nonce, refillsGap: nonce < nonces.given };
}
/**
* Whether a transaction may be stored at `nonce`: no block holds it or a later nonce of the
* account, and no `signed` or `sent` transaction of the account holds it.
*/
export function isNonceFree(
nonce: number,
nonces: Pick<AccountNonces, "blockFloor" | "held">,
): boolean {
return nonce >= nonces.blockFloor && !nonces.held.includes(nonce);
}
import type { SendLevelState } from "../agents/send-level-record.js";
import type { SendLevel } from "./policy-rules.js";
/**
* How long a looser setting waits before it takes effect: 24 hours (ARCHITECTURE.md section 11),
* so a hijacked surface cannot quietly loosen what guards the funds.
*/
export const looseningWaitMs = 86_400_000;
/** What a request for a send level does: the state to write, and whether it loosens. */
export interface SendLevelMove {
readonly next: SendLevelState;
/** The level asked is looser than the one in effect: the caller needs the `loosen` scope. */
readonly loosens: boolean;
}
/**
* The send level in effect at `nowMs`: a pending level whose time has come replaces the level,
* and one still waiting stays pending. Every reader of a stored state goes through this.
*/
export function sendLevelAt(state: SendLevelState, nowMs: number): SendLevelState {
const { pending } = state;
return pending !== undefined && pending.atMs <= nowMs ? { level: pending.level } : state;
}
/**
* Moves the send level toward the level asked, judged against the level in effect at `nowMs`.
* A stricter level, or the level in effect, applies at once and drops any looser level that
* waits, failing closed. A looser level waits 24 hours; asking again for the one that already
* waits keeps its time, and asking for another starts the wait again.
*/
export function moveSendLevel(
state: SendLevelState,
asked: SendLevel,
nowMs: number,
): SendLevelMove {
const settled = sendLevelAt(state, nowMs);
if (asked >= settled.level) {
return { next: { level: asked }, loosens: false };
}
const pending =
settled.pending?.level === asked
? settled.pending
: { level: asked, atMs: nowMs + looseningWaitMs };
return { next: { level: settled.level, pending }, loosens: true };
}
import type { NonceGrant } from "./nonce-grant.js";
import type { TransactionState } from "./transaction-record.js";
/** The states in which a transaction may still use its nonce on chain before a block holds it. */
export const holdingStates: readonly TransactionState[] = ["signed", "sent"];
/** The states of a transaction a block holds: its nonce, and every one below, are used on chain. */
export const inBlockStates: readonly TransactionState[] = ["included", "final", "reverted"];
/** What the store knows of one account's nonces, read in the transaction that decides on one. */
export interface AccountNonces {
/**
* One past the highest nonce of the account's transactions a block holds (`included`, `final`
* or `reverted`), or 0 when none does. Every nonce below it is used on chain.
*/
readonly blockFloor: number;
/** The nonces the account's `signed` and `sent` transactions hold, in any order. */
readonly held: readonly number[];
/** One past the highest nonce the queue gave the account, or 0 before the first. */
readonly given: number;
}
/**
* The lowest free nonce rule: the wallet queue gives the lowest nonce at or above both the chain's
* count and the block floor that no `signed` or `sent` transaction of the account holds. A nonce
* given to a step that was never signed (a stop, a refusal, a crash) or held by a transaction that
* was dropped is free again, so the next step takes it and leaves no gap behind.
*/
export function lowestFreeNonce(chainNonce: number, nonces: AccountNonces): NonceGrant {
const start = Math.max(chainNonce, nonces.blockFloor);
const above = [...new Set(nonces.held)]
.filter((nonce) => nonce >= start)
.toSorted((left, right) => left - right);
const gap = above.findIndex((nonce, index) => nonce !== start + index);
const nonce = start + (gap === -1 ? above.length : gap);
return { nonce, refillsGap: nonce < nonces.given };
}
/**
* Whether a transaction may be stored at `nonce`: no block holds it or a later nonce of the
* account, and no `signed` or `sent` transaction of the account holds it.
*/
export function isNonceFree(
nonce: number,
nonces: Pick<AccountNonces, "blockFloor" | "held">,
): boolean {
return nonce >= nonces.blockFloor && !nonces.held.includes(nonce);
}
import type { SendLevelState } from "../agents/send-level-record.js";
import type { SendLevel } from "./policy-rules.js";
/**
* How long a looser setting waits before it takes effect: 24 hours (ARCHITECTURE.md section 11),
* so a hijacked surface cannot quietly loosen what guards the funds.
*/
export const looseningWaitMs = 86_400_000;
/** What a request for a send level does: the state to write, and whether it loosens. */
export interface SendLevelMove {
readonly next: SendLevelState;
/** The level asked is looser than the one in effect: the caller needs the `loosen` scope. */
readonly loosens: boolean;
}
/**
* The send level in effect at `nowMs`: a pending level whose time has come replaces the level,
* and one still waiting stays pending. Every reader of a stored state goes through this.
*/
export function sendLevelAt(state: SendLevelState, nowMs: number): SendLevelState {
const { pending } = state;
return pending !== undefined && pending.atMs <= nowMs ? { level: pending.level } : state;
}
/**
* Moves the send level toward the level asked, judged against the level in effect at `nowMs`.
* A stricter level, or the level in effect, applies at once and drops any looser level that
* waits, failing closed. A looser level waits 24 hours; asking again for the one that already
* waits keeps its time, and asking for another starts the wait again.
*/
export function moveSendLevel(
state: SendLevelState,
asked: SendLevel,
nowMs: number,
): SendLevelMove {
const settled = sendLevelAt(state, nowMs);
if (asked >= settled.level) {
return { next: { level: asked }, loosens: false };
}
const pending =
settled.pending?.level === asked
? settled.pending
: { level: asked, atMs: nowMs + looseningWaitMs };
return { next: { level: settled.level, pending }, loosens: true };
}
import type { AccountRef } from "@binference/chain";
import { looseningWaitMs } from "./send-level-change.js";
/** A new rescue address the owner asked for, and when it takes the place of the one now. */
export interface PendingRescue {
readonly address: AccountRef;
/** Epoch milliseconds from which a rescue pays it: 24 hours after it was asked. */
readonly atMs: number;
}
/**
* The install's rescue address as it was written, and a new one that waits for its time. A
* pending address whose time has come is the rescue address, though the row still names it as
* pending; read the address in effect through `rescueAt`.
*/
export interface RescueState {
readonly rescueAddress?: AccountRef;
readonly pendingRescue?: PendingRescue;
}
/**
* The rescue address in effect at `nowMs`, and nothing else of the state it is given: a pending
* address whose time has come replaces it, and one still waiting stays pending. Every reader of a
* stored state goes through this.
*/
export function rescueAt(state: RescueState, nowMs: number): RescueState {
const { rescueAddress, pendingRescue } = state;
if (pendingRescue !== undefined && pendingRescue.atMs <= nowMs) {
return { rescueAddress: pendingRescue.address };
}
return {
...(rescueAddress === undefined ? {} : { rescueAddress }),
...(pendingRescue === undefined ? {} : { pendingRescue }),
};
}
/**
* Moves the rescue address toward `address`, judged against the address in effect at `nowMs`
* (decision 0044). Any new address waits 24 hours, a first one too, so a hijacked surface cannot
* redirect a rescue before the owner sees the announcement. Asking again for the address that
* already waits keeps its time; asking for the address in effect drops the one that waits.
*/
export function changeRescue(state: RescueState, address: AccountRef, nowMs: number): RescueState {
const { rescueAddress, pendingRescue } = rescueAt(state, nowMs);
const kept = rescueAddress === undefined ? {} : { rescueAddress };
if (address === rescueAddress) {
return kept;
}
return {
...kept,
pendingRescue:
pendingRescue?.address === address
? pendingRescue
: { address, atMs: nowMs + looseningWaitMs },
};
}
/** Drops a new rescue address that still waits at `nowMs`; the address in effect stays. */
export function cancelRescue(state: RescueState, nowMs: number): RescueState {
const { rescueAddress } = rescueAt(state, nowMs);
return rescueAddress === undefined ? {} : { rescueAddress };
}
signal: AbortSignal,
): Promise<bigint | undefined> {
const moving = outflows.filter((outflow) => outflow.base !== 0n);
const assets = [...new Set(moving.map((outflow) => outflow.asset))];
const found = await Promise.all(assets.map(async (asset) => priceOf(asset, prices, signal)));
const byAsset = new Map(assets.map((asset, index) => [asset, found[index]]));
let totalUsdMicros = 0n;
for (const outflow of moving) {
const price = byAsset.get(outflow.asset);
if (price === undefined) {
return undefined;
}
totalUsdMicros += mulDiv(outflow.base, price, "up");
}
return totalUsdMicros;
}
function verdictOf(input: PolicyInput): PolicyVerdict {
const { figures } = input;
const withFigures = figures === undefined ? {} : { figures };
const [first, ...rest] = policyRefusals(input);
return first === undefined
? ok({ ...withFigures, sellsDeniedToken: sellsDeniedToken(input) })
: { ok: false, error: first, reasons: [first, ...rest], ...withFigures };
}
interface CheckCall extends PolicyCheckCall {
readonly subject: PolicySubject;
readonly facts: PolicyFacts;
}
async function checkIntent(
{ subject, facts, signal, quote }: CheckCall,
options: PolicyCheckOptions,
): Promise<PolicyVerdict> {
const nowMs = options.clock.now();
if (subject.kind === "rescue") {
return verdictOf({ subject, facts, nowMs });
}
const prices = quote === undefined ? options.prices : withQuotePrice(options.prices, quote);
import type { AccountRef } from "@binference/chain";
import { looseningWaitMs } from "./send-level-change.js";
/** A new rescue address the owner asked for, and when it takes the place of the one now. */
export interface PendingRescue {
readonly address: AccountRef;
/** Epoch milliseconds from which a rescue pays it: 24 hours after it was asked. */
readonly atMs: number;
}
/**
* The install's rescue address as it was written, and a new one that waits for its time. A
* pending address whose time has come is the rescue address, though the row still names it as
* pending; read the address in effect through `rescueAt`.
*/
export interface RescueState {
readonly rescueAddress?: AccountRef;
readonly pendingRescue?: PendingRescue;
}
/**
* The rescue address in effect at `nowMs`, and nothing else of the state it is given: a pending
* address whose time has come replaces it, and one still waiting stays pending. Every reader of a
* stored state goes through this.
*/
export function rescueAt(state: RescueState, nowMs: number): RescueState {
const { rescueAddress, pendingRescue } = state;
if (pendingRescue !== undefined && pendingRescue.atMs <= nowMs) {
return { rescueAddress: pendingRescue.address };
}
return {
...(rescueAddress === undefined ? {} : { rescueAddress }),
...(pendingRescue === undefined ? {} : { pendingRescue }),
};
}
/**
* Moves the rescue address toward `address`, judged against the address in effect at `nowMs`
* (decision 0044). Any new address waits 24 hours, a first one too, so a hijacked surface cannot
* redirect a rescue before the owner sees the announcement. Asking again for the address that
* already waits keeps its time; asking for the address in effect drops the one that waits.
*/
export function changeRescue(state: RescueState, address: AccountRef, nowMs: number): RescueState {
const { rescueAddress, pendingRescue } = rescueAt(state, nowMs);
const kept = rescueAddress === undefined ? {} : { rescueAddress };
if (address === rescueAddress) {
return kept;
}
return {
...kept,
pendingRescue:
pendingRescue?.address === address
? pendingRescue
: { address, atMs: nowMs + looseningWaitMs },
};
}
/** Drops a new rescue address that still waits at `nowMs`; the address in effect stays. */
export function cancelRescue(state: RescueState, nowMs: number): RescueState {
const { rescueAddress } = rescueAt(state, nowMs);
return rescueAddress === undefined ? {} : { rescueAddress };
}
signal: AbortSignal,
): Promise<bigint | undefined> {
const moving = outflows.filter((outflow) => outflow.base !== 0n);
const assets = [...new Set(moving.map((outflow) => outflow.asset))];
const found = await Promise.all(assets.map(async (asset) => priceOf(asset, prices, signal)));
const byAsset = new Map(assets.map((asset, index) => [asset, found[index]]));
let totalUsdMicros = 0n;
for (const outflow of moving) {
const price = byAsset.get(outflow.asset);
if (price === undefined) {
return undefined;
}
totalUsdMicros += mulDiv(outflow.base, price, "up");
}
return totalUsdMicros;
}
function verdictOf(input: PolicyInput): PolicyVerdict {
const { figures } = input;
const withFigures = figures === undefined ? {} : { figures };
const [first, ...rest] = policyRefusals(input);
return first === undefined
? ok({ ...withFigures, sellsDeniedToken: sellsDeniedToken(input) })
: { ok: false, error: first, reasons: [first, ...rest], ...withFigures };
}
interface CheckCall extends PolicyCheckCall {
readonly subject: PolicySubject;
readonly facts: PolicyFacts;
}
async function checkIntent(
{ subject, facts, signal, quote }: CheckCall,
options: PolicyCheckOptions,
): Promise<PolicyVerdict> {
const nowMs = options.clock.now();
if (subject.kind === "rescue") {
return verdictOf({ subject, facts, nowMs });
}
const prices = quote === undefined ? options.prices : withQuotePrice(options.prices, quote);
我只有两个部分能碰到资金。
对话和模型只能提议。引擎做决定,签名进程签名,都在你设定的上限之内。
我由什么组成。
一个会推理的模型。它读链上数据和新闻,然后提议。
一个会做决定的引擎。你的限额和你的卡片。没有什么能绕过它。
一个守住你的上限的签名进程。密钥留在安全隔区里,只在上限之内签名。
还有你,说了算。
一个 Agent。属于你。
从安装到第一笔交易。
- 1
安装我
在终端里粘贴一行。如果你的 Mac 需要,它会先装好 Node。
~ % curl -fsSL https://binference.io/install.sh | sh -s -- --beta
- 2
设置我
你的模型、你的 Privy 钱包、你的 Telegram 机器人和你的限额。每一项我都会检查。
~ % binference init
- 3
配对你的 Telegram
打开我打印出的链接。从那以后,我只回答你。
- 4
先用模拟盘交易
用平常的话提出要求,然后点按卡片。
用 BNB 买入 10 USDT。
- 5
上实盘
给你的 Agent 钱包充值,然后在 Mac 上运行一条命令。
~ % binference live