@audren-xyz/sdk 0.0.0-stage → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/swap.d.ts ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Protocol-Agnostic Shielded DeFi Execution (`ExecViaEscrow`) & Aggregator Route Helpers.
3
+ *
4
+ * Works with any compatible PDA-signing Solana program (DEX aggregators, supply lending,
5
+ * yield vaults, liquid staking, perp LP, RWA mint/redeem) that satisfies Audren custody
6
+ * checks and transaction limits.
7
+ */
8
+ /**
9
+ * Jupiter DEX labels that reject PDA CPI callers (e.g. `InvalidRealUser` / top-level
10
+ * instruction sysvar introspection) and are excluded by default when routing through
11
+ * Audren's isolated `escrow` PDA.
12
+ */
13
+ export declare const JUPITER_CPI_EXCLUDED_DEXES: readonly string[];
14
+ export interface RouterQuoteParams {
15
+ inputMint: string;
16
+ outputMint: string;
17
+ amount: string;
18
+ slippageBps: number;
19
+ onlyDirectRoutes?: boolean;
20
+ /** Cap total route accounts to fit inside Solana Transaction v1's 64-account budget (default 28). */
21
+ maxAccounts?: number;
22
+ /** Override DEX exclusions (defaults to `JUPITER_CPI_EXCLUDED_DEXES`; pass `[]` to disable). */
23
+ excludeDexes?: readonly string[];
24
+ }
25
+ export interface RouterAccountMeta {
26
+ pubkey: string;
27
+ isSigner: boolean;
28
+ isWritable: boolean;
29
+ }
30
+ export interface RouterSwapInstruction {
31
+ programId: string;
32
+ accounts: RouterAccountMeta[];
33
+ data: string;
34
+ }
35
+ export interface RouterSwapInstructionsResponse {
36
+ swapInstruction: RouterSwapInstruction;
37
+ addressLookupTableAddresses?: string[];
38
+ computeUnitLimit?: number;
39
+ }
40
+ export interface ResolvedEscrowIndices {
41
+ escrowIdx: number;
42
+ escrowInIdx: number;
43
+ escrowOutIdx: number;
44
+ }
45
+ export interface FetchSwapRouteOptions {
46
+ /** Approved router program IDs (defaults to `AUDREN_AUDITED_SWAP_ROUTERS` fail-closed). */
47
+ allowedRouterPrograms?: readonly string[];
48
+ /** Explicitly opt out of router program allowlist validation (use with caution). */
49
+ allowUnverifiedRouter?: boolean;
50
+ /** Per-request timeout in ms (default `30_000`). Ignored when `signal` is passed. */
51
+ timeoutMs?: number;
52
+ /** Optional external abort signal for both `/quote` and `/swap-instructions`. */
53
+ signal?: AbortSignal;
54
+ }
55
+ /**
56
+ * Request a quote + `swap-instructions` payload from a Jupiter-compatible aggregator API
57
+ * targeting Audren's shared sharded `escrow` PDA (e.g. `https://api.jup.ag/swap/v1`
58
+ * or any self-hosted / custom aggregator endpoint).
59
+ *
60
+ * Enforces `AUDREN_AUDITED_SWAP_ROUTERS` fail-closed by default unless `allowUnverifiedRouter: true`
61
+ * or a custom `allowedRouterPrograms` list is provided.
62
+ */
63
+ export declare function fetchAggregatorPrivateSwapRoute(aggregatorBaseUrl: string, quoteParams: RouterQuoteParams, escrowAddress: string, options?: FetchSwapRouteOptions): Promise<{
64
+ quote: Record<string, unknown>;
65
+ swap: RouterSwapInstructionsResponse;
66
+ }>;
67
+ /**
68
+ * Locate `(escrowIdx, escrowInIdx, escrowOutIdx)` inside an arbitrary external program
69
+ * account list for compatible PDA-signing instructions accepted by Audren's `ExecViaEscrow`.
70
+ */
71
+ export declare function resolveEscrowIndices(actionAccounts: readonly RouterAccountMeta[], escrowAddress: string, escrowInAta: string, escrowOutAta: string): ResolvedEscrowIndices;
72
+ /**
73
+ * Strip the external signer bit on `escrowAddress` AND promote `isWritable: true` on any
74
+ * account whose pubkey is `escrowAddress`, listed in `extraWritablePubkeys`, or appears
75
+ * with `isWritable: true` anywhere in `actionAccounts` (matching Solana's transaction-wide
76
+ * writability union so on-chain `hash_router_accounts_arena` matches `ctx_hash` bit-for-bit).
77
+ */
78
+ export declare function prepareEscrowAccountsForAudren(actionAccounts: readonly RouterAccountMeta[], escrowAddress: string, extraWritablePubkeys?: readonly string[]): RouterAccountMeta[];
79
+ export interface PreparedEscrowAccounts {
80
+ escrowPda: string;
81
+ escrowInAta: string;
82
+ escrowOutAta: string;
83
+ escrowIdx: number;
84
+ escrowInIdx: number;
85
+ escrowOutIdx: number;
86
+ accounts: RouterAccountMeta[];
87
+ }
88
+ /**
89
+ * High-level helper (mirrors Rust `prepare_escrow_accounts`): derives the sharded `escrow`
90
+ * PDA and its input/output ATAs, locates `(escrowIdx, escrowInIdx, escrowOutIdx)`, strips
91
+ * the external signer bit on `escrow` so Audren can sign via `invoke_signed`, and applies
92
+ * Solana's transaction-wide writability promotion across `escrow`, escrow ATAs, and any
93
+ * `extraWritablePubkeys`.
94
+ */
95
+ export declare function prepareEscrowAccounts(params: {
96
+ poolId: number;
97
+ shardId: number;
98
+ inputMint: string;
99
+ outputMint: string;
100
+ inputTokenProgram?: string;
101
+ outputTokenProgram?: string;
102
+ actionAccounts: readonly RouterAccountMeta[];
103
+ extraWritablePubkeys?: readonly string[];
104
+ programId?: string;
105
+ }): Promise<PreparedEscrowAccounts>;
package/dist/swap.js ADDED
@@ -0,0 +1,156 @@
1
+ import { AUDREN_PROGRAM_ID, CLASSIC_TOKEN_PROGRAM_ID } from './constants.js';
2
+ import { deriveAssociatedTokenAddress, deriveEscrowPda } from './pda.js';
3
+ import { AUDREN_AUDITED_SWAP_ROUTERS } from './relayer.js';
4
+ /**
5
+ * Protocol-Agnostic Shielded DeFi Execution (`ExecViaEscrow`) & Aggregator Route Helpers.
6
+ *
7
+ * Works with any compatible PDA-signing Solana program (DEX aggregators, supply lending,
8
+ * yield vaults, liquid staking, perp LP, RWA mint/redeem) that satisfies Audren custody
9
+ * checks and transaction limits.
10
+ */
11
+ /**
12
+ * Jupiter DEX labels that reject PDA CPI callers (e.g. `InvalidRealUser` / top-level
13
+ * instruction sysvar introspection) and are excluded by default when routing through
14
+ * Audren's isolated `escrow` PDA.
15
+ */
16
+ export const JUPITER_CPI_EXCLUDED_DEXES = [
17
+ 'Kipseli',
18
+ 'Quantum',
19
+ 'BisonFi',
20
+ 'BisonFi Predict',
21
+ 'BinaryFi',
22
+ 'Obsidian',
23
+ 'VaultLiquidUnstake',
24
+ 'Sanctum Prop S',
25
+ ];
26
+ /**
27
+ * Request a quote + `swap-instructions` payload from a Jupiter-compatible aggregator API
28
+ * targeting Audren's shared sharded `escrow` PDA (e.g. `https://api.jup.ag/swap/v1`
29
+ * or any self-hosted / custom aggregator endpoint).
30
+ *
31
+ * Enforces `AUDREN_AUDITED_SWAP_ROUTERS` fail-closed by default unless `allowUnverifiedRouter: true`
32
+ * or a custom `allowedRouterPrograms` list is provided.
33
+ */
34
+ export async function fetchAggregatorPrivateSwapRoute(aggregatorBaseUrl, quoteParams, escrowAddress, options) {
35
+ const base = aggregatorBaseUrl.replace(/\/$/, '');
36
+ const excluded = quoteParams.excludeDexes ?? JUPITER_CPI_EXCLUDED_DEXES;
37
+ const timeoutMs = options?.timeoutMs ?? 30_000;
38
+ const makeSignal = () => {
39
+ if (options?.signal)
40
+ return options.signal;
41
+ if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function' && timeoutMs > 0) {
42
+ return AbortSignal.timeout(timeoutMs);
43
+ }
44
+ return undefined;
45
+ };
46
+ const qs = new URLSearchParams({
47
+ inputMint: quoteParams.inputMint,
48
+ outputMint: quoteParams.outputMint,
49
+ amount: quoteParams.amount,
50
+ slippageBps: String(quoteParams.slippageBps),
51
+ maxAccounts: String(quoteParams.maxAccounts ?? 28),
52
+ ...(quoteParams.onlyDirectRoutes ? { onlyDirectRoutes: 'true' } : {}),
53
+ ...(excluded.length > 0 ? { excludeDexes: excluded.join(',') } : {}),
54
+ });
55
+ const quoteRes = await fetch(`${base}/quote?${qs.toString()}`, { signal: makeSignal() });
56
+ if (!quoteRes.ok) {
57
+ throw new Error(`Aggregator /quote failed: HTTP ${quoteRes.status}`);
58
+ }
59
+ const quote = (await quoteRes.json());
60
+ const swapRes = await fetch(`${base}/swap-instructions`, {
61
+ method: 'POST',
62
+ headers: { 'content-type': 'application/json' },
63
+ signal: makeSignal(),
64
+ body: JSON.stringify({
65
+ quoteResponse: quote,
66
+ userPublicKey: escrowAddress,
67
+ wrapAndUnwrapSol: false,
68
+ useSharedAccounts: false,
69
+ dynamicComputeUnitLimit: false,
70
+ skipUserAccountsRpcCalls: true,
71
+ }),
72
+ });
73
+ if (!swapRes.ok) {
74
+ throw new Error(`Aggregator /swap-instructions failed: HTTP ${swapRes.status}`);
75
+ }
76
+ const swap = (await swapRes.json());
77
+ if (!options?.allowUnverifiedRouter) {
78
+ const allowed = options?.allowedRouterPrograms ?? AUDREN_AUDITED_SWAP_ROUTERS;
79
+ const routerProg = swap?.swapInstruction?.programId;
80
+ if (typeof routerProg !== 'string' || !allowed.includes(routerProg)) {
81
+ throw new Error(`Aggregator returned unapproved swap router program: ${String(routerProg)}`);
82
+ }
83
+ }
84
+ return { quote, swap };
85
+ }
86
+ /**
87
+ * Locate `(escrowIdx, escrowInIdx, escrowOutIdx)` inside an arbitrary external program
88
+ * account list for compatible PDA-signing instructions accepted by Audren's `ExecViaEscrow`.
89
+ */
90
+ export function resolveEscrowIndices(actionAccounts, escrowAddress, escrowInAta, escrowOutAta) {
91
+ if (!Array.isArray(actionAccounts)) {
92
+ throw new RangeError('actionAccounts must be an array');
93
+ }
94
+ const escrowIdx = actionAccounts.findIndex((m) => m.pubkey === escrowAddress);
95
+ const escrowInIdx = actionAccounts.findIndex((m) => m.pubkey === escrowInAta);
96
+ const escrowOutIdx = actionAccounts.findIndex((m) => m.pubkey === escrowOutAta);
97
+ if (escrowIdx < 0 || escrowInIdx < 0 || escrowOutIdx < 0) {
98
+ throw new Error(`Missing escrow account in action instruction (escrow=${escrowIdx}, in=${escrowInIdx}, out=${escrowOutIdx})`);
99
+ }
100
+ return { escrowIdx, escrowInIdx, escrowOutIdx };
101
+ }
102
+ /**
103
+ * Strip the external signer bit on `escrowAddress` AND promote `isWritable: true` on any
104
+ * account whose pubkey is `escrowAddress`, listed in `extraWritablePubkeys`, or appears
105
+ * with `isWritable: true` anywhere in `actionAccounts` (matching Solana's transaction-wide
106
+ * writability union so on-chain `hash_router_accounts_arena` matches `ctx_hash` bit-for-bit).
107
+ */
108
+ export function prepareEscrowAccountsForAudren(actionAccounts, escrowAddress, extraWritablePubkeys) {
109
+ if (!Array.isArray(actionAccounts)) {
110
+ throw new RangeError('actionAccounts must be an array');
111
+ }
112
+ const writableSet = new Set([escrowAddress]);
113
+ if (extraWritablePubkeys) {
114
+ for (const pk of extraWritablePubkeys)
115
+ writableSet.add(pk);
116
+ }
117
+ for (const meta of actionAccounts) {
118
+ if (meta.isWritable)
119
+ writableSet.add(meta.pubkey);
120
+ }
121
+ return actionAccounts.map((meta) => ({
122
+ pubkey: meta.pubkey,
123
+ isSigner: meta.pubkey === escrowAddress ? false : meta.isSigner,
124
+ isWritable: meta.isWritable || writableSet.has(meta.pubkey),
125
+ }));
126
+ }
127
+ /**
128
+ * High-level helper (mirrors Rust `prepare_escrow_accounts`): derives the sharded `escrow`
129
+ * PDA and its input/output ATAs, locates `(escrowIdx, escrowInIdx, escrowOutIdx)`, strips
130
+ * the external signer bit on `escrow` so Audren can sign via `invoke_signed`, and applies
131
+ * Solana's transaction-wide writability promotion across `escrow`, escrow ATAs, and any
132
+ * `extraWritablePubkeys`.
133
+ */
134
+ export async function prepareEscrowAccounts(params) {
135
+ const programId = params.programId ?? AUDREN_PROGRAM_ID;
136
+ const inputTp = params.inputTokenProgram ?? CLASSIC_TOKEN_PROGRAM_ID;
137
+ const outputTp = params.outputTokenProgram ?? CLASSIC_TOKEN_PROGRAM_ID;
138
+ const { address: escrowPda } = await deriveEscrowPda(params.poolId, params.shardId, programId);
139
+ const { address: escrowInAta } = await deriveAssociatedTokenAddress(escrowPda, params.inputMint, inputTp);
140
+ const { address: escrowOutAta } = await deriveAssociatedTokenAddress(escrowPda, params.outputMint, outputTp);
141
+ const { escrowIdx, escrowInIdx, escrowOutIdx } = resolveEscrowIndices(params.actionAccounts, escrowPda, escrowInAta, escrowOutAta);
142
+ const accounts = prepareEscrowAccountsForAudren(params.actionAccounts, escrowPda, [
143
+ escrowInAta,
144
+ escrowOutAta,
145
+ ...(params.extraWritablePubkeys ?? []),
146
+ ]);
147
+ return {
148
+ escrowPda,
149
+ escrowInAta,
150
+ escrowOutAta,
151
+ escrowIdx,
152
+ escrowInIdx,
153
+ escrowOutIdx,
154
+ accounts,
155
+ };
156
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * SPL Token-2022 mint extension parsers and fee-on-transfer net amount helpers.
3
+ *
4
+ * Shared canonical implementation used by `@audren-xyz/sdk`, `apps/relay`, and `apps/web`
5
+ * so wallets and relayers never drift on Token-2022 TLV offsets or epoch-aware fee selection.
6
+ */
7
+ /** Maximum TransferFeeConfig basis points permitted for relayer self-pay fee settlement (5%). */
8
+ export declare const MAX_SELF_PAY_TRANSFER_FEE_BPS = 500;
9
+ export interface Token2022TransferFee {
10
+ bps: bigint;
11
+ maxFee: bigint;
12
+ epoch: bigint;
13
+ }
14
+ export declare function parseToken2022TransferFeeConfig(mintData: Uint8Array | null | undefined, currentEpoch: bigint | number): Token2022TransferFee | null;
15
+ /**
16
+ * Compute exact net received base units after SPL Token-2022 `TransferFee` ceiling deduction.
17
+ */
18
+ export declare function computeToken2022NetAmount(grossAmount: bigint, fee: Token2022TransferFee | null): bigint;
19
+ /**
20
+ * Return `true` if a Token-2022 mint carries extensions unsafe for relayer self-pay fee settlement:
21
+ * - Malformed length (`!== 82` and `< 166`), non-zero padding in `[82..165]`, non-Mint account
22
+ * type at offset `165`, truncated TLV value, or trailing partial TLV header (`1..3` bytes)
23
+ * - `DefaultAccountState` (6) if truncated (`< 1` byte) or `Frozen` (`state === 2`)
24
+ * - `NonTransferable` (9), `PermanentDelegate` (12), `ScaledUiAmount` (25), or `Pausable` (26)
25
+ * - `TransferHook` (14) if truncated (`< 64` bytes) or carrying any non-zero `authority` or `program_id`
26
+ * - `TransferFeeConfig` (1) if truncated (`< 108` bytes), carrying a non-zero mutable
27
+ * `transfer_fee_config_authority` (`[0..32]`), or either older or newer fee > 500 bps (5%)
28
+ */
29
+ export declare function inspectToken2022UnsafeSelfPay(mintData: Uint8Array | null | undefined): boolean;
@@ -0,0 +1,168 @@
1
+ /**
2
+ * SPL Token-2022 mint extension parsers and fee-on-transfer net amount helpers.
3
+ *
4
+ * Shared canonical implementation used by `@audren-xyz/sdk`, `apps/relay`, and `apps/web`
5
+ * so wallets and relayers never drift on Token-2022 TLV offsets or epoch-aware fee selection.
6
+ */
7
+ const TOKEN_2022_ACCOUNT_TYPE_OFFSET = 165;
8
+ const TOKEN_2022_ACCOUNT_TYPE_MINT = 1;
9
+ const TOKEN_2022_TLV_START = 166;
10
+ const EXT_TRANSFER_FEE_CONFIG = 1;
11
+ const EXT_DEFAULT_ACCOUNT_STATE = 6;
12
+ const EXT_NON_TRANSFERABLE = 9;
13
+ const EXT_INTEREST_BEARING_CONFIG = 10;
14
+ const EXT_PERMANENT_DELEGATE = 12;
15
+ const EXT_TRANSFER_HOOK = 14;
16
+ const EXT_SCALED_UI_AMOUNT = 25;
17
+ const EXT_PAUSABLE = 26;
18
+ /** Maximum TransferFeeConfig basis points permitted for relayer self-pay fee settlement (5%). */
19
+ export const MAX_SELF_PAY_TRANSFER_FEE_BPS = 500;
20
+ /**
21
+ * Parse a Token-2022 mint's `TransferFeeConfig` extension (TLV type `1`, 108 bytes)
22
+ * and select the active fee schedule for `currentEpoch` (`newer_transfer_fee` if
23
+ * `BigInt(currentEpoch) >= newerEpoch`, else `older_transfer_fee`).
24
+ *
25
+ * Returns `null` if the mint has no `TransferFeeConfig` extension or the active `bps === 0n`.
26
+ */
27
+ const U64_MAX = 0xffffffffffffffffn;
28
+ export function parseToken2022TransferFeeConfig(mintData, currentEpoch) {
29
+ let epoch;
30
+ if (typeof currentEpoch === 'bigint') {
31
+ if (currentEpoch < 0n || currentEpoch > U64_MAX) {
32
+ throw new RangeError(`currentEpoch must be a u64 bigint, got ${String(currentEpoch)}`);
33
+ }
34
+ epoch = currentEpoch;
35
+ }
36
+ else if (typeof currentEpoch === 'number' && Number.isSafeInteger(currentEpoch) && currentEpoch >= 0) {
37
+ epoch = BigInt(currentEpoch);
38
+ }
39
+ else {
40
+ throw new RangeError(`currentEpoch must be a non-negative integer or u64 bigint, got ${String(currentEpoch)}`);
41
+ }
42
+ if (!(mintData instanceof Uint8Array) ||
43
+ mintData.byteLength <= TOKEN_2022_TLV_START ||
44
+ mintData[TOKEN_2022_ACCOUNT_TYPE_OFFSET] !== TOKEN_2022_ACCOUNT_TYPE_MINT) {
45
+ return null;
46
+ }
47
+ const dv = new DataView(mintData.buffer, mintData.byteOffset, mintData.byteLength);
48
+ let pos = TOKEN_2022_TLV_START;
49
+ while (pos + 4 <= mintData.byteLength) {
50
+ const extType = dv.getUint16(pos, true);
51
+ if (extType === 0)
52
+ break;
53
+ const extLen = dv.getUint16(pos + 2, true);
54
+ const valStart = pos + 4;
55
+ const valEnd = valStart + extLen;
56
+ if (valEnd > mintData.byteLength)
57
+ break;
58
+ if (extType === EXT_TRANSFER_FEE_CONFIG && extLen >= 108) {
59
+ // TransferFeeConfig layout:
60
+ // 0..32 transfer_fee_config_authority
61
+ // 32..64 withdraw_withheld_authority
62
+ // 64..72 withheld_amount (u64 LE)
63
+ // 72..90 older_transfer_fee { epoch: u64 LE, maximum_fee: u64 LE, bps: u16 LE }
64
+ // 90..108 newer_transfer_fee { epoch: u64 LE, maximum_fee: u64 LE, bps: u16 LE }
65
+ const olderEpoch = dv.getBigUint64(valStart + 72, true);
66
+ const olderMaxFee = dv.getBigUint64(valStart + 80, true);
67
+ const olderBps = BigInt(dv.getUint16(valStart + 88, true));
68
+ const newerEpoch = dv.getBigUint64(valStart + 90, true);
69
+ const newerMaxFee = dv.getBigUint64(valStart + 98, true);
70
+ const newerBps = BigInt(dv.getUint16(valStart + 106, true));
71
+ const active = epoch >= newerEpoch
72
+ ? { epoch: newerEpoch, maxFee: newerMaxFee, bps: newerBps }
73
+ : { epoch: olderEpoch, maxFee: olderMaxFee, bps: olderBps };
74
+ return active.bps === 0n ? null : active;
75
+ }
76
+ pos = valEnd;
77
+ }
78
+ return null;
79
+ }
80
+ /**
81
+ * Compute exact net received base units after SPL Token-2022 `TransferFee` ceiling deduction.
82
+ */
83
+ export function computeToken2022NetAmount(grossAmount, fee) {
84
+ if (typeof grossAmount !== 'bigint') {
85
+ throw new RangeError(`grossAmount must be a bigint, got ${typeof grossAmount}`);
86
+ }
87
+ if (!fee || fee.bps <= 0n || grossAmount <= 0n)
88
+ return grossAmount;
89
+ const rawFee = fee.bps >= 10000n ? grossAmount : (grossAmount * fee.bps + 9999n) / 10000n;
90
+ const capped = rawFee > fee.maxFee ? fee.maxFee : rawFee;
91
+ return grossAmount > capped ? grossAmount - capped : 0n;
92
+ }
93
+ /**
94
+ * Return `true` if a Token-2022 mint carries extensions unsafe for relayer self-pay fee settlement:
95
+ * - Malformed length (`!== 82` and `< 166`), non-zero padding in `[82..165]`, non-Mint account
96
+ * type at offset `165`, truncated TLV value, or trailing partial TLV header (`1..3` bytes)
97
+ * - `DefaultAccountState` (6) if truncated (`< 1` byte) or `Frozen` (`state === 2`)
98
+ * - `NonTransferable` (9), `PermanentDelegate` (12), `ScaledUiAmount` (25), or `Pausable` (26)
99
+ * - `TransferHook` (14) if truncated (`< 64` bytes) or carrying any non-zero `authority` or `program_id`
100
+ * - `TransferFeeConfig` (1) if truncated (`< 108` bytes), carrying a non-zero mutable
101
+ * `transfer_fee_config_authority` (`[0..32]`), or either older or newer fee > 500 bps (5%)
102
+ */
103
+ export function inspectToken2022UnsafeSelfPay(mintData) {
104
+ if (mintData == null)
105
+ return false;
106
+ if (!(mintData instanceof Uint8Array))
107
+ return true;
108
+ if (mintData.byteLength === 82)
109
+ return false;
110
+ if (mintData.byteLength < TOKEN_2022_TLV_START ||
111
+ mintData[TOKEN_2022_ACCOUNT_TYPE_OFFSET] !== TOKEN_2022_ACCOUNT_TYPE_MINT) {
112
+ return true;
113
+ }
114
+ for (let i = 82; i < TOKEN_2022_ACCOUNT_TYPE_OFFSET; i++) {
115
+ if (mintData[i] !== 0)
116
+ return true;
117
+ }
118
+ const dv = new DataView(mintData.buffer, mintData.byteOffset, mintData.byteLength);
119
+ let pos = TOKEN_2022_TLV_START;
120
+ while (pos < mintData.byteLength) {
121
+ if (pos + 4 > mintData.byteLength)
122
+ return true;
123
+ const extType = dv.getUint16(pos, true);
124
+ if (extType === 0)
125
+ break;
126
+ const extLen = dv.getUint16(pos + 2, true);
127
+ const valStart = pos + 4;
128
+ const valEnd = valStart + extLen;
129
+ if (valEnd > mintData.byteLength)
130
+ return true;
131
+ if (extType === EXT_NON_TRANSFERABLE ||
132
+ extType === EXT_INTEREST_BEARING_CONFIG ||
133
+ extType === EXT_PERMANENT_DELEGATE ||
134
+ extType === EXT_SCALED_UI_AMOUNT ||
135
+ extType === EXT_PAUSABLE) {
136
+ return true;
137
+ }
138
+ if (extType === EXT_DEFAULT_ACCOUNT_STATE) {
139
+ // DefaultAccountState: 1 byte AccountState (0=Uninitialized, 1=Initialized, 2=Frozen)
140
+ if (extLen < 1 || mintData[valStart] === 2)
141
+ return true;
142
+ }
143
+ if (extType === EXT_TRANSFER_HOOK) {
144
+ if (extLen < 64)
145
+ return true;
146
+ for (let i = 0; i < 64; i++) {
147
+ if (mintData[valStart + i] !== 0)
148
+ return true;
149
+ }
150
+ }
151
+ if (extType === EXT_TRANSFER_FEE_CONFIG) {
152
+ if (extLen < 108)
153
+ return true;
154
+ // Bytes [0..32] = OptionalNonZeroPubkey transfer_fee_config_authority (reject if mutable)
155
+ for (let i = 0; i < 32; i++) {
156
+ if (mintData[valStart + i] !== 0)
157
+ return true;
158
+ }
159
+ const olderBps = dv.getUint16(valStart + 88, true);
160
+ const newerBps = dv.getUint16(valStart + 106, true);
161
+ if (olderBps > MAX_SELF_PAY_TRANSFER_FEE_BPS || newerBps > MAX_SELF_PAY_TRANSFER_FEE_BPS) {
162
+ return true;
163
+ }
164
+ }
165
+ pos = valEnd;
166
+ }
167
+ return false;
168
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Zero-dependency Solana Transaction Version 1 (SIMD-0385 / `0x81`) compiler and wire serializer.
3
+ *
4
+ * Wire layout (`<= 4,096 B` total):
5
+ * wireBytes = messageBytes || signatures (fixed-len `numRequiredSignatures * 64 B`, no short_vec)
6
+ * messageBytes = 0x81
7
+ * | header(3 B: numRequiredSignatures, numReadonlySigned, numReadonlyUnsigned)
8
+ * | configMask(u32 LE)
9
+ * | lifetimeSpecifier(recentBlockhash: 32 B)
10
+ * | numInstructions(u8) | numAddresses(u8)
11
+ * | accountKeys(numAddresses * 32 B)
12
+ * | configValues (bit order: priorityFee u64 LE, computeUnitLimit u32 LE,
13
+ * loadedAccountsDataSizeLimit u32 LE, heapSize u32 LE)
14
+ * | instructionHeaders(numInstructions * 4 B: programIdx u8, numAccounts u8, dataLen u16 LE)
15
+ * | instructionPayloads(for each ix: accountIndices || data)
16
+ *
17
+ * Compute budget limits and priority fees are carried natively inside the v1 header
18
+ * without separate `ComputeBudgetInstruction`s.
19
+ */
20
+ export declare const SOLANA_TX_V1_PREFIX = 129;
21
+ export declare const SOLANA_TX_V1_MAX_SIZE = 4096;
22
+ export declare const SOLANA_TX_V1_MAX_SIGNATURES = 12;
23
+ export declare const SOLANA_TX_V1_DEFAULT_LOADED_ACCOUNTS_DATA_SIZE: number;
24
+ export interface V1AccountMeta {
25
+ pubkey: Uint8Array;
26
+ isSigner: boolean;
27
+ isWritable: boolean;
28
+ }
29
+ export interface V1Instruction {
30
+ programId: Uint8Array;
31
+ accounts: V1AccountMeta[];
32
+ data: Uint8Array;
33
+ }
34
+ export interface V1TransactionConfig {
35
+ /** Required in Solana v1 (unset budgets 0 CU). */
36
+ computeUnitLimit: number;
37
+ /** Required in Solana v1 (unset budgets 0 bytes). Defaults to 64 MiB. */
38
+ loadedAccountsDataSizeLimit?: number;
39
+ /** Optional total priority fee in lamports (u64 LE). */
40
+ priorityFeeLamports?: bigint;
41
+ /** Optional heap size in bytes (multiple of 1024, 32 KiB..=256 KiB). */
42
+ heapSize?: number;
43
+ }
44
+ export interface CompiledV1Message {
45
+ messageBytes: Uint8Array;
46
+ numRequiredSignatures: number;
47
+ signerPubkeys: Uint8Array[];
48
+ }
49
+ /**
50
+ * Compile instructions and inline `TransactionConfig` into the exact Solana Transaction v1
51
+ * message byte buffer (`0x81...`) that signers sign with Ed25519.
52
+ */
53
+ export declare function compileV1Message(params: {
54
+ feePayer: Uint8Array;
55
+ recentBlockhash: Uint8Array;
56
+ instructions: V1Instruction[];
57
+ config: V1TransactionConfig;
58
+ }): CompiledV1Message;
59
+ /**
60
+ * Assemble a finalized Solana Transaction v1 wire packet (`messageBytes || signatures`).
61
+ * Each signature must be a 64-byte Ed25519 signature over `compiled.messageBytes`.
62
+ */
63
+ export declare function serializeV1Transaction(compiled: CompiledV1Message, signatures: Uint8Array[]): Uint8Array;