bInference Agent
Your agent
On BNB Smart Chain.
Research. Trade. Stake. Bridge.
Day and night, on your Mac.Nothing moves without your tap.
~ %
- macOSLinux and Windows next
- Open sourceMIT license
- No feesSelf-hosted
- Talk to meTry the demo
I read
The chain, the charts, X and any page.
I check
The token, a test sale, the route, the fee.
I ask
One card. Then I wait for you.
Talk to me where you are.
One card on every screen.
The first tap counts.
Every screen knows at once.
Your agentbot
Buy 0.1 BNB of CAKE if it looks safe.
Checked: clean, and the test sale passed. Your card:
Confirm buy
0.1 BNB → at least 23.41 CAKE
ConfirmCancel
Confirmed0.1 BNB → 23.58 CAKE
Message
binference console
Nothing waits for you.
Confirm buy
0.1 BNB → at least 23.41 CAKE
ConfirmCancel
Confirmed0.1 BNB → 23.58 CAKE
Waiting for your tapConfirmed
zsh
~ % binference chat
Checked: clean, and the test sale passed. Your card:
Confirm buy
0.1 BNB → at least 23.41 CAKE
⌃Y confirm · ⌃N cancel
Confirmed · 0.1 BNB → 23.58 CAKE
Waiting for your tapConfirmed
Claude Code
binference_intents
1 card waits for your tap.
Confirmed · 0.1 BNB → 23.58 CAKE
Waiting for your tapConfirmed
A day with me.
an example day · scroll to move the clock
Read 214 new launches. Saved the three that passed my checks.
Your morning summary: positions, profit, what moved.
CAKE crossed your alert. A trade waits for your tap.
Your stop-loss on CAKE held all morning.
Read 40 posts on BNB staking. The answer is in your chat.
Still here. Still watching.
What I can do.
I bring every trade as one card.
Checked before you see it.
Then you tap.
Done. Proof on chain.
0.1 BNB → 23.58 CAKE
Sent privately, where bots cannot see it first.
View on BscScanYou set my rules.
They hold even after your tap.
Mode
Every transaction waits for your tap.
- Buy 0.1 BNB of CAKEAsks you
- Stake 1 BNB with a validatorAsks you
- Send 1 BNB to a saved addressAsks you
- Bridge 50 USDT to BaseAsks you
- Buy a token no one has checkedAsks you
binference approval manual
Limits
Drag a limit.
Stops every agent at once.
/freeze
Everything to your own wallet, but the BNB kept for network fees.
/rescue
Paper first
1 BNB and 500 USDT of virtual money. Real quotes, real checks.
Live when you are ready
Only from the terminal on your Mac.
binference live
Now talk to me.
Pick a request. I do the work, then wait for your tap. A scripted demo.
/** 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);
Read me.
I am open source. The code behind these words is the code I run. Move the pointer to read.
Only two parts of me touch money.
Chats and models only propose. The engine decides and the signer signs, inside your ceiling.
What I am made of.
A model that reasons.It reads the chain and the news, then proposes.
An engine that decides.Your limits and your card. Nothing gets around them.
A signer that keeps to your ceiling.The key stays in an enclave and signs only inside it.
And you, with the last word.
One agent. Yours.
From install to your first trade.
- 1
Install me
One line in Terminal. It brings Node if your Mac needs it.
~ % curl -fsSL https://binference.io/install.sh | sh -s -- --beta
- 2
Set me up
Your model, your Privy wallet, your Telegram bot and your limits. I check each one.
~ % binference init
- 3
Pair your Telegram
Open the link I print. From then on, I answer only you.
- 4
Trade on paper
Ask in plain words, then tap the card.
Buy 10 USDT with BNB.
- 5
Go live
Fund your agent wallet, then run one command on your Mac.
~ % binference live