Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add reverse-engineered @pump-fun/agent-payments-sdk
nirholas88944b4da269
diff --git a/agent-payments-sdk/README.md b/agent-payments-sdk/README.mdnew file mode 100644index 000000000..e1f2e30d5--- /dev/null+++ b/agent-payments-sdk/README.md@@ -0,0 +1,171 @@+# @pump-fun/agent-payments-sdk++TypeScript SDK for the **Pump Agent Payments** Solana program (`AgenTMiC2hvxGebTsgmsD4HHBa8WEcqGFf87iwRRxLo7`).++Reverse-engineered from the published npm package. Original by [@pump-fun](https://github.com/pump-fun).++## Architecture++```+src/+├── idl/+│ ├── pump_agent_payments.json # Anchor IDL (snake_case, runtime)+│ └── pump_agent_payments.ts # Anchor IDL type (camelCase, compile-time)+├── pdas.ts # PDA derivation helpers (seeds + constants)+├── program.ts # Anchor Program creation / offline instance+├── types.ts # All parameter interfaces & decoded account types+├── PumpAgentOffline.ts # Instruction builder — no RPC required+├── PumpAgent.ts # Online agent — extends Offline with RPC calls+├── decoders.ts # Account data decoders (GlobalConfig, etc.)+├── events.ts # Event parsing, types & WebSocket subscriptions+├── x402/ # x402 HTTP 402 Payment Required protocol+│ ├── types.ts # Protocol constants & type definitions+│ ├── headers.ts # Header encoding/decoding helpers+│ ├── facilitator.ts # Server-side verify & settle + resource server+│ └── client.ts # Client-side fetch wrapper (auto 402 handling)+└── index.ts # Barrel export+```++## Install++```bash+npm install @pump-fun/agent-payments-sdk+```++## Build++```bash+npm install+npm run build+```++## Development++```bash+npm run dev # watch mode+npm run typecheck # tsc --noEmit+npm run lint # eslint+npm run lint:fix # eslint --fix+```++## Usage++```typescript+import { PumpAgent, PumpAgentOffline, PROGRAM_ID } from "@pump-fun/agent-payments-sdk";+import { Connection, PublicKey } from "@solana/web3.js";++// Offline — build instructions without an RPC connection+const offline = new PumpAgentOffline(mintPubkey);+const createIx = await offline.create({+ authority: walletPubkey,+ mint: mintPubkey,+ agentAuthority: agentPubkey,+ buybackBps: 500, // 5%+});++// Online — with RPC for balance queries and invoice validation+const connection = new Connection("https://api.mainnet-beta.solana.com");+const agent = new PumpAgent(mintPubkey, "mainnet", connection);+const balances = await agent.getBalances(currencyMint);+```++### Invoice Validation++```typescript+const paid = await agent.validateInvoicePayment({+ user: payerPubkey,+ currencyMint: usdcMint,+ amount: 1_000_000, // 1 USDC (6 decimals)+ memo: 12345,+ startTime: Math.floor(Date.now() / 1000),+ endTime: Math.floor(Date.now() / 1000) + 300,+});+```++### Event Parsing++```typescript+import { parseAgentEvents, subscribeToAgentEvents } from "@pump-fun/agent-payments-sdk";++// Parse events from transaction logs+const events = parseAgentEvents(tx.meta.logMessages);+for (const event of events) {+ if (event.name === "agentAcceptPaymentEvent") {+ console.log("Payment amount:", event.data.amount.toString());+ }+}++// Subscribe to real-time events via WebSocket+const sub = subscribeToAgentEvents(connection, (event, slot) => {+ console.log(`[slot ${slot}] ${event.name}`, event.data);+}, { eventNames: ["agentAcceptPaymentEvent"] });++// Later: stop listening+sub.unsubscribe();+```++### x402 (HTTP 402 Payment Required)++The SDK includes an x402 sub-package for pay-gating HTTP endpoints:++```typescript+import { x402 } from "@pump-fun/agent-payments-sdk";++// Server: build payment requirements for a 402 response+const requirements = x402.buildPumpAgentRequirements({+ agentMint: "YourAgentMintAddress...",+ payTo: "PaymentVaultAddress...",+ amount: "1000000", // 1 USDC in minor units+});++// Client: auto-pay 402 responses+const x402fetch = x402.createX402Fetch({+ payer: wallet.publicKey.toBase58(),+ connection,+ signTransaction: async (tx) => { /* sign */ },+ sendTransaction: async (tx) => { /* send */ },+});+const res = await x402fetch("https://api.agent.example/inference");+```++## Program Instructions++| Instruction | Description |+|---|---|+| `agentInitialize` | Register a new agent for a token mint |+| `agentAcceptPayment` | Accept a payment in a supported currency |+| `agentDistributePayments` | Split vault funds between buyback and withdraw |+| `agentBuybackTrigger` | Execute buyback via CPI swap + burn |+| `agentWithdraw` | Withdraw funds from the withdraw vault |+| `agentUpdateBuybackBps` | Update the buyback basis points |+| `agentUpdateAuthority` | Transfer agent authority |+| `agentTransferExtraLamports` | Transfer excess lamports (native SOL) |+| `extendAccount` | Extend account size |+| `closeAccount` | Close an account |+| `globalConfigInitialize` | Initialize the global config |+| `globalAddNewCurrency` | Add a supported currency |+| `globalRemoveCurrency` | Remove a supported currency |+| `globalUpdateAuthorities` | Update protocol / buyback authorities |++## On-Chain Accounts++| Account | Description |+|---|---|+| `GlobalConfig` | Protocol-wide config: authorities, supported currencies |+| `TokenAgentPayments` | Per-mint agent config: authority, buyback bps |+| `TokenAgentPaymentInCurrency` | Per-mint per-currency accounting |+| `BondingCurve` | Pump bonding curve state (read-only) |++## Key Exports++- **Classes**: `PumpAgent`, `PumpAgentOffline`+- **Constants**: `PROGRAM_ID`, `PUMP_PROGRAM_ID`, `PUMP_AGENT_PAYMENTS_PROGRAM_ID`+- **PDAs**: `getGlobalConfigPDA`, `getTokenAgentPaymentsPDA`, `getPaymentInCurrencyPDA`, `getInvoiceIdPDA`, `getBuybackAuthorityPDA`, `getWithdrawAuthorityPDA`, `getBondingCurvePDA`+- **Decoders**: `decodeGlobalConfig`, `decodeTokenAgentPaymentInCurrency`, `decodeTokenAgentPayments`+- **Events**: `createEventParser`, `parseAgentEvents`, `subscribeToAgentEvents` + all event type interfaces+- **Program**: `getPumpProgram`, `getPumpProgramWithFallback`, `getOfflineProgram`, `getProgram`+- **x402**: `x402.createX402Fetch`, `x402.PumpAgentFacilitator`, `x402.createResourceServer`, `x402.buildPumpAgentRequirements`, header helpers++## License++ISCdiff --git a/agent-payments-sdk/docs/api.md b/agent-payments-sdk/docs/api.mdnew file mode 100644index 000000000..ff4f4f891--- /dev/null+++ b/agent-payments-sdk/docs/api.md@@ -0,0 +1,257 @@+# API Reference — @pump-fun/agent-payments-sdk++Program ID: `AgenTMiC2hvxGebTsgmsD4HHBa8WEcqGFf87iwRRxLo7`++---++## Classes++### `PumpAgentOffline`++Instruction builder. No RPC connection required — all methods return a `TransactionInstruction` you include in your own transaction.++```ts+import { PumpAgentOffline } from "@pump-fun/agent-payments-sdk";+import { PublicKey } from "@solana/web3.js";++const agent = new PumpAgentOffline(mintPubkey);+// or+const agent = PumpAgentOffline.load(mintPubkey, connection);+```++| Method | Returns | Description |+|---|---|---|+| `create(params)` | `Promise<TransactionInstruction>` | Register a new agent (`agentInitialize`) |+| `withdraw(params)` | `Promise<TransactionInstruction>` | Withdraw from the withdraw vault |+| `updateBuybackBps(params, options)` | `Promise<TransactionInstruction>` | Update buyback basis points |+| `acceptPayment(params)` | `Promise<TransactionInstruction>` | Accept a payment (full params) |+| `acceptPaymentSimple(params)` | `Promise<TransactionInstruction[]>` | Accept payment + compute budget instructions |+| `buildAcceptPaymentTransaction(params)` | `Promise<Transaction>` | Build a ready-to-sign transaction |+| `distributePayments(params)` | `Promise<TransactionInstruction[]>` | Split vault to buyback + withdraw |+| `buybackTrigger(params)` | `Promise<TransactionInstruction>` | Trigger a buyback swap + burn |+| `updateAuthority(params)` | `Promise<TransactionInstruction>` | Transfer agent authority |+| `extendAccount(params)` | `Promise<TransactionInstruction>` | Extend account size |+| `closeAccount(params)` | `Promise<TransactionInstruction>` | Close an account |++**Static constants:**+- `DEFAULT_COMPUTE_UNIT_LIMIT_FOR_AGENT_PAYMENTS = 100_000`+- `DEFAULT_PRIORITY_FEE_MICRO_LAMPORTS = 1_000`++---++### `PumpAgent`++Extends `PumpAgentOffline` with RPC calls for account fetching, balance queries, payment history, and invoice validation.++```ts+import { PumpAgent } from "@pump-fun/agent-payments-sdk";+import { Connection, PublicKey } from "@solana/web3.js";++const connection = new Connection("https://api.mainnet-beta.solana.com");+const agent = new PumpAgent(mintPubkey, "mainnet", connection);+```++**Constructor:** `new PumpAgent(mint, environment?, connection?)`+- `environment`: `"mainnet"` | `"devnet"` (default: `"mainnet"`)++Inherits all `PumpAgentOffline` methods, plus:++| Method | Returns | Description |+|---|---|---|+| `getBalances(currencyMint, tokenProgram?)` | `Promise<AgentBalances>` | Fetch all three vault balances |+| `updateBuybackBps(params)` | `Promise<TransactionInstruction>` | Auto-fetches supported currencies from GlobalConfig |+| `getAgentConfig()` | `Promise<TokenAgentPayments>` | Fetch the on-chain agent config |+| `getGlobalConfig()` | `Promise<GlobalConfig>` | Fetch the protocol GlobalConfig |+| `getPaymentStats(currencyMint)` | `Promise<TokenAgentPaymentInCurrency>` | Fetch per-currency accounting |+| `getSupportedCurrencies()` | `Promise<PublicKey[]>` | List supported currency mints |+| `isInitialized()` | `Promise<boolean>` | Check if the agent account exists |+| `getPaymentHistory(limit?)` | `Promise<AgentAcceptPaymentEvent[]>` | Fetch recent payment events (default limit: 50) |+| `getEventHistory(limit?)` | `Promise<ParsedAgentEvent[]>` | Fetch all recent events (default limit: 50) |+| `validateInvoicePayment(params)` | `Promise<boolean>` | Validate a payment was made (API then RPC fallback) |++---++## Parameter Types++### `CreateParams`+```ts+interface CreateParams {+ authority: PublicKey; // bonding-curve creator for this mint+ mint: PublicKey; // token mint this agent manages+ agentAuthority: PublicKey; // agent authority (for withdraw / update)+ buybackBps: number; // 0–10 000 (basis points)+}+```++### `AcceptPaymentParams`+```ts+interface AcceptPaymentParams {+ user: PublicKey;+ userTokenAccount: PublicKey;+ currencyMint: PublicKey;+ amount: BN;+ memo: BN;+ startTime: BN;+ endTime: BN;+ tokenProgram?: PublicKey; // defaults to TOKEN_PROGRAM_ID+}+```++### `AcceptPaymentSimpleParams`+Same as above but `amount / memo / startTime / endTime` accept `bigint | number | string`, plus:+```ts+computeUnitLimit?: number; // default 130_000+computeUnitPrice?: number; // micro lamports per CU, default 1_000+```++### `BuildAcceptPaymentParams`+```ts+interface BuildAcceptPaymentParams {+ user: PublicKey;+ currencyMint: PublicKey;+ amount: bigint | number | string;+ memo: bigint | number | string;+ startTime: bigint | number | string;+ endTime: bigint | number | string;+ tokenProgram?: PublicKey;+ computeUnitLimit?: number; // default 100_000+ computeUnitPrice?: number;+}+```++### `DistributePaymentsParams`+```ts+interface DistributePaymentsParams {+ user: PublicKey;+ currencyMint: PublicKey;+ tokenProgram?: PublicKey;+ includeTransferExtraLamportsForNative?: boolean; // default false+}+```++### `BuybackTriggerParams`+```ts+interface BuybackTriggerParams {+ globalBuybackAuthority: PublicKey;+ currencyMint: PublicKey;+ swapProgramToInvoke: PublicKey;+ swapInstructionData: Buffer; // empty Buffer = skip swap, just burn+ remainingAccounts: AccountMeta[];+ tokenProgramCurrency?: PublicKey;+ tokenProgram?: PublicKey;+}+```++### `UpdateBuybackBpsParams`+```ts+interface UpdateBuybackBpsParams {+ authority: PublicKey;+ buybackBps: number; // 0–10 000+}+```++### `WithdrawParams`+```ts+interface WithdrawParams {+ authority: PublicKey;+ currencyMint: PublicKey;+ receiverAta: PublicKey;+ tokenProgram?: PublicKey;+}+```++### `UpdateAuthorityParams`+```ts+interface UpdateAuthorityParams {+ authority: PublicKey;+ newAuthority: PublicKey;+}+```++### `ExtendAccountParams` / `CloseAccountParams`+```ts+interface ExtendAccountParams { account: PublicKey; user: PublicKey; }+interface CloseAccountParams { account: PublicKey; user: PublicKey; }+```++---++## Account Types++### `AgentBalances`+```ts+interface AgentBalances {+ paymentVault: VaultBalance; // incoming payments land here+ buybackVault: VaultBalance; // earmarked for buyback+ withdrawVault: VaultBalance; // earmarked for withdrawal+}++interface VaultBalance {+ address: PublicKey;+ balance: bigint;+}+```++### `GlobalConfig`+Fetched via `agent.getGlobalConfig()` or `OFFLINE_PUMP_PROGRAM.account.GlobalConfig.fetch(pda)`.+Fields: `protocolAuthority`, `buybackAuthority`, `supportedCurrenciesMint[]`.++### `TokenAgentPayments`+Fetched via `agent.getAgentConfig()`.+Fields: `authority`, `buybackBps`, `mint`, `tokenizedAgentSequence`.++### `TokenAgentPaymentInCurrency`+Fetched via `agent.getPaymentStats(currencyMint)`.+Fields: `totalPayments`, `totalBuyback`, `totalWithdraw`, `totalTokensBurned`.++---++## Program Helpers++```ts+import { getPumpProgram, getPumpProgramWithFallback, getOfflineProgram, getProgram } from "@pump-fun/agent-payments-sdk";+```++| Helper | Description |+|---|---|+| `getPumpProgram(connection)` | Create an Anchor `Program` with a live connection |+| `getPumpProgramWithFallback(connection?)` | Use connection if provided, else offline |+| `getOfflineProgram()` | Get the static offline program instance |+| `getProgram(connection)` | Convenience alias for `getPumpProgram` |+| `OFFLINE_PUMP_PROGRAM` | Pre-built offline program instance (no connection) |++---++## Constants++```ts+import {+ PROGRAM_ID,+ PUMP_PROGRAM_ID,+ PUMP_AGENT_PAYMENTS_PROGRAM_ID,+ TOKEN_AGENT_PAYMENTS_MIN_RENT_EXEMPT_LAMPORTS,+} from "@pump-fun/agent-payments-sdk";+```++| Constant | Value |+|---|---|+| `PROGRAM_ID` | `AgenTMiC2hvxGebTsgmsD4HHBa8WEcqGFf87iwRRxLo7` |+| `PUMP_PROGRAM_ID` | `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P` |+| `PUMP_AGENT_PAYMENTS_PROGRAM_ID` | same as `PROGRAM_ID` (convenience) |+| `TOKEN_AGENT_PAYMENTS_MIN_RENT_EXEMPT_LAMPORTS` | `1_412_880` (~0.00141 SOL) |++---++## Decoders++For raw account data (e.g. from `getAccountInfo`):++```ts+import {+ decodeGlobalConfig,+ decodeTokenAgentPaymentInCurrency,+ decodeTokenAgentPayments,+} from "@pump-fun/agent-payments-sdk";+```++Each decoder accepts a `Buffer` of raw account data and returns the typed struct.diff --git a/agent-payments-sdk/docs/events.md b/agent-payments-sdk/docs/events.mdnew file mode 100644index 000000000..e444c0f25--- /dev/null+++ b/agent-payments-sdk/docs/events.md@@ -0,0 +1,205 @@+# Events — @pump-fun/agent-payments-sdk++The SDK provides typed event parsing from transaction logs and real-time WebSocket subscriptions.++## Quick Start++```ts+import { parseAgentEvents, subscribeToAgentEvents } from "@pump-fun/agent-payments-sdk";++// Parse from a fetched transaction+const tx = await connection.getTransaction(sig, { maxSupportedTransactionVersion: 0 });+const events = parseAgentEvents(tx.meta.logMessages);++for (const event of events) {+ if (event.name === "agentAcceptPaymentEvent") {+ console.log("Payment:", event.data.amount.toString());+ }+}++// Subscribe to real-time events+const sub = subscribeToAgentEvents(connection, (event, slot) => {+ console.log(`[slot ${slot}] ${event.name}`, event.data);+}, {+ eventNames: ["agentAcceptPaymentEvent", "agentDistributePaymentsEvent"],+});++// Stop listening+sub.unsubscribe();+```++---++## Functions++### `parseAgentEvents(logs, connection?)`+Parse an array of log messages (from `tx.meta.logMessages`) into typed events. Works offline; `connection` is optional.++### `createEventParser(connection?)`+Returns a raw Anchor `EventParser` bound to the Pump Agent Payments program. Use this if you need lower-level control.++### `subscribeToAgentEvents(connection, callback, options?)`+Opens a WebSocket subscription (`connection.onLogs`) and calls `callback` for each matching event.+- `options.eventNames`: array of event names to filter to. If omitted, all events fire.+- Returns `{ unsubscribe() }`.++---++## Event Types++### `agentAcceptPaymentEvent`+Emitted when a user pays an invoice.+```ts+interface AgentAcceptPaymentEvent {+ user: PublicKey;+ tokenizedAgentMint: PublicKey;+ tokenAgentPayments: PublicKey;+ currencyMint: PublicKey;+ amount: BN;+ memo: BN;+ startTime: BN;+ endTime: BN;+ invoiceId: PublicKey;+ agentPostBalance: BN;+ timestamp: BN;+}+```++### `agentDistributePaymentsEvent`+Emitted when vault funds are split between buyback and withdraw.+```ts+interface AgentDistributePaymentsEvent {+ tokenAgentPayments: PublicKey;+ currencyMint: PublicKey;+ buybackBps: number;+ buybackAmount: BN;+ withdrawAmount: BN;+ timestamp: BN;+}+```++### `agentBuybackTriggerEvent`+Emitted when a buyback swap + burn is executed.+```ts+interface AgentBuybackTriggerEvent {+ tokenizedAgentMint: PublicKey;+ currencyMint: PublicKey;+ amountBurned: BN;+ swapProgram: PublicKey;+ newTokensBoughtAndBurnedForCurrency: BN;+ agentPostBalance: BN;+ timestamp: BN;+ currencyMintAmountForBuyback: BN;+}+```++### `agentWithdrawEvent`+Emitted when the agent authority withdraws funds.+```ts+interface AgentWithdrawEvent {+ tokenizedAgentMint: PublicKey;+ currencyMint: PublicKey;+ amount: BN;+ receiver: PublicKey;+ timestamp: BN;+}+```++### `agentInitializeEvent`+Emitted when a new agent is registered.+```ts+interface AgentInitializeEvent {+ tokenAgentPayments: PublicKey;+ mint: PublicKey;+ authority: PublicKey;+ buybackBps: number;+ timestamp: BN;+ tokenizedAgentSequence: BN;+}+```++### `agentUpdateAuthorityEvent`+```ts+interface AgentUpdateAuthorityEvent {+ tokenAgentPayments: PublicKey;+ oldAuthority: PublicKey;+ newAuthority: PublicKey;+ timestamp: BN;+}+```++### `agentUpdateBuybackBpsEvent`+```ts+interface AgentUpdateBuybackBpsEvent {+ tokenAgentPayments: PublicKey;+ mint: PublicKey;+ oldBuybackBps: number;+ newBuybackBps: number;+ timestamp: BN;+}+```++### `extendAccountEvent`+```ts+interface ExtendAccountEvent {+ account: PublicKey;+ user: PublicKey;+ currentSize: BN;+ newSize: BN;+ timestamp: BN;+}+```++### Global events++```ts+interface GlobalConfigInitializeEvent {+ globalConfig: PublicKey;+ protocolAuthority: PublicKey;+ buybackAuthority: PublicKey;+ timestamp: BN;+}++interface GlobalAddNewCurrencyEvent {+ globalConfig: PublicKey;+ currencyMint: PublicKey;+ timestamp: BN;+}++interface GlobalUpdateAuthoritiesEvent {+ globalConfig: PublicKey;+ protocolAuthority: PublicKey | null;+ buybackAuthority: PublicKey | null;+ timestamp: BN;+}+```++---++## `AgentEventName` union++```ts+type AgentEventName =+ | "agentAcceptPaymentEvent"+ | "agentBuybackTriggerEvent"+ | "agentDistributePaymentsEvent"+ | "agentInitializeEvent"+ | "agentUpdateAuthorityEvent"+ | "agentUpdateBuybackBpsEvent"+ | "agentWithdrawEvent"+ | "extendAccountEvent"+ | "globalAddNewCurrencyEvent"+ | "globalConfigInitializeEvent"+ | "globalUpdateAuthoritiesEvent";+```++## `ParsedAgentEvent<T>`++```ts+interface ParsedAgentEvent<T extends AgentEventData = AgentEventData> {+ name: AgentEventName;+ data: T;+}+```++Narrow `data` by checking `event.name` — TypeScript will infer the correct `data` type.diff --git a/agent-payments-sdk/docs/pdas.md b/agent-payments-sdk/docs/pdas.mdnew file mode 100644index 000000000..355847ea2--- /dev/null+++ b/agent-payments-sdk/docs/pdas.md@@ -0,0 +1,115 @@+# PDA Reference — @pump-fun/agent-payments-sdk++All PDAs are derived from program `AgenTMiC2hvxGebTsgmsD4HHBa8WEcqGFf87iwRRxLo7` unless noted.++## Derivation Helpers++```ts+import {+ getGlobalConfigPDA,+ getTokenAgentPaymentsPDA,+ getPaymentInCurrencyPDA,+ getInvoiceIdPDA,+ getBuybackAuthorityPDA,+ getWithdrawAuthorityPDA,+ getBondingCurvePDA,+} from "@pump-fun/agent-payments-sdk";+```++All functions return `[PublicKey, number]` (address + bump).++---++### `getGlobalConfigPDA()`+Seeds: `["global-config"]`++Protocol-wide config account. Stores authorities and the list of supported currency mints.++---++### `getTokenAgentPaymentsPDA(mint)`+Seeds: `["token-agent-payments", mint]`++Per-agent config account. One per token mint. Stores authority, buyback BPS, and mint.++---++### `getPaymentInCurrencyPDA(tokenMint, currencyMint)`+Seeds: `["payment-in-currency", tokenMint, currencyMint]`++Per-agent per-currency accounting. Tracks total payments, buybacks, withdrawals, and tokens burned.++---++### `getInvoiceIdPDA(tokenMint, currencyMint, amount, memo, startTime, endTime)`+Seeds: `["invoice-id", tokenMint, currencyMint, amount_le8, memo_le8, startTime_le8, endTime_le8]`++Unique invoice identifier. Used to prevent double-payment and to validate whether an invoice was settled. `amount`, `memo`, `startTime`, `endTime` are `BN` encoded as little-endian 8-byte buffers.++---++### `getBuybackAuthorityPDA(tokenMint)`+Seeds: `["buyback-authority", tokenMint]`++PDA that acts as the owner of the buyback vault ATA. Only the protocol buyback authority can trigger swaps from here.++---++### `getWithdrawAuthorityPDA(tokenMint)`+Seeds: `["withdraw-authority", tokenMint]`++PDA that acts as the owner of the withdraw vault ATA. Only the agent authority can withdraw from here.++---++### `getBondingCurvePDA(mint)`+Seeds: `["bonding-curve", mint]`+Program: `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P` (Pump bonding curve program)++Read-only reference to the Pump bonding curve state for a token. Used during `agentInitialize` to verify the caller is the bonding-curve creator.++---++## PDA Seeds (raw)++```ts+import {+ GLOBAL_CONFIG_SEED,+ TOKEN_AGENT_PAYMENTS_SEED,+ PAYMENT_IN_CURRENCY_SEED,+ INVOICE_ID_SEED,+ BUYBACK_AUTHORITY_SEED,+ WITHDRAW_AUTHORITY_SEED,+ BONDING_CURVE_SEED,+} from "@pump-fun/agent-payments-sdk";+```++| Constant | Value |+|---|---|+| `GLOBAL_CONFIG_SEED` | `Buffer.from("global-config")` |+| `TOKEN_AGENT_PAYMENTS_SEED` | `Buffer.from("token-agent-payments")` |+| `PAYMENT_IN_CURRENCY_SEED` | `Buffer.from("payment-in-currency")` |+| `INVOICE_ID_SEED` | `Buffer.from("invoice-id")` |+| `BUYBACK_AUTHORITY_SEED` | `Buffer.from("buyback-authority")` |+| `WITHDRAW_AUTHORITY_SEED` | `Buffer.from("withdraw-authority")` |+| `BONDING_CURVE_SEED` | `Buffer.from("bonding-curve")` |++---++## Vault ATAs++Vault token accounts are standard ATAs owned by the PDA authorities:++```ts+import { getAssociatedTokenAddressSync } from "@solana/spl-token";++const [tokenAgentPayments] = getTokenAgentPaymentsPDA(mint);+const [buybackAuthority] = getBuybackAuthorityPDA(mint);+const [withdrawAuthority] = getWithdrawAuthorityPDA(mint);++const paymentVaultAta = getAssociatedTokenAddressSync(currencyMint, tokenAgentPayments, true, tokenProgram);+const buybackVaultAta = getAssociatedTokenAddressSync(currencyMint, buybackAuthority, true, tokenProgram);+const withdrawVaultAta = getAssociatedTokenAddressSync(currencyMint, withdrawAuthority, true, tokenProgram);+```++`PumpAgent.getBalances(currencyMint)` returns all three with their current balances.diff --git a/agent-payments-sdk/docs/x402.md b/agent-payments-sdk/docs/x402.mdnew file mode 100644index 000000000..17f1d8ade--- /dev/null+++ b/agent-payments-sdk/docs/x402.md@@ -0,0 +1,171 @@+# x402 — HTTP 402 Payment Required Protocol++The `x402` sub-package implements the [coinbase/x402 v2 specification](https://github.com/coinbase/x402) for pay-gating HTTP endpoints using on-chain Pump Agent invoice payments.++```ts+import { x402 } from "@pump-fun/agent-payments-sdk";+// or direct import:+import { createX402Fetch, PumpAgentFacilitator, buildPumpAgentRequirements } from "@pump-fun/agent-payments-sdk/x402";+```++---++## Server Side++### `buildPumpAgentRequirements(config)`++Build the `PaymentRequirements` array for a `402` response body.++```ts+const requirements = x402.buildPumpAgentRequirements({+ agentMint: "YourAgentMintAddress",+ payTo: "PaymentVaultAddress",+ amount: "1000000", // 1 USDC in minor units (6 decimals)+ asset: x402.USDC_MAINNET,+ network: x402.SOLANA_MAINNET,+ maxTimeoutSeconds: 60,+ memo: "12345",+ startTime: Math.floor(Date.now() / 1000),+ endTime: Math.floor(Date.now() / 1000) + 300,+});+```++### `PumpAgentFacilitator`++Server-side facilitator that verifies and settles payments. Implements `FacilitatorClient`.++```ts+const facilitator = new x402.PumpAgentFacilitator({+ connection,+ // optional: override verify/settle endpoints+});++// Verify a payment payload+const result = await facilitator.verify(payload, requirements);+if (!result.isValid) throw new Error(result.invalidReason);++// Settle+const settled = await facilitator.settle(payload, requirements);+```++### `createResourceServer(config)`++Creates an Express middleware that automatically handles `402` payment gating:++```ts+import express from "express";++const app = express();+const paymentMiddleware = x402.createResourceServer({+ facilitator,+ requirements,+ resource: {+ url: "https://api.agent.example/inference",+ description: "AI inference endpoint",+ },+});++app.use("/inference", paymentMiddleware, (req, res) => {+ res.json({ result: "..." });+});+```++---++## Client Side++### `createX402Fetch(config)`++Wraps `fetch` to automatically handle `402` responses — detects payment requirements, builds the invoice transaction, signs + sends it, then retries the original request.++```ts+const x402fetch = x402.createX402Fetch({+ payer: wallet.publicKey.toBase58(),+ signTransaction: async (txBase64) => {+ const tx = Transaction.from(Buffer.from(txBase64, "base64"));+ const signed = await wallet.signTransaction(tx);+ return Buffer.from(signed.serialize()).toString("base64");+ },+ sendTransaction: async (signedTxBase64) => {+ const sig = await connection.sendRawTransaction(+ Buffer.from(signedTxBase64, "base64")+ );+ return sig;+ },+ network: x402.SOLANA_MAINNET,+ confirmationTimeoutMs: 30_000,+});++// Use exactly like fetch — payment is handled automatically+const res = await x402fetch("https://api.agent.example/inference");+const data = await res.json();+```++---++## Header Helpers++```ts+import {+ encodePaymentRequired,+ decodePaymentRequired,+ encodePaymentPayload,+ decodePaymentPayload,+ encodePaymentResponse,+ decodePaymentResponse,+ getPaymentRequiredFromResponse,+ getPaymentPayloadFromRequest,+ getPaymentResponseFromResponse,+} from "@pump-fun/agent-payments-sdk/x402";+```++These encode/decode the three protocol headers as base64 JSON:++| Header constant | Value |+|---|---|+| `X402_HEADER_PAYMENT_REQUIRED` | `"PAYMENT-REQUIRED"` |+| `X402_HEADER_PAYMENT_SIGNATURE` | `"PAYMENT-SIGNATURE"` |+| `X402_HEADER_PAYMENT_RESPONSE` | `"PAYMENT-RESPONSE"` |++---++## Protocol Flow++```+Client Server Facilitator+ │ │ │+ │── GET /resource ─────────────►│ │+ │◄── 402 PAYMENT-REQUIRED ──────│ │+ │ { accepts: [...] } │ │+ │ │ │+ │ (build + sign + send tx) │ │+ │ │ │+ │── GET /resource ─────────────►│ │+ │ PAYMENT-SIGNATURE: <proof> │── verify(payload, req) ──────►│+ │ │◄── { isValid: true } ─────────│+ │ │── settle(payload, req) ───────►│+ │ │◄── { success: true, tx } ─────│+ │◄── 200 PAYMENT-RESPONSE ──────│ │+```++---++## Payment Schemes++### `"pump-agent"` scheme+On-chain invoice via `agentAcceptPayment`. The client calls the Pump Agent Payments program with the invoice params from `requirements.extra` (memo, startTime, endTime, agentMint). Verification checks the `invoiceId` PDA on-chain.++### `"exact"` scheme+Standard SPL `TransferChecked` — transfer tokens directly to `payTo`. No invoice PDA involved.++---++## Network & Asset Constants++```ts+x402.SOLANA_MAINNET // "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"+x402.SOLANA_DEVNET // "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"+x402.USDC_MAINNET // "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"+x402.USDC_DEVNET // "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU"+x402.X402_VERSION // 2+```diff --git a/agent-payments-sdk/jest.config.ts b/agent-payments-sdk/jest.config.tsnew file mode 100644index 000000000..eead7f910--- /dev/null+++ b/agent-payments-sdk/jest.config.ts@@ -0,0 +1,11 @@+import type { Config } from "jest";++const config: Config = {+ preset: "ts-jest/presets/default-esm",+ testEnvironment: "node",+ extensionsToTreatAsEsm: [".ts"],+ moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1" },+ transform: { "^.+\\.tsx?$": ["ts-jest", { useESM: true }] },+};++export default config;diff --git a/agent-payments-sdk/package.json b/agent-payments-sdk/package.jsonnew file mode 100644index 000000000..725de5f3b--- /dev/null+++ b/agent-payments-sdk/package.json@@ -0,0 +1,79 @@+{+ "name": "@pump-fun/agent-payments-sdk",+ "version": "3.0.1",+ "description": "TypeScript SDK for Pump Agent Payments",+ "publishConfig": {+ "access": "public"+ },+ "author": "Pump Fun",+ "license": "ISC",+ "type": "module",+ "main": "./dist/index.cjs",+ "module": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "import": "./dist/index.js",+ "require": "./dist/index.cjs"+ },+ "./x402": {+ "types": "./dist/x402/index.d.ts",+ "import": "./dist/x402/index.js",+ "require": "./dist/x402/index.cjs"+ },+ "./solana-agent-kit": {+ "types": "./dist/solana-agent-kit/index.d.ts",+ "import": "./dist/solana-agent-kit/index.js",+ "require": "./dist/solana-agent-kit/index.cjs"+ }+ },+ "files": [+ "dist"+ ],+ "scripts": {+ "build": "tsup",+ "build:prod": "tsup --minify",+ "dev": "tsup --watch",+ "typecheck": "tsc --noEmit",+ "lint": "eslint src/ --cache --quiet",+ "lint:fix": "eslint src/ --cache --fix --quiet",+ "clean": "rm -rf dist",+ "test": "node --experimental-vm-modules node_modules/.bin/jest",+ "prepublishOnly": "npm run typecheck && npm run build:prod"+ },+ "dependencies": {+ "@coral-xyz/anchor": "^0.31.1",+ "@solana/spl-token": "^0.4.9",+ "@solana/web3.js": "^1.98.0",+ "express": "^5.2.1",+ "express-rate-limit": "^8.3.1",+ "helmet": "^8.1.0"+ },+ "peerDependencies": {+ "zod": "^3.0.0"+ },+ "peerDependenciesMeta": {+ "zod": {+ "optional": true+ }+ },+ "optionalDependencies": {+ "@rollup/rollup-linux-x64-gnu": "*"+ },+ "devDependencies": {+ "@eslint/js": "^9.17.0",+ "@types/bn.js": "^5.2.0",+ "@types/express": "^5.0.6",+ "@types/jest": "^30.0.0",+ "@types/node": "^22.0.0",+ "eslint": "^9.17.0",+ "eslint-config-prettier": "^9.1.0",+ "jest": "^30.3.0",+ "ts-jest": "^29.4.6",+ "tsup": "^8.3.5",+ "typescript": "^5.7.3",+ "typescript-eslint": "^8.18.0",+ "zod": "^3.25.76"+ }+}diff --git a/agent-payments-sdk/src/PumpAgent.ts b/agent-payments-sdk/src/PumpAgent.tsnew file mode 100644index 000000000..526a0efa8--- /dev/null+++ b/agent-payments-sdk/src/PumpAgent.ts@@ -0,0 +1,416 @@+import {+ type Connection,+ PublicKey,+ type TransactionInstruction,+} from "@solana/web3.js";+import {+ TOKEN_PROGRAM_ID,+ getAssociatedTokenAddressSync,+} from "@solana/spl-token";+import { BN, EventParser } from "@coral-xyz/anchor";++import { PumpAgentOffline } from "./PumpAgentOffline";+import { getPumpProgramWithFallback } from "./program";+import {+ getBuybackAuthorityPDA,+ getGlobalConfigPDA,+ getInvoiceIdPDA,+ getPaymentInCurrencyPDA,+ getTokenAgentPaymentsPDA,+ getWithdrawAuthorityPDA,+} from "./pdas";+import type {+ AgentBalances,+ GlobalConfig,+ PumpEnvironment,+ TokenAgentPaymentInCurrency,+ TokenAgentPayments,+ UpdateBuybackBpsParams,+} from "./types";+import {+ parseAgentEvents,+ type AgentAcceptPaymentEvent,+ type ParsedAgentEvent,+} from "./events";++export class PumpAgent extends PumpAgentOffline {+ private connection?: Connection;+ private environment: PumpEnvironment;++ constructor(+ mint: PublicKey,+ environment: PumpEnvironment = "mainnet",+ connection?: Connection,+ ) {+ super(mint, getPumpProgramWithFallback(connection));+ this.connection = connection;+ this.environment = environment;+ }++ private get blockchainClientBaseUrl(): string {+ return this.environment === "devnet"+ ? "https://blockchain-client.internal.pump.fun"+ : "https://fun-block.pump.fun";+ }++ /**+ * Fetches the current balances for all three vaults for a given currency.+ * Returns the vault address and its token balance.+ * If a vault ATA does not exist yet the balance is reported as 0n.+ */+ async getBalances(+ currencyMint: PublicKey,+ currencyTokenProgram: PublicKey = TOKEN_PROGRAM_ID,+ ): Promise<AgentBalances> {+ const connection = this.connection;+ if (!connection) throw new Error("Connection is required");++ const [tokenAgentPayments] = getTokenAgentPaymentsPDA(this.mint);+ const [buybackAuthority] = getBuybackAuthorityPDA(this.mint);+ const [withdrawAuthority] = getWithdrawAuthorityPDA(this.mint);++ const paymentAta = getAssociatedTokenAddressSync(+ currencyMint,+ tokenAgentPayments,+ true,+ currencyTokenProgram,+ );+ const buybackAta = getAssociatedTokenAddressSync(+ currencyMint,+ buybackAuthority,+ true,+ currencyTokenProgram,+ );+ const withdrawAta = getAssociatedTokenAddressSync(+ currencyMint,+ withdrawAuthority,+ true,+ currencyTokenProgram,+ );++ const fetchBalance = async (ata: PublicKey): Promise<bigint> => {+ try {+ const resp = await connection.getTokenAccountBalance(ata);+ return BigInt(resp.value.amount);+ } catch {+ return 0n;+ }+ };++ const [paymentBal, buybackBal, withdrawBal] = await Promise.all([+ fetchBalance(paymentAta),+ fetchBalance(buybackAta),+ fetchBalance(withdrawAta),+ ]);++ return {+ paymentVault: { address: paymentAta, balance: paymentBal },+ buybackVault: { address: buybackAta, balance: buybackBal },+ withdrawVault: { address: withdrawAta, balance: withdrawBal },+ };+ }++ /**+ * Returns the `agent_update_buyback_bps` instruction and auto-fetches+ * supported currencies from GlobalConfig when options are omitted.+ */+ async updateBuybackBps(+ params: UpdateBuybackBpsParams,+ ): Promise<TransactionInstruction> {+ const { authority, buybackBps } = params;+ const [globalConfigPda] = getGlobalConfigPDA();++ const connection = this.connection;+ if (!connection) throw new Error("Connection is required");++ const globalConfigAccount =+ await this.program.account.GlobalConfig.fetch(globalConfigPda);++ const mints = globalConfigAccount.supportedCurrenciesMint.filter(+ (m: PublicKey) => !PublicKey.default.equals(m),+ );++ const accountInfos = await connection.getMultipleAccountsInfo(mints);++ const supportedCurrencies: { mint: PublicKey; tokenProgram: PublicKey }[] =+ [];+ for (const [idx, mint] of mints.entries()) {+ const info = accountInfos[idx];+ if (info) {+ supportedCurrencies.push({ mint, tokenProgram: info.owner });+ }+ }++ return super.updateBuybackBps(+ { authority, buybackBps },+ { supportedCurrencies },+ );+ }++ // ─── Account Fetch Helpers ──────────────────────────────────────────────++ /**+ * Fetch the on-chain TokenAgentPayments config for this agent's mint.+ * Returns the authority, buyback bps, and mint.+ */+ async getAgentConfig(): Promise<TokenAgentPayments> {+ const connection = this.connection;+ if (!connection) throw new Error("Connection is required");++ const [pda] = getTokenAgentPaymentsPDA(this.mint);+ return this.program.account.TokenAgentPayments.fetch(pda);+ }++ /**+ * Fetch the protocol-wide GlobalConfig account.+ * Returns authorities and the list of supported currency mints.+ */+ async getGlobalConfig(): Promise<GlobalConfig> {+ const connection = this.connection;+ if (!connection) throw new Error("Connection is required");++ const [pda] = getGlobalConfigPDA();+ return this.program.account.GlobalConfig.fetch(pda);+ }++ /**+ * Fetch the per-currency accounting stats for this agent.+ * Returns total payments, buybacks, withdrawals, and tokens burned.+ */+ async getPaymentStats(+ currencyMint: PublicKey,+ ): Promise<TokenAgentPaymentInCurrency> {+ const connection = this.connection;+ if (!connection) throw new Error("Connection is required");++ const [pda] = getPaymentInCurrencyPDA(this.mint, currencyMint);+ return this.program.account.TokenAgentPaymentInCurrency.fetch(pda);+ }++ /**+ * Fetch the list of supported currency mints from GlobalConfig,+ * filtered to only non-default (non-zero) entries.+ */+ async getSupportedCurrencies(): Promise<PublicKey[]> {+ const config = await this.getGlobalConfig();+ return config.supportedCurrenciesMint.filter(+ (m: PublicKey) => !PublicKey.default.equals(m),+ );+ }++ /**+ * Check whether the TokenAgentPayments account exists on-chain+ * (i.e. whether this agent has been initialized).+ */+ async isInitialized(): Promise<boolean> {+ const connection = this.connection;+ if (!connection) throw new Error("Connection is required");++ const [pda] = getTokenAgentPaymentsPDA(this.mint);+ const info = await connection.getAccountInfo(pda);+ return info !== null;+ }++ // ─── Payment History ────────────────────────────────────────────────────++ /**+ * Fetch recent payment events for this agent by scanning on-chain+ * transaction logs on the TokenAgentPayments PDA.+ *+ * @param limit - Maximum number of transactions to scan (default: 50)+ * @returns Parsed `AgentAcceptPaymentEvent`s in reverse chronological order+ */+ async getPaymentHistory(+ limit = 50,+ ): Promise<AgentAcceptPaymentEvent[]> {+ const connection = this.connection;+ if (!connection) throw new Error("Connection is required");++ const [tokenAgentPayments] = getTokenAgentPaymentsPDA(this.mint);+ const signatures = await connection.getSignaturesForAddress(+ tokenAgentPayments,+ { limit },+ );++ const payments: AgentAcceptPaymentEvent[] = [];++ for (const sig of signatures) {+ if (sig.err) continue;+ const tx = await connection.getTransaction(sig.signature, {+ maxSupportedTransactionVersion: 0,+ });+ if (!tx?.meta?.logMessages) continue;++ const events = parseAgentEvents(tx.meta.logMessages, connection);+ for (const event of events) {+ if (event.name === "agentAcceptPaymentEvent") {+ payments.push(event.data as AgentAcceptPaymentEvent);+ }+ }+ }++ return payments;+ }++ /**+ * Fetch all recent events for this agent (payments, distributions,+ * buybacks, withdrawals, etc.) from on-chain transaction logs.+ *+ * @param limit - Maximum number of transactions to scan (default: 50)+ */+ async getEventHistory(+ limit = 50,+ ): Promise<ParsedAgentEvent[]> {+ const connection = this.connection;+ if (!connection) throw new Error("Connection is required");++ const [tokenAgentPayments] = getTokenAgentPaymentsPDA(this.mint);+ const signatures = await connection.getSignaturesForAddress(+ tokenAgentPayments,+ { limit },+ );++ const allEvents: ParsedAgentEvent[] = [];++ for (const sig of signatures) {+ if (sig.err) continue;+ const tx = await connection.getTransaction(sig.signature, {+ maxSupportedTransactionVersion: 0,+ });+ if (!tx?.meta?.logMessages) continue;++ const events = parseAgentEvents(tx.meta.logMessages, connection);+ allEvents.push(...events);+ }++ return allEvents;+ }++ // ─── Invoice Validation ─────────────────────────────────────────────────++ async validateInvoicePayment(params: {+ user: PublicKey;+ currencyMint: PublicKey;+ amount: number;+ memo: number;+ startTime: number;+ endTime: number;+ }): Promise<boolean> {+ const { user, currencyMint } = params;+ const amount = new BN(params.amount);+ const memo = new BN(params.memo);+ const startTime = new BN(params.startTime);+ const endTime = new BN(params.endTime);++ const [invoiceId] = getInvoiceIdPDA(+ this.mint,+ currencyMint,+ amount,+ memo,+ startTime,+ endTime,+ );++ try {+ const url = new URL(+ "/agents/invoice-id",+ this.blockchainClientBaseUrl,+ );+ url.searchParams.set("invoice-id", invoiceId.toBase58());+ url.searchParams.set("mint", this.mint.toBase58());++ const response = await fetch(url.toString());+ if (response.ok) {+ const data = await response.json();+ return (+ data.user === user.toBase58() &&+ data.tokenized_agent_mint === this.mint.toBase58() &&+ data.currency_mint === currencyMint.toBase58() &&+ new BN(data.amount).eq(amount) &&+ new BN(data.memo).eq(memo) &&+ new BN(data.start_time).eq(startTime) &&+ new BN(data.end_time).eq(endTime)+ );+ }+ } catch {+ // Fall through to RPC validation+ }++ return this.validateInvoicePaymentViaRpc({+ user,+ currencyMint,+ amount,+ memo,+ startTime,+ endTime,+ });+ }++ /** RPC-based fallback: scans on-chain transaction logs for the payment event. */+ private async validateInvoicePaymentViaRpc(params: {+ user: PublicKey;+ currencyMint: PublicKey;+ amount: BN;+ memo: BN;+ startTime: BN;+ endTime: BN;+ }): Promise<boolean> {+ const { user, currencyMint, amount, memo, startTime, endTime } = params;+ const connection = this.connection;+ if (!connection) throw new Error("Connection is required");++ const [invoiceId] = getInvoiceIdPDA(+ this.mint,+ currencyMint,+ amount,+ memo,+ startTime,+ endTime,+ );++ const signatures = await connection.getSignaturesForAddress(invoiceId);++ for (const sig of signatures) {+ const tx = await connection.getTransaction(sig.signature, {+ maxSupportedTransactionVersion: 0,+ });+ if (!tx || tx.meta?.err) continue;++ const logs = tx.meta?.logMessages;+ if (!logs) continue;++ const parser = new EventParser(+ this.program.programId,+ this.program.coder,+ );++ for (const event of parser.parseLogs(logs)) {+ if (event.name !== "agentAcceptPaymentEvent") continue;++ const data = event.data as {+ user: PublicKey;+ tokenizedAgentMint: PublicKey;+ currencyMint: PublicKey;+ amount: BN;+ memo: BN;+ startTime: BN;+ endTime: BN;+ };++ if (+ data.user.equals(user) &&+ data.tokenizedAgentMint.equals(this.mint) &&+ data.currencyMint.equals(currencyMint) &&+ data.amount.eq(amount) &&+ data.memo.eq(memo) &&+ data.startTime.eq(startTime) &&+ data.endTime.eq(endTime)+ ) {+ return true;+ }+ }+ }++ return false;+ }+}diff --git a/agent-payments-sdk/src/PumpAgentOffline.ts b/agent-payments-sdk/src/PumpAgentOffline.tsnew file mode 100644index 000000000..931db430c--- /dev/null+++ b/agent-payments-sdk/src/PumpAgentOffline.ts@@ -0,0 +1,432 @@+import {+ ComputeBudgetProgram,+ PublicKey,+ SystemProgram,+ type Connection,+ type TransactionInstruction,+} from "@solana/web3.js";+import {+ getAssociatedTokenAddressSync,+ TOKEN_PROGRAM_ID,+ NATIVE_MINT,+ createAssociatedTokenAccountIdempotentInstruction,+ createSyncNativeInstruction,+ createCloseAccountInstruction,+} from "@solana/spl-token";+import { BN, type Program } from "@coral-xyz/anchor";++import type { PumpAgentPayments as PumpAgentPaymentsIDL } from "./idl/pump_agent_payments";+import { getPumpProgramWithFallback } from "./program";+import {+ getBondingCurvePDA,+ getBuybackAuthorityPDA,+ getGlobalConfigPDA,+ getInvoiceIdPDA,+ getPaymentInCurrencyPDA,+ getTokenAgentPaymentsPDA,+ getWithdrawAuthorityPDA,+} from "./pdas";+import type {+ AcceptPaymentParams,+ BuildAcceptPaymentParams,+ BuybackTriggerParams,+ CloseAccountParams,+ CreateParams,+ DistributePaymentsParams,+ ExtendAccountParams,+ UpdateAuthorityParams,+ UpdateBuybackBpsOptions,+ UpdateBuybackBpsParams,+ WithdrawParams,+} from "./types";++function toBN(value: bigint | number | string): BN {+ return new BN(value.toString());+}++export class PumpAgentOffline {+ readonly mint: PublicKey;+ protected readonly program: Program<PumpAgentPaymentsIDL>;++ static readonly DEFAULT_COMPUTE_UNIT_LIMIT_FOR_AGENT_PAYMENTS = 100_000;+ static readonly DEFAULT_PRIORITY_FEE_MICRO_LAMPORTS = 1_000;++ constructor(+ mint: PublicKey,+ program: Program<PumpAgentPaymentsIDL> = getPumpProgramWithFallback(),+ ) {+ this.mint = mint;+ this.program = program;+ }++ static load(+ mint: PublicKey,+ connection?: Connection,+ ): PumpAgentOffline {+ return new PumpAgentOffline(mint, getPumpProgramWithFallback(connection));+ }++ async create(params: CreateParams): Promise<TransactionInstruction> {+ const { authority, mint, agentAuthority, buybackBps } = params;+ const [bondingCurve] = getBondingCurvePDA(mint);+ const [tokenAgentPayments] = getTokenAgentPaymentsPDA(mint);++ return this.program.methods+ .agentInitialize(agentAuthority, buybackBps)+ .accountsPartial({+ authority,+ bondingCurve,+ mint,+ tokenAgentPayments,+ })+ .instruction();+ }++ async withdraw(params: WithdrawParams): Promise<TransactionInstruction> {+ const { authority, currencyMint, receiverAta, tokenProgram } = params;+ const tp = tokenProgram ?? TOKEN_PROGRAM_ID;+ const [tokenAgentPayments] = getTokenAgentPaymentsPDA(this.mint);+ const [withdrawAuthority] = getWithdrawAuthorityPDA(this.mint);+ const withdrawVault = getAssociatedTokenAddressSync(+ currencyMint,+ withdrawAuthority,+ true,+ tp,+ );++ return this.program.methods+ .agentWithdraw()+ .accountsPartial({+ authority,+ tokenAgentPayments,+ currencyMint,+ withdrawAuthority,+ withdrawVault,+ receiverAta,+ tokenProgram: tp,+ })+ .instruction();+ }++ async updateBuybackBps(+ params: UpdateBuybackBpsParams,+ options: UpdateBuybackBpsOptions,+ ): Promise<TransactionInstruction> {+ const { authority, buybackBps } = params;+ const supportedCurrencies = options.supportedCurrencies;+ const [tokenAgentPayments] = getTokenAgentPaymentsPDA(this.mint);+ const [globalConfig] = getGlobalConfigPDA();++ const remainingAccounts: {+ pubkey: PublicKey;+ isWritable: boolean;+ isSigner: boolean;+ }[] = [];++ for (const currency of supportedCurrencies) {+ if (currency.mint.equals(PublicKey.default)) continue;+ const ata = getAssociatedTokenAddressSync(+ currency.mint,+ tokenAgentPayments,+ true,+ currency.tokenProgram,+ );+ remainingAccounts.push({+ pubkey: ata,+ isWritable: false,+ isSigner: false,+ });+ }++ return this.program.methods+ .agentUpdateBuybackBps(buybackBps)+ .accountsPartial({+ authority,+ tokenAgentPayments,+ globalConfig,+ })+ .remainingAccounts(remainingAccounts)+ .instruction();+ }++ async acceptPayment(+ params: AcceptPaymentParams,+ ): Promise<TransactionInstruction> {+ const {+ user,+ userTokenAccount,+ currencyMint,+ amount,+ memo,+ startTime,+ endTime,+ tokenProgram,+ } = params;+ const tp = tokenProgram ?? TOKEN_PROGRAM_ID;+ const [tokenAgentPayments] = getTokenAgentPaymentsPDA(this.mint);+ const [globalConfig] = getGlobalConfigPDA();+ const [paymentInCurrency] = getPaymentInCurrencyPDA(+ this.mint,+ currencyMint,+ );+ const [invoiceId] = getInvoiceIdPDA(+ this.mint,+ currencyMint,+ amount,+ memo,+ startTime,+ endTime,+ );+ const tokenAgentAssociatedAccount = getAssociatedTokenAddressSync(+ currencyMint,+ tokenAgentPayments,+ true,+ tp,+ );++ return this.program.methods+ .agentAcceptPayment(amount, memo, startTime, endTime)+ .accountsPartial({+ user,+ userTokenAccount,+ tokenAgentPayments,+ tokenAgentAssociatedAccount,+ tokenAgentPaymentInCurrency: paymentInCurrency,+ globalConfig,+ invoiceId,+ currencyMint,+ tokenProgram: tp,+ })+ .instruction();+ }++ async buildAcceptPaymentInstructions(+ params: BuildAcceptPaymentParams,+ ): Promise<TransactionInstruction[]> {+ const { user, currencyMint } = params;+ const computeUnitLimit =+ params.computeUnitLimit ??+ PumpAgentOffline.DEFAULT_COMPUTE_UNIT_LIMIT_FOR_AGENT_PAYMENTS;+ const tp = params.tokenProgram ?? TOKEN_PROGRAM_ID;++ const userTokenAccount = getAssociatedTokenAddressSync(+ currencyMint,+ user,+ false,+ tp,+ );++ const acceptIx = await this.acceptPayment({+ user,+ userTokenAccount,+ currencyMint,+ amount: toBN(params.amount),+ memo: toBN(params.memo),+ startTime: toBN(params.startTime),+ endTime: toBN(params.endTime),+ tokenProgram: params.tokenProgram,+ });++ const ixs: TransactionInstruction[] = [+ ComputeBudgetProgram.setComputeUnitLimit({ units: computeUnitLimit }),+ ];++ if (params.computeUnitPrice != null) {+ ixs.push(+ ComputeBudgetProgram.setComputeUnitPrice({+ microLamports: params.computeUnitPrice,+ }),+ );+ }++ if (currencyMint.equals(NATIVE_MINT)) {+ return [+ ...ixs,+ createAssociatedTokenAccountIdempotentInstruction(+ user,+ userTokenAccount,+ user,+ NATIVE_MINT,+ ),+ SystemProgram.transfer({+ fromPubkey: user,+ toPubkey: userTokenAccount,+ lamports: BigInt(params.amount.toString()),+ }),+ createSyncNativeInstruction(userTokenAccount),+ acceptIx,+ createCloseAccountInstruction(userTokenAccount, user, user),+ ];+ }++ return [...ixs, acceptIx];+ }++ async distributePayments(+ params: DistributePaymentsParams,+ ): Promise<TransactionInstruction[]> {+ const {+ user,+ currencyMint,+ tokenProgram,+ includeTransferExtraLamportsForNative = false,+ } = params;+ const tp = tokenProgram ?? TOKEN_PROGRAM_ID;+ const [tokenAgentPayments] = getTokenAgentPaymentsPDA(this.mint);+ const [globalConfig] = getGlobalConfigPDA();+ const [paymentInCurrency] = getPaymentInCurrencyPDA(+ this.mint,+ currencyMint,+ );+ const [buybackAuthority] = getBuybackAuthorityPDA(this.mint);+ const [withdrawAuthority] = getWithdrawAuthorityPDA(this.mint);++ const tokenAgentAssociatedAccount = getAssociatedTokenAddressSync(+ currencyMint,+ tokenAgentPayments,+ true,+ tp,+ );+ const buybackVault = getAssociatedTokenAddressSync(+ currencyMint,+ buybackAuthority,+ true,+ tp,+ );+ const withdrawVault = getAssociatedTokenAddressSync(+ currencyMint,+ withdrawAuthority,+ true,+ tp,+ );++ const distributeIx = await this.program.methods+ .agentDistributePayments()+ .accountsPartial({+ user,+ globalConfig,+ currencyMint,+ tokenAgentPayments,+ tokenAgentPaymentInCurrency: paymentInCurrency,+ tokenAgentAssociatedAccount,+ buybackAuthority,+ withdrawAuthority,+ buybackVault,+ withdrawVault,+ tokenProgram: tp,+ })+ .instruction();++ if (includeTransferExtraLamportsForNative && currencyMint.equals(NATIVE_MINT)) {+ const transferIx = await this.program.methods+ .agentTransferExtraLamports()+ .accountsPartial({+ tokenAgentPayments,+ tokenAgentAssociatedAccount,+ })+ .instruction();+ return [transferIx, distributeIx];+ }++ return [distributeIx];+ }++ async buybackTrigger(+ params: BuybackTriggerParams,+ ): Promise<TransactionInstruction> {+ const {+ globalBuybackAuthority,+ currencyMint,+ swapProgramToInvoke,+ swapInstructionData,+ remainingAccounts,+ tokenProgramCurrency,+ tokenProgram,+ } = params;+ const tp = tokenProgram ?? TOKEN_PROGRAM_ID;+ const tpCurrency = tokenProgramCurrency ?? TOKEN_PROGRAM_ID;+ const [tokenAgentPayments] = getTokenAgentPaymentsPDA(this.mint);+ const [globalConfig] = getGlobalConfigPDA();+ const [buybackAuthority] = getBuybackAuthorityPDA(this.mint);+ const [paymentInCurrency] = getPaymentInCurrencyPDA(+ this.mint,+ currencyMint,+ );+ const burnMintVault = getAssociatedTokenAddressSync(+ this.mint,+ buybackAuthority,+ true,+ tp,+ );+ const burnCurrencyMintVault = getAssociatedTokenAddressSync(+ currencyMint,+ buybackAuthority,+ true,+ tpCurrency,+ );++ return this.program.methods+ .agentBuybackTrigger(swapInstructionData)+ .accountsPartial({+ globalBuybackAuthority,+ mint: this.mint,+ tokenAgentPayments,+ tokenAgentPaymentInCurrency: paymentInCurrency,+ currencyMint,+ globalConfig,+ swapProgramToInvoke,+ burnAuthority: buybackAuthority,+ burnMintVault,+ burnCurrencyMintVault,+ tokenProgram: tp,+ tokenProgramCurrency: tpCurrency,+ })+ .remainingAccounts(remainingAccounts)+ .instruction();+ }++ async extendAccount(+ params: ExtendAccountParams,+ ): Promise<TransactionInstruction> {+ const { account, user } = params;+ return this.program.methods+ .extendAccount()+ .accountsPartial({ account, user })+ .instruction();+ }++ async updateAuthority(+ params: UpdateAuthorityParams,+ ): Promise<TransactionInstruction> {+ const { authority, newAuthority } = params;+ const [tokenAgentPayments] = getTokenAgentPaymentsPDA(this.mint);++ return this.program.methods+ .agentUpdateAuthority(newAuthority)+ .accountsPartial({+ authority,+ tokenAgentPayments,+ })+ .instruction();+ }++ /**+ * Returns the `close_account` instruction to close a program account+ * and reclaim its rent-exempt lamports.+ */+ async closeAccount(+ params: CloseAccountParams,+ ): Promise<TransactionInstruction> {+ const { account, user } = params;+ const [globalConfig] = getGlobalConfigPDA();++ return this.program.methods+ .closeAccount()+ .accountsPartial({+ account,+ user,+ globalConfig,+ })+ .instruction();+ }+}diff --git a/agent-payments-sdk/src/decoders.ts b/agent-payments-sdk/src/decoders.tsnew file mode 100644index 000000000..922507469--- /dev/null+++ b/agent-payments-sdk/src/decoders.ts@@ -0,0 +1,31 @@+import { OFFLINE_PUMP_PROGRAM } from "./program";+import type {+ GlobalConfig,+ TokenAgentPaymentInCurrency,+ TokenAgentPayments,+} from "./types";++export function decodeGlobalConfig(accountData: Buffer): GlobalConfig {+ return OFFLINE_PUMP_PROGRAM.coder.accounts.decode(+ "globalConfig",+ accountData,+ );+}++export function decodeTokenAgentPaymentInCurrency(+ accountData: Buffer,+): TokenAgentPaymentInCurrency {+ return OFFLINE_PUMP_PROGRAM.coder.accounts.decode(+ "tokenAgentPaymentInCurrency",+ accountData,+ );+}++export function decodeTokenAgentPayments(+ accountData: Buffer,+): TokenAgentPayments {+ return OFFLINE_PUMP_PROGRAM.coder.accounts.decode(+ "tokenAgentPayments",+ accountData,+ );+}diff --git a/agent-payments-sdk/src/events.ts b/agent-payments-sdk/src/events.tsnew file mode 100644index 000000000..2aa47876a--- /dev/null+++ b/agent-payments-sdk/src/events.ts@@ -0,0 +1,242 @@+import { PublicKey, type Connection } from "@solana/web3.js";+import { BN, EventParser, type Program } from "@coral-xyz/anchor";+import type { PumpAgentPayments as PumpAgentPaymentsIDL } from "./idl/pump_agent_payments";+import { getPumpProgramWithFallback, OFFLINE_PUMP_PROGRAM } from "./program";++// ─── Typed Event Interfaces ─────────────────────────────────────────────────++export interface AgentAcceptPaymentEvent {+ user: PublicKey;+ tokenizedAgentMint: PublicKey;+ tokenAgentPayments: PublicKey;+ currencyMint: PublicKey;+ amount: BN;+ memo: BN;+ startTime: BN;+ endTime: BN;+ invoiceId: PublicKey;+ agentPostBalance: BN;+ timestamp: BN;+}++export interface AgentBuybackTriggerEvent {+ tokenizedAgentMint: PublicKey;+ currencyMint: PublicKey;+ amountBurned: BN;+ swapProgram: PublicKey;+ newTokensBoughtAndBurnedForCurrency: BN;+ agentPostBalance: BN;+ timestamp: BN;+ currencyMintAmountForBuyback: BN;+}++export interface AgentDistributePaymentsEvent {+ tokenAgentPayments: PublicKey;+ currencyMint: PublicKey;+ buybackBps: number;+ buybackAmount: BN;+ withdrawAmount: BN;+ timestamp: BN;+}++export interface AgentInitializeEvent {+ tokenAgentPayments: PublicKey;+ mint: PublicKey;+ authority: PublicKey;+ buybackBps: number;+ timestamp: BN;+ tokenizedAgentSequence: BN;+}++export interface AgentUpdateAuthorityEvent {+ tokenAgentPayments: PublicKey;+ oldAuthority: PublicKey;+ newAuthority: PublicKey;+ timestamp: BN;+}++export interface AgentUpdateBuybackBpsEvent {+ tokenAgentPayments: PublicKey;+ mint: PublicKey;+ oldBuybackBps: number;+ newBuybackBps: number;+ timestamp: BN;+}++export interface AgentWithdrawEvent {+ tokenizedAgentMint: PublicKey;+ currencyMint: PublicKey;+ amount: BN;+ receiver: PublicKey;+ timestamp: BN;+}++export interface ExtendAccountEvent {+ account: PublicKey;+ user: PublicKey;+ currentSize: BN;+ newSize: BN;+ timestamp: BN;+}++export interface GlobalAddNewCurrencyEvent {+ globalConfig: PublicKey;+ currencyMint: PublicKey;+ timestamp: BN;+}++export interface GlobalConfigInitializeEvent {+ globalConfig: PublicKey;+ protocolAuthority: PublicKey;+ buybackAuthority: PublicKey;+ timestamp: BN;+}++export interface GlobalUpdateAuthoritiesEvent {+ globalConfig: PublicKey;+ protocolAuthority: PublicKey | null;+ buybackAuthority: PublicKey | null;+ timestamp: BN;+}++// ─── Event Name Union ───────────────────────────────────────────────────────++export type AgentEventName =+ | "agentAcceptPaymentEvent"+ | "agentBuybackTriggerEvent"+ | "agentDistributePaymentsEvent"+ | "agentInitializeEvent"+ | "agentUpdateAuthorityEvent"+ | "agentUpdateBuybackBpsEvent"+ | "agentWithdrawEvent"+ | "extendAccountEvent"+ | "globalAddNewCurrencyEvent"+ | "globalConfigInitializeEvent"+ | "globalUpdateAuthoritiesEvent";++export type AgentEventData =+ | AgentAcceptPaymentEvent+ | AgentBuybackTriggerEvent+ | AgentDistributePaymentsEvent+ | AgentInitializeEvent+ | AgentUpdateAuthorityEvent+ | AgentUpdateBuybackBpsEvent+ | AgentWithdrawEvent+ | ExtendAccountEvent+ | GlobalAddNewCurrencyEvent+ | GlobalConfigInitializeEvent+ | GlobalUpdateAuthoritiesEvent;++export interface ParsedAgentEvent<+ T extends AgentEventData = AgentEventData,+> {+ name: AgentEventName;+ data: T;+}++// ─── Event Parser ───────────────────────────────────────────────────────────++/**+ * Create an Anchor EventParser bound to the Pump Agent Payments program.+ * Works offline (no connection required) or with a connection.+ */+export function createEventParser(+ connection?: Connection,+): EventParser {+ const program: Program<PumpAgentPaymentsIDL> = connection+ ? getPumpProgramWithFallback(connection)+ : OFFLINE_PUMP_PROGRAM;+ return new EventParser(program.programId, program.coder);+}++/**+ * Parse transaction log messages into typed agent events.+ *+ * @example+ * ```ts+ * const tx = await connection.getTransaction(sig, { maxSupportedTransactionVersion: 0 });+ * const events = parseAgentEvents(tx.meta.logMessages);+ * for (const event of events) {+ * if (event.name === "agentAcceptPaymentEvent") {+ * console.log("Payment:", event.data.amount.toString());+ * }+ * }+ * ```+ */+export function parseAgentEvents(+ logs: string[],+ connection?: Connection,+): ParsedAgentEvent[] {+ const parser = createEventParser(connection);+ const events: ParsedAgentEvent[] = [];++ for (const event of parser.parseLogs(logs)) {+ events.push({+ name: event.name as AgentEventName,+ data: event.data as AgentEventData,+ });+ }++ return events;+}++// ─── Event Subscription ─────────────────────────────────────────────────────++export interface EventSubscriptionOptions {+ /** Filter to specific event names. If omitted, all events are emitted. */+ eventNames?: AgentEventName[];+}++export interface EventSubscription {+ /** Stop listening and clean up the WebSocket subscription. */+ unsubscribe(): void;+}++/**+ * Subscribe to real-time Pump Agent Payments program events via WebSocket.+ * Calls the provided callback whenever a matching event is detected.+ *+ * @example+ * ```ts+ * const sub = subscribeToAgentEvents(connection, (event, slot) => {+ * console.log(`[slot ${slot}] ${event.name}`, event.data);+ * }, { eventNames: ["agentAcceptPaymentEvent"] });+ *+ * // Later: stop listening+ * sub.unsubscribe();+ * ```+ */+export function subscribeToAgentEvents(+ connection: Connection,+ callback: (event: ParsedAgentEvent, slot: number) => void,+ options?: EventSubscriptionOptions,+): EventSubscription {+ const parser = createEventParser(connection);+ const filterNames = options?.eventNames+ ? new Set(options.eventNames)+ : null;++ const subId = connection.onLogs(+ OFFLINE_PUMP_PROGRAM.programId,+ (logInfo, ctx) => {+ if (logInfo.err) return;++ for (const event of parser.parseLogs(logInfo.logs)) {+ const parsed: ParsedAgentEvent = {+ name: event.name as AgentEventName,+ data: event.data as AgentEventData,+ };++ if (filterNames && !filterNames.has(parsed.name)) continue;+ callback(parsed, ctx.slot);+ }+ },+ "confirmed",+ );++ return {+ unsubscribe() {+ connection.removeOnLogsListener(subId);+ },+ };+}diff --git a/agent-payments-sdk/src/idl/pump_agent_payments.json b/agent-payments-sdk/src/idl/pump_agent_payments.jsonnew file mode 100644index 000000000..40015e533--- /dev/null+++ b/agent-payments-sdk/src/idl/pump_agent_payments.json@@ -0,0 +1,766 @@+{+ "address": "AgenTMiC2hvxGebTsgmsD4HHBa8WEcqGFf87iwRRxLo7",+ "metadata": {+ "name": "pump_agent_payments",+ "version": "0.1.0",+ "spec": "0.1.0",+ "description": "Created with Anchor"+ },+ "instructions": [+ {+ "name": "agent_accept_payment",+ "discriminator": [34, 157, 64, 220, 74, 32, 48, 225],+ "accounts": [+ { "name": "user", "writable": true, "signer": true },+ { "name": "user_token_account", "writable": true },+ { "name": "token_agent_payments" },+ {+ "name": "token_agent_associated_account",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "account", "path": "token_agent_payments" },+ {+ "kind": "const",+ "value": [6,221,246,225,215,101,161,147,217,203,225,70,206,235,121,172,28,180,133,237,95,91,55,145,58,140,245,133,126,255,0,169]+ },+ { "kind": "account", "path": "currency_mint" }+ ],+ "program": {+ "kind": "const",+ "value": [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89]+ }+ }+ },+ {+ "name": "token_agent_payment_in_currency",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "const", "value": [112,97,121,109,101,110,116,45,105,110,45,99,117,114,114,101,110,99,121] },+ { "kind": "account", "path": "token_agent_payments.mint", "account": "TokenAgentPayments" },+ { "kind": "account", "path": "currency_mint" }+ ]+ }+ },+ {+ "name": "global_config",+ "pda": { "seeds": [{ "kind": "const", "value": [103,108,111,98,97,108,45,99,111,110,102,105,103] }] }+ },+ { "name": "invoice_id" },+ { "name": "currency_mint" },+ { "name": "token_program" },+ { "name": "associated_token_program", "address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" },+ { "name": "system_program", "address": "11111111111111111111111111111111" },+ {+ "name": "event_authority",+ "pda": { "seeds": [{ "kind": "const", "value": [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] }+ },+ { "name": "program" }+ ],+ "args": [+ { "name": "amount", "type": "u64" },+ { "name": "memo", "type": "u64" },+ { "name": "start_time", "type": "i64" },+ { "name": "end_time", "type": "i64" }+ ]+ },+ {+ "name": "agent_buyback_trigger",+ "discriminator": [95, 231, 193, 2, 245, 75, 125, 155],+ "accounts": [+ { "name": "global_buyback_authority", "writable": true, "signer": true },+ { "name": "mint", "writable": true },+ {+ "name": "token_agent_payments",+ "pda": {+ "seeds": [+ { "kind": "const", "value": [116,111,107,101,110,45,97,103,101,110,116,45,112,97,121,109,101,110,116,115] },+ { "kind": "account", "path": "mint" }+ ]+ }+ },+ {+ "name": "token_agent_payment_in_currency",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "const", "value": [112,97,121,109,101,110,116,45,105,110,45,99,117,114,114,101,110,99,121] },+ { "kind": "account", "path": "token_agent_payments.mint", "account": "TokenAgentPayments" },+ { "kind": "account", "path": "currency_mint" }+ ]+ }+ },+ { "name": "currency_mint" },+ {+ "name": "global_config",+ "pda": { "seeds": [{ "kind": "const", "value": [103,108,111,98,97,108,45,99,111,110,102,105,103] }] }+ },+ { "name": "swap_program_to_invoke" },+ {+ "name": "burn_authority",+ "docs": ["Intentionally called burn_authority", "TO avoid any confusion with the global buyback authority."],+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "const", "value": [98,117,121,98,97,99,107,45,97,117,116,104,111,114,105,116,121] },+ { "kind": "account", "path": "token_agent_payments.mint", "account": "TokenAgentPayments" }+ ]+ }+ },+ {+ "name": "burn_mint_vault",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "account", "path": "burn_authority" },+ { "kind": "account", "path": "token_program" },+ { "kind": "account", "path": "mint" }+ ],+ "program": {+ "kind": "const",+ "value": [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89]+ }+ }+ },+ {+ "name": "burn_currency_mint_vault",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "account", "path": "burn_authority" },+ { "kind": "account", "path": "token_program_currency" },+ { "kind": "account", "path": "currency_mint" }+ ],+ "program": {+ "kind": "const",+ "value": [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89]+ }+ }+ },+ { "name": "token_program" },+ { "name": "token_program_currency" },+ { "name": "associated_token_program", "address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" },+ { "name": "system_program", "address": "11111111111111111111111111111111" },+ {+ "name": "event_authority",+ "pda": { "seeds": [{ "kind": "const", "value": [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] }+ },+ { "name": "program" }+ ],+ "args": [+ { "name": "swap_instruction_data", "type": "bytes" }+ ]+ },+ {+ "name": "agent_distribute_payments",+ "discriminator": [145, 44, 246, 47, 192, 204, 95, 32],+ "accounts": [+ { "name": "user", "writable": true, "signer": true },+ {+ "name": "global_config",+ "pda": { "seeds": [{ "kind": "const", "value": [103,108,111,98,97,108,45,99,111,110,102,105,103] }] }+ },+ { "name": "currency_mint" },+ { "name": "token_agent_payments", "writable": true },+ {+ "name": "token_agent_payment_in_currency",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "const", "value": [112,97,121,109,101,110,116,45,105,110,45,99,117,114,114,101,110,99,121] },+ { "kind": "account", "path": "token_agent_payments.mint", "account": "TokenAgentPayments" },+ { "kind": "account", "path": "currency_mint" }+ ]+ }+ },+ {+ "name": "token_agent_associated_account",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "account", "path": "token_agent_payments" },+ { "kind": "const", "value": [6,221,246,225,215,101,161,147,217,203,225,70,206,235,121,172,28,180,133,237,95,91,55,145,58,140,245,133,126,255,0,169] },+ { "kind": "account", "path": "currency_mint" }+ ],+ "program": {+ "kind": "const",+ "value": [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89]+ }+ }+ },+ {+ "name": "buyback_authority",+ "pda": {+ "seeds": [+ { "kind": "const", "value": [98,117,121,98,97,99,107,45,97,117,116,104,111,114,105,116,121] },+ { "kind": "account", "path": "token_agent_payments.mint", "account": "TokenAgentPayments" }+ ]+ }+ },+ {+ "name": "withdraw_authority",+ "pda": {+ "seeds": [+ { "kind": "const", "value": [119,105,116,104,100,114,97,119,45,97,117,116,104,111,114,105,116,121] },+ { "kind": "account", "path": "token_agent_payments.mint", "account": "TokenAgentPayments" }+ ]+ }+ },+ {+ "name": "buyback_vault",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "account", "path": "buyback_authority" },+ { "kind": "const", "value": [6,221,246,225,215,101,161,147,217,203,225,70,206,235,121,172,28,180,133,237,95,91,55,145,58,140,245,133,126,255,0,169] },+ { "kind": "account", "path": "currency_mint" }+ ],+ "program": {+ "kind": "const",+ "value": [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89]+ }+ }+ },+ {+ "name": "withdraw_vault",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "account", "path": "withdraw_authority" },+ { "kind": "const", "value": [6,221,246,225,215,101,161,147,217,203,225,70,206,235,121,172,28,180,133,237,95,91,55,145,58,140,245,133,126,255,0,169] },+ { "kind": "account", "path": "currency_mint" }+ ],+ "program": {+ "kind": "const",+ "value": [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89]+ }+ }+ },+ { "name": "token_program" },+ { "name": "associated_token_program", "address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" },+ { "name": "system_program", "address": "11111111111111111111111111111111" },+ {+ "name": "event_authority",+ "pda": { "seeds": [{ "kind": "const", "value": [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] }+ },+ { "name": "program" }+ ],+ "args": []+ },+ {+ "name": "agent_initialize",+ "discriminator": [180, 248, 163, 8, 49, 94, 126, 96],+ "accounts": [+ { "name": "authority", "writable": true, "signer": true },+ {+ "name": "bonding_curve",+ "pda": {+ "seeds": [+ { "kind": "const", "value": [98,111,110,100,105,110,103,45,99,117,114,118,101] },+ { "kind": "account", "path": "mint" }+ ],+ "program": {+ "kind": "const",+ "value": [1,86,224,246,147,102,90,207,68,219,21,104,191,23,91,170,81,137,203,151,245,210,255,59,101,93,43,182,253,109,24,176]+ }+ }+ },+ {+ "name": "global_config",+ "writable": true,+ "pda": { "seeds": [{ "kind": "const", "value": [103,108,111,98,97,108,45,99,111,110,102,105,103] }] }+ },+ { "name": "mint" },+ {+ "name": "token_agent_payments",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "const", "value": [116,111,107,101,110,45,97,103,101,110,116,45,112,97,121,109,101,110,116,115] },+ { "kind": "account", "path": "mint" }+ ]+ }+ },+ { "name": "system_program", "address": "11111111111111111111111111111111" },+ {+ "name": "event_authority",+ "pda": { "seeds": [{ "kind": "const", "value": [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] }+ },+ { "name": "program" }+ ],+ "args": [+ { "name": "authority", "type": "pubkey" },+ { "name": "buyback_bps", "type": "u16" }+ ]+ },+ {+ "name": "agent_transfer_extra_lamports",+ "discriminator": [39, 206, 214, 167, 55, 44, 221, 81],+ "accounts": [+ {+ "name": "token_agent_payments",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "const", "value": [116,111,107,101,110,45,97,103,101,110,116,45,112,97,121,109,101,110,116,115] },+ { "kind": "account", "path": "token_agent_payments.mint", "account": "TokenAgentPayments" }+ ]+ }+ },+ {+ "name": "token_agent_associated_account",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "account", "path": "token_agent_payments" },+ { "kind": "const", "value": [6,221,246,225,215,101,161,147,217,203,225,70,206,235,121,172,28,180,133,237,95,91,55,145,58,140,245,133,126,255,0,169] },+ { "kind": "const", "value": [6,155,136,87,254,171,129,132,251,104,127,99,70,24,192,53,218,196,57,220,26,235,59,85,152,160,240,0,0,0,0,1] }+ ],+ "program": {+ "kind": "const",+ "value": [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89]+ }+ }+ }+ ],+ "args": []+ },+ {+ "name": "agent_update_authority",+ "discriminator": [237, 228, 227, 224, 226, 198, 167, 83],+ "accounts": [+ { "name": "authority", "writable": true, "signer": true },+ {+ "name": "global_config",+ "pda": { "seeds": [{ "kind": "const", "value": [103,108,111,98,97,108,45,99,111,110,102,105,103] }] }+ },+ { "name": "token_agent_payments", "writable": true },+ { "name": "system_program", "address": "11111111111111111111111111111111" },+ {+ "name": "event_authority",+ "pda": { "seeds": [{ "kind": "const", "value": [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] }+ },+ { "name": "program" }+ ],+ "args": [+ { "name": "new_authority", "type": "pubkey" }+ ]+ },+ {+ "name": "agent_update_buyback_bps",+ "discriminator": [41, 28, 118, 90, 53, 24, 63, 160],+ "accounts": [+ { "name": "authority", "writable": true, "signer": true },+ { "name": "token_agent_payments", "writable": true },+ {+ "name": "global_config",+ "pda": { "seeds": [{ "kind": "const", "value": [103,108,111,98,97,108,45,99,111,110,102,105,103] }] }+ },+ {+ "name": "event_authority",+ "pda": { "seeds": [{ "kind": "const", "value": [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] }+ },+ { "name": "program" }+ ],+ "args": [+ { "name": "buyback_bps", "type": "u16" }+ ]+ },+ {+ "name": "agent_withdraw",+ "discriminator": [13, 149, 99, 245, 171, 171, 185, 53],+ "accounts": [+ { "name": "authority", "writable": true, "signer": true },+ { "name": "token_agent_payments" },+ { "name": "currency_mint" },+ {+ "name": "withdraw_authority",+ "pda": {+ "seeds": [+ { "kind": "const", "value": [119,105,116,104,100,114,97,119,45,97,117,116,104,111,114,105,116,121] },+ { "kind": "account", "path": "token_agent_payments.mint", "account": "TokenAgentPayments" }+ ]+ }+ },+ {+ "name": "withdraw_vault",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "account", "path": "withdraw_authority" },+ { "kind": "const", "value": [6,221,246,225,215,101,161,147,217,203,225,70,206,235,121,172,28,180,133,237,95,91,55,145,58,140,245,133,126,255,0,169] },+ { "kind": "account", "path": "currency_mint" }+ ],+ "program": {+ "kind": "const",+ "value": [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89]+ }+ }+ },+ { "name": "receiver_ata", "writable": true },+ { "name": "token_program" },+ { "name": "associated_token_program", "address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" },+ { "name": "system_program", "address": "11111111111111111111111111111111" },+ {+ "name": "event_authority",+ "pda": { "seeds": [{ "kind": "const", "value": [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] }+ },+ { "name": "program" }+ ],+ "args": []+ },+ {+ "name": "close_account",+ "discriminator": [125, 255, 149, 14, 110, 34, 72, 24],+ "accounts": [+ { "name": "account", "writable": true },+ { "name": "user", "writable": true, "signer": true },+ {+ "name": "global_config",+ "pda": { "seeds": [{ "kind": "const", "value": [103,108,111,98,97,108,45,99,111,110,102,105,103] }] }+ },+ { "name": "system_program", "address": "11111111111111111111111111111111" }+ ],+ "args": []+ },+ {+ "name": "extend_account",+ "discriminator": [234, 102, 194, 203, 150, 72, 62, 229],+ "accounts": [+ { "name": "account", "writable": true },+ { "name": "user", "writable": true, "signer": true },+ { "name": "system_program", "address": "11111111111111111111111111111111" },+ {+ "name": "event_authority",+ "pda": { "seeds": [{ "kind": "const", "value": [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] }+ },+ { "name": "program" }+ ],+ "args": []+ },+ {+ "name": "global_add_new_currency",+ "discriminator": [46, 135, 47, 120, 118, 204, 177, 224],+ "accounts": [+ { "name": "authority", "writable": true, "signer": true },+ {+ "name": "global_config",+ "writable": true,+ "pda": { "seeds": [{ "kind": "const", "value": [103,108,111,98,97,108,45,99,111,110,102,105,103] }] }+ },+ { "name": "mint" },+ {+ "name": "event_authority",+ "pda": { "seeds": [{ "kind": "const", "value": [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] }+ },+ { "name": "program" }+ ],+ "args": []+ },+ {+ "name": "global_config_initialize",+ "discriminator": [61, 23, 208, 192, 232, 52, 8, 66],+ "accounts": [+ { "name": "authority", "writable": true, "signer": true },+ {+ "name": "global_config",+ "writable": true,+ "pda": { "seeds": [{ "kind": "const", "value": [103,108,111,98,97,108,45,99,111,110,102,105,103] }] }+ },+ { "name": "system_program", "address": "11111111111111111111111111111111" },+ {+ "name": "event_authority",+ "pda": { "seeds": [{ "kind": "const", "value": [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] }+ },+ { "name": "program" }+ ],+ "args": [+ { "name": "protocol_authority", "type": "pubkey" },+ { "name": "buyback_authority", "type": "pubkey" }+ ]+ },+ {+ "name": "global_remove_currency",+ "discriminator": [57, 226, 180, 140, 91, 14, 231, 196],+ "accounts": [+ { "name": "authority", "writable": true, "signer": true },+ {+ "name": "global_config",+ "writable": true,+ "pda": { "seeds": [{ "kind": "const", "value": [103,108,111,98,97,108,45,99,111,110,102,105,103] }] }+ },+ {+ "name": "event_authority",+ "pda": { "seeds": [{ "kind": "const", "value": [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] }+ },+ { "name": "program" }+ ],+ "args": [+ { "name": "index", "type": "u8" }+ ]+ },+ {+ "name": "global_update_authorities",+ "discriminator": [91, 137, 72, 77, 183, 184, 168, 125],+ "accounts": [+ { "name": "authority", "writable": true, "signer": true },+ {+ "name": "global_config",+ "writable": true,+ "pda": { "seeds": [{ "kind": "const", "value": [103,108,111,98,97,108,45,99,111,110,102,105,103] }] }+ },+ {+ "name": "event_authority",+ "pda": { "seeds": [{ "kind": "const", "value": [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] }+ },+ { "name": "program" }+ ],+ "args": [+ { "name": "protocol_authority", "type": { "option": "pubkey" } },+ { "name": "buyback_authority", "type": { "option": "pubkey" } }+ ]+ }+ ],+ "accounts": [+ { "name": "BondingCurve", "discriminator": [23, 183, 248, 55, 96, 216, 172, 96] },+ { "name": "GlobalConfig", "discriminator": [149, 8, 156, 202, 160, 252, 176, 217] },+ { "name": "TokenAgentPaymentInCurrency", "discriminator": [225, 195, 81, 227, 115, 43, 25, 177] },+ { "name": "TokenAgentPayments", "discriminator": [136, 241, 242, 217, 173, 77, 112, 186] }+ ],+ "events": [+ { "name": "AgentAcceptPaymentEvent", "discriminator": [114, 190, 188, 192, 105, 79, 41, 147] },+ { "name": "AgentBuybackTriggerEvent", "discriminator": [139, 240, 9, 225, 214, 63, 232, 165] },+ { "name": "AgentDistributePaymentsEvent", "discriminator": [137, 116, 114, 140, 54, 111, 230, 26] },+ { "name": "AgentInitializeEvent", "discriminator": [192, 5, 183, 151, 0, 64, 100, 207] },+ { "name": "AgentUpdateAuthorityEvent", "discriminator": [36, 212, 117, 235, 74, 166, 60, 16] },+ { "name": "AgentUpdateBuybackBpsEvent", "discriminator": [165, 251, 40, 19, 114, 26, 128, 232] },+ { "name": "AgentWithdrawEvent", "discriminator": [174, 231, 201, 69, 254, 183, 49, 85] },+ { "name": "ExtendAccountEvent", "discriminator": [97, 97, 215, 144, 93, 146, 22, 124] },+ { "name": "GlobalAddNewCurrencyEvent", "discriminator": [130, 202, 37, 248, 241, 182, 233, 35] },+ { "name": "GlobalConfigInitializeEvent", "discriminator": [241, 51, 222, 190, 142, 245, 176, 53] },+ { "name": "GlobalUpdateAuthoritiesEvent", "discriminator": [82, 27, 22, 232, 53, 66, 35, 207] }+ ],+ "errors": [+ { "code": 6000, "name": "UnauthorizedSigner", "msg": "The given account is not authorized to execute this instruction." },+ { "code": 6001, "name": "CurrencyAlreadySupported", "msg": "The given currency is already supported." },+ { "code": 6002, "name": "MaxCurrenciesReached", "msg": "The maximum number of currencies has been reached." },+ { "code": 6003, "name": "InvalidBuybackBps", "msg": "The buyback basis points is greater than 10000." },+ { "code": 6004, "name": "CurrencyNotSupported", "msg": "The given currency is not supported." },+ { "code": 6005, "name": "MathOverflow", "msg": "Math overflow." },+ { "code": 6006, "name": "InvalidRemainingAccountAddress", "msg": "The given remaining account address is invalid." },+ { "code": 6007, "name": "PaymentVaultNotEmpty", "msg": "The payment vault is not empty. Distribute the payments first." },+ { "code": 6008, "name": "InvalidInvoiceAccount", "msg": "The invoice account does not match the expected PDA seeds" },+ { "code": 6009, "name": "InvalidProgramToInvoke", "msg": "The program to invoke is not allowed." },+ { "code": 6010, "name": "InvalidCallbackProgram", "msg": "The callback program is invalid." },+ { "code": 6011, "name": "SwapFailedAmountDidNotIncrease", "msg": "The swap failed and the amount did not increase." },+ { "code": 6012, "name": "AccountTypeNotSupported", "msg": "The account type is not supported for extension." },+ { "code": 6013, "name": "InvalidIndex", "msg": "The index is invalid." }+ ],+ "types": [+ {+ "name": "AgentAcceptPaymentEvent",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "user", "type": "pubkey" },+ { "name": "tokenized_agent_mint", "type": "pubkey" },+ { "name": "token_agent_payments", "type": "pubkey" },+ { "name": "currency_mint", "type": "pubkey" },+ { "name": "amount", "type": "u64" },+ { "name": "memo", "type": "u64" },+ { "name": "start_time", "type": "i64" },+ { "name": "end_time", "type": "i64" },+ { "name": "invoice_id", "type": "pubkey" },+ { "name": "agent_post_balance", "type": "u64" },+ { "name": "timestamp", "type": "i64" }+ ]+ }+ },+ {+ "name": "AgentBuybackTriggerEvent",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "tokenized_agent_mint", "type": "pubkey" },+ { "name": "currency_mint", "type": "pubkey" },+ { "name": "amount_burned", "type": "u64" },+ { "name": "swap_program", "type": "pubkey" },+ { "name": "new_tokens_bought_and_burned_for_currency", "type": "u64" },+ { "name": "agent_post_balance", "type": "u64" },+ { "name": "timestamp", "type": "i64" },+ { "name": "currency_mint_amount_for_buyback", "type": "u64" }+ ]+ }+ },+ {+ "name": "AgentDistributePaymentsEvent",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "token_agent_payments", "type": "pubkey" },+ { "name": "currency_mint", "type": "pubkey" },+ { "name": "buyback_bps", "type": "u16" },+ { "name": "buyback_amount", "type": "u64" },+ { "name": "withdraw_amount", "type": "u64" },+ { "name": "timestamp", "type": "i64" }+ ]+ }+ },+ {+ "name": "AgentInitializeEvent",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "token_agent_payments", "type": "pubkey" },+ { "name": "mint", "type": "pubkey" },+ { "name": "authority", "type": "pubkey" },+ { "name": "buyback_bps", "type": "u16" },+ { "name": "timestamp", "type": "i64" },+ { "name": "tokenized_agent_sequence", "type": "u64" }+ ]+ }+ },+ {+ "name": "AgentUpdateAuthorityEvent",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "token_agent_payments", "type": "pubkey" },+ { "name": "old_authority", "type": "pubkey" },+ { "name": "new_authority", "type": "pubkey" },+ { "name": "timestamp", "type": "i64" }+ ]+ }+ },+ {+ "name": "AgentUpdateBuybackBpsEvent",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "token_agent_payments", "type": "pubkey" },+ { "name": "mint", "type": "pubkey" },+ { "name": "old_buyback_bps", "type": "u16" },+ { "name": "new_buyback_bps", "type": "u16" },+ { "name": "timestamp", "type": "i64" }+ ]+ }+ },+ {+ "name": "AgentWithdrawEvent",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "tokenized_agent_mint", "type": "pubkey" },+ { "name": "currency_mint", "type": "pubkey" },+ { "name": "amount", "type": "u64" },+ { "name": "receiver", "type": "pubkey" },+ { "name": "timestamp", "type": "i64" }+ ]+ }+ },+ {+ "name": "BondingCurve",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "virtual_token_reserves", "type": "u64" },+ { "name": "virtual_sol_reserves", "type": "u64" },+ { "name": "real_token_reserves", "type": "u64" },+ { "name": "real_sol_reserves", "type": "u64" },+ { "name": "token_total_supply", "type": "u64" },+ { "name": "complete", "type": "bool" },+ { "name": "creator", "type": "pubkey" },+ { "name": "is_mayhem_mode", "type": "bool" }+ ]+ }+ },+ {+ "name": "ExtendAccountEvent",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "account", "type": "pubkey" },+ { "name": "user", "type": "pubkey" },+ { "name": "current_size", "type": "u64" },+ { "name": "new_size", "type": "u64" },+ { "name": "timestamp", "type": "i64" }+ ]+ }+ },+ {+ "name": "GlobalAddNewCurrencyEvent",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "global_config", "type": "pubkey" },+ { "name": "currency_mint", "type": "pubkey" },+ { "name": "timestamp", "type": "i64" }+ ]+ }+ },+ {+ "name": "GlobalConfig",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "bump", "type": "u8" },+ { "name": "protocol_authority", "type": "pubkey" },+ { "name": "buyback_authority", "type": "pubkey" },+ { "name": "supported_currencies_mint", "type": { "array": ["pubkey", 10] } },+ { "name": "tokenized_agent_sequence", "type": "u64" }+ ]+ }+ },+ {+ "name": "GlobalConfigInitializeEvent",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "global_config", "type": "pubkey" },+ { "name": "protocol_authority", "type": "pubkey" },+ { "name": "buyback_authority", "type": "pubkey" },+ { "name": "timestamp", "type": "i64" }+ ]+ }+ },+ {+ "name": "GlobalUpdateAuthoritiesEvent",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "global_config", "type": "pubkey" },+ { "name": "protocol_authority", "type": { "option": "pubkey" } },+ { "name": "buyback_authority", "type": { "option": "pubkey" } },+ { "name": "timestamp", "type": "i64" }+ ]+ }+ },+ {+ "name": "TokenAgentPaymentInCurrency",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "mint", "type": "pubkey" },+ { "name": "currency_mint", "type": "pubkey" },+ { "name": "total_invoice_payments_made", "type": "u64" },+ { "name": "total_buyback", "type": "u64" },+ { "name": "total_withdrawals", "type": "u64" },+ { "name": "tokens_bought_back_and_burned", "type": "u64" }+ ]+ }+ },+ {+ "name": "TokenAgentPayments",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "bump", "type": "u8" },+ { "name": "mint", "type": "pubkey" },+ { "name": "authority", "type": "pubkey" },+ { "name": "buyback_bps", "type": "u16" }+ ]+ }+ }+ ]+}diff --git a/agent-payments-sdk/src/idl/pump_agent_payments.ts b/agent-payments-sdk/src/idl/pump_agent_payments.tsnew file mode 100644index 000000000..1fcca0cbb--- /dev/null+++ b/agent-payments-sdk/src/idl/pump_agent_payments.ts@@ -0,0 +1,782 @@+/**+ * Program IDL in camelCase format in order to be used in JS/TS.+ *+ * Note that this is only a type helper and is not the actual IDL. The original+ * IDL can be found at `target/idl/pump_agent_payments.json`.+ */+export type PumpAgentPayments = {+ address: "AgenTMiC2hvxGebTsgmsD4HHBa8WEcqGFf87iwRRxLo7";+ metadata: {+ name: "pumpAgentPayments";+ version: "0.1.0";+ spec: "0.1.0";+ description: "Created with Anchor";+ };+ instructions: [+ {+ name: "agentAcceptPayment";+ discriminator: [34, 157, 64, 220, 74, 32, 48, 225];+ accounts: [+ { name: "user"; writable: true; signer: true },+ { name: "userTokenAccount"; writable: true },+ { name: "tokenAgentPayments" },+ {+ name: "tokenAgentAssociatedAccount";+ writable: true;+ pda: {+ seeds: [+ { kind: "account"; path: "tokenAgentPayments" },+ {+ kind: "const";+ value: [6,221,246,225,215,101,161,147,217,203,225,70,206,235,121,172,28,180,133,237,95,91,55,145,58,140,245,133,126,255,0,169];+ },+ { kind: "account"; path: "currencyMint" },+ ];+ program: {+ kind: "const";+ value: [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89];+ };+ };+ },+ {+ name: "tokenAgentPaymentInCurrency";+ writable: true;+ pda: {+ seeds: [+ { kind: "const"; value: [112,97,121,109,101,110,116,45,105,110,45,99,117,114,114,101,110,99,121] },+ { kind: "account"; path: "tokenAgentPayments.mint"; account: "TokenAgentPayments" },+ { kind: "account"; path: "currencyMint" },+ ];+ };+ },+ {+ name: "globalConfig";+ pda: { seeds: [{ kind: "const"; value: [103,108,111,98,97,108,45,99,111,110,102,105,103] }] };+ },+ { name: "invoiceId" },+ { name: "currencyMint" },+ { name: "tokenProgram" },+ { name: "associatedTokenProgram"; address: "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" },+ { name: "systemProgram"; address: "11111111111111111111111111111111" },+ {+ name: "eventAuthority";+ pda: { seeds: [{ kind: "const"; value: [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] };+ },+ { name: "program" },+ ];+ args: [+ { name: "amount"; type: "u64" },+ { name: "memo"; type: "u64" },+ { name: "startTime"; type: "i64" },+ { name: "endTime"; type: "i64" },+ ];+ },+ {+ name: "agentBuybackTrigger";+ discriminator: [95, 231, 193, 2, 245, 75, 125, 155];+ accounts: [+ { name: "globalBuybackAuthority"; writable: true; signer: true },+ { name: "mint"; writable: true },+ {+ name: "tokenAgentPayments";+ pda: {+ seeds: [+ { kind: "const"; value: [116,111,107,101,110,45,97,103,101,110,116,45,112,97,121,109,101,110,116,115] },+ { kind: "account"; path: "mint" },+ ];+ };+ },+ {+ name: "tokenAgentPaymentInCurrency";+ writable: true;+ pda: {+ seeds: [+ { kind: "const"; value: [112,97,121,109,101,110,116,45,105,110,45,99,117,114,114,101,110,99,121] },+ { kind: "account"; path: "tokenAgentPayments.mint"; account: "TokenAgentPayments" },+ { kind: "account"; path: "currencyMint" },+ ];+ };+ },+ { name: "currencyMint" },+ {+ name: "globalConfig";+ pda: { seeds: [{ kind: "const"; value: [103,108,111,98,97,108,45,99,111,110,102,105,103] }] };+ },+ { name: "swapProgramToInvoke" },+ {+ name: "burnAuthority";+ docs: ["Intentionally called burn_authority", "TO avoid any confusion with the global buyback authority."];+ writable: true;+ pda: {+ seeds: [+ { kind: "const"; value: [98,117,121,98,97,99,107,45,97,117,116,104,111,114,105,116,121] },+ { kind: "account"; path: "tokenAgentPayments.mint"; account: "TokenAgentPayments" },+ ];+ };+ },+ {+ name: "burnMintVault";+ writable: true;+ pda: {+ seeds: [+ { kind: "account"; path: "burnAuthority" },+ { kind: "account"; path: "tokenProgram" },+ { kind: "account"; path: "mint" },+ ];+ program: {+ kind: "const";+ value: [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89];+ };+ };+ },+ {+ name: "burnCurrencyMintVault";+ writable: true;+ pda: {+ seeds: [+ { kind: "account"; path: "burnAuthority" },+ { kind: "account"; path: "tokenProgramCurrency" },+ { kind: "account"; path: "currencyMint" },+ ];+ program: {+ kind: "const";+ value: [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89];+ };+ };+ },+ { name: "tokenProgram" },+ { name: "tokenProgramCurrency" },+ { name: "associatedTokenProgram"; address: "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" },+ { name: "systemProgram"; address: "11111111111111111111111111111111" },+ {+ name: "eventAuthority";+ pda: { seeds: [{ kind: "const"; value: [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] };+ },+ { name: "program" },+ ];+ args: [{ name: "swapInstructionData"; type: "bytes" }];+ },+ {+ name: "agentDistributePayments";+ discriminator: [145, 44, 246, 47, 192, 204, 95, 32];+ accounts: [+ { name: "user"; writable: true; signer: true },+ {+ name: "globalConfig";+ pda: { seeds: [{ kind: "const"; value: [103,108,111,98,97,108,45,99,111,110,102,105,103] }] };+ },+ { name: "currencyMint" },+ { name: "tokenAgentPayments"; writable: true },+ {+ name: "tokenAgentPaymentInCurrency";+ writable: true;+ pda: {+ seeds: [+ { kind: "const"; value: [112,97,121,109,101,110,116,45,105,110,45,99,117,114,114,101,110,99,121] },+ { kind: "account"; path: "tokenAgentPayments.mint"; account: "TokenAgentPayments" },+ { kind: "account"; path: "currencyMint" },+ ];+ };+ },+ {+ name: "tokenAgentAssociatedAccount";+ writable: true;+ pda: {+ seeds: [+ { kind: "account"; path: "tokenAgentPayments" },+ {+ kind: "const";+ value: [6,221,246,225,215,101,161,147,217,203,225,70,206,235,121,172,28,180,133,237,95,91,55,145,58,140,245,133,126,255,0,169];+ },+ { kind: "account"; path: "currencyMint" },+ ];+ program: {+ kind: "const";+ value: [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89];+ };+ };+ },+ {+ name: "buybackAuthority";+ pda: {+ seeds: [+ { kind: "const"; value: [98,117,121,98,97,99,107,45,97,117,116,104,111,114,105,116,121] },+ { kind: "account"; path: "tokenAgentPayments.mint"; account: "TokenAgentPayments" },+ ];+ };+ },+ {+ name: "withdrawAuthority";+ pda: {+ seeds: [+ { kind: "const"; value: [119,105,116,104,100,114,97,119,45,97,117,116,104,111,114,105,116,121] },+ { kind: "account"; path: "tokenAgentPayments.mint"; account: "TokenAgentPayments" },+ ];+ };+ },+ {+ name: "buybackVault";+ writable: true;+ pda: {+ seeds: [+ { kind: "account"; path: "buybackAuthority" },+ {+ kind: "const";+ value: [6,221,246,225,215,101,161,147,217,203,225,70,206,235,121,172,28,180,133,237,95,91,55,145,58,140,245,133,126,255,0,169];+ },+ { kind: "account"; path: "currencyMint" },+ ];+ program: {+ kind: "const";+ value: [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89];+ };+ };+ },+ {+ name: "withdrawVault";+ writable: true;+ pda: {+ seeds: [+ { kind: "account"; path: "withdrawAuthority" },+ {+ kind: "const";+ value: [6,221,246,225,215,101,161,147,217,203,225,70,206,235,121,172,28,180,133,237,95,91,55,145,58,140,245,133,126,255,0,169];+ },+ { kind: "account"; path: "currencyMint" },+ ];+ program: {+ kind: "const";+ value: [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89];+ };+ };+ },+ { name: "tokenProgram" },+ { name: "associatedTokenProgram"; address: "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" },+ { name: "systemProgram"; address: "11111111111111111111111111111111" },+ {+ name: "eventAuthority";+ pda: { seeds: [{ kind: "const"; value: [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] };+ },+ { name: "program" },+ ];+ args: [];+ },+ {+ name: "agentInitialize";+ discriminator: [180, 248, 163, 8, 49, 94, 126, 96];+ accounts: [+ { name: "authority"; writable: true; signer: true },+ {+ name: "bondingCurve";+ pda: {+ seeds: [+ { kind: "const"; value: [98,111,110,100,105,110,103,45,99,117,114,118,101] },+ { kind: "account"; path: "mint" },+ ];+ program: {+ kind: "const";+ value: [1,86,224,246,147,102,90,207,68,219,21,104,191,23,91,170,81,137,203,151,245,210,255,59,101,93,43,182,253,109,24,176];+ };+ };+ },+ {+ name: "globalConfig";+ writable: true;+ pda: { seeds: [{ kind: "const"; value: [103,108,111,98,97,108,45,99,111,110,102,105,103] }] };+ },+ { name: "mint" },+ {+ name: "tokenAgentPayments";+ writable: true;+ pda: {+ seeds: [+ { kind: "const"; value: [116,111,107,101,110,45,97,103,101,110,116,45,112,97,121,109,101,110,116,115] },+ { kind: "account"; path: "mint" },+ ];+ };+ },+ { name: "systemProgram"; address: "11111111111111111111111111111111" },+ {+ name: "eventAuthority";+ pda: { seeds: [{ kind: "const"; value: [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] };+ },+ { name: "program" },+ ];+ args: [+ { name: "authority"; type: "pubkey" },+ { name: "buybackBps"; type: "u16" },+ ];+ },+ {+ name: "agentTransferExtraLamports";+ discriminator: [39, 206, 214, 167, 55, 44, 221, 81];+ accounts: [+ {+ name: "tokenAgentPayments";+ writable: true;+ pda: {+ seeds: [+ { kind: "const"; value: [116,111,107,101,110,45,97,103,101,110,116,45,112,97,121,109,101,110,116,115] },+ { kind: "account"; path: "tokenAgentPayments.mint"; account: "TokenAgentPayments" },+ ];+ };+ },+ {+ name: "tokenAgentAssociatedAccount";+ writable: true;+ pda: {+ seeds: [+ { kind: "account"; path: "tokenAgentPayments" },+ {+ kind: "const";+ value: [6,221,246,225,215,101,161,147,217,203,225,70,206,235,121,172,28,180,133,237,95,91,55,145,58,140,245,133,126,255,0,169];+ },+ {+ kind: "const";+ value: [6,155,136,87,254,171,129,132,251,104,127,99,70,24,192,53,218,196,57,220,26,235,59,85,152,160,240,0,0,0,0,1];+ },+ ];+ program: {+ kind: "const";+ value: [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89];+ };+ };+ },+ ];+ args: [];+ },+ {+ name: "agentUpdateAuthority";+ discriminator: [237, 228, 227, 224, 226, 198, 167, 83];+ accounts: [+ { name: "authority"; writable: true; signer: true },+ {+ name: "globalConfig";+ pda: { seeds: [{ kind: "const"; value: [103,108,111,98,97,108,45,99,111,110,102,105,103] }] };+ },+ { name: "tokenAgentPayments"; writable: true },+ { name: "systemProgram"; address: "11111111111111111111111111111111" },+ {+ name: "eventAuthority";+ pda: { seeds: [{ kind: "const"; value: [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] };+ },+ { name: "program" },+ ];+ args: [{ name: "newAuthority"; type: "pubkey" }];+ },+ {+ name: "agentUpdateBuybackBps";+ discriminator: [41, 28, 118, 90, 53, 24, 63, 160];+ accounts: [+ { name: "authority"; writable: true; signer: true },+ { name: "tokenAgentPayments"; writable: true },+ {+ name: "globalConfig";+ pda: { seeds: [{ kind: "const"; value: [103,108,111,98,97,108,45,99,111,110,102,105,103] }] };+ },+ {+ name: "eventAuthority";+ pda: { seeds: [{ kind: "const"; value: [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] };+ },+ { name: "program" },+ ];+ args: [{ name: "buybackBps"; type: "u16" }];+ },+ {+ name: "agentWithdraw";+ discriminator: [13, 149, 99, 245, 171, 171, 185, 53];+ accounts: [+ { name: "authority"; writable: true; signer: true },+ { name: "tokenAgentPayments" },+ { name: "currencyMint" },+ {+ name: "withdrawAuthority";+ pda: {+ seeds: [+ { kind: "const"; value: [119,105,116,104,100,114,97,119,45,97,117,116,104,111,114,105,116,121] },+ { kind: "account"; path: "tokenAgentPayments.mint"; account: "TokenAgentPayments" },+ ];+ };+ },+ {+ name: "withdrawVault";+ writable: true;+ pda: {+ seeds: [+ { kind: "account"; path: "withdrawAuthority" },+ {+ kind: "const";+ value: [6,221,246,225,215,101,161,147,217,203,225,70,206,235,121,172,28,180,133,237,95,91,55,145,58,140,245,133,126,255,0,169];+ },+ { kind: "account"; path: "currencyMint" },+ ];+ program: {+ kind: "const";+ value: [140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89];+ };+ };+ },+ { name: "receiverAta"; writable: true },+ { name: "tokenProgram" },+ { name: "associatedTokenProgram"; address: "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" },+ { name: "systemProgram"; address: "11111111111111111111111111111111" },+ {+ name: "eventAuthority";+ pda: { seeds: [{ kind: "const"; value: [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] };+ },+ { name: "program" },+ ];+ args: [];+ },+ {+ name: "closeAccount";+ discriminator: [125, 255, 149, 14, 110, 34, 72, 24];+ accounts: [+ { name: "account"; writable: true },+ { name: "user"; writable: true; signer: true },+ {+ name: "globalConfig";+ pda: { seeds: [{ kind: "const"; value: [103,108,111,98,97,108,45,99,111,110,102,105,103] }] };+ },+ { name: "systemProgram"; address: "11111111111111111111111111111111" },+ ];+ args: [];+ },+ {+ name: "extendAccount";+ discriminator: [234, 102, 194, 203, 150, 72, 62, 229];+ accounts: [+ { name: "account"; writable: true },+ { name: "user"; writable: true; signer: true },+ { name: "systemProgram"; address: "11111111111111111111111111111111" },+ {+ name: "eventAuthority";+ pda: { seeds: [{ kind: "const"; value: [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] };+ },+ { name: "program" },+ ];+ args: [];+ },+ {+ name: "globalAddNewCurrency";+ discriminator: [46, 135, 47, 120, 118, 204, 177, 224];+ accounts: [+ { name: "authority"; writable: true; signer: true },+ {+ name: "globalConfig";+ writable: true;+ pda: { seeds: [{ kind: "const"; value: [103,108,111,98,97,108,45,99,111,110,102,105,103] }] };+ },+ { name: "mint" },+ {+ name: "eventAuthority";+ pda: { seeds: [{ kind: "const"; value: [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] };+ },+ { name: "program" },+ ];+ args: [];+ },+ {+ name: "globalConfigInitialize";+ discriminator: [61, 23, 208, 192, 232, 52, 8, 66];+ accounts: [+ { name: "authority"; writable: true; signer: true },+ {+ name: "globalConfig";+ writable: true;+ pda: { seeds: [{ kind: "const"; value: [103,108,111,98,97,108,45,99,111,110,102,105,103] }] };+ },+ { name: "systemProgram"; address: "11111111111111111111111111111111" },+ {+ name: "eventAuthority";+ pda: { seeds: [{ kind: "const"; value: [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] };+ },+ { name: "program" },+ ];+ args: [+ { name: "protocolAuthority"; type: "pubkey" },+ { name: "buybackAuthority"; type: "pubkey" },+ ];+ },+ {+ name: "globalRemoveCurrency";+ discriminator: [57, 226, 180, 140, 91, 14, 231, 196];+ accounts: [+ { name: "authority"; writable: true; signer: true },+ {+ name: "globalConfig";+ writable: true;+ pda: { seeds: [{ kind: "const"; value: [103,108,111,98,97,108,45,99,111,110,102,105,103] }] };+ },+ {+ name: "eventAuthority";+ pda: { seeds: [{ kind: "const"; value: [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] };+ },+ { name: "program" },+ ];+ args: [{ name: "index"; type: "u8" }];+ },+ {+ name: "globalUpdateAuthorities";+ discriminator: [91, 137, 72, 77, 183, 184, 168, 125];+ accounts: [+ { name: "authority"; writable: true; signer: true },+ {+ name: "globalConfig";+ writable: true;+ pda: { seeds: [{ kind: "const"; value: [103,108,111,98,97,108,45,99,111,110,102,105,103] }] };+ },+ {+ name: "eventAuthority";+ pda: { seeds: [{ kind: "const"; value: [95,95,101,118,101,110,116,95,97,117,116,104,111,114,105,116,121] }] };+ },+ { name: "program" },+ ];+ args: [+ { name: "protocolAuthority"; type: { option: "pubkey" } },+ { name: "buybackAuthority"; type: { option: "pubkey" } },+ ];+ },+ ];+ accounts: [+ { name: "BondingCurve"; discriminator: [23, 183, 248, 55, 96, 216, 172, 96] },+ { name: "GlobalConfig"; discriminator: [149, 8, 156, 202, 160, 252, 176, 217] },+ { name: "TokenAgentPaymentInCurrency"; discriminator: [225, 195, 81, 227, 115, 43, 25, 177] },+ { name: "TokenAgentPayments"; discriminator: [136, 241, 242, 217, 173, 77, 112, 186] },+ ];+ events: [+ { name: "AgentAcceptPaymentEvent"; discriminator: [114, 190, 188, 192, 105, 79, 41, 147] },+ { name: "AgentBuybackTriggerEvent"; discriminator: [139, 240, 9, 225, 214, 63, 232, 165] },+ { name: "AgentDistributePaymentsEvent"; discriminator: [137, 116, 114, 140, 54, 111, 230, 26] },+ { name: "AgentInitializeEvent"; discriminator: [192, 5, 183, 151, 0, 64, 100, 207] },+ { name: "AgentUpdateAuthorityEvent"; discriminator: [36, 212, 117, 235, 74, 166, 60, 16] },+ { name: "AgentUpdateBuybackBpsEvent"; discriminator: [165, 251, 40, 19, 114, 26, 128, 232] },+ { name: "AgentWithdrawEvent"; discriminator: [174, 231, 201, 69, 254, 183, 49, 85] },+ { name: "ExtendAccountEvent"; discriminator: [97, 97, 215, 144, 93, 146, 22, 124] },+ { name: "GlobalAddNewCurrencyEvent"; discriminator: [130, 202, 37, 248, 241, 182, 233, 35] },+ { name: "GlobalConfigInitializeEvent"; discriminator: [241, 51, 222, 190, 142, 245, 176, 53] },+ { name: "GlobalUpdateAuthoritiesEvent"; discriminator: [82, 27, 22, 232, 53, 66, 35, 207] },+ ];+ errors: [+ { code: 6000; name: "UnauthorizedSigner"; msg: "The given account is not authorized to execute this instruction." },+ { code: 6001; name: "CurrencyAlreadySupported"; msg: "The given currency is already supported." },+ { code: 6002; name: "MaxCurrenciesReached"; msg: "The maximum number of currencies has been reached." },+ { code: 6003; name: "InvalidBuybackBps"; msg: "The buyback basis points is greater than 10000." },+ { code: 6004; name: "CurrencyNotSupported"; msg: "The given currency is not supported." },+ { code: 6005; name: "MathOverflow"; msg: "Math overflow." },+ { code: 6006; name: "InvalidRemainingAccountAddress"; msg: "The given remaining account address is invalid." },+ { code: 6007; name: "PaymentVaultNotEmpty"; msg: "The payment vault is not empty. Distribute the payments first." },+ { code: 6008; name: "InvalidInvoiceAccount"; msg: "The invoice account does not match the expected PDA seeds" },+ { code: 6009; name: "InvalidProgramToInvoke"; msg: "The program to invoke is not allowed." },+ { code: 6010; name: "InvalidCallbackProgram"; msg: "The callback program is invalid." },+ { code: 6011; name: "SwapFailedAmountDidNotIncrease"; msg: "The swap failed and the amount did not increase." },+ { code: 6012; name: "AccountTypeNotSupported"; msg: "The account type is not supported for extension." },+ { code: 6013; name: "InvalidIndex"; msg: "The index is invalid." },+ ];+ types: [+ {+ name: "AgentAcceptPaymentEvent";+ type: {+ kind: "struct";+ fields: [+ { name: "user"; type: "pubkey" },+ { name: "tokenizedAgentMint"; type: "pubkey" },+ { name: "tokenAgentPayments"; type: "pubkey" },+ { name: "currencyMint"; type: "pubkey" },+ { name: "amount"; type: "u64" },+ { name: "memo"; type: "u64" },+ { name: "startTime"; type: "i64" },+ { name: "endTime"; type: "i64" },+ { name: "invoiceId"; type: "pubkey" },+ { name: "agentPostBalance"; type: "u64" },+ { name: "timestamp"; type: "i64" },+ ];+ };+ },+ {+ name: "AgentBuybackTriggerEvent";+ type: {+ kind: "struct";+ fields: [+ { name: "tokenizedAgentMint"; type: "pubkey" },+ { name: "currencyMint"; type: "pubkey" },+ { name: "amountBurned"; type: "u64" },+ { name: "swapProgram"; type: "pubkey" },+ { name: "newTokensBoughtAndBurnedForCurrency"; type: "u64" },+ { name: "agentPostBalance"; type: "u64" },+ { name: "timestamp"; type: "i64" },+ { name: "currencyMintAmountForBuyback"; type: "u64" },+ ];+ };+ },+ {+ name: "AgentDistributePaymentsEvent";+ type: {+ kind: "struct";+ fields: [+ { name: "tokenAgentPayments"; type: "pubkey" },+ { name: "currencyMint"; type: "pubkey" },+ { name: "buybackBps"; type: "u16" },+ { name: "buybackAmount"; type: "u64" },+ { name: "withdrawAmount"; type: "u64" },+ { name: "timestamp"; type: "i64" },+ ];+ };+ },+ {+ name: "AgentInitializeEvent";+ type: {+ kind: "struct";+ fields: [+ { name: "tokenAgentPayments"; type: "pubkey" },+ { name: "mint"; type: "pubkey" },+ { name: "authority"; type: "pubkey" },+ { name: "buybackBps"; type: "u16" },+ { name: "timestamp"; type: "i64" },+ { name: "tokenizedAgentSequence"; type: "u64" },+ ];+ };+ },+ {+ name: "AgentUpdateAuthorityEvent";+ type: {+ kind: "struct";+ fields: [+ { name: "tokenAgentPayments"; type: "pubkey" },+ { name: "oldAuthority"; type: "pubkey" },+ { name: "newAuthority"; type: "pubkey" },+ { name: "timestamp"; type: "i64" },+ ];+ };+ },+ {+ name: "AgentUpdateBuybackBpsEvent";+ type: {+ kind: "struct";+ fields: [+ { name: "tokenAgentPayments"; type: "pubkey" },+ { name: "mint"; type: "pubkey" },+ { name: "oldBuybackBps"; type: "u16" },+ { name: "newBuybackBps"; type: "u16" },+ { name: "timestamp"; type: "i64" },+ ];+ };+ },+ {+ name: "AgentWithdrawEvent";+ type: {+ kind: "struct";+ fields: [+ { name: "tokenizedAgentMint"; type: "pubkey" },+ { name: "currencyMint"; type: "pubkey" },+ { name: "amount"; type: "u64" },+ { name: "receiver"; type: "pubkey" },+ { name: "timestamp"; type: "i64" },+ ];+ };+ },+ {+ name: "BondingCurve";+ type: {+ kind: "struct";+ fields: [+ { name: "virtualTokenReserves"; type: "u64" },+ { name: "virtualSolReserves"; type: "u64" },+ { name: "realTokenReserves"; type: "u64" },+ { name: "realSolReserves"; type: "u64" },+ { name: "tokenTotalSupply"; type: "u64" },+ { name: "complete"; type: "bool" },+ { name: "creator"; type: "pubkey" },+ { name: "isMayhemMode"; type: "bool" },+ ];+ };+ },+ {+ name: "ExtendAccountEvent";+ type: {+ kind: "struct";+ fields: [+ { name: "account"; type: "pubkey" },+ { name: "user"; type: "pubkey" },+ { name: "currentSize"; type: "u64" },+ { name: "newSize"; type: "u64" },+ { name: "timestamp"; type: "i64" },+ ];+ };+ },+ {+ name: "GlobalAddNewCurrencyEvent";+ type: {+ kind: "struct";+ fields: [+ { name: "globalConfig"; type: "pubkey" },+ { name: "currencyMint"; type: "pubkey" },+ { name: "timestamp"; type: "i64" },+ ];+ };+ },+ {+ name: "GlobalConfig";+ type: {+ kind: "struct";+ fields: [+ { name: "bump"; type: "u8" },+ { name: "protocolAuthority"; type: "pubkey" },+ { name: "buybackAuthority"; type: "pubkey" },+ { name: "supportedCurrenciesMint"; type: { array: ["pubkey", 10] } },+ { name: "tokenizedAgentSequence"; type: "u64" },+ ];+ };+ },+ {+ name: "GlobalConfigInitializeEvent";+ type: {+ kind: "struct";+ fields: [+ { name: "globalConfig"; type: "pubkey" },+ { name: "protocolAuthority"; type: "pubkey" },+ { name: "buybackAuthority"; type: "pubkey" },+ { name: "timestamp"; type: "i64" },+ ];+ };+ },+ {+ name: "GlobalUpdateAuthoritiesEvent";+ type: {+ kind: "struct";+ fields: [+ { name: "globalConfig"; type: "pubkey" },+ { name: "protocolAuthority"; type: { option: "pubkey" } },+ { name: "buybackAuthority"; type: { option: "pubkey" } },+ { name: "timestamp"; type: "i64" },+ ];+ };+ },+ {+ name: "TokenAgentPaymentInCurrency";+ type: {+ kind: "struct";+ fields: [+ { name: "mint"; type: "pubkey" },+ { name: "currencyMint"; type: "pubkey" },+ { name: "totalInvoicePaymentsMade"; type: "u64" },+ { name: "totalBuyback"; type: "u64" },+ { name: "totalWithdrawals"; type: "u64" },+ { name: "tokensBoughtBackAndBurned"; type: "u64" },+ ];+ };+ },+ {+ name: "TokenAgentPayments";+ type: {+ kind: "struct";+ fields: [+ { name: "bump"; type: "u8" },+ { name: "mint"; type: "pubkey" },+ { name: "authority"; type: "pubkey" },+ { name: "buybackBps"; type: "u16" },+ ];+ };+ },+ ];+};diff --git a/agent-payments-sdk/src/index.ts b/agent-payments-sdk/src/index.tsnew file mode 100644index 000000000..84ac98a89--- /dev/null+++ b/agent-payments-sdk/src/index.ts@@ -0,0 +1,118 @@+/**+ * @pump-fun/agent-payments-sdk+ * TypeScript SDK for Pump Agent Payments+ */++// IDL type+export type { PumpAgentPayments } from "./idl/pump_agent_payments";++// Program helpers+export {+ getPumpProgram,+ OFFLINE_PUMP_PROGRAM,+ getPumpProgramWithFallback,+ getOfflineProgram,+} from "./program";++// PDA derivation+export {+ PROGRAM_ID,+ PUMP_PROGRAM_ID,+ GLOBAL_CONFIG_SEED,+ TOKEN_AGENT_PAYMENTS_SEED,+ PAYMENT_IN_CURRENCY_SEED,+ INVOICE_ID_SEED,+ BUYBACK_AUTHORITY_SEED,+ WITHDRAW_AUTHORITY_SEED,+ BONDING_CURVE_SEED,+ TOKEN_AGENT_PAYMENTS_MIN_RENT_EXEMPT_LAMPORTS,+ getGlobalConfigPDA,+ getTokenAgentPaymentsPDA,+ getPaymentInCurrencyPDA,+ getInvoiceIdPDA,+ getBuybackAuthorityPDA,+ getWithdrawAuthorityPDA,+ getBondingCurvePDA,+} from "./pdas";++// Classes+export { PumpAgentOffline } from "./PumpAgentOffline";+export { PumpAgent } from "./PumpAgent";++// Decoders+export {+ decodeGlobalConfig,+ decodeTokenAgentPaymentInCurrency,+ decodeTokenAgentPayments,+} from "./decoders";++// Types+export type {+ PumpEnvironment,+ VaultBalance,+ AgentBalances,+ CreateParams,+ WithdrawParams,+ UpdateBuybackBpsParams,+ UpdateBuybackBpsOptions,+ AcceptPaymentParams,+ AcceptPaymentSimpleParams,+ BuildAcceptPaymentParams,+ DistributePaymentsParams,+ BuybackTriggerParams,+ ExtendAccountParams,+ UpdateAuthorityParams,+ CloseAccountParams,+ GlobalConfig,+ TokenAgentPaymentInCurrency,+ TokenAgentPayments,+} from "./types";++// Convenience re-export+import { PublicKey, type Connection } from "@solana/web3.js";+import type { Program } from "@coral-xyz/anchor";+import type { PumpAgentPayments } from "./idl/pump_agent_payments";+import IDL from "./idl/pump_agent_payments.json";+import { getPumpProgram } from "./program";++export const PUMP_AGENT_PAYMENTS_PROGRAM_ID = new PublicKey(IDL.address);++export function getProgram(+ connection: Connection,+): Program<PumpAgentPayments> {+ return getPumpProgram(connection);+}++// Events+export {+ createEventParser,+ parseAgentEvents,+ subscribeToAgentEvents,+} from "./events";+export type {+ AgentAcceptPaymentEvent,+ AgentBuybackTriggerEvent,+ AgentDistributePaymentsEvent,+ AgentInitializeEvent,+ AgentUpdateAuthorityEvent,+ AgentUpdateBuybackBpsEvent,+ AgentWithdrawEvent,+ ExtendAccountEvent,+ GlobalAddNewCurrencyEvent,+ GlobalConfigInitializeEvent,+ GlobalUpdateAuthoritiesEvent,+ AgentEventName,+ AgentEventData,+ ParsedAgentEvent,+ EventSubscriptionOptions,+ EventSubscription,+} from "./events";++// solana-agent-kit plugin+export { PumpAgentPaymentsPlugin } from "./solana-agent-kit";++// x402 protocol+export * as x402 from "./x402";++// solana-agent-kit plugin+export { PumpAgentPaymentsPlugin } from "./solana-agent-kit";diff --git a/agent-payments-sdk/src/pdas.ts b/agent-payments-sdk/src/pdas.tsnew file mode 100644index 000000000..e98ceff00--- /dev/null+++ b/agent-payments-sdk/src/pdas.ts@@ -0,0 +1,127 @@+import { PublicKey } from "@solana/web3.js";+import type BN from "bn.js";++/** Pump Agent Payments program ID */+export const PROGRAM_ID = new PublicKey(+ "AgenTMiC2hvxGebTsgmsD4HHBa8WEcqGFf87iwRRxLo7",+);++/** Pump (bonding curve) program ID */+export const PUMP_PROGRAM_ID = new PublicKey(+ "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P",+);++// PDA seeds+export const GLOBAL_CONFIG_SEED = Buffer.from("global-config");+export const TOKEN_AGENT_PAYMENTS_SEED = Buffer.from("token-agent-payments");+export const PAYMENT_IN_CURRENCY_SEED = Buffer.from("payment-in-currency");+export const INVOICE_ID_SEED = Buffer.from("invoice-id");+export const BUYBACK_AUTHORITY_SEED = Buffer.from("buyback-authority");+export const WITHDRAW_AUTHORITY_SEED = Buffer.from("withdraw-authority");+export const BONDING_CURVE_SEED = Buffer.from("bonding-curve");++/**+ * Minimum rent-exempt lamports for TokenAgentPayments account.+ * 0.00141288 SOL.+ */+export const TOKEN_AGENT_PAYMENTS_MIN_RENT_EXEMPT_LAMPORTS = 1_412_880;++/**+ * Derives the GlobalConfig PDA.+ * Seeds: ["global-config"]+ */+export function getGlobalConfigPDA(): [PublicKey, number] {+ return PublicKey.findProgramAddressSync([GLOBAL_CONFIG_SEED], PROGRAM_ID);+}++/**+ * Derives the TokenAgentPayments PDA for a given mint.+ * Seeds: ["token-agent-payments", mint]+ */+export function getTokenAgentPaymentsPDA(+ mint: PublicKey,+): [PublicKey, number] {+ return PublicKey.findProgramAddressSync(+ [TOKEN_AGENT_PAYMENTS_SEED, mint.toBuffer()],+ PROGRAM_ID,+ );+}++/**+ * Derives the TokenAgentPaymentInCurrency PDA.+ * Seeds: ["payment-in-currency", tokenMint, currencyMint]+ */+export function getPaymentInCurrencyPDA(+ tokenMint: PublicKey,+ currencyMint: PublicKey,+): [PublicKey, number] {+ return PublicKey.findProgramAddressSync(+ [PAYMENT_IN_CURRENCY_SEED, tokenMint.toBuffer(), currencyMint.toBuffer()],+ PROGRAM_ID,+ );+}++/**+ * Derives the Invoice ID PDA used to validate payment uniqueness.+ * Seeds: ["invoice-id", tokenMint, currencyMint, amount, memo, startTime, endTime]+ */+export function getInvoiceIdPDA(+ tokenMint: PublicKey,+ currencyMint: PublicKey,+ amount: BN,+ memo: BN,+ startTime: BN,+ endTime: BN,+): [PublicKey, number] {+ return PublicKey.findProgramAddressSync(+ [+ INVOICE_ID_SEED,+ tokenMint.toBuffer(),+ currencyMint.toBuffer(),+ amount.toArrayLike(Buffer, "le", 8),+ memo.toArrayLike(Buffer, "le", 8),+ startTime.toArrayLike(Buffer, "le", 8),+ endTime.toArrayLike(Buffer, "le", 8),+ ],+ PROGRAM_ID,+ );+}++/**+ * Derives the Buyback Authority PDA for a given token mint.+ * Seeds: ["buyback-authority", tokenMint]+ */+export function getBuybackAuthorityPDA(+ tokenMint: PublicKey,+): [PublicKey, number] {+ return PublicKey.findProgramAddressSync(+ [BUYBACK_AUTHORITY_SEED, tokenMint.toBuffer()],+ PROGRAM_ID,+ );+}++/**+ * Derives the Withdraw Authority PDA for a given token mint.+ * Seeds: ["withdraw-authority", tokenMint]+ */+export function getWithdrawAuthorityPDA(+ tokenMint: PublicKey,+): [PublicKey, number] {+ return PublicKey.findProgramAddressSync(+ [WITHDRAW_AUTHORITY_SEED, tokenMint.toBuffer()],+ PROGRAM_ID,+ );+}++/**+ * Derives the BondingCurve PDA from the Pump program for a given mint.+ * Seeds: ["bonding-curve", mint] (program = Pump)+ */+export function getBondingCurvePDA(+ mint: PublicKey,+): [PublicKey, number] {+ return PublicKey.findProgramAddressSync(+ [BONDING_CURVE_SEED, mint.toBuffer()],+ PUMP_PROGRAM_ID,+ );+}diff --git a/agent-payments-sdk/src/program.ts b/agent-payments-sdk/src/program.tsnew file mode 100644index 000000000..e04dbfa7e--- /dev/null+++ b/agent-payments-sdk/src/program.ts@@ -0,0 +1,50 @@+import { AnchorProvider, Program } from "@coral-xyz/anchor";+import { Connection, PublicKey } from "@solana/web3.js";+import type { PumpAgentPayments } from "./idl/pump_agent_payments";++// The IDL object is imported at runtime from the JSON file via tsup bundling.+// We use a require/import pattern that tsup resolves.+import IDL from "./idl/pump_agent_payments.json";++/**+ * Creates an Anchor Program instance for the Pump Agent Payments program.+ * Uses a dummy wallet since most operations only build instructions.+ */+export function getPumpProgram(+ connection: Connection,+): Program<PumpAgentPayments> {+ const dummyWallet = {+ publicKey: PublicKey.default,+ signTransaction: () => Promise.reject(),+ signAllTransactions: () => Promise.reject(),+ };+ return new Program(+ IDL as unknown as PumpAgentPayments,+ new AnchorProvider(connection, dummyWallet, {}),+ );+}++/**+ * Offline program instance (no connection required).+ * Useful for instruction building and account decoding without RPC.+ */+// eslint-disable-next-line @typescript-eslint/no-explicit-any+export const OFFLINE_PUMP_PROGRAM: Program<PumpAgentPayments> =+ getPumpProgram(null as any);++/**+ * Returns the program instance, falling back to the offline program+ * if no connection is provided.+ */+export function getPumpProgramWithFallback(+ connection?: Connection,+): Program<PumpAgentPayments> {+ return connection ? getPumpProgram(connection) : OFFLINE_PUMP_PROGRAM;+}++/**+ * Returns the offline program instance (alias for convenience).+ */+export function getOfflineProgram(): Program<PumpAgentPayments> {+ return OFFLINE_PUMP_PROGRAM;+}diff --git a/agent-payments-sdk/src/solana-agent-kit/actions.ts b/agent-payments-sdk/src/solana-agent-kit/actions.tsnew file mode 100644index 000000000..a9d579e33--- /dev/null+++ b/agent-payments-sdk/src/solana-agent-kit/actions.ts@@ -0,0 +1,534 @@+import { z } from "zod";+import {+ PublicKey,+ type TransactionInstruction,+} from "@solana/web3.js";+import { NATIVE_MINT, getAssociatedTokenAddressSync } from "@solana/spl-token";++import { PumpAgent } from "../PumpAgent";+import { PumpAgentOffline } from "../PumpAgentOffline";+import type { Action, SolanaAgentKitLike } from "./types";++// ─── Helpers ──────────────────────────────────────────────────────────────────++function pk(value: string): PublicKey {+ return new PublicKey(value);+}++function serializeIx(ix: TransactionInstruction) {+ return {+ programId: ix.programId.toBase58(),+ keys: ix.keys.map((k) => ({+ pubkey: k.pubkey.toBase58(),+ isSigner: k.isSigner,+ isWritable: k.isWritable,+ })),+ data: Buffer.from(ix.data).toString("base64"),+ };+}++function agent(kit: SolanaAgentKitLike, mint: string): PumpAgent {+ return new PumpAgent(pk(mint), "mainnet", kit.connection);+}++// ─── Action definitions ───────────────────────────────────────────────────────++export const createAgentPaymentsAction: Action = {+ name: "pump_agent_create",+ similes: [+ "initialize agent payments",+ "set up agent monetization",+ "create tokenized agent payment config",+ "enable payments for my agent",+ ],+ description:+ "Initialize the on-chain Agent Payments configuration for a Pump Fun token. " ++ "This must be called once by the token's bonding-curve creator before the agent " ++ "can accept payments. Sets the agent authority and buyback basis points.",+ examples: [+ [+ {+ input: {+ mint: "So11111111111111111111111111111111111111112",+ buybackBps: "500",+ },+ output: {+ status: "success",+ signature: "5K4b...txSig",+ },+ explanation:+ "Initialize agent payments for the given token with 5% buyback.",+ },+ ],+ ],+ schema: z.object({+ mint: z.string().describe("Token mint address"),+ agentAuthority: z+ .string()+ .optional()+ .describe(+ "Public key of the agent authority. Defaults to the agent wallet.",+ ),+ buybackBps: z+ .number()+ .int()+ .min(0)+ .max(10000)+ .describe("Buyback basis points (0–10000, e.g. 500 = 5%)"),+ }),+ handler: async (kit, input) => {+ const pumpAgent = PumpAgentOffline.load(pk(input.mint), kit.connection);+ const authority = kit.wallet_address;+ const agentAuthority = input.agentAuthority+ ? pk(input.agentAuthority)+ : kit.wallet_address;++ const ix = await pumpAgent.create({+ authority,+ mint: pk(input.mint),+ agentAuthority,+ buybackBps: input.buybackBps,+ });++ return { instruction: serializeIx(ix) };+ },+};++export const buildPaymentInstructionsAction: Action = {+ name: "pump_agent_build_payment_instructions",+ similes: [+ "build payment instructions",+ "create payment transaction",+ "generate agent payment",+ "prepare agent payment",+ "build agent invoice",+ ],+ description:+ "Build the accept-payment instructions for a tokenized agent. Returns serialized " ++ "instructions that the payer must sign — does NOT auto-submit. Handles native SOL " ++ "wrapping automatically when paying in SOL.",+ examples: [+ [+ {+ input: {+ mint: "So11111111111111111111111111111111111111112",+ user: "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",+ amount: "1000000",+ memo: "1",+ },+ output: {+ instructions: "[...serialized instructions]",+ },+ explanation:+ "Build payment instructions for 0.001 SOL to the agent with memo 1.",+ },+ ],+ ],+ schema: z.object({+ mint: z.string().describe("Token mint address of the agent to pay"),+ user: z.string().describe("Public key of the payer"),+ currencyMint: z+ .string()+ .optional()+ .describe("Currency mint to pay in. Defaults to native SOL (wrapped)."),+ amount: z.string().describe("Payment amount in the currency's smallest unit"),+ memo: z.string().default("0").describe("Invoice memo / identifier"),+ startTime: z+ .string()+ .default("0")+ .describe("Invoice start time (unix seconds). Defaults to 0."),+ endTime: z+ .string()+ .default("0")+ .describe("Invoice end time (unix seconds). Defaults to 0."),+ }),+ handler: async (kit, input) => {+ const pumpAgent = PumpAgentOffline.load(pk(input.mint), kit.connection);+ const currencyMint = input.currencyMint+ ? pk(input.currencyMint)+ : NATIVE_MINT;++ const ixs = await pumpAgent.buildAcceptPaymentInstructions({+ user: pk(input.user),+ currencyMint,+ amount: input.amount,+ memo: input.memo,+ startTime: input.startTime,+ endTime: input.endTime,+ });++ return { instructions: ixs.map(serializeIx) };+ },+};++export const getBalancesAction: Action = {+ name: "pump_agent_get_balances",+ similes: [+ "check agent balances",+ "get agent earnings",+ "view agent vault balances",+ "how much has the agent earned",+ ],+ description:+ "Fetch the current balances across all three agent vaults (payment, buyback, " ++ "withdraw) for a given currency. Returns vault addresses and token balances.",+ examples: [+ [+ {+ input: {+ mint: "So11111111111111111111111111111111111111112",+ },+ output: {+ paymentVault: '{"address":"...","balance":"500000"}',+ buybackVault: '{"address":"...","balance":"100000"}',+ withdrawVault: '{"address":"...","balance":"400000"}',+ },+ explanation: "Check SOL balances across all vaults for the agent.",+ },+ ],+ ],+ schema: z.object({+ mint: z.string().describe("Token mint address of the agent"),+ currencyMint: z+ .string()+ .optional()+ .describe("Currency mint to check balances for. Defaults to native SOL."),+ }),+ handler: async (kit, input) => {+ const pumpAgent = agent(kit, input.mint);+ const currencyMint = input.currencyMint+ ? pk(input.currencyMint)+ : NATIVE_MINT;++ const balances = await pumpAgent.getBalances(currencyMint);++ return {+ paymentVault: {+ address: balances.paymentVault.address.toBase58(),+ balance: balances.paymentVault.balance.toString(),+ },+ buybackVault: {+ address: balances.buybackVault.address.toBase58(),+ balance: balances.buybackVault.balance.toString(),+ },+ withdrawVault: {+ address: balances.withdrawVault.address.toBase58(),+ balance: balances.withdrawVault.balance.toString(),+ },+ };+ },+};++export const validateInvoiceAction: Action = {+ name: "pump_agent_validate_invoice",+ similes: [+ "verify payment",+ "check if user paid",+ "validate invoice",+ "confirm agent payment",+ "did the user pay",+ ],+ description:+ "Validate that a specific payment was made to an agent. Checks on-chain records " ++ "to confirm the invoice parameters match. Returns true if the payment is valid.",+ examples: [+ [+ {+ input: {+ mint: "So11111111111111111111111111111111111111112",+ user: "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",+ currencyMint: "So11111111111111111111111111111111111111112",+ amount: "1000000",+ memo: "42",+ startTime: "0",+ endTime: "0",+ },+ output: {+ valid: "true",+ },+ explanation: "Validate that the user paid 0.001 SOL with memo 42.",+ },+ ],+ ],+ schema: z.object({+ mint: z.string().describe("Token mint address of the agent"),+ user: z.string().describe("Public key of the payer to validate"),+ currencyMint: z.string().describe("Currency mint used for payment"),+ amount: z.string().describe("Expected payment amount"),+ memo: z.string().describe("Expected invoice memo"),+ startTime: z.string().describe("Expected invoice start time (unix seconds)"),+ endTime: z.string().describe("Expected invoice end time (unix seconds)"),+ }),+ handler: async (kit, input) => {+ const pumpAgent = agent(kit, input.mint);++ const valid = await pumpAgent.validateInvoicePayment({+ user: pk(input.user),+ currencyMint: pk(input.currencyMint),+ amount: Number(input.amount),+ memo: Number(input.memo),+ startTime: Number(input.startTime),+ endTime: Number(input.endTime),+ });++ return { valid };+ },+};++export const distributePaymentsAction: Action = {+ name: "pump_agent_distribute_payments",+ similes: [+ "distribute agent payments",+ "split agent revenue",+ "process agent payments",+ "trigger payment distribution",+ ],+ description:+ "Distribute accumulated payments between the buyback and withdraw vaults " ++ "according to the configured buyback basis points. This is permissionless — " ++ "anyone can trigger it.",+ examples: [+ [+ {+ input: {+ mint: "So11111111111111111111111111111111111111112",+ },+ output: {+ status: "success",+ signature: "3Yp7...txSig",+ },+ explanation: "Distribute accumulated SOL payments for the agent.",+ },+ ],+ ],+ schema: z.object({+ mint: z.string().describe("Token mint address of the agent"),+ currencyMint: z+ .string()+ .optional()+ .describe("Currency mint to distribute. Defaults to native SOL."),+ }),+ handler: async (kit, input) => {+ const pumpAgent = PumpAgentOffline.load(pk(input.mint), kit.connection);+ const currencyMint = input.currencyMint+ ? pk(input.currencyMint)+ : NATIVE_MINT;++ const ixs = await pumpAgent.distributePayments({+ user: kit.wallet_address,+ currencyMint,+ includeTransferExtraLamportsForNative: currencyMint.equals(NATIVE_MINT),+ });++ return { instructions: ixs.map(serializeIx) };+ },+};++export const withdrawAction: Action = {+ name: "pump_agent_withdraw",+ similes: [+ "withdraw agent earnings",+ "withdraw agent payments",+ "claim agent revenue",+ "withdraw from agent vault",+ ],+ description:+ "Withdraw accumulated earnings from the agent withdraw vault. " ++ "Must be called by the agent authority. Transfers tokens from the " ++ "withdraw vault to the specified receiver token account.",+ examples: [+ [+ {+ input: {+ mint: "So11111111111111111111111111111111111111112",+ currencyMint: "So11111111111111111111111111111111111111112",+ },+ output: {+ status: "success",+ signature: "4Rz8...txSig",+ },+ explanation: "Withdraw accumulated SOL earnings from the agent.",+ },+ ],+ ],+ schema: z.object({+ mint: z.string().describe("Token mint address of the agent"),+ currencyMint: z.string().describe("Currency mint to withdraw"),+ receiverAta: z+ .string()+ .optional()+ .describe(+ "Receiver token account. Defaults to the agent wallet's ATA for the currency.",+ ),+ }),+ handler: async (kit, input) => {+ const pumpAgent = PumpAgentOffline.load(pk(input.mint), kit.connection);+ const currencyMint = pk(input.currencyMint);++ const receiverAta = input.receiverAta+ ? pk(input.receiverAta)+ : getAssociatedTokenAddressSync(currencyMint, kit.wallet_address);++ const ix = await pumpAgent.withdraw({+ authority: kit.wallet_address,+ currencyMint,+ receiverAta,+ });++ return { instruction: serializeIx(ix) };+ },+};++export const getConfigAction: Action = {+ name: "pump_agent_get_config",+ similes: [+ "get agent config",+ "check agent settings",+ "view agent payment config",+ "agent payment configuration",+ ],+ description:+ "Fetch the on-chain Agent Payments configuration for a token. " ++ "Returns the agent authority, buyback basis points, and token mint.",+ examples: [+ [+ {+ input: {+ mint: "So11111111111111111111111111111111111111112",+ },+ output: {+ authority: "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",+ buybackBps: "500",+ mint: "So11111111111111111111111111111111111111112",+ },+ explanation: "Fetch the agent payment configuration.",+ },+ ],+ ],+ schema: z.object({+ mint: z.string().describe("Token mint address of the agent"),+ }),+ handler: async (kit, input) => {+ const pumpAgent = agent(kit, input.mint);+ const config = await pumpAgent.getAgentConfig();++ return {+ authority: config.authority.toBase58(),+ buybackBps: config.buybackBps,+ mint: config.mint.toBase58(),+ };+ },+};++export const getPaymentStatsAction: Action = {+ name: "pump_agent_get_payment_stats",+ similes: [+ "get payment stats",+ "agent payment statistics",+ "how much has the agent earned",+ "payment analytics",+ ],+ description:+ "Fetch per-currency payment statistics for an agent. Returns total payments " ++ "received, total distributed to buyback, total distributed to withdraw, and " ++ "tokens burned.",+ examples: [+ [+ {+ input: {+ mint: "So11111111111111111111111111111111111111112",+ currencyMint: "So11111111111111111111111111111111111111112",+ },+ output: {+ totalPayments: "10000000",+ totalBuyback: "2000000",+ totalWithdraw: "8000000",+ },+ explanation: "Get SOL payment statistics for the agent.",+ },+ ],+ ],+ schema: z.object({+ mint: z.string().describe("Token mint address of the agent"),+ currencyMint: z.string().describe("Currency mint to get stats for"),+ }),+ handler: async (kit, input) => {+ const pumpAgent = agent(kit, input.mint);+ const stats = await pumpAgent.getPaymentStats(pk(input.currencyMint));++ // Convert all BN / bigint fields to strings for JSON serialization+ const result: Record<string, any> = {};+ for (const [key, value] of Object.entries(stats as Record<string, unknown>)) {+ if (value instanceof PublicKey) {+ result[key] = value.toBase58();+ } else if (typeof value === "bigint") {+ result[key] = value.toString();+ } else if (value != null && typeof value === "object" && "toString" in value) {+ result[key] = String(value);+ } else {+ result[key] = value;+ }+ }+ return result;+ },+};++export const updateBuybackBpsAction: Action = {+ name: "pump_agent_update_buyback_bps",+ similes: [+ "update buyback percentage",+ "change buyback bps",+ "set buyback rate",+ "modify agent buyback",+ ],+ description:+ "Update the buyback basis points for an agent's payment configuration. " ++ "Must be called by the agent authority. The new bps value determines what " ++ "percentage of future payments are allocated to token buyback and burn.",+ examples: [+ [+ {+ input: {+ mint: "So11111111111111111111111111111111111111112",+ buybackBps: "1000",+ },+ output: {+ status: "success",+ signature: "5Tz9...txSig",+ },+ explanation: "Update buyback to 10% (1000 bps) for the agent.",+ },+ ],+ ],+ schema: z.object({+ mint: z.string().describe("Token mint address of the agent"),+ buybackBps: z+ .number()+ .int()+ .min(0)+ .max(10000)+ .describe("New buyback basis points (0–10000, e.g. 1000 = 10%)"),+ }),+ handler: async (kit, input) => {+ const pumpAgent = agent(kit, input.mint);++ const ix = await pumpAgent.updateBuybackBps({+ authority: kit.wallet_address,+ buybackBps: input.buybackBps,+ });++ return { instruction: serializeIx(ix) };+ },+};++export const allActions: Action[] = [+ createAgentPaymentsAction,+ buildPaymentInstructionsAction,+ getBalancesAction,+ validateInvoiceAction,+ distributePaymentsAction,+ withdrawAction,+ getConfigAction,+ getPaymentStatsAction,+ updateBuybackBpsAction,+];diff --git a/agent-payments-sdk/src/solana-agent-kit/index.ts b/agent-payments-sdk/src/solana-agent-kit/index.tsnew file mode 100644index 000000000..13945ee23--- /dev/null+++ b/agent-payments-sdk/src/solana-agent-kit/index.ts@@ -0,0 +1,185 @@+/**+ * solana-agent-kit plugin for @pump-fun/agent-payments-sdk+ *+ * Usage with solana-agent-kit v2:+ * ```ts+ * import { SolanaAgentKit } from "solana-agent-kit";+ * import { PumpAgentPaymentsPlugin } from "@pump-fun/agent-payments-sdk/solana-agent-kit";+ *+ * const agent = new SolanaAgentKit(privateKey, rpcUrl, {});+ * agent.use(PumpAgentPaymentsPlugin);+ * ```+ */++import { PublicKey } from "@solana/web3.js";+import { NATIVE_MINT, getAssociatedTokenAddressSync } from "@solana/spl-token";++import { PumpAgent } from "../PumpAgent";+import { PumpAgentOffline } from "../PumpAgentOffline";+import type { Plugin, SolanaAgentKitLike } from "./types";+import { allActions } from "./actions";++// ─── Typed helper methods (programmatic API) ─────────────────────────────────++async function createAgentPayments(+ agent: SolanaAgentKitLike,+ mint: PublicKey,+ buybackBps: number,+ agentAuthority?: PublicKey,+) {+ const pump = PumpAgentOffline.load(mint, agent.connection);+ return pump.create({+ authority: agent.wallet_address,+ mint,+ agentAuthority: agentAuthority ?? agent.wallet_address,+ buybackBps,+ });+}++async function buildPayAgentInstructions(+ agent: SolanaAgentKitLike,+ mint: PublicKey,+ currencyMint: PublicKey,+ amount: string,+ memo = "0",+ startTime = "0",+ endTime = "0",+) {+ const pump = PumpAgentOffline.load(mint, agent.connection);+ return pump.buildAcceptPaymentInstructions({+ user: agent.wallet_address,+ currencyMint,+ amount,+ memo,+ startTime,+ endTime,+ });+}++async function getAgentBalances(+ agent: SolanaAgentKitLike,+ mint: PublicKey,+ currencyMint: PublicKey = NATIVE_MINT,+) {+ const pump = new PumpAgent(mint, "mainnet", agent.connection);+ return pump.getBalances(currencyMint);+}++async function validateInvoicePayment(+ agent: SolanaAgentKitLike,+ mint: PublicKey,+ user: PublicKey,+ currencyMint: PublicKey,+ amount: number,+ memo: number,+ startTime: number,+ endTime: number,+) {+ const pump = new PumpAgent(mint, "mainnet", agent.connection);+ return pump.validateInvoicePayment({+ user,+ currencyMint,+ amount,+ memo,+ startTime,+ endTime,+ });+}++async function distributeAgentPayments(+ agent: SolanaAgentKitLike,+ mint: PublicKey,+ currencyMint: PublicKey = NATIVE_MINT,+) {+ const pump = PumpAgentOffline.load(mint, agent.connection);+ return pump.distributePayments({+ user: agent.wallet_address,+ currencyMint,+ includeTransferExtraLamportsForNative: currencyMint.equals(NATIVE_MINT),+ });+}++async function withdrawAgentPayments(+ agent: SolanaAgentKitLike,+ mint: PublicKey,+ currencyMint: PublicKey,+ receiverAta?: PublicKey,+) {+ const pump = PumpAgentOffline.load(mint, agent.connection);+ return pump.withdraw({+ authority: agent.wallet_address,+ currencyMint,+ receiverAta:+ receiverAta ??+ getAssociatedTokenAddressSync(currencyMint, agent.wallet_address),+ });+}++async function getAgentConfig(agent: SolanaAgentKitLike, mint: PublicKey) {+ const pump = new PumpAgent(mint, "mainnet", agent.connection);+ return pump.getAgentConfig();+}++async function getPaymentStats(+ agent: SolanaAgentKitLike,+ mint: PublicKey,+ currencyMint: PublicKey,+) {+ const pump = new PumpAgent(mint, "mainnet", agent.connection);+ return pump.getPaymentStats(currencyMint);+}++async function updateBuybackBps(+ agent: SolanaAgentKitLike,+ mint: PublicKey,+ buybackBps: number,+) {+ const pump = new PumpAgent(mint, "mainnet", agent.connection);+ return pump.updateBuybackBps({+ authority: agent.wallet_address,+ buybackBps,+ });+}++// ─── Plugin ───────────────────────────────────────────────────────────────────++export const PumpAgentPaymentsPlugin: Plugin = {+ name: "pump-agent-payments",++ methods: {+ createAgentPayments,+ buildPayAgentInstructions,+ getAgentBalances,+ validateInvoicePayment,+ distributeAgentPayments,+ withdrawAgentPayments,+ getAgentConfig,+ getPaymentStats,+ updateBuybackBps,+ },++ actions: allActions,+};++// ─── Re-exports ───────────────────────────────────────────────────────────────++export type {+ Action,+ ActionExample,+ ActionHandler,+ Plugin,+ SolanaAgentKitLike,+} from "./types";++export {+ createAgentPaymentsAction,+ buildPaymentInstructionsAction,+ getBalancesAction,+ validateInvoiceAction,+ distributePaymentsAction,+ withdrawAction,+ getConfigAction,+ getPaymentStatsAction,+ updateBuybackBpsAction,+ allActions,+} from "./actions";diff --git a/agent-payments-sdk/src/solana-agent-kit/types.ts b/agent-payments-sdk/src/solana-agent-kit/types.tsnew file mode 100644index 000000000..c81ffd36b--- /dev/null+++ b/agent-payments-sdk/src/solana-agent-kit/types.ts@@ -0,0 +1,38 @@+import type { Connection, Keypair, PublicKey } from "@solana/web3.js";+import type { z } from "zod";++/**+ * Minimal structural interface compatible with solana-agent-kit's SolanaAgentKit.+ * Uses structural typing so consumers don't need to import SolanaAgentKit directly.+ */+export interface SolanaAgentKitLike {+ connection: Connection;+ wallet: Keypair;+ wallet_address: PublicKey;+}++export type ActionHandler = (+ agent: SolanaAgentKitLike,+ input: Record<string, any>,+) => Promise<Record<string, any>>;++export interface ActionExample {+ input: Record<string, string>;+ output: Record<string, string>;+ explanation: string;+}++export interface Action {+ name: string;+ similes: string[];+ description: string;+ examples: ActionExample[][];+ schema: z.ZodType<any>;+ handler: ActionHandler;+}++export interface Plugin {+ name: string;+ methods: Record<string, Function>;+ actions: Action[];+}diff --git a/agent-payments-sdk/src/types.ts b/agent-payments-sdk/src/types.tsnew file mode 100644index 000000000..9146788ae--- /dev/null+++ b/agent-payments-sdk/src/types.ts@@ -0,0 +1,173 @@+import type { AccountMeta, PublicKey } from "@solana/web3.js";+import type { BN } from "@coral-xyz/anchor";++// ─── Environment ────────────────────────────────────────────────────────────++export type PumpEnvironment = "devnet" | "mainnet";++// ─── Vault / Balance types ──────────────────────────────────────────────────++export interface VaultBalance {+ address: PublicKey;+ balance: bigint;+}++export interface AgentBalances {+ /** ATA of the TokenAgentPayments PDA (incoming payments land here) */+ paymentVault: VaultBalance;+ /** ATA of the Buyback Authority PDA */+ buybackVault: VaultBalance;+ /** ATA of the Withdraw Authority PDA */+ withdrawVault: VaultBalance;+}++// ─── Instruction parameter interfaces ───────────────────────────────────────++export interface CreateParams {+ /** Signer – must be the bonding-curve creator for this mint */+ authority: PublicKey;+ /** The token mint this agent manages */+ mint: PublicKey;+ /** The pubkey that will act as the agent authority (for withdraw / update) */+ agentAuthority: PublicKey;+ /** Basis points allocated to buyback (0–10 000) */+ buybackBps: number;+}++export interface WithdrawParams {+ /** Agent authority signer */+ authority: PublicKey;+ /** Currency mint to withdraw */+ currencyMint: PublicKey;+ /** Receiver's token account for the currency */+ receiverAta: PublicKey;+ /** Token program for the currency mint (defaults to TOKEN_PROGRAM_ID) */+ tokenProgram?: PublicKey;+}++export interface UpdateBuybackBpsParams {+ /** Agent authority signer */+ authority: PublicKey;+ /** New buyback basis points (0–10 000) */+ buybackBps: number;+}++export interface UpdateBuybackBpsOptions {+ /** Supported currencies and their token programs */+ supportedCurrencies: {+ mint: PublicKey;+ tokenProgram: PublicKey;+ }[];+}++export interface AcceptPaymentParams {+ /** Payer / user signer */+ user: PublicKey;+ /** User's token account holding the currency */+ userTokenAccount: PublicKey;+ /** The currency mint being paid */+ currencyMint: PublicKey;+ amount: BN;+ memo: BN;+ startTime: BN;+ endTime: BN;+ /** Token program for the currency mint (defaults to TOKEN_PROGRAM_ID) */+ tokenProgram?: PublicKey;+}++export interface AcceptPaymentSimpleParams {+ user: PublicKey;+ userTokenAccount: PublicKey;+ currencyMint: PublicKey;+ amount: bigint | number | string;+ memo: bigint | number | string;+ startTime: bigint | number | string;+ endTime: bigint | number | string;+ tokenProgram?: PublicKey;+ /** Compute unit limit (defaults to 130_000) */+ computeUnitLimit?: number;+ /** Priority fee in micro lamports per compute unit (defaults to 1_000) */+ computeUnitPrice?: number;+}++export interface BuildAcceptPaymentParams {+ user: PublicKey;+ currencyMint: PublicKey;+ amount: bigint | number | string;+ memo: bigint | number | string;+ startTime: bigint | number | string;+ endTime: bigint | number | string;+ tokenProgram?: PublicKey;+ /** Compute unit limit for the transaction (defaults to 100_000) */+ computeUnitLimit?: number;+ /** Priority fee in microlamports per compute unit. If provided, a SetComputeUnitPrice instruction is prepended. */+ computeUnitPrice?: number;+}++export interface DistributePaymentsParams {+ /** Any signer (permissionless) */+ user: PublicKey;+ /** Currency mint to distribute */+ currencyMint: PublicKey;+ /** Token program for the currency mint (defaults to TOKEN_PROGRAM_ID) */+ tokenProgram?: PublicKey;+ /**+ * For native SOL only: prepend `agentTransferExtraLamports` before distribute.+ * Default is false.+ */+ includeTransferExtraLamportsForNative?: boolean;+}++export interface BuybackTriggerParams {+ /** Must match globalConfig.buybackAuthority */+ globalBuybackAuthority: PublicKey;+ /** The currency mint used for the swap (tracks per-currency buyback accounting) */+ currencyMint: PublicKey;+ /** Swap program to CPI into (must be in the allowed list) */+ swapProgramToInvoke: PublicKey;+ /** Serialised swap instruction data (pass empty Buffer to skip swap & just burn) */+ swapInstructionData: Buffer;+ /** All accounts the swap instruction requires */+ remainingAccounts: AccountMeta[];+ /** Token program for the currency mint (defaults to TOKEN_PROGRAM_ID) */+ tokenProgramCurrency?: PublicKey;+ /** Token program for the agent token mint (defaults to TOKEN_PROGRAM_ID) */+ tokenProgram?: PublicKey;+}++export interface ExtendAccountParams {+ /** Account to extend (must be a supported account type on-chain) */+ account: PublicKey;+ /** Signer paying rent for extension */+ user: PublicKey;+}++export interface UpdateAuthorityParams {+ /** Current agent authority signer (or protocol authority for recovery) */+ authority: PublicKey;+ /** The new authority pubkey to set */+ newAuthority: PublicKey;+}++export interface CloseAccountParams {+ /** The account to close (TokenAgentPayments, PaymentInCurrency, etc.) */+ account: PublicKey;+ /** Signer who receives the reclaimed rent lamports */+ user: PublicKey;+}++// ─── Decoded account types (derived from the Anchor program) ────────────────++import { OFFLINE_PUMP_PROGRAM } from "./program";++export type GlobalConfig = Awaited<+ ReturnType<typeof OFFLINE_PUMP_PROGRAM.account.GlobalConfig.fetch>+>;++export type TokenAgentPaymentInCurrency = Awaited<+ ReturnType<typeof OFFLINE_PUMP_PROGRAM.account.TokenAgentPaymentInCurrency.fetch>+>;++export type TokenAgentPayments = Awaited<+ ReturnType<typeof OFFLINE_PUMP_PROGRAM.account.TokenAgentPayments.fetch>+>;diff --git a/agent-payments-sdk/src/x402/client.ts b/agent-payments-sdk/src/x402/client.tsnew file mode 100644index 000000000..6f8961b3b--- /dev/null+++ b/agent-payments-sdk/src/x402/client.ts@@ -0,0 +1,246 @@+/**+ * x402 v2 Client – automatic 402 handling+ *+ * A fetch wrapper that intercepts HTTP 402 responses, builds and signs+ * a payment transaction matching the server's PaymentRequirements, and+ * retries the request with a PAYMENT-SIGNATURE header.+ *+ * Supports both "pump-agent" (Pump Agent invoice) and "exact" (SPL+ * TransferChecked) schemes.+ */++import {+ Connection,+ PublicKey,+ Transaction,+} from "@solana/web3.js";+import { PumpAgentOffline } from "../PumpAgentOffline";+import {+ encodePaymentPayload,+ getPaymentRequiredFromResponse,+} from "./headers";+import type {+ X402ClientConfig,+ PaymentPayload,+ PaymentRequired,+ PaymentRequirements,+ PumpAgentPaymentRequirements,+} from "./types";+import {+ X402_HEADER_PAYMENT_SIGNATURE,+ X402_VERSION,+ SOLANA_MAINNET,+} from "./types";++// ─── Client-side x402 fetch wrapper ─────────────────────────────────────────++/**+ * Create a fetch function that automatically handles HTTP 402 responses+ * by building a payment transaction, signing, sending, and retrying+ * the original request with payment proof in the PAYMENT-SIGNATURE header.+ *+ * @example+ * ```ts+ * import { createX402Fetch } from "@pump-fun/agent-payments-sdk/x402";+ *+ * const x402fetch = createX402Fetch({+ * payer: wallet.publicKey.toBase58(),+ * signTransaction: async (txBase64) => {+ * const tx = Transaction.from(Buffer.from(txBase64, "base64"));+ * const signed = await wallet.signTransaction(tx);+ * return Buffer.from(signed.serialize()).toString("base64");+ * },+ * sendTransaction: async (signedTxBase64) => {+ * const raw = Buffer.from(signedTxBase64, "base64");+ * const sig = await connection.sendRawTransaction(raw);+ * await connection.confirmTransaction(sig, "confirmed");+ * return sig;+ * },+ * });+ *+ * const res = await x402fetch("https://api.agent.example/inference", {+ * method: "POST",+ * body: JSON.stringify({ prompt: "Hello" }),+ * });+ * ```+ */+export function createX402Fetch(+ config: X402ClientConfig & { connection: Connection },+): typeof fetch {+ const {+ payer,+ signTransaction,+ sendTransaction,+ connection,+ network = SOLANA_MAINNET,+ confirmationTimeoutMs = 30_000,+ } = config;++ return async (+ input: RequestInfo | URL,+ init?: RequestInit,+ ): Promise<Response> => {+ const response = await fetch(input, init);++ if (response.status !== 402) return response;++ const paymentRequired = getPaymentRequiredFromResponse(response);+ if (!paymentRequired) return response;++ // Find a compatible requirement+ const accepted = selectRequirement(paymentRequired, network);+ if (!accepted) return response;++ // Build, sign, and send the payment+ const proof = await buildPaymentProof(+ accepted,+ payer,+ connection,+ signTransaction,+ sendTransaction,+ confirmationTimeoutMs,+ );++ // Build the PaymentPayload+ const paymentPayload: PaymentPayload = {+ x402Version: X402_VERSION,+ resource: typeof input === "string" ? input : input instanceof URL ? input.href : input.url,+ accepted,+ payload: proof,+ };++ // Retry the original request with PAYMENT-SIGNATURE header+ const retryInit: RequestInit = { ...init };+ const headers = new Headers(retryInit.headers);+ headers.set(X402_HEADER_PAYMENT_SIGNATURE, encodePaymentPayload(paymentPayload));+ retryInit.headers = headers;++ return fetch(input, retryInit);+ };+}++// ─── Requirement Selection ──────────────────────────────────────────────────++function selectRequirement(+ paymentRequired: PaymentRequired,+ network: string,+): PaymentRequirements | null {+ // Prefer pump-agent scheme on the matching network, then fall back to exact+ return (+ paymentRequired.accepts.find(+ (r) => r.scheme === "pump-agent" && r.network === network,+ ) ??+ paymentRequired.accepts.find(+ (r) => r.scheme === "exact" && r.network === network,+ ) ??+ null+ );+}++// ─── Payment Proof Builder ──────────────────────────────────────────────────++async function buildPaymentProof(+ requirements: PaymentRequirements,+ payer: string,+ connection: Connection,+ signTransaction: (txBase64: string) => Promise<string>,+ sendTransaction: (signedTxBase64: string) => Promise<string>,+ confirmationTimeoutMs: number,+): Promise<Record<string, unknown>> {+ if (requirements.scheme === "pump-agent") {+ return buildPumpAgentProof(+ requirements as PumpAgentPaymentRequirements,+ payer,+ connection,+ signTransaction,+ sendTransaction,+ confirmationTimeoutMs,+ );+ }++ throw new Error(`Unsupported scheme: ${requirements.scheme}`);+}++async function buildPumpAgentProof(+ requirements: PumpAgentPaymentRequirements,+ payer: string,+ connection: Connection,+ signTransaction: (txBase64: string) => Promise<string>,+ sendTransaction: (signedTxBase64: string) => Promise<string>,+ confirmationTimeoutMs: number,+): Promise<Record<string, unknown>> {+ const { extra } = requirements;++ const agent = new PumpAgentOffline(new PublicKey(extra.agentMint));+ const instructions = await agent.buildAcceptPaymentInstructions({+ user: new PublicKey(payer),+ currencyMint: new PublicKey(requirements.asset),+ amount: requirements.amount,+ memo: extra.memo,+ startTime: extra.startTime,+ endTime: extra.endTime,+ });++ const { blockhash, lastValidBlockHeight } =+ await connection.getLatestBlockhash("confirmed");++ const tx = new Transaction();+ tx.recentBlockhash = blockhash;+ tx.lastValidBlockHeight = lastValidBlockHeight;+ tx.feePayer = new PublicKey(payer);+ tx.add(...instructions);++ const txBase64 = Buffer.from(+ tx.serialize({ requireAllSignatures: false }),+ ).toString("base64");++ const signedTxBase64 = await signTransaction(txBase64);+ const signature = await sendTransaction(signedTxBase64);++ await waitForConfirmation(+ connection,+ signature,+ lastValidBlockHeight,+ confirmationTimeoutMs,+ );++ return {+ signature,+ payer,+ agentMint: extra.agentMint,+ asset: requirements.asset,+ amount: requirements.amount,+ memo: extra.memo,+ startTime: extra.startTime,+ endTime: extra.endTime,+ };+}++// ─── Confirmation Helper ────────────────────────────────────────────────────++async function waitForConfirmation(+ connection: Connection,+ signature: string,+ lastValidBlockHeight: number,+ timeoutMs: number,+): Promise<void> {+ const start = Date.now();+ while (Date.now() - start < timeoutMs) {+ const status = await connection.getSignatureStatus(signature);+ const value = status?.value;+ if (+ value?.confirmationStatus === "confirmed" ||+ value?.confirmationStatus === "finalized"+ ) {+ if (value.err)+ throw new Error(`Transaction failed: ${JSON.stringify(value.err)}`);+ return;+ }+ const blockHeight = await connection.getBlockHeight();+ if (blockHeight > lastValidBlockHeight) {+ throw new Error("Transaction expired (blockhash no longer valid)");+ }+ await new Promise((r) => setTimeout(r, 2_000));+ }+ throw new Error("Transaction confirmation timed out");+}diff --git a/agent-payments-sdk/src/x402/facilitator.ts b/agent-payments-sdk/src/x402/facilitator.tsnew file mode 100644index 000000000..a390210fc--- /dev/null+++ b/agent-payments-sdk/src/x402/facilitator.ts@@ -0,0 +1,380 @@+/**+ * x402 v2 Facilitator & Resource Server+ *+ * Implements the coinbase/x402 3-party architecture:+ * Client → Resource Server → Facilitator (verify / settle)+ *+ * Provides:+ * - PumpAgentFacilitator: FacilitatorClient that verifies & settles+ * "pump-agent" scheme payments using PumpAgent on-chain validation.+ * - createResourceServer: framework-agnostic Request/Response middleware+ * that returns 402s, verifies payment via a facilitator, and settles.+ */++import { PublicKey, Connection } from "@solana/web3.js";+import { PumpAgent } from "../PumpAgent";+import {+ decodePaymentPayload,+ encodePaymentRequired,+ encodePaymentResponse,+} from "./headers";+import type {+ FacilitatorClient,+ PaymentPayload,+ PaymentRequired,+ PaymentRequirements,+ PaymentResponse,+ PumpAgentPaymentRequirements,+ ResourceServerConfig,+ SettleResponse,+ SupportedResponse,+ VerifyResponse,+} from "./types";+import {+ X402_VERSION,+ X402_HEADER_PAYMENT_REQUIRED,+ X402_HEADER_PAYMENT_SIGNATURE,+ X402_HEADER_PAYMENT_RESPONSE,+ SOLANA_MAINNET,+ USDC_MAINNET,+} from "./types";++// ─── Settlement Cache ───────────────────────────────────────────────────────++class SettlementCache {+ private cache = new Map<string, number>();+ private maxSize: number;+ private ttlMs: number;++ constructor(maxSize = 10_000, ttlMs = 120_000) {+ this.maxSize = maxSize;+ this.ttlMs = ttlMs;+ }++ has(key: string): boolean {+ const ts = this.cache.get(key);+ if (!ts) return false;+ if (Date.now() - ts > this.ttlMs) {+ this.cache.delete(key);+ return false;+ }+ return true;+ }++ set(key: string): void {+ this.cache.set(key, Date.now());+ if (this.cache.size > this.maxSize) {+ const cutoff = Date.now() - this.ttlMs;+ for (const [k, v] of this.cache) {+ if (v < cutoff) this.cache.delete(k);+ }+ }+ }+}++// ─── Invoice Memo Generation ────────────────────────────────────────────────++let memoCounter = 0;++function generateMemo(): string {+ const ts = Date.now();+ memoCounter = (memoCounter + 1) % 1_000_000;+ return `${ts}${String(memoCounter).padStart(6, "0")}`;+}++// ─── Pump Agent Facilitator ─────────────────────────────────────────────────++export interface PumpAgentFacilitatorConfig {+ /** Solana RPC connection */+ connection: Connection;+ /** CAIP-2 network (default: SOLANA_MAINNET) */+ network?: string;+}++/**+ * FacilitatorClient implementation for the "pump-agent" scheme.+ *+ * Uses PumpAgent.validateInvoicePayment() for on-chain verification,+ * and treats the client-submitted transaction signature as the settlement.+ */+export class PumpAgentFacilitator implements FacilitatorClient {+ private connection: Connection;+ private network: string;+ private settlementCache = new SettlementCache();++ constructor(config: PumpAgentFacilitatorConfig) {+ this.connection = config.connection;+ this.network = config.network ?? SOLANA_MAINNET;+ }++ async verify(+ payload: PaymentPayload,+ requirements: PaymentRequirements,+ ): Promise<VerifyResponse> {+ if (requirements.scheme !== "pump-agent") {+ return { isValid: false, invalidReason: "Unsupported scheme" };+ }++ if (payload.x402Version !== X402_VERSION) {+ return { isValid: false, invalidReason: `Expected x402Version ${X402_VERSION}` };+ }++ const req = requirements as PumpAgentPaymentRequirements;+ const proof = payload.payload as Record<string, unknown>;+ const signature = proof.signature as string | undefined;+ const payer = proof.payer as string | undefined;++ if (!signature || !payer) {+ return { isValid: false, invalidReason: "Missing signature or payer" };+ }++ // Duplicate check+ if (this.settlementCache.has(signature)) {+ return { isValid: false, invalidReason: "Duplicate payment" };+ }++ // Verify amount matches+ if (+ payload.accepted.amount !== requirements.amount ||+ payload.accepted.asset !== requirements.asset+ ) {+ return { isValid: false, invalidReason: "Amount or asset mismatch" };+ }++ try {+ const agent = new PumpAgent(+ new PublicKey(req.extra.agentMint),+ req.network === SOLANA_MAINNET ? "mainnet" : "devnet",+ this.connection,+ );++ const valid = await agent.validateInvoicePayment({+ user: new PublicKey(payer),+ currencyMint: new PublicKey(req.asset),+ amount: Number(req.amount),+ memo: Number(req.extra.memo),+ startTime: req.extra.startTime,+ endTime: req.extra.endTime,+ });++ if (!valid) {+ return { isValid: false, invalidReason: "On-chain validation failed", payer };+ }++ return { isValid: true, payer };+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ return { isValid: false, invalidReason: `Verification error: ${message}` };+ }+ }++ async settle(+ payload: PaymentPayload,+ requirements: PaymentRequirements,+ ): Promise<SettleResponse> {+ // For pump-agent scheme the client already submitted the transaction.+ // We just verify and cache to prevent double-spend.+ const verifyResult = await this.verify(payload, requirements);++ if (!verifyResult.isValid) {+ return {+ success: false,+ errorReason: verifyResult.invalidReason,+ payer: verifyResult.payer,+ };+ }++ const proof = payload.payload as Record<string, unknown>;+ const signature = proof.signature as string;+ const payer = proof.payer as string;++ this.settlementCache.set(signature);++ return {+ success: true,+ payer,+ transaction: signature,+ network: this.network,+ };+ }++ async getSupported(): Promise<SupportedResponse> {+ return {+ kinds: [+ {+ scheme: "pump-agent",+ network: this.network,+ asset: USDC_MAINNET,+ },+ ],+ };+ }+}++// ─── Payment Requirements Builder ───────────────────────────────────────────++export interface PumpAgentRequirementsConfig {+ /** Agent token mint (base58) */+ agentMint: string;+ /** Currency / asset mint (base58). Defaults to USDC mainnet */+ asset?: string;+ /** Recipient address (generally the payment vault) */+ payTo: string;+ /** Price in minor units */+ amount: string;+ /** CAIP-2 network (default: SOLANA_MAINNET) */+ network?: string;+ /** Invoice window in seconds (default: 300) */+ invoiceWindowSeconds?: number;+ /** Max settlement timeout in seconds (default: 60) */+ maxTimeoutSeconds?: number;+}++/**+ * Build fresh PumpAgentPaymentRequirements with a unique invoice memo.+ */+export function buildPumpAgentRequirements(+ config: PumpAgentRequirementsConfig,+): PumpAgentPaymentRequirements {+ const windowSec = config.invoiceWindowSeconds ?? 300;+ const now = Math.floor(Date.now() / 1000);++ return {+ scheme: "pump-agent",+ network: config.network ?? SOLANA_MAINNET,+ asset: config.asset ?? USDC_MAINNET,+ amount: config.amount,+ payTo: config.payTo,+ maxTimeoutSeconds: config.maxTimeoutSeconds ?? 60,+ extra: {+ agentMint: config.agentMint,+ memo: generateMemo(),+ startTime: now,+ endTime: now + windowSec,+ },+ };+}++// ─── Resource Server Middleware ──────────────────────────────────────────────++/**+ * Creates a handler wrapper that implements the x402 Resource Server role.+ *+ * On requests without PAYMENT-SIGNATURE: returns 402 with PAYMENT-REQUIRED.+ * On requests with PAYMENT-SIGNATURE: verifies → settles → forwards to handler.+ *+ * Works with any framework using the standard Request/Response API+ * (Hono, Next.js App Router, Cloudflare Workers, Bun, Deno, etc.).+ *+ * @example+ * ```ts+ * const gate = createResourceServer({+ * facilitator: new PumpAgentFacilitator({ connection }),+ * requirements: [buildPumpAgentRequirements({+ * agentMint: "YourMint...",+ * payTo: "PaymentVault...",+ * amount: "1000000",+ * })],+ * resource: { url: "/api/inference", description: "AI call" },+ * });+ *+ * // Hono+ * app.get("/api/inference", (c) =>+ * gate(c.req.raw, () => c.json({ result: "..." }))+ * );+ * ```+ */+export function createResourceServer(+ config: ResourceServerConfig,+): (+ request: Request,+ handler: () => Response | Promise<Response>,+) => Promise<Response> {+ const { facilitator, resource } = config;++ return async (+ request: Request,+ handler: () => Response | Promise<Response>,+ ): Promise<Response> => {+ const paymentHeader = request.headers.get(X402_HEADER_PAYMENT_SIGNATURE);++ if (!paymentHeader) {+ // Build fresh requirements (with new invoice memos)+ const body: PaymentRequired = {+ x402Version: X402_VERSION,+ resource,+ accepts: config.requirements,+ };++ return new Response(JSON.stringify(body), {+ status: 402,+ statusText: "Payment Required",+ headers: {+ "Content-Type": "application/json",+ [X402_HEADER_PAYMENT_REQUIRED]: encodePaymentRequired(body),+ },+ });+ }++ // Decode the payment payload+ let paymentPayload: PaymentPayload;+ try {+ paymentPayload = decodePaymentPayload(paymentHeader);+ } catch {+ return new Response("Invalid PAYMENT-SIGNATURE header", { status: 400 });+ }++ // Find the matching requirement+ const accepted = paymentPayload.accepted;+ const matchedReq = config.requirements.find(+ (r) => r.scheme === accepted.scheme && r.network === accepted.network,+ );++ if (!matchedReq) {+ return new Response("No matching payment requirement", { status: 400 });+ }++ // Verify+ const verifyResult = await facilitator.verify(paymentPayload, matchedReq);+ if (!verifyResult.isValid) {+ return new Response(+ JSON.stringify({ error: verifyResult.invalidReason }),+ { status: 402, headers: { "Content-Type": "application/json" } },+ );+ }++ // Settle+ const settleResult = await facilitator.settle(paymentPayload, matchedReq);++ if (!settleResult.success) {+ return new Response(+ JSON.stringify({ error: settleResult.errorReason }),+ { status: 402, headers: { "Content-Type": "application/json" } },+ );+ }++ // Invoke the actual handler+ const finalResponse = await handler();++ // Attach PAYMENT-RESPONSE header to the success response+ const paymentResponse: PaymentResponse = {+ success: true,+ transaction: settleResult.transaction,+ network: settleResult.network,+ payer: settleResult.payer,+ };++ // Clone to allow header mutation+ const outResponse = new Response(finalResponse.body, {+ status: finalResponse.status,+ statusText: finalResponse.statusText,+ headers: new Headers(finalResponse.headers),+ });+ outResponse.headers.set(+ X402_HEADER_PAYMENT_RESPONSE,+ encodePaymentResponse(paymentResponse),+ );++ return outResponse;+ };+}diff --git a/agent-payments-sdk/src/x402/headers.ts b/agent-payments-sdk/src/x402/headers.tsnew file mode 100644index 000000000..b3e5ae005--- /dev/null+++ b/agent-payments-sdk/src/x402/headers.ts@@ -0,0 +1,86 @@+/**+ * x402 v2 Header encoding / decoding+ *+ * Standard headers (per coinbase/x402 v2 spec):+ * PAYMENT-REQUIRED – server → client (402 response)+ * PAYMENT-SIGNATURE – client → server (retry request)+ * PAYMENT-RESPONSE – server → client (200 after settlement)+ *+ * All values are base64-encoded JSON.+ */++import type {+ PaymentPayload,+ PaymentRequired,+ PaymentResponse,+} from "./types";+import {+ X402_HEADER_PAYMENT_REQUIRED,+ X402_HEADER_PAYMENT_SIGNATURE,+ X402_HEADER_PAYMENT_RESPONSE,+} from "./types";++// ─── Encode / Decode primitives ─────────────────────────────────────────────++export function encodePaymentRequired(pr: PaymentRequired): string {+ return btoa(JSON.stringify(pr));+}++export function decodePaymentRequired(headerValue: string): PaymentRequired {+ return JSON.parse(atob(headerValue)) as PaymentRequired;+}++export function encodePaymentPayload(payload: PaymentPayload): string {+ return btoa(JSON.stringify(payload));+}++export function decodePaymentPayload(headerValue: string): PaymentPayload {+ return JSON.parse(atob(headerValue)) as PaymentPayload;+}++export function encodePaymentResponse(pr: PaymentResponse): string {+ return btoa(JSON.stringify(pr));+}++export function decodePaymentResponse(headerValue: string): PaymentResponse {+ return JSON.parse(atob(headerValue)) as PaymentResponse;+}++// ─── Request / Response helpers ─────────────────────────────────────────────++/**+ * Extract PAYMENT-REQUIRED from a 402 Response.+ * Returns null if not a 402 or header is missing.+ */+export function getPaymentRequiredFromResponse(+ response: Response,+): PaymentRequired | null {+ if (response.status !== 402) return null;+ const raw = response.headers.get(X402_HEADER_PAYMENT_REQUIRED);+ if (!raw) return null;+ return decodePaymentRequired(raw);+}++/**+ * Extract PAYMENT-SIGNATURE from a Request.+ * Returns null if header is missing.+ */+export function getPaymentPayloadFromRequest(+ request: Request,+): PaymentPayload | null {+ const raw = request.headers.get(X402_HEADER_PAYMENT_SIGNATURE);+ if (!raw) return null;+ return decodePaymentPayload(raw);+}++/**+ * Extract PAYMENT-RESPONSE from a Response.+ * Returns null if header is missing.+ */+export function getPaymentResponseFromResponse(+ response: Response,+): PaymentResponse | null {+ const raw = response.headers.get(X402_HEADER_PAYMENT_RESPONSE);+ if (!raw) return null;+ return decodePaymentResponse(raw);+}diff --git a/agent-payments-sdk/src/x402/index.ts b/agent-payments-sdk/src/x402/index.tsnew file mode 100644index 000000000..f6bfd7117--- /dev/null+++ b/agent-payments-sdk/src/x402/index.ts@@ -0,0 +1,68 @@+/**+ * x402 v2 – HTTP 402 Payment Required protocol for Pump Agent Payments+ *+ * Aligned with the coinbase/x402 v2 specification.+ * @see https://github.com/coinbase/x402+ *+ * Server-side: PumpAgentFacilitator, createResourceServer, buildPumpAgentRequirements+ * Client-side: createX402Fetch+ * Helpers: encode/decode headers, constants+ */++// Types+export type {+ PaymentScheme,+ ExactScheme,+ PumpAgentScheme,+ ResourceInfo,+ PaymentRequirementsBase,+ ExactPaymentRequirements,+ PumpAgentPaymentRequirements,+ PaymentRequirements,+ PaymentRequired,+ PaymentPayload,+ VerifyResponse,+ SettleResponse,+ SupportedKind,+ SupportedResponse,+ FacilitatorClient,+ PaymentResponse,+ ResourceServerConfig,+ X402ClientConfig,+ TransactionSigner,+ TransactionSender,+} from "./types";+export {+ X402_VERSION,+ X402_HEADER_PAYMENT_REQUIRED,+ X402_HEADER_PAYMENT_SIGNATURE,+ X402_HEADER_PAYMENT_RESPONSE,+ SOLANA_MAINNET,+ SOLANA_DEVNET,+ USDC_MAINNET,+ USDC_DEVNET,+} from "./types";++// Headers+export {+ encodePaymentRequired,+ decodePaymentRequired,+ encodePaymentPayload,+ decodePaymentPayload,+ encodePaymentResponse,+ decodePaymentResponse,+ getPaymentRequiredFromResponse,+ getPaymentPayloadFromRequest,+ getPaymentResponseFromResponse,+} from "./headers";++// Facilitator+export type { PumpAgentFacilitatorConfig, PumpAgentRequirementsConfig } from "./facilitator";+export {+ PumpAgentFacilitator,+ buildPumpAgentRequirements,+ createResourceServer,+} from "./facilitator";++// Client+export { createX402Fetch } from "./client";diff --git a/agent-payments-sdk/src/x402/types.ts b/agent-payments-sdk/src/x402/types.tsnew file mode 100644index 000000000..a523745c5--- /dev/null+++ b/agent-payments-sdk/src/x402/types.ts@@ -0,0 +1,194 @@+/**+ * x402 v2 Protocol Types+ *+ * Aligned with the coinbase/x402 specification.+ * Supports "pump-agent" scheme (on-chain invoice payments) and+ * the standard "exact" scheme (SPL TransferChecked).+ *+ * @see https://github.com/coinbase/x402+ */++// ─── Protocol Constants ─────────────────────────────────────────────────────++export const X402_VERSION = 2;++/** Standard x402 header names (v2 spec) */+export const X402_HEADER_PAYMENT_REQUIRED = "PAYMENT-REQUIRED";+export const X402_HEADER_PAYMENT_SIGNATURE = "PAYMENT-SIGNATURE";+export const X402_HEADER_PAYMENT_RESPONSE = "PAYMENT-RESPONSE";++/** CAIP-2 network identifiers for Solana */+export const SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";+export const SOLANA_DEVNET = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";++/** Well-known Solana asset addresses */+export const USDC_MAINNET = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";+export const USDC_DEVNET = "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU";++// ─── Scheme types ───────────────────────────────────────────────────────────++/** Standard x402 "exact" scheme – SPL TransferChecked */+export type ExactScheme = "exact";+/** Pump Agent invoice scheme */+export type PumpAgentScheme = "pump-agent";+/** Supported payment schemes */+export type PaymentScheme = ExactScheme | PumpAgentScheme;++// ─── Resource Info (server describes what is being sold) ────────────────────++export interface ResourceInfo {+ /** The URL of the paid resource */+ url: string;+ /** Human-readable description */+ description?: string;+}++// ─── Payment Requirements (per-scheme offer in 402 body) ────────────────────++/** Base fields shared by all schemes */+export interface PaymentRequirementsBase {+ /** Payment scheme identifier */+ scheme: PaymentScheme;+ /** CAIP-2 network identifier */+ network: string;+ /** Token/asset mint address (base58) */+ asset: string;+ /** Amount in minor units (string to avoid floating point) */+ amount: string;+ /** Recipient address (base58) */+ payTo: string;+ /** Max seconds the facilitator will wait for settlement */+ maxTimeoutSeconds: number;+ /** Scheme-specific extra data */+ extra?: Record<string, unknown>;+}++/** "exact" scheme – standard SPL TransferChecked */+export interface ExactPaymentRequirements extends PaymentRequirementsBase {+ scheme: "exact";+}++/** "pump-agent" scheme – Pump Agent on-chain invoice */+export interface PumpAgentPaymentRequirements extends PaymentRequirementsBase {+ scheme: "pump-agent";+ extra: {+ /** Agent token mint (base58) */+ agentMint: string;+ /** Numeric invoice memo */+ memo: string;+ /** Unix timestamp – invoice valid from */+ startTime: number;+ /** Unix timestamp – invoice valid until */+ endTime: number;+ };+}++/** Union of all supported requirements */+export type PaymentRequirements =+ | ExactPaymentRequirements+ | PumpAgentPaymentRequirements;++// ─── Payment Required (402 response body) ───────────────────────────────────++export interface PaymentRequired {+ x402Version: 2;+ error?: string;+ resource: ResourceInfo;+ accepts: PaymentRequirements[];+}++// ─── Payment Payload (client → server proof in PAYMENT-SIGNATURE) ───────────++export interface PaymentPayload {+ x402Version: 2;+ /** The resource URL this payment is for */+ resource?: string;+ /** Which accepted scheme/requirements this payment matches */+ accepted: PaymentRequirements;+ /** Scheme-specific proof data */+ payload: Record<string, unknown>;+}++// ─── Facilitator Responses ──────────────────────────────────────────────────++export interface VerifyResponse {+ isValid: boolean;+ invalidReason?: string;+ payer?: string;+}++export interface SettleResponse {+ success: boolean;+ errorReason?: string;+ payer?: string;+ transaction?: string;+ network?: string;+}++export interface SupportedKind {+ scheme: PaymentScheme;+ network: string;+ asset: string;+}++export interface SupportedResponse {+ kinds: SupportedKind[];+}++// ─── Facilitator Client Interface ───────────────────────────────────────────++export interface FacilitatorClient {+ /** Verify a payment payload against its requirements */+ verify(+ payload: PaymentPayload,+ requirements: PaymentRequirements,+ ): Promise<VerifyResponse>;++ /** Settle (submit) a verified payment and return the result */+ settle(+ payload: PaymentPayload,+ requirements: PaymentRequirements,+ ): Promise<SettleResponse>;++ /** Return the schemes/networks/assets this facilitator supports */+ getSupported(): Promise<SupportedResponse>;+}++// ─── Payment Response (server → client via PAYMENT-RESPONSE header) ─────────++export interface PaymentResponse {+ success: boolean;+ transaction?: string;+ network?: string;+ payer?: string;+ errorReason?: string;+}++// ─── Server / Middleware Configuration ───────────────────────────────────────++export interface ResourceServerConfig {+ /** Facilitator client to use for verify + settle */+ facilitator: FacilitatorClient;+ /** Default payment requirements for this resource */+ requirements: PaymentRequirements[];+ /** Resource info describing what's for sale */+ resource: ResourceInfo;+}++// ─── Client Configuration ───────────────────────────────────────────────────++export type TransactionSigner = (txBase64: string) => Promise<string>;+export type TransactionSender = (signedTxBase64: string) => Promise<string>;++export interface X402ClientConfig {+ /** Payer's public key (base58) */+ payer: string;+ /** Sign a serialised transaction, return signed base64 */+ signTransaction: TransactionSigner;+ /** Send a signed transaction, return the tx signature (base58) */+ sendTransaction: TransactionSender;+ /** CAIP-2 network identifier (default: SOLANA_MAINNET) */+ network?: string;+ /** Max time to wait for tx confirmation in ms (default: 30_000) */+ confirmationTimeoutMs?: number;+}diff --git a/agent-payments-sdk/tsconfig.json b/agent-payments-sdk/tsconfig.jsonnew file mode 100644index 000000000..958f2625a--- /dev/null+++ b/agent-payments-sdk/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true,+ "declaration": true,+ "declarationMap": true,+ "sourceMap": true,+ "outDir": "dist",+ "rootDir": "src",+ "noUncheckedIndexedAccess": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules", "dist"]+}diff --git a/agent-payments-sdk/tsup.config.ts b/agent-payments-sdk/tsup.config.tsnew file mode 100644index 000000000..13ac7d4a9--- /dev/null+++ b/agent-payments-sdk/tsup.config.ts@@ -0,0 +1,10 @@+import { defineConfig } from "tsup";++export default defineConfig({+ entry: ["src/index.ts", "src/x402/index.ts", "src/solana-agent-kit/index.ts"],+ format: ["cjs", "esm"],+ dts: true,+ clean: true,+ sourcemap: true,+ splitting: false,+});