Docs / SDK API

SDK reference

TypeScript contracts generated from the packaged SDK declarations.

Public entry point

Import public symbols from near-swarmkit. The index below lists the public exports; module declarations provide their full types. Supporting internal types are shown for context and are not separate package entry points.

index

export { commitBid, createRound } from "./round.ts";
export type { Allocation, Bid, Demand, RoundSnapshot, RoundSpec } from "./round.ts";
export type { RoundCommand, RoundEvent, RoundTranscript } from "./round.ts";
export { cheapestCapacity, lowestPrice } from "./mechanism.ts";
export type { EligibleOffer, FulfillmentLine, ProcurementMechanism, SplitAllocation } from "./mechanism.ts";
export { openStoredRound, replayRound, resumeRound, settlementPlanFromTranscript, submitStoredRoundEvent, } from "./replay.ts";
export type { RoundStore } from "./replay.ts";
export { simulateProcurement } from "./simulation.ts";
export type { BuyerStrategy, SellerStrategy, SimulationOptions } from "./simulation.ts";
export { createSettlementPlan, summarizeSettlement } from "./settlement.ts";
export type { Payment, PaymentReceipt, SettlementPlan } from "./settlement.ts";
export { INTENTS_VERIFIER, nearIntentsExecutionCall, planNearSubaccounts, prepareNearIntentsTransfers, readNearIntentsSalt, signNearIntentsTransfers, } from "./near.ts";
export type { NearIntentSigningRequest } from "./near.ts";
export { executeSettlement } from "./execute.ts";
export type { SignedPayment, SettlementEntry, SettlementJournal, SettlementTransport } from "./execute.ts";
export { NATIVE_TESTNET_NEAR, nearTestnetTransport } from "./near-testnet.ts";
export { nearIntentsTransport } from "./near-intents-transport.ts";
export { auditSettlement } from "./audit.ts";
export type { ReceiptClaim } from "./audit.ts";
export { authorizeWithSpendingPolicies, executeWithSpendingPolicies, spendingPolicyMessage } from "./spending-policy.ts";
export type { SpendingPolicy } from "./spending-policy.ts";
export { startSimulation, advanceSimulation, explainAllocation } from "./session.ts";
export type { SimulationSession } from "./session.ts";

audit

import type { PaymentReceipt } from "./settlement.ts";
import type { RoundTranscript } from "./round.ts";
import type { ProcurementMechanism } from "./mechanism.ts";
import type { SettlementTransport } from "./execute.ts";
export type ReceiptClaim = PaymentReceipt & {
    transactionHash?: string;
};
export declare function auditSettlement(transcript: RoundTranscript, claims: readonly ReceiptClaim[], options?: {
    mechanism?: ProcurementMechanism;
    verifier?: Pick<SettlementTransport, "asset" | "inspect">;
}): Promise<{
    plan: import("./settlement.ts").SettlementPlan;
    claimedSummary: {
        pending: string;
        confirmed: string;
        failed: string;
        paid: boolean;
    };
    verifiedSummary: {
        pending: string;
        confirmed: string;
        failed: string;
        paid: boolean;
    } | undefined;
    checks: {
        paymentId: string;
        transactionHash: string | undefined;
        claimed: "failed" | "pending" | "confirmed";
        observed: "failed" | "pending" | "confirmed" | undefined;
        matches: boolean | undefined;
    }[];
}>;

execute

import type { Payment, PaymentReceipt, SettlementPlan } from "./settlement.ts";
export type SignedPayment = {
    hash: string;
    bytes: string;
};
export type SettlementEntry = {
    payment: Payment;
    signed: SignedPayment;
};
export type SettlementJournal = {
    reserve(scope: string, candidate: SettlementEntry): Promise<SettlementEntry>;
    read(scope: string): Promise<SettlementEntry | undefined>;
    bindPlan?(scope: string, fingerprint: string): Promise<boolean>;
};
export type SettlementTransport = {
    scope: string;
    asset: string;
    prepare(payment: Readonly<Payment>): Promise<SignedPayment>;
    broadcast(signed: Readonly<SignedPayment>): Promise<void>;
    inspect(payment: Readonly<Payment>, hash: string): Promise<PaymentReceipt["status"]>;
};
export declare function executeSettlement(input: SettlementPlan, options: {
    transport: SettlementTransport;
    journal: SettlementJournal;
    authorize: (payment: Readonly<Payment>) => boolean | Promise<boolean>;
}): Promise<{
    receipts: (PaymentReceipt & {
        transactionHash?: string;
        broadcastUncertain?: true;
    })[];
    summary: {
        pending: string;
        confirmed: string;
        failed: string;
        paid: boolean;
    };
}>;

mechanism

export type EligibleOffer = Readonly<{
    sellerId: string;
    unitPrice: string;
    capacity: string;
}>;
export type FulfillmentLine = {
    buyerId: string;
    sellerId: string;
    quantity: string;
};
export type SplitAllocation = {
    lines: (FulfillmentLine & {
        unitPrice: string;
        amount: string;
    })[];
    total: string;
};
type Buyer = Readonly<{
    buyerId: string;
    quantity: string;
    budget: string;
}>;
export type ProcurementMechanism = Readonly<{
    id: string;
} & ({
    selectWinner: (offers: readonly EligibleOffer[]) => string | null;
} | {
    allocate: (buyers: readonly Buyer[], offers: readonly EligibleOffer[]) => readonly FulfillmentLine[] | null;
})>;
export declare const cheapestCapacity: ProcurementMechanism;
export declare function validateSplit(buyers: readonly Buyer[], offers: readonly EligibleOffer[], lines: readonly FulfillmentLine[]): SplitAllocation;
export declare const lowestPrice: ProcurementMechanism;
export {};

near-intents-transport

import type { SettlementTransport, SignedPayment } from "./execute.ts";
import { nearIntentsExecutionCall, signNearIntentsTransfers } from "./near.ts";
type SigningCallback = Parameters<typeof signNearIntentsTransfers>[1];
type ExecutionCall = ReturnType<typeof nearIntentsExecutionCall>;
export declare function nearIntentsTransport(options: {
    asset: string;
    relayerId: string;
    signIntent: SigningCallback;
    signTransaction: (call: ExecutionCall) => Promise<SignedPayment>;
    rpcUrl?: string;
}): SettlementTransport;
export {};

near-testnet

import type { SettlementTransport, SignedPayment } from "./execute.ts";
import type { Payment } from "./settlement.ts";
export declare const NATIVE_TESTNET_NEAR = "near:testnet:native";
export declare const nearTransactionHash: RegExp;
export declare function nearTestnetTransport(sign: (payment: Readonly<Payment>) => Promise<SignedPayment>, rpcUrl?: string): SettlementTransport;

near

import type { Payment, SettlementPlan } from "./settlement.ts";
export declare const INTENTS_VERIFIER = "intents.near";
export declare function planNearSubaccounts(parentId: string, agents: readonly {
    label: string;
    publicKey: string;
    fundingYoctoNear: string;
}[]): {
    signerId: string;
    receiverId: string;
    actions: readonly [{
        readonly type: "CreateAccount";
    }, {
        readonly type: "Transfer";
        readonly deposit: string;
    }, {
        readonly type: "AddFullAccessKey";
        readonly publicKey: string;
    }];
}[];
export type NearIntentSigningRequest = Readonly<{
    payment: Readonly<Payment>;
    recipient: typeof INTENTS_VERIFIER;
    message: string;
    nonce: string;
}>;
type IntentSignature = {
    publicKey: string;
    signature: string;
};
type SignedIntent = {
    standard: "nep413";
    payload: Pick<NearIntentSigningRequest, "recipient" | "message" | "nonce">;
    public_key: string;
    signature: string;
};
export declare function prepareNearIntentsTransfers(plan: SettlementPlan, options: {
    salt: string;
    deadline: Date;
}): NearIntentSigningRequest[];
export declare function signNearIntentsTransfers(requests: readonly NearIntentSigningRequest[], sign: (request: NearIntentSigningRequest) => Promise<IntentSignature>): Promise<{
    signed: SignedIntent[];
}>;
export declare function nearIntentsExecutionCall(args: Awaited<ReturnType<typeof signNearIntentsTransfers>>): {
    readonly network: "mainnet";
    readonly receiverId: "intents.near";
    readonly methodName: "execute_intents";
    readonly args: {
        signed: SignedIntent[];
    };
    readonly attachedDepositYoctoNear: "0";
};
export declare function readNearIntentsSalt(rpcUrl?: string): Promise<string>;
export {};

replay

import type { RoundCommand, RoundTranscript } from "./round.ts";
import type { ProcurementMechanism } from "./mechanism.ts";
export declare function resumeRound(transcript: RoundTranscript, clock?: () => number, mechanism?: ProcurementMechanism): Promise<{
    submitDemand: (buyerId: string, request: import("./types.ts").Demand | null) => boolean;
    submitCommitment: (sellerId: string, hash: string) => boolean;
    revealBid: (sellerId: string, bid: import("./types.ts").Bid) => Promise<boolean>;
    snapshot: () => {
        splitAllocation?: import("./mechanism.ts").SplitAllocation | null | undefined;
        spec: import("./types.ts").RoundSpec;
        phase: string;
        buyers: {
            quantity: string;
            budget: string;
            buyerId: string;
        }[];
        quantity: string;
        bids: {
            sellerId: string;
            commitment: string;
            reveal: {
                capacity: string;
                unitPrice: string;
                salt: string;
            } | null;
            rejection: string | null;
        }[];
        allocation: import("./types.ts").Allocation | null;
    };
    transcript: () => RoundTranscript;
}>;
export declare function replayRound(transcript: RoundTranscript, mechanism?: ProcurementMechanism): Promise<{
    splitAllocation?: import("./mechanism.ts").SplitAllocation | null | undefined;
    spec: import("./types.ts").RoundSpec;
    phase: string;
    buyers: {
        quantity: string;
        budget: string;
        buyerId: string;
    }[];
    quantity: string;
    bids: {
        sellerId: string;
        commitment: string;
        reveal: {
            capacity: string;
            unitPrice: string;
            salt: string;
        } | null;
        rejection: string | null;
    }[];
    allocation: import("./types.ts").Allocation | null;
}>;
export declare function settlementPlanFromTranscript(transcript: RoundTranscript, mechanism?: ProcurementMechanism): Promise<import("./settlement.ts").SettlementPlan>;
export type RoundStore = {
    read(roundId: string): Promise<RoundTranscript | undefined>;
    compareAndSet(next: RoundTranscript, expectedRevision: number | null): Promise<boolean>;
};
export declare function openStoredRound(spec: RoundTranscript["spec"], store: RoundStore, clock?: () => number, mechanism?: ProcurementMechanism): Promise<RoundTranscript>;
export declare function submitStoredRoundEvent(roundId: string, event: RoundCommand, store: RoundStore, clock?: () => number, mechanism?: ProcurementMechanism): Promise<{
    readonly status: "rejected";
    readonly transcript?: undefined;
} | {
    readonly status: "conflict";
    readonly transcript?: undefined;
} | {
    readonly status: "accepted";
    readonly transcript: RoundTranscript;
}>;

round

import type { Allocation, Bid, Demand, RoundSpec } from "./types.ts";
import type { ProcurementMechanism, SplitAllocation } from "./mechanism.ts";
export type { Allocation, Bid, Demand, RoundSpec } from "./types.ts";
export type RoundCommand = {
    type: "demand";
    buyerId: string;
    request: Demand | null;
} | {
    type: "commitment";
    sellerId: string;
    hash: string;
} | {
    type: "reveal";
    sellerId: string;
    bid: Bid;
};
export type RoundEvent = RoundCommand & {
    at: number;
};
export type RoundTranscript = {
    version: 1;
    spec: RoundSpec;
    events: readonly RoundEvent[];
    observedAt: number;
};
export declare function commitBid(roundId: string, sellerId: string, bid: Bid): Promise<string>;
export declare function createRound(input: RoundSpec, clock?: () => number, mechanism?: ProcurementMechanism): {
    submitDemand: (buyerId: string, request: Demand | null) => boolean;
    submitCommitment: (sellerId: string, hash: string) => boolean;
    revealBid: (sellerId: string, bid: Bid) => Promise<boolean>;
    snapshot: () => {
        splitAllocation?: SplitAllocation | null | undefined;
        spec: RoundSpec;
        phase: string;
        buyers: {
            quantity: string;
            budget: string;
            buyerId: string;
        }[];
        quantity: string;
        bids: {
            sellerId: string;
            commitment: string;
            reveal: {
                capacity: string;
                unitPrice: string;
                salt: string;
            } | null;
            rejection: string | null;
        }[];
        allocation: Allocation | null;
    };
    transcript: () => RoundTranscript;
};
export type RoundSnapshot = ReturnType<ReturnType<typeof createRound>["snapshot"]>;

session

import type { RoundSnapshot, RoundTranscript } from "./round.ts";
import type { Bid } from "./types.ts";
import type { SimulationOptions } from "./simulation.ts";
/** Private simulation checkpoint. Contains unrevealed offers; never publish it. */
export type SimulationSession = {
    version: 1;
    stage: "ready" | "demand" | "commit" | "reveal" | "closed";
    randomState: number;
    transcript: RoundTranscript;
    sealedOffers: {
        sellerId: string;
        bid: Bid;
        reveal: boolean;
    }[];
};
/** Start an empty simulation. No strategies execute until advanceSimulation is called. */
export declare function startSimulation(options: Pick<SimulationOptions, "spec" | "seed" | "buyers" | "sellers" | "mechanism">): SimulationSession;
/** Advance exactly one stage. Persist the returned checkpoint before calling again.
 * Strategies must be side-effect-free: an uncommitted attempt may be retried.
 * The supplied callbacks may be asynchronous; clocks are logical simulation time.
 */
export declare function advanceSimulation(input: SimulationSession, strategies: Pick<SimulationOptions, "buyers" | "sellers" | "mechanism">): Promise<SimulationSession>;
/** Explain the recorded outcome without claiming the heuristic proves infeasibility. */
export declare function explainAllocation(snapshot: RoundSnapshot): {
    outcome: "allocated" | "no-sale";
    reason: string;
    buyers: {
        spent: string;
        remainingBudget: string;
        lines: (import("./mechanism.ts").FulfillmentLine & {
            unitPrice: string;
            amount: string;
        })[];
        quantity: string;
        budget: string;
        buyerId: string;
    }[];
    sellers: {
        sellerId: string;
        reason: string;
        quantity: string;
    }[];
};

settlement

import type { RoundSnapshot } from "./round.ts";
export type Payment = {
    id: string;
    buyerId: string;
    sellerId: string;
    amount: string;
};
export type SettlementPlan = {
    version: 1 | 2;
    roundId: string;
    asset: string;
    payments: readonly Payment[];
};
export declare function paymentIdFor(version: SettlementPlan["version"], roundId: string, buyerId: string, sellerId: string): string;
export type PaymentReceipt = {
    paymentId: string;
    status: "pending" | "confirmed" | "failed";
};
export declare function createSettlementPlan(round: RoundSnapshot): SettlementPlan;
export declare function summarizeSettlement(plan: SettlementPlan, receipts: readonly PaymentReceipt[]): {
    pending: string;
    confirmed: string;
    failed: string;
    paid: boolean;
};

simulation

import type { Bid, Demand, RoundSpec } from "./types.ts";
import type { Payment, PaymentReceipt } from "./settlement.ts";
import type { ProcurementMechanism } from "./mechanism.ts";
type StrategyContext = {
    resource: Readonly<RoundSpec["resource"]>;
    asset: string;
    random: () => number;
};
export type BuyerStrategy = {
    id: string;
    demand: (context: StrategyContext) => Demand | null | Promise<Demand | null>;
};
export type SellerStrategy = {
    id: string;
    offer: (context: StrategyContext & {
        pooledQuantity: string;
    }) => Omit<Bid, "salt"> | null | Promise<Omit<Bid, "salt"> | null>;
    reveal?: boolean;
};
export type SimulationOptions = {
    spec: Omit<RoundSpec, "buyers" | "sellers">;
    seed: number;
    mechanism?: ProcurementMechanism;
    buyers: readonly BuyerStrategy[];
    sellers: readonly SellerStrategy[];
    paymentOutcome?: (payment: Readonly<Payment>) => PaymentReceipt["status"];
};
export declare function simulateProcurement(options: SimulationOptions): Promise<{
    mode: "simulation";
    transcript: import("./round.ts").RoundTranscript;
    stages: readonly [{
        splitAllocation?: import("./mechanism.ts").SplitAllocation | null | undefined;
        spec: RoundSpec;
        phase: string;
        buyers: {
            quantity: string;
            budget: string;
            buyerId: string;
        }[];
        quantity: string;
        bids: {
            sellerId: string;
            commitment: string;
            reveal: {
                capacity: string;
                unitPrice: string;
                salt: string;
            } | null;
            rejection: string | null;
        }[];
        allocation: import("./types.ts").Allocation | null;
    }, {
        splitAllocation?: import("./mechanism.ts").SplitAllocation | null | undefined;
        spec: RoundSpec;
        phase: string;
        buyers: {
            quantity: string;
            budget: string;
            buyerId: string;
        }[];
        quantity: string;
        bids: {
            sellerId: string;
            commitment: string;
            reveal: {
                capacity: string;
                unitPrice: string;
                salt: string;
            } | null;
            rejection: string | null;
        }[];
        allocation: import("./types.ts").Allocation | null;
    }, {
        splitAllocation?: import("./mechanism.ts").SplitAllocation | null | undefined;
        spec: RoundSpec;
        phase: string;
        buyers: {
            quantity: string;
            budget: string;
            buyerId: string;
        }[];
        quantity: string;
        bids: {
            sellerId: string;
            commitment: string;
            reveal: {
                capacity: string;
                unitPrice: string;
                salt: string;
            } | null;
            rejection: string | null;
        }[];
        allocation: import("./types.ts").Allocation | null;
    }, {
        splitAllocation?: import("./mechanism.ts").SplitAllocation | null | undefined;
        spec: RoundSpec;
        phase: string;
        buyers: {
            quantity: string;
            budget: string;
            buyerId: string;
        }[];
        quantity: string;
        bids: {
            sellerId: string;
            commitment: string;
            reveal: {
                capacity: string;
                unitPrice: string;
                salt: string;
            } | null;
            rejection: string | null;
        }[];
        allocation: import("./types.ts").Allocation | null;
    }];
    plan: import("./settlement.ts").SettlementPlan;
    settlement: {
        pending: string;
        confirmed: string;
        failed: string;
        paid: boolean;
    };
    payments: {
        buyerId: string;
        amount: string;
        status: "failed" | "pending" | "simulated";
    }[];
}>;
export {};

spending-policy

import type { Payment, SettlementPlan } from "./settlement.ts";
import { executeSettlement } from "./execute.ts";
export type SpendingPolicy = {
    roundId: string;
    buyerId: string;
    asset: string;
    transportScope: string;
    sellers: readonly string[];
    maxAmount: string;
    expiresAt: number;
};
export declare function spendingPolicyMessage(policy: SpendingPolicy): Uint8Array<ArrayBuffer>;
export declare function authorizeWithSpendingPolicies(input: SettlementPlan, transportScope: string, approvals: readonly {
    policy: SpendingPolicy;
    signature: Uint8Array;
}[], resolveBuyerKey: (buyerId: string) => Promise<Parameters<typeof globalThis.crypto.subtle.verify>[1] | undefined>, clock?: () => number): Promise<(payment: Readonly<Payment>) => boolean>;
export declare function executeWithSpendingPolicies(input: SettlementPlan, options: Omit<Parameters<typeof executeSettlement>[1], "authorize"> & {
    approvals: Parameters<typeof authorizeWithSpendingPolicies>[2];
    resolveBuyerKey: Parameters<typeof authorizeWithSpendingPolicies>[3];
    clock?: () => number;
}): Promise<{
    receipts: (import("./settlement.ts").PaymentReceipt & {
        transactionHash?: string;
        broadcastUncertain?: true;
    })[];
    summary: {
        pending: string;
        confirmed: string;
        failed: string;
        paid: boolean;
    };
}>;

types

export type RoundSpec = {
    id: string;
    resource: {
        label: string;
        unit: string;
        deliveryWindow: string;
    };
    asset: string;
    mechanismId?: string;
    buyers: readonly string[];
    sellers: readonly string[];
    demandCloses: number;
    commitCloses: number;
    revealCloses: number;
};
export type Demand = {
    quantity: string;
    budget: string;
};
export type Bid = {
    capacity: string;
    unitPrice: string;
    salt: string;
};
export type Allocation = {
    sellerId: string;
    unitPrice: string;
    total: string;
    shares: {
        buyerId: string;
        quantity: string;
        amount: string;
    }[];
};