@floorlaunchpad/sdk 0.6.0 → 0.8.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.
Files changed (125) hide show
  1. package/CHANGELOG.md +279 -0
  2. package/README.md +12 -1
  3. package/dist/abi/evm-event-names.js +7 -0
  4. package/dist/abi/evm.gen.js +81 -2
  5. package/dist/abi/functions.gen.js +135 -1
  6. package/dist/abi/solana.gen.js +64 -0
  7. package/dist/client/solana/index.js +25 -6
  8. package/dist/config/generated.js +803 -26374
  9. package/dist/errors.js +21 -2
  10. package/dist/events/types.gen.js +1 -1
  11. package/dist/evm/chains.js +80 -0
  12. package/dist/evm/floor/abi.gen.js +115 -0
  13. package/dist/evm/floor/calls.js +5 -0
  14. package/dist/evm/squid.js +21 -5
  15. package/dist/evm/venues.js +302 -0
  16. package/dist/generated/interface.gen.js +93 -44
  17. package/dist/index.js +7 -0
  18. package/dist/indexer/bodies.js +288 -5
  19. package/dist/indexer/client.js +17 -1
  20. package/dist/indexer/contract.js +141 -15
  21. package/dist/indexer/paths.js +80 -7
  22. package/dist/indexer/read.js +25 -3
  23. package/dist/indexer/stream.js +2 -2
  24. package/dist/math/v2/book.js +24 -7
  25. package/dist/math/v2/create.js +1 -1
  26. package/dist/math/v2/escrow.js +205 -0
  27. package/dist/math/v2/fees.js +30 -4
  28. package/dist/math/v2/milestones.js +1 -1
  29. package/dist/math/v2/office.js +110 -0
  30. package/dist/math/v2/receipt.js +3 -3
  31. package/dist/math/v2/relay.js +263 -96
  32. package/dist/math/v2/rows.js +17 -0
  33. package/dist/math/v2/team.js +42 -1
  34. package/dist/math/v2/trade.js +3 -1
  35. package/dist/reprice.js +88 -0
  36. package/dist/route/quote.js +16 -0
  37. package/dist/scaledUi.js +113 -0
  38. package/dist/solana/floor/accounts.js +38 -5
  39. package/dist/solana/floor/events.js +62 -1
  40. package/dist/solana/floor/instructions.js +39 -1
  41. package/dist/solana/floor/program.js +3 -0
  42. package/dist/stockRefresh.js +99 -0
  43. package/dist/ton/consts.generated.js +2 -2
  44. package/dist/ton/gas.js +3 -3
  45. package/dist/v2/claims.js +28 -5
  46. package/dist/v2/devbuy.js +28 -3
  47. package/dist/v2/events.js +2 -0
  48. package/dist/v2/evm.js +183 -5
  49. package/dist/v2/layouts.js +102 -2
  50. package/dist/v2/office-events.js +127 -0
  51. package/dist/v2/office-evm.js +68 -0
  52. package/dist/v2/office-read.js +182 -0
  53. package/dist/v2/office-solana.js +134 -0
  54. package/dist/v2/office-trade.js +73 -0
  55. package/dist/v2/route-alt.js +1 -0
  56. package/dist/v2/route.js +1 -1
  57. package/dist/v2/solana.js +224 -5
  58. package/dist/v2/solanaSettle.js +2 -0
  59. package/dist/v2/tx/evm.js +66 -2
  60. package/dist/v2/tx/solana.js +3 -3
  61. package/dist/v2/types.js +4 -0
  62. package/docs/aggregator.md +19 -0
  63. package/docs/cursor-pages.md +9 -3
  64. package/docs/ton.md +1 -1
  65. package/examples/floor-line.html +1 -1
  66. package/package.json +26 -1
  67. package/src/abi/evm-event-names.ts +7 -0
  68. package/src/abi/evm.gen.ts +81 -2
  69. package/src/abi/functions.gen.ts +135 -1
  70. package/src/abi/solana.gen.ts +64 -0
  71. package/src/client/solana/index.ts +25 -6
  72. package/src/config/generated.ts +803 -26374
  73. package/src/errors.ts +21 -2
  74. package/src/events/types.gen.ts +458 -1
  75. package/src/evm/chains.ts +89 -0
  76. package/src/evm/floor/abi.gen.ts +115 -0
  77. package/src/evm/floor/calls.ts +5 -0
  78. package/src/evm/squid.ts +22 -6
  79. package/src/evm/venues.ts +340 -0
  80. package/src/generated/interface.gen.ts +93 -44
  81. package/src/index.ts +7 -0
  82. package/src/indexer/bodies.ts +308 -5
  83. package/src/indexer/client.ts +31 -4
  84. package/src/indexer/contract.ts +148 -17
  85. package/src/indexer/paths.ts +139 -7
  86. package/src/indexer/read.ts +27 -5
  87. package/src/indexer/stream.ts +4 -4
  88. package/src/math/v2/book.ts +23 -7
  89. package/src/math/v2/create.ts +1 -1
  90. package/src/math/v2/escrow.ts +213 -0
  91. package/src/math/v2/fees.ts +30 -4
  92. package/src/math/v2/milestones.ts +1 -1
  93. package/src/math/v2/office.ts +114 -0
  94. package/src/math/v2/receipt.ts +7 -3
  95. package/src/math/v2/relay.ts +269 -96
  96. package/src/math/v2/rows.ts +17 -0
  97. package/src/math/v2/team.ts +42 -1
  98. package/src/math/v2/trade.ts +3 -1
  99. package/src/reprice.ts +121 -0
  100. package/src/route/quote.ts +16 -0
  101. package/src/scaledUi.ts +123 -0
  102. package/src/solana/floor/accounts.ts +38 -5
  103. package/src/solana/floor/events.ts +63 -2
  104. package/src/solana/floor/instructions.ts +39 -1
  105. package/src/solana/floor/program.ts +3 -0
  106. package/src/stockRefresh.ts +131 -0
  107. package/src/ton/consts.generated.ts +2 -2
  108. package/src/ton/gas.ts +3 -3
  109. package/src/v2/claims.ts +34 -5
  110. package/src/v2/devbuy.ts +38 -3
  111. package/src/v2/events.ts +3 -1
  112. package/src/v2/evm.ts +209 -5
  113. package/src/v2/layouts.ts +102 -2
  114. package/src/v2/office-events.ts +133 -0
  115. package/src/v2/office-evm.ts +76 -0
  116. package/src/v2/office-read.ts +264 -0
  117. package/src/v2/office-solana.ts +159 -0
  118. package/src/v2/office-trade.ts +96 -0
  119. package/src/v2/route-alt.ts +1 -0
  120. package/src/v2/route.ts +1 -1
  121. package/src/v2/solana.ts +235 -5
  122. package/src/v2/solanaSettle.ts +2 -0
  123. package/src/v2/tx/evm.ts +66 -2
  124. package/src/v2/tx/solana.ts +5 -3
  125. package/src/v2/types.ts +76 -1
@@ -0,0 +1,159 @@
1
+
2
+
3
+ import { R, RS, W, WS, instructionDiscriminator } from "../solana/instruction.ts";
4
+ import type { AccountMeta, Instruction } from "../solana/instruction.ts";
5
+ import { Writer } from "../solana/floor/borsh.ts";
6
+ import { ASSOCIATED_TOKEN_PROGRAM_ID, SYSTEM_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, associatedTokenAddress, findProgramAddress } from "../solana/pda.ts";
7
+ import type { Pda } from "../solana/pda.ts";
8
+ import { FLOOR_AMM_PROGRAM_ID, floorEventAuthorityPda, quoteEntryPda } from "../solana/floor/program.ts";
9
+ import { hexToBytes } from "../evm/abi.ts";
10
+ import type { Ctx } from "./solana.ts";
11
+
12
+ const pid = (c?: Ctx): string => c?.programId ?? FLOOR_AMM_PROGRAM_ID;
13
+
14
+ export const officePda = (officeId: Uint8Array | string, p = FLOOR_AMM_PROGRAM_ID): Pda => findProgramAddress(["office", idBytes(officeId)], p);
15
+
16
+ export const officeQuoteVault = (office: string, quoteMint: string, quoteTokenProgram = TOKEN_PROGRAM_ID): string => associatedTokenAddress(office, quoteMint, quoteTokenProgram);
17
+
18
+ export const officeBaseVault = (office: string, baseMint: string): string => associatedTokenAddress(office, baseMint, TOKEN_2022_PROGRAM_ID);
19
+
20
+ function idBytes(id: Uint8Array | string): Uint8Array {
21
+ const b = typeof id === "string" ? hexToBytes(id) : id;
22
+ if (b.length !== 32) throw new RangeError("office_id is 32 bytes");
23
+ if (b.every((x) => x === 0)) throw new RangeError("office_id is non-zero (OfficeExists)");
24
+ return b;
25
+ }
26
+
27
+ export interface OfficeValuePosition { launch: string; baseMint: string }
28
+
29
+ export interface OfficeLeavePosition extends OfficeValuePosition {
30
+
31
+ memberBaseAta?: string;
32
+
33
+ poolBaseAta?: string;
34
+
35
+ hookExtra: AccountMeta[];
36
+ }
37
+
38
+ export interface OfficeLaunchAccounts extends OfficeValuePosition {
39
+ tokenVault: string;
40
+ quoteVault: string;
41
+ poolBaseAta?: string;
42
+
43
+ hookExtra: AccountMeta[];
44
+ }
45
+ const HOOK_EXTRAS = 6;
46
+ const six = (x: AccountMeta[], what: string): AccountMeta[] => {
47
+ if (x.length !== HOOK_EXTRAS) throw new RangeError(`${what}: the hook takes exactly ${HOOK_EXTRAS} extra accounts`);
48
+ return x;
49
+ };
50
+ const valueBlock = (ps: readonly OfficeValuePosition[] = []): AccountMeta[] => ps.flatMap((l) => [R(l.launch), R(l.baseMint)]);
51
+
52
+ const quoteTail = (q?: AccountMeta[]): AccountMeta[] => (q === undefined ? [] : six(q, "quoteExtra"));
53
+
54
+ function ix(name: string, accounts: AccountMeta[], args: (w: Writer) => Writer, rest: AccountMeta[], c?: Ctx): Instruction {
55
+ const w = args(new Writer().bytes(instructionDiscriminator(name)));
56
+ return { programAddress: pid(c), accounts: [...accounts, R(floorEventAuthorityPda(pid(c))[0]), R(pid(c)), ...rest], data: w.done() };
57
+ }
58
+ const none = (w: Writer): Writer => w;
59
+ const idArg = (id: Uint8Array | string) => (w: Writer): Writer => w.bytes(idBytes(id));
60
+
61
+ export interface OfficeBase extends Ctx {
62
+ officeId: Uint8Array | string;
63
+
64
+ office?: string;
65
+ }
66
+ const officeOf = (p: OfficeBase): string => p.office ?? officePda(p.officeId, pid(p))[0];
67
+ interface QuoteCtx { quoteMint: string; quoteTokenProgram?: string; quoteExtra?: AccountMeta[] }
68
+
69
+ export function officeOpenInstruction(p: OfficeBase & { signer: string; quoteMint: string; quoteTokenProgram?: string }): Instruction {
70
+ const office = officeOf(p);
71
+ const tp = p.quoteTokenProgram ?? TOKEN_PROGRAM_ID;
72
+ return ix("office_open", [WS(p.signer), W(office), R(p.quoteMint), R(quoteEntryPda(p.quoteMint, pid(p))[0]), W(officeQuoteVault(office, p.quoteMint, tp)), R(tp), R(ASSOCIATED_TOKEN_PROGRAM_ID), R(SYSTEM_PROGRAM_ID)],
73
+ (w) => idArg(p.officeId)(w), [], p);
74
+ }
75
+ export function officeAddMemberInstruction(p: OfficeBase & { controller: string; member: string }): Instruction {
76
+ return ix("office_add_member", [RS(p.controller), W(officeOf(p))], (w) => w.pubkey(p.member), [], p);
77
+ }
78
+ export function officeSetShareInstruction(p: OfficeBase & { controller: string; member: string; shareBps: number }): Instruction {
79
+ if (!Number.isInteger(p.shareBps) || p.shareBps < 0 || p.shareBps > 10_000) throw new RangeError("shareBps is 0..=10000 (ShareSum)");
80
+ return ix("office_set_share", [RS(p.controller), W(officeOf(p))], (w) => w.pubkey(p.member).u16(p.shareBps), [], p);
81
+ }
82
+ function leaveAccounts(signer: string, member: string, office: string, memberQuoteAta: string, q: QuoteCtx): AccountMeta[] {
83
+ const tp = q.quoteTokenProgram ?? TOKEN_PROGRAM_ID;
84
+ return [WS(signer), W(office), R(member), R(q.quoteMint), W(officeQuoteVault(office, q.quoteMint, tp)), W(memberQuoteAta), R(tp), R(TOKEN_2022_PROGRAM_ID), R(ASSOCIATED_TOKEN_PROGRAM_ID), R(SYSTEM_PROGRAM_ID)];
85
+ }
86
+
87
+ function leaveRest(office: string, member: string, positions: readonly OfficeLeavePosition[] = [], q: QuoteCtx): AccountMeta[] {
88
+ return [
89
+ ...positions.flatMap((l) => [R(l.launch), R(l.baseMint), W(l.poolBaseAta ?? officeBaseVault(office, l.baseMint)), W(l.memberBaseAta ?? associatedTokenAddress(member, l.baseMint, TOKEN_2022_PROGRAM_ID)), ...six(l.hookExtra, "hookExtra")]),
90
+ ...quoteTail(q.quoteExtra),
91
+ ];
92
+ }
93
+
94
+ export function officeRemoveMemberInstruction(p: OfficeBase & QuoteCtx & { controller: string; member: string; memberQuoteAta: string; positions?: OfficeLeavePosition[] }): Instruction {
95
+ const office = officeOf(p);
96
+ return ix("office_remove_member", leaveAccounts(p.controller, p.member, office, p.memberQuoteAta, p), (w) => w.pubkey(p.member), leaveRest(office, p.member, p.positions, p), p);
97
+ }
98
+ export function officeLeaveInstruction(p: OfficeBase & QuoteCtx & { member: string; memberQuoteAta: string; positions?: OfficeLeavePosition[] }): Instruction {
99
+ const office = officeOf(p);
100
+ return ix("office_leave", leaveAccounts(p.member, p.member, office, p.memberQuoteAta, p), none, leaveRest(office, p.member, p.positions, p), p);
101
+ }
102
+
103
+ export function officeDepositInstruction(p: OfficeBase & QuoteCtx & { member: string; memberQuoteAta: string; amount: bigint; positions?: OfficeValuePosition[] }): Instruction {
104
+ const office = officeOf(p);
105
+ const tp = p.quoteTokenProgram ?? TOKEN_PROGRAM_ID;
106
+ return ix("office_deposit", [RS(p.member), W(office), R(p.quoteMint), W(p.memberQuoteAta), W(officeQuoteVault(office, p.quoteMint, tp)), R(tp)], (w) => w.u64(p.amount),
107
+ [...valueBlock(p.positions), ...quoteTail(p.quoteExtra)], p);
108
+ }
109
+ function tradeAccounts(signer: string, office: string, l: OfficeLaunchAccounts, q: QuoteCtx): AccountMeta[] {
110
+ const tp = q.quoteTokenProgram ?? TOKEN_PROGRAM_ID;
111
+ return [WS(signer), W(office), W(l.launch), R(l.baseMint), R(q.quoteMint), W(l.tokenVault), W(l.quoteVault), W(l.poolBaseAta ?? officeBaseVault(office, l.baseMint)), W(officeQuoteVault(office, q.quoteMint, tp)),
112
+ R(TOKEN_2022_PROGRAM_ID), R(tp), R(ASSOCIATED_TOKEN_PROGRAM_ID), R(SYSTEM_PROGRAM_ID)];
113
+ }
114
+
115
+ export function officeBuyInstruction(p: OfficeBase & QuoteCtx & { member: string; launch: OfficeLaunchAccounts; gross: bigint; minTokens: bigint; positions?: OfficeValuePosition[] }): Instruction {
116
+ const office = officeOf(p);
117
+ return ix("office_buy", tradeAccounts(p.member, office, p.launch, p), (w) => w.u64(p.gross).u64(p.minTokens),
118
+ [...valueBlock(p.positions), ...six(p.launch.hookExtra, "hookExtra"), ...quoteTail(p.quoteExtra)], p);
119
+ }
120
+
121
+ export function officeSellInstruction(p: OfficeBase & QuoteCtx & { signer: string; launch: OfficeLaunchAccounts; buyer: string; tokens: bigint; minOut: bigint }): Instruction {
122
+ const office = officeOf(p);
123
+ return ix("office_sell", tradeAccounts(p.signer, office, p.launch, p), (w) => w.pubkey(p.buyer).u64(p.tokens).u64(p.minOut),
124
+ [...six(p.launch.hookExtra, "hookExtra"), ...quoteTail(p.quoteExtra)], p);
125
+ }
126
+
127
+ export function officeProposeControllerInstruction(p: OfficeBase & { controller: string; member?: string }): Instruction {
128
+ return ix("office_propose_controller", [RS(p.controller), W(officeOf(p))], (w) => w.pubkey(p.member ?? SYSTEM_PROGRAM_ID), [], p);
129
+ }
130
+ export function officeAcceptControllerInstruction(p: OfficeBase & { member: string }): Instruction {
131
+ return ix("office_accept_controller", [RS(p.member), W(officeOf(p))], none, [], p);
132
+ }
133
+ export function officeProposeMergeInstruction(p: OfficeBase & { controller: string; otherOfficeId: Uint8Array | string; newController: string }): Instruction {
134
+ return ix("office_propose_merge", [RS(p.controller), W(officeOf(p))], (w) => idArg(p.otherOfficeId)(w).pubkey(p.newController), [], p);
135
+ }
136
+
137
+ export interface OfficeMergePosition { baseMint: string; bAta?: string; aAta?: string; hookExtra: AccountMeta[] }
138
+
139
+ export function officeAcceptMergeInstruction(p: OfficeBase & QuoteCtx & { controller: string; otherOfficeId: Uint8Array | string; newController: string; otherOffice?: string; aPositions?: OfficeValuePosition[]; bPositions?: OfficeMergePosition[]; bLaunches?: OfficeValuePosition[] }): Instruction {
140
+ const b = officeOf(p);
141
+ const a = p.otherOffice ?? officePda(p.otherOfficeId, pid(p))[0];
142
+ const tp = p.quoteTokenProgram ?? TOKEN_PROGRAM_ID;
143
+ const bPos = p.bPositions ?? [];
144
+ const bVal = p.bLaunches ?? [];
145
+ if (bVal.length !== bPos.length) throw new RangeError("bLaunches (B's value block) and bPositions (B's transfer groups) are one per B position");
146
+ return ix("office_accept_merge", [WS(p.controller), W(a), W(b), R(p.quoteMint), W(officeQuoteVault(a, p.quoteMint, tp)), W(officeQuoteVault(b, p.quoteMint, tp)), R(tp), R(TOKEN_2022_PROGRAM_ID), R(ASSOCIATED_TOKEN_PROGRAM_ID), R(SYSTEM_PROGRAM_ID)],
147
+ (w) => idArg(p.otherOfficeId)(w).pubkey(p.newController),
148
+ [...valueBlock(p.aPositions), ...valueBlock(bVal), ...quoteTail(p.quoteExtra),
149
+ ...bPos.flatMap((g) => [R(g.baseMint), W(g.bAta ?? officeBaseVault(b, g.baseMint)), W(g.aAta ?? officeBaseVault(a, g.baseMint)), ...six(g.hookExtra, "hookExtra")])], p);
150
+ }
151
+
152
+ export function officeMergeStepInstruction(p: OfficeBase & { signer: string; otherOfficeId: Uint8Array | string; otherOffice?: string }): Instruction {
153
+ const a = officeOf(p);
154
+ const b = p.otherOffice ?? officePda(p.otherOfficeId, pid(p))[0];
155
+ return ix("office_merge_step", [WS(p.signer), W(a), W(b), R(SYSTEM_PROGRAM_ID)], none, [], p);
156
+ }
157
+ export function officeCancelMergeInstruction(p: OfficeBase & { controller: string }): Instruction {
158
+ return ix("office_cancel_merge", [RS(p.controller), W(officeOf(p))], none, [], p);
159
+ }
@@ -0,0 +1,96 @@
1
+
2
+
3
+ import { addressBytes } from "../codec.ts";
4
+ import { launchPda } from "../solana/floor/program.ts";
5
+ import { TOKEN_2022_PROGRAM_ID } from "../solana/pda.ts";
6
+ import type { AccountMeta, Instruction } from "../solana/instruction.ts";
7
+ import { decodeLaunchV2 } from "./layouts.ts";
8
+ import { mintTlvV2 } from "./quoteMint.ts";
9
+ import { FLOOR_HOOK_PROGRAM_ID, hookAccountsFor } from "./solana.ts";
10
+ import type { Ctx } from "./solana.ts";
11
+ import { officeBuyInstruction, officePda, officeSellInstruction } from "./office-solana.ts";
12
+ import type { OfficeLaunchAccounts, OfficeValuePosition } from "./office-solana.ts";
13
+ import { decodeOffice, officeAccountToRead } from "./office-read.ts";
14
+ import type { OfficeRead } from "./office-read.ts";
15
+
16
+ const EXT_TRANSFER_HOOK = 14;
17
+
18
+ export function isHookedQuoteMint(mintData: Uint8Array, hookProgramId: string = FLOOR_HOOK_PROGRAM_ID): boolean {
19
+ const hook = addressBytes(hookProgramId);
20
+ return mintTlvV2(mintData).some((e) => e.type === EXT_TRANSFER_HOOK && e.value.length >= 64 && e.value.subarray(32, 64).every((b, i) => b === hook[i]));
21
+ }
22
+
23
+ export interface OfficeQuoteSide { quoteMint: string; quoteTokenProgram: string; quoteExtra?: AccountMeta[] }
24
+
25
+ export interface OfficeTradeSetup {
26
+
27
+ launch: string;
28
+ baseMint: string;
29
+ quoteMint: string;
30
+ quoteTokenProgram: string;
31
+
32
+ quoteHooked: boolean;
33
+
34
+ buy: { launch: OfficeLaunchAccounts } & OfficeQuoteSide;
35
+
36
+ sell: { launch: OfficeLaunchAccounts } & OfficeQuoteSide;
37
+ }
38
+
39
+ export function officeLaunchAccounts(p: { launchData: Uint8Array; officeId: Uint8Array | string; office?: string; launch?: string; quoteMintData?: Uint8Array } & Ctx): OfficeTradeSetup {
40
+ const l = decodeLaunchV2(p.launchData);
41
+ const baseMint: string = l.baseMint;
42
+ const quoteMint: string = l.quoteMint;
43
+ const quoteTokenProgram: string = l.quoteTokenProgram;
44
+ const launch = launchPda(baseMint, p.programId)[0];
45
+ if (p.launch !== undefined && p.launch !== launch) throw new RangeError(`launch ${p.launch} is not the launch PDA of base mint ${baseMint} (${launch})`);
46
+ const office = p.office ?? officePda(p.officeId, p.programId)[0];
47
+ const hooked = quoteTokenProgram === TOKEN_2022_PROGRAM_ID && p.quoteMintData !== undefined && isHookedQuoteMint(p.quoteMintData, p.hookProgramId);
48
+ const ctx = { programId: p.programId, hookProgramId: p.hookProgramId };
49
+ const accounts = (isBuy: boolean): OfficeLaunchAccounts => ({
50
+ launch, baseMint, tokenVault: l.tokenVault, quoteVault: l.quoteVault,
51
+ hookExtra: hookAccountsFor({ baseMint, srcOwner: isBuy ? launch : office, dstOwner: isBuy ? office : launch, ...ctx }),
52
+ });
53
+ const side = (isBuy: boolean): OfficeQuoteSide => ({
54
+ quoteMint, quoteTokenProgram,
55
+ ...(hooked ? { quoteExtra: hookAccountsFor({ baseMint: quoteMint, srcOwner: isBuy ? office : launch, dstOwner: isBuy ? launch : office, ...ctx }) } : {}),
56
+ });
57
+ return { launch, baseMint, quoteMint, quoteTokenProgram, quoteHooked: hooked, buy: { launch: accounts(true), ...side(true) }, sell: { launch: accounts(false), ...side(false) } };
58
+ }
59
+
60
+ export interface OfficeTradeRead {
61
+ officeId: string;
62
+ office: OfficeRead;
63
+
64
+ positions: OfficeValuePosition[];
65
+ trade: OfficeTradeSetup;
66
+
67
+ ctx: Ctx;
68
+ }
69
+
70
+ export async function readOfficeTrade(p: { officeId: Uint8Array | string; baseMint: string; fetch: (address: string) => Promise<Uint8Array | null> } & Ctx): Promise<OfficeTradeRead> {
71
+ const ctx = { programId: p.programId, hookProgramId: p.hookProgramId };
72
+ const officeAddr = officePda(p.officeId, p.programId)[0];
73
+ const launchAddr = launchPda(p.baseMint, p.programId)[0];
74
+ const [officeData, launchData] = await Promise.all([p.fetch(officeAddr), p.fetch(launchAddr)]);
75
+ if (!officeData) throw new Error(`Office ${officeAddr} does not exist`);
76
+ const acc = decodeOffice(officeData);
77
+ const office = officeAccountToRead(acc);
78
+ if (!office.opened) throw new Error(`Office ${officeAddr} is not opened (merged away)`);
79
+ if (!launchData) throw new Error(`launch ${launchAddr} does not exist`);
80
+ const l = decodeLaunchV2(launchData);
81
+ if (l.baseMint !== p.baseMint) throw new Error(`launch ${launchAddr} holds base mint ${l.baseMint}, not ${p.baseMint}`);
82
+ if (l.quoteMint !== acc.quoteMint) throw new Error(`launch quote ${l.quoteMint} is not the Office's quote ${acc.quoteMint} (OfficeWrongQuote)`);
83
+ const quoteMintData = l.quoteTokenProgram === TOKEN_2022_PROGRAM_ID ? (await p.fetch(l.quoteMint)) ?? undefined : undefined;
84
+ if (l.quoteTokenProgram === TOKEN_2022_PROGRAM_ID && !quoteMintData) throw new Error(`quote mint ${l.quoteMint} does not exist`);
85
+ const trade = officeLaunchAccounts({ launchData, officeId: p.officeId, office: officeAddr, quoteMintData, ...ctx });
86
+ const positions = office.positions.map((x) => ({ launch: launchPda(x.launch, p.programId)[0], baseMint: x.launch }));
87
+ return { officeId: typeof p.officeId === "string" ? p.officeId : "0x" + [...p.officeId].map((b) => b.toString(16).padStart(2, "0")).join(""), office, positions, trade, ctx };
88
+ }
89
+
90
+ export function officeBuyFromRead(r: OfficeTradeRead, a: { member: string; gross: bigint; minTokens: bigint }): Instruction {
91
+ return officeBuyInstruction({ ...r.ctx, officeId: r.officeId, member: a.member, gross: a.gross, minTokens: a.minTokens, positions: r.positions, ...r.trade.buy });
92
+ }
93
+
94
+ export function officeSellFromRead(r: OfficeTradeRead, a: { signer: string; buyer: string; tokens: bigint; minOut: bigint }): Instruction {
95
+ return officeSellInstruction({ ...r.ctx, officeId: r.officeId, signer: a.signer, buyer: a.buyer, tokens: a.tokens, minOut: a.minOut, ...r.trade.sell });
96
+ }
@@ -28,6 +28,7 @@ function hopForms(trader: string, pool: PoolV2, all: readonly PoolV2[], programI
28
28
  const a = { ...routeTradeAccountsV2(trader, pool, qp, programId), quoteIsLaunch: pool.quoteIsLaunch ?? all.some((x) => coinKey(x.token) === coinKey(pool.quote)), programId };
29
29
  return [
30
30
  buyInstructionV2({ ...a, amountIn: 1n, minOut: 1n }),
31
+ buyInstructionV2({ ...a, amountIn: 1n, minOut: 1n, refVolumeBook: true }),
31
32
  buyFromBalanceInstructionV2({ ...a, keep: 0n, minOut: 1n }),
32
33
  sellInstructionV2({ ...a, tokensIn: 1n, minOut: 1n }),
33
34
  sellFromBalanceInstructionV2({ ...a, keep: 0n, minOut: 1n }),
package/src/v2/route.ts CHANGED
@@ -275,7 +275,7 @@ export function routeTradeAccountsV2(trader: string, pool: PoolV2, quoteTokenPro
275
275
  tokenVault: tokenVault(launch, pool.token), quoteVault: quoteVault(launch, pool.quote, quoteTokenProgram),
276
276
  traderBase: associatedTokenAddress(trader, pool.token, TOKEN_2022_PROGRAM_ID), traderQuote: associatedTokenAddress(trader, pool.quote, quoteTokenProgram),
277
277
  quoteTokenProgram, traderRef, escrow: traderRef ? traderRefEscrow(traderRef, pool.quote, quoteTokenProgram) : null,
278
- user: pool.linked ? trader : null,
278
+ user: pool.linked ? trader : null, refVolumeBook: traderRef ? true : undefined,
279
279
  };
280
280
  }
281
281
 
package/src/v2/solana.ts CHANGED
@@ -6,7 +6,7 @@ import { R, RS, W, WS, instructionDiscriminator } from "../solana/instruction.ts
6
6
  import type { AccountMeta, Instruction } from "../solana/instruction.ts";
7
7
  import { ASSOCIATED_TOKEN_PROGRAM_ID, SYSTEM_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, WSOL_MINT, associatedTokenAddress, findProgramAddress } from "../solana/pda.ts";
8
8
  import type { Pda } from "../solana/pda.ts";
9
- import { FLOOR_AMM_ERRORS, FLOOR_AMM_PROGRAM_ID, INSTRUCTIONS_SYSVAR_ID, METADATA_PROGRAM_ID, configPda, floorEventAuthorityPda, genesisConvertBandPda, genesisRaisePda, launchPda, teamSlotPda, traderLinkPda, traderRefPda, unwrapPda } from "../solana/floor/program.ts";
9
+ import { FLOOR_AMM_ERRORS, FLOOR_AMM_PROGRAM_ID, INSTRUCTIONS_SYSVAR_ID, METADATA_PROGRAM_ID, configPda, floorEventAuthorityPda, genesisConvertBandPda, genesisRaisePda, launchPda, refOwedPda, teamSlotPda, traderLinkPda, traderRefPda, unwrapPda } from "../solana/floor/program.ts";
10
10
  import { Writer } from "../solana/floor/borsh.ts";
11
11
  import { CLAIM_CREATOR, CLAIM_CREATOR_REF, CLAIM_EXTRA, CLAIM_KNOWN_WIDE, CLAIM_TEAM_BUY, CLAIM_TEAM_SLOT, CLAIM_TRADER_REF, CLAIM_SHARE_BOUGHT, MAX_NAME_LEN, MAX_SYMBOL_LEN, createMintAccounts, withdrawPlatformManyInstruction } from "../solana/floor/instructions.ts";
12
12
  import type { ClaimLaunch, TradeAccounts } from "../solana/floor/instructions.ts";
@@ -14,6 +14,7 @@ import { MEMBERS_MAX, ROW_LEN } from "./layouts.ts";
14
14
  import { freshRegistryPrice } from "../registryPrice.ts";
15
15
  import type { RegistryPrice } from "../registryPrice.ts";
16
16
  import { CLAIM_BITS, CLAIM_KNOWN_MASKS, PROGRAM_IDS } from "../generated/index.ts";
17
+ import { DEAL_ESCROW_STEPS_MAX, STEP_VOLUME } from "../math/v2/escrow.ts";
17
18
 
18
19
  export const FLOOR_HOOK_PROGRAM_ID: string = PROGRAM_IDS.floorHook;
19
20
 
@@ -38,7 +39,14 @@ export const extraAccountMetasPda = (baseMint: string, hook = FLOOR_HOOK_PROGRAM
38
39
 
39
40
  const V2_ERROR_NAMES = [
40
41
  "NothingToSettle", "HolderPositionExists", "HolderPositionNotEmpty", "HolderBookMismatch", "DeadAccountNotDead",
41
- "HookAccountsMissing", "RowTooManyRanges", "RowNotFeasible",
42
+ "HookAccountsMissing", "RowTooManyRanges", "RowNotFeasible", "OgFull", "DealFeeOverCap", "DealFeeFixed",
43
+ "DealEscrowSteps", "DealEscrowExpiry", "DealEscrowTarget", "DealEscrowNotArmed", "DealEscrowTooSoon", "DealEscrowDone", "DealEscrowExpired", "DealEscrowNotExpired", "DealEscrowFunding", "DealEscrowNotParty",
44
+
45
+ "DealEscrowAgency", "DealEscrowProofNotRequired", "DealEscrowProofState", "DealEscrowWindowClosed", "DealEscrowNoObjectionLeft", "DealEscrowNotProven", "DealEscrowVersion",
46
+
47
+ "RefVolumeBookFull",
48
+
49
+ "OfficeNotMember", "OfficeNotController", "OfficeFull", "OfficeAlreadyMember", "OfficeShareSum", "OfficeOverShare", "OfficeNoCash", "OfficePositions", "OfficeZeroAmount", "OfficeZeroUnits", "OfficeZeroValue", "OfficeNotHeld", "OfficeMergeSize", "OfficeNotMergeable", "OfficeMergeMismatch", "OfficeNotSeller", "OfficeWrongQuote", "OfficeControllerLeaves", "OfficeSlippage", "OfficeOverflow", "OfficeExists", "OfficeMergeLocked", "OfficeNoMerge",
42
50
  ] as const;
43
51
 
44
52
  export const V2_ERROR_BASE = FLOOR_AMM_ERRORS.BurnTooLarge + 1;
@@ -112,6 +120,178 @@ export function creditBackingInstructionV2(p: { donor: string; launch: string; b
112
120
  return { ...base, accounts: [...base.accounts, ...hookAccountsFor({ baseMint: p.quoteMint, srcOwner: p.donor, dstOwner: p.launch, programId: p.programId, hookProgramId: p.hookProgramId })] };
113
121
  }
114
122
 
123
+ export function creditPlatformInstruction(p: { payer: string; launch: string; baseMint: string; quoteMint: string; payerQuote: string; quoteVault: string; quoteTokenProgram: string; amount: bigint; memo?: Uint8Array; quoteIsLaunch?: boolean } & Ctx): Instruction {
124
+ if (p.amount <= 0n) throw new RangeError("credit_platform: the amount must be > 0 (NothingToDo)");
125
+ const memo = p.memo ?? new Uint8Array(32);
126
+ if (memo.length !== 32) throw new RangeError("credit_platform: the memo is 32 bytes");
127
+ const base = ix("credit_platform", [RS(p.payer), W(p.launch), R(p.baseMint), R(p.quoteMint), W(p.payerQuote), W(p.quoteVault), R(p.quoteTokenProgram)], (w) => w.u64(p.amount).bytes(memo), p);
128
+ if (!p.quoteIsLaunch) return base;
129
+ return { ...base, accounts: [...base.accounts, ...hookAccountsFor({ baseMint: p.quoteMint, srcOwner: p.payer, dstOwner: p.launch, programId: p.programId, hookProgramId: p.hookProgramId })] };
130
+ }
131
+
132
+ export const ESCROW_KIND_QUOTE = 0;
133
+
134
+ export const ESCROW_KIND_TOKEN = 1;
135
+
136
+ export function dealEscrowPda(launch: string, kol: string, ref32: Uint8Array, programId = FLOOR_AMM_PROGRAM_ID): Pda {
137
+ if (ref32.length !== 32) throw new RangeError("deal_escrow: ref32 is 32 bytes");
138
+ return findProgramAddress(["deal_escrow", k(launch), k(kol), ref32], programId);
139
+ }
140
+
141
+ const i64le = (w: Writer, v: bigint): Writer => {
142
+ if (v < -(1n << 63n) || v >= 1n << 63n) throw new RangeError("an i64 out of range");
143
+ return w.uint(BigInt.asUintN(64, v), 8);
144
+ };
145
+
146
+ function escrowAsset(p: { kind: number; baseMint: string; quoteMint?: string; quoteTokenProgram?: string }): [mint: string, tokenProgram: string] {
147
+ if (p.kind === ESCROW_KIND_TOKEN) return [p.baseMint, TOKEN_2022_PROGRAM_ID];
148
+ if (p.kind !== ESCROW_KIND_QUOTE) throw new RangeError("deal_escrow: kind is 0 (quote) or 1 (the launch's token)");
149
+ if (!p.quoteMint || !p.quoteTokenProgram) throw new RangeError("deal_escrow: a quote escrow names quoteMint and quoteTokenProgram");
150
+ return [p.quoteMint, p.quoteTokenProgram];
151
+ }
152
+
153
+ type EscrowAsset = { kind: number; baseMint: string; quoteMint?: string; quoteTokenProgram?: string; hooked?: boolean };
154
+
155
+ export function dealEscrowOpenInstruction(p: { launcher: string; launch: string; kol: string; ref32: Uint8Array; targets: readonly bigint[]; amounts: readonly bigint[]; expiry: bigint; escrow?: string; launcherAsset?: string; vault?: string } & EscrowAsset & Ctx): Instruction {
156
+ const n = p.targets.length;
157
+ if (n < 1 || n > DEAL_ESCROW_STEPS_MAX || p.amounts.length !== n) throw new RangeError(`deal_escrow_open: 1..=${DEAL_ESCROW_STEPS_MAX} steps, one amount each (DealEscrowSteps)`);
158
+ const [mint, tp] = escrowAsset(p);
159
+ const escrow = p.escrow ?? dealEscrowPda(p.launch, p.kol, p.ref32, pid(p))[0];
160
+ const accounts = [WS(p.launcher), R(p.launch), R(p.baseMint), W(escrow), R(mint), W(p.launcherAsset ?? associatedTokenAddress(p.launcher, mint, tp)), W(p.vault ?? associatedTokenAddress(escrow, mint, tp)), R(tp), R(ASSOCIATED_TOKEN_PROGRAM_ID), R(SYSTEM_PROGRAM_ID)];
161
+ const base = ix("deal_escrow_open", accounts, (w) => {
162
+ w.pubkey(p.kol).bytes(p.ref32).u8(p.kind);
163
+ for (let i = 0; i < DEAL_ESCROW_STEPS_MAX; i++) w.u128(i < n ? p.targets[i] : 0n);
164
+ for (let i = 0; i < DEAL_ESCROW_STEPS_MAX; i++) w.u64(i < n ? p.amounts[i] : 0n);
165
+ return i64le(w.u8(n), p.expiry);
166
+ }, p);
167
+ if (!p.hooked) return base;
168
+ return { ...base, accounts: [...base.accounts, ...hookAccountsFor({ baseMint: mint, srcOwner: p.launcher, dstOwner: escrow, programId: p.programId, hookProgramId: p.hookProgramId })] };
169
+ }
170
+
171
+ export function dealEscrowArmInstruction(p: { launch: string; baseMint: string; escrow: string; step: number } & Ctx): Instruction {
172
+ if (!Number.isInteger(p.step) || p.step < 0 || p.step >= DEAL_ESCROW_STEPS_MAX) throw new RangeError("deal_escrow_arm: step in 0..8");
173
+ return ix("deal_escrow_arm", [R(p.launch), R(p.baseMint), W(p.escrow)], (w) => w.u8(p.step), p);
174
+ }
175
+
176
+ export function dealEscrowReleaseInstruction(p: { caller: string; launch: string; kol: string; ref32: Uint8Array; step: number; treasury: string; quoteVault?: string; config?: string; escrow?: string; vault?: string; kolAsset?: string; feeDest?: string } & EscrowAsset & Ctx): Instruction {
177
+ if (!Number.isInteger(p.step) || p.step < 0 || p.step >= DEAL_ESCROW_STEPS_MAX) throw new RangeError("deal_escrow_release: step in 0..8");
178
+ const [mint, tp] = escrowAsset(p);
179
+ const escrow = p.escrow ?? dealEscrowPda(p.launch, p.kol, p.ref32, pid(p))[0];
180
+ const isToken = p.kind === ESCROW_KIND_TOKEN;
181
+ const feeOwner = isToken ? p.treasury : p.launch;
182
+ const feeDest = p.feeDest ?? (isToken ? associatedTokenAddress(p.treasury, mint, tp) : p.quoteVault ?? associatedTokenAddress(p.launch, mint, tp));
183
+ const accounts = [WS(p.caller), R(p.config ?? configPda(pid(p))[0]), W(p.launch), R(p.baseMint), W(escrow), R(mint), W(p.vault ?? associatedTokenAddress(escrow, mint, tp)), R(p.kol), W(p.kolAsset ?? associatedTokenAddress(p.kol, mint, tp)), W(feeDest), R(p.treasury), R(tp), R(ASSOCIATED_TOKEN_PROGRAM_ID), R(SYSTEM_PROGRAM_ID)];
184
+ const base = ix("deal_escrow_release", accounts, (w) => w.u8(p.step), p);
185
+ if (!p.hooked) return base;
186
+ const h = (dst: string) => hookAccountsFor({ baseMint: mint, srcOwner: escrow, dstOwner: dst, programId: p.programId, hookProgramId: p.hookProgramId });
187
+ return { ...base, accounts: [...base.accounts, ...h(p.kol), ...h(feeOwner)] };
188
+ }
189
+
190
+ export function dealEscrowRefundInstruction(p: { caller: string; launch: string; launcher: string; kol: string; ref32: Uint8Array; escrow?: string; vault?: string; launcherAsset?: string } & EscrowAsset & Ctx): Instruction {
191
+ const [mint, tp] = escrowAsset(p);
192
+ const escrow = p.escrow ?? dealEscrowPda(p.launch, p.kol, p.ref32, pid(p))[0];
193
+ const accounts = [WS(p.caller), W(escrow), R(mint), W(p.vault ?? associatedTokenAddress(escrow, mint, tp)), R(p.launcher), W(p.launcherAsset ?? associatedTokenAddress(p.launcher, mint, tp)), R(tp), R(ASSOCIATED_TOKEN_PROGRAM_ID), R(SYSTEM_PROGRAM_ID)];
194
+ const base = ix("deal_escrow_refund", accounts, (w) => w, p);
195
+ if (!p.hooked) return base;
196
+ return { ...base, accounts: [...base.accounts, ...hookAccountsFor({ baseMint: mint, srcOwner: escrow, dstOwner: p.launcher, programId: p.programId, hookProgramId: p.hookProgramId })] };
197
+ }
198
+
199
+ export function dealEscrowCancelInstruction(p: { party: string; launch: string; launcher: string; kol: string; ref32: Uint8Array; escrow?: string; vault?: string; launcherAsset?: string } & EscrowAsset & Ctx): Instruction {
200
+ const [mint, tp] = escrowAsset(p);
201
+ const escrow = p.escrow ?? dealEscrowPda(p.launch, p.kol, p.ref32, pid(p))[0];
202
+ const accounts = [WS(p.party), W(escrow), R(mint), W(p.vault ?? associatedTokenAddress(escrow, mint, tp)), R(p.launcher), W(p.launcherAsset ?? associatedTokenAddress(p.launcher, mint, tp)), R(tp), R(ASSOCIATED_TOKEN_PROGRAM_ID), R(SYSTEM_PROGRAM_ID)];
203
+ const base = ix("deal_escrow_cancel", accounts, (w) => w, p);
204
+ if (!p.hooked) return base;
205
+ return { ...base, accounts: [...base.accounts, ...hookAccountsFor({ baseMint: mint, srcOwner: escrow, dstOwner: p.launcher, programId: p.programId, hookProgramId: p.hookProgramId })] };
206
+ }
207
+
208
+ export function refVolumePda(launch: string, referrer: string, programId = FLOOR_AMM_PROGRAM_ID): Pda {
209
+ return findProgramAddress(["ref_volume", k(launch), k(referrer)], programId);
210
+ }
211
+
212
+ export function refVolumeBookPda(launch: string, programId = FLOOR_AMM_PROGRAM_ID): Pda {
213
+ return findProgramAddress(["ref_volume_book", k(launch)], programId);
214
+ }
215
+
216
+ const stepArg = (step: number, what: string): number => {
217
+ if (!Number.isInteger(step) || step < 0 || step >= DEAL_ESCROW_STEPS_MAX) throw new RangeError(`${what}: step in 0..8`);
218
+ return step;
219
+ };
220
+
221
+ export function openRefVolumeInstruction(p: { payer: string; launch: string; baseMint: string; referrer: string } & Ctx): Instruction {
222
+ return ix("open_ref_volume", [WS(p.payer), R(p.launch), R(p.baseMint), W(refVolumePda(p.launch, p.referrer, pid(p))[0]), R(SYSTEM_PROGRAM_ID)], (w) => w.pubkey(p.referrer), p);
223
+ }
224
+
225
+ export function dealEscrowOpenV3Instruction(p: { launcher: string; launch: string; kol: string; ref32: Uint8Array; targets: readonly bigint[]; amounts: readonly bigint[]; expiry: bigint; stepKinds: readonly number[]; proofMask?: number; agency?: string; agencyBps?: number; refVolume?: string | boolean; escrow?: string; launcherAsset?: string; vault?: string } & EscrowAsset & Ctx): Instruction {
226
+ const n = p.targets.length;
227
+ if (n < 1 || n > DEAL_ESCROW_STEPS_MAX || p.amounts.length !== n || p.stepKinds.length !== n) throw new RangeError(`deal_escrow_open_v3: 1..=${DEAL_ESCROW_STEPS_MAX} steps, one amount and one kind each (DealEscrowSteps)`);
228
+ const mask = p.proofMask ?? 0;
229
+ if (!Number.isInteger(mask) || mask < 0 || mask >> n !== 0) throw new RangeError("deal_escrow_open_v3: proofMask bits only below n (DealEscrowSteps)");
230
+ const [mint, tp] = escrowAsset(p);
231
+ const escrow = p.escrow ?? dealEscrowPda(p.launch, p.kol, p.ref32, pid(p))[0];
232
+ const wantsVolume = p.refVolume ?? (p.stepKinds.includes(STEP_VOLUME) ? "book" : false);
233
+ const rv = wantsVolume === "book" ? refVolumeBookPda(p.launch, pid(p))[0] : typeof wantsVolume === "string" ? wantsVolume : wantsVolume ? refVolumePda(p.launch, p.kol, pid(p))[0] : null;
234
+ const accounts = [WS(p.launcher), R(p.launch), R(p.baseMint), W(escrow), R(mint), W(p.launcherAsset ?? associatedTokenAddress(p.launcher, mint, tp)), W(p.vault ?? associatedTokenAddress(escrow, mint, tp)), R(tp), R(ASSOCIATED_TOKEN_PROGRAM_ID), R(SYSTEM_PROGRAM_ID), opt(rv, p, W)];
235
+ const base = ix("deal_escrow_open_v3", accounts, (w) => {
236
+ w.pubkey(p.kol).bytes(p.ref32).u8(p.kind);
237
+ for (let i = 0; i < DEAL_ESCROW_STEPS_MAX; i++) w.u128(i < n ? p.targets[i] : 0n);
238
+ for (let i = 0; i < DEAL_ESCROW_STEPS_MAX; i++) w.u64(i < n ? p.amounts[i] : 0n);
239
+ i64le(w.u8(n), p.expiry);
240
+ for (let i = 0; i < DEAL_ESCROW_STEPS_MAX; i++) w.u8(i < n ? p.stepKinds[i] : 0);
241
+ return w.u8(mask).pubkey(p.agency ?? SYSTEM_PROGRAM_ID).u16(p.agencyBps ?? 0);
242
+ }, p);
243
+ if (!p.hooked) return base;
244
+ return { ...base, accounts: [...base.accounts, ...hookAccountsFor({ baseMint: mint, srcOwner: p.launcher, dstOwner: escrow, programId: p.programId, hookProgramId: p.hookProgramId })] };
245
+ }
246
+
247
+ const volumeCounter = (rv: string | boolean | undefined, launch: string, kol: string | undefined, p: Ctx): string | undefined => {
248
+ if (rv === undefined || rv === false) return undefined;
249
+ if (rv === "book") return refVolumeBookPda(launch, pid(p))[0];
250
+ if (rv === true) {
251
+ if (!kol) throw new RangeError("refVolume: true derives PDA(launch, kol): name the kol");
252
+ return refVolumePda(launch, kol, pid(p))[0];
253
+ }
254
+ return rv;
255
+ };
256
+
257
+ export function dealEscrowArmV3Instruction(p: { launch: string; baseMint: string; escrow: string; step: number; refVolume?: string | boolean; kol?: string } & Ctx): Instruction {
258
+ const step = stepArg(p.step, "deal_escrow_arm_v3");
259
+ return ix("deal_escrow_arm_v3", [R(p.launch), R(p.baseMint), W(p.escrow), opt(volumeCounter(p.refVolume, p.launch, p.kol, p), p, R)], (w) => w.u8(step), p);
260
+ }
261
+
262
+ export function dealEscrowReleaseV3Instruction(p: { caller: string; launch: string; kol: string; ref32: Uint8Array; step: number; treasury: string; agency?: string; refVolume?: string | boolean; kolTiers?: readonly string[]; quoteVault?: string; config?: string; escrow?: string; vault?: string; kolAsset?: string; feeDest?: string; agencyAsset?: string } & EscrowAsset & Ctx): Instruction {
263
+ const step = stepArg(p.step, "deal_escrow_release_v3");
264
+ const [mint, tp] = escrowAsset(p);
265
+ const escrow = p.escrow ?? dealEscrowPda(p.launch, p.kol, p.ref32, pid(p))[0];
266
+ const isToken = p.kind === ESCROW_KIND_TOKEN;
267
+ const feeOwner = isToken ? p.treasury : p.launch;
268
+ const feeDest = p.feeDest ?? (isToken ? associatedTokenAddress(p.treasury, mint, tp) : p.quoteVault ?? associatedTokenAddress(p.launch, mint, tp));
269
+ const agencyAsset = p.agency ? (p.agencyAsset ?? associatedTokenAddress(p.agency, mint, tp)) : null;
270
+ const accounts = [WS(p.caller), R(p.config ?? configPda(pid(p))[0]), W(p.launch), R(p.baseMint), W(escrow), R(mint), W(p.vault ?? associatedTokenAddress(escrow, mint, tp)), R(p.kol), W(p.kolAsset ?? associatedTokenAddress(p.kol, mint, tp)), W(feeDest), R(p.treasury), R(tp), R(ASSOCIATED_TOKEN_PROGRAM_ID), R(SYSTEM_PROGRAM_ID),
271
+ opt(p.agency, p, R), opt(agencyAsset, p, W), opt(volumeCounter(p.refVolume, p.launch, p.kol, p), p, R), R(traderLinkPda(p.kol, pid(p))[0])];
272
+ const base = ix("deal_escrow_release_v3", accounts, (w) => w.u8(step), p);
273
+ const tiers = p.kolTiers ?? [];
274
+ if (tiers.length > 3) throw new RangeError("deal_escrow_release_v3: at most 3 tiers");
275
+ const h = (dst: string) => hookAccountsFor({ baseMint: mint, srcOwner: escrow, dstOwner: dst, programId: p.programId, hookProgramId: p.hookProgramId });
276
+ const groups: AccountMeta[] = p.hooked ? [...h(p.kol), ...h(feeOwner), ...(p.agency ? h(p.agency) : [])] : [];
277
+ for (const t of tiers) {
278
+ const owed = refOwedPda(t, mint, pid(p))[0];
279
+ groups.push(W(owed), W(associatedTokenAddress(owed, mint, tp)), ...(p.hooked ? h(owed) : []));
280
+ }
281
+ return { ...base, accounts: [...base.accounts, ...groups] };
282
+ }
283
+
284
+ export function dealEscrowSubmitProofInstruction(p: { kol: string; escrow: string; step: number; proofHash: Uint8Array } & Ctx): Instruction {
285
+ const step = stepArg(p.step, "deal_escrow_submit_proof");
286
+ if (p.proofHash.length !== 32) throw new RangeError("deal_escrow_submit_proof: the proof hash is 32 bytes");
287
+ return ix("deal_escrow_submit_proof", [RS(p.kol), W(p.escrow)], (w) => w.u8(step).bytes(p.proofHash), p);
288
+ }
289
+
290
+ export function dealEscrowObjectInstruction(p: { launcher: string; escrow: string; step: number } & Ctx): Instruction {
291
+ const step = stepArg(p.step, "deal_escrow_object");
292
+ return ix("deal_escrow_object", [RS(p.launcher), W(p.escrow)], (w) => w.u8(step), p);
293
+ }
294
+
115
295
  export const SYNC_DEAD_MAX_PAIRS = 8;
116
296
 
117
297
  export function syncDeadInstruction(p: { payer: string; launch: string; baseMint: string; deadTokenAccounts: readonly string[] } & Ctx): Instruction {
@@ -184,18 +364,20 @@ export type TeamShareBuyBaseV2 = {
184
364
 
185
365
  quoteIsLaunch?: boolean;
186
366
  } & Ctx;
187
- export function teamShareBuyInstructionV2(p: TeamShareBuyBaseV2 & { amountIn: bigint; minOut: bigint }): Instruction {
367
+
368
+ export function teamShareBuyInstructionV2(p: TeamShareBuyBaseV2 & { amountIn: bigint; minOut: bigint; seatAgency?: ShareBuyAgency }): Instruction {
188
369
  if (!p.traderRef !== !p.escrow) throw new RangeError("team_share_buy: traderRef and escrow go together");
189
370
  const referred = Boolean(p.traderRef);
190
371
  if (referred && !p.quoteTokenProgram) throw new RangeError("team_share_buy: a referred buyback needs quoteTokenProgram");
191
372
  const base = ix(
192
373
  "team_share_buy",
193
374
 
194
- [WS(p.member), W(p.launch), R(p.baseMint), R(p.quoteMint), W(p.tokenVault), referred ? W(p.quoteVault) : R(p.quoteVault), R(p.teamSlot ?? teamSlotPda(p.launch, pid(p))[0]), W(p.memberBase), R(TOKEN_2022_PROGRAM_ID)],
375
+ [WS(p.member), W(p.launch), R(p.baseMint), R(p.quoteMint), W(p.tokenVault), referred || p.seatAgency ? W(p.quoteVault) : R(p.quoteVault), R(p.teamSlot ?? teamSlotPda(p.launch, pid(p))[0]), W(p.memberBase), R(TOKEN_2022_PROGRAM_ID)],
195
376
  (w) => w.u64(p.amountIn).u64(minOut(p.minOut, "minOut")),
196
377
  p,
197
378
  );
198
379
  const accounts = [...base.accounts, ...hookAccountsFor({ baseMint: p.baseMint, srcOwner: p.launch, dstOwner: p.member, programId: p.programId, hookProgramId: p.hookProgramId })];
380
+ if (p.seatAgency) accounts.push(...shareBuyAgencyBlock(p.launch, p.quoteMint, p.seatAgency, p));
199
381
  if (!referred) return { ...base, accounts };
200
382
  accounts.push(W(p.traderRef!), W(p.escrow!), R(p.quoteTokenProgram!));
201
383
  if (p.quoteIsLaunch) {
@@ -205,6 +387,14 @@ export function teamShareBuyInstructionV2(p: TeamShareBuyBaseV2 & { amountIn: bi
205
387
  return { ...base, accounts };
206
388
  }
207
389
 
390
+ export type ShareBuyAgency = { index: number; agency: string; quoteTokenProgram: string; quoteIsLaunch?: boolean };
391
+
392
+ export function shareBuyAgencyBlock(launch: string, quoteMint: string, a: ShareBuyAgency, p: Ctx = {}): AccountMeta[] {
393
+ const b = [R(seatAgencyPda(launch, a.index, pid(p))[0]), R(a.agency), W(associatedTokenAddress(a.agency, quoteMint, a.quoteTokenProgram)), R(a.quoteTokenProgram)];
394
+ if (a.quoteIsLaunch) b.push(...hookAccountsFor({ baseMint: quoteMint, srcOwner: launch, dstOwner: a.agency, programId: p.programId, hookProgramId: p.hookProgramId }));
395
+ return b;
396
+ }
397
+
208
398
  const REM_HOOK_AT = 5;
209
399
 
210
400
  export interface TradeAccountsV2 extends TradeAccounts {
@@ -214,6 +404,10 @@ export interface TradeAccountsV2 extends TradeAccounts {
214
404
  quoteIsLaunch?: boolean;
215
405
 
216
406
  quoteOwner?: string;
407
+
408
+ refVolume?: string;
409
+
410
+ refVolumeBook?: string | boolean;
217
411
  }
218
412
 
219
413
  export const REM_QUOTE_HOOK_AT = 11;
@@ -250,13 +444,19 @@ function remMetas(a: TradeAccountsV2, isBuy: boolean, c?: Ctx): AccountMeta[] {
250
444
  return [...q, W(holderPositionPda(launchPda(a.quoteMint, pid(c))[0], a.traderRef, hid(c))[0])];
251
445
  }
252
446
 
447
+ const remWithVolume = (a: TradeAccountsV2, isBuy: boolean, c?: Ctx): AccountMeta[] => {
448
+ if (!isBuy) return remMetas(a, isBuy, c);
449
+ const book = a.refVolumeBook === true ? refVolumeBookPda(a.launch, pid(c))[0] : a.refVolumeBook || null;
450
+ return [...remMetas(a, isBuy, c), ...(a.refVolume ? [W(a.refVolume)] : []), ...(book ? [W(book)] : [])];
451
+ };
452
+
253
453
  const minOut = (v: bigint, what: string): bigint => {
254
454
  if (v <= 0n) throw new RangeError(`${what} must be > 0 (the NO_MINIMUM rule)`);
255
455
  return v;
256
456
  };
257
457
  function trade(name: string, a: TradeAccountsV2 & Ctx, isBuy: boolean, x: bigint, m: bigint, what: string): Instruction {
258
458
  const base = ix(name, tradeMetas(a, a), (w) => w.u64(x).u64(minOut(m, what)), a);
259
- return { ...base, accounts: [...base.accounts, ...remMetas(a, isBuy, a)] };
459
+ return { ...base, accounts: [...base.accounts, ...remWithVolume(a, isBuy, a)] };
260
460
  }
261
461
 
262
462
  export type BuyArgsV2 = TradeAccountsV2 & Ctx & { amountIn: bigint; minOut: bigint };
@@ -397,6 +597,8 @@ export interface ClaimLaunchV2 extends ClaimLaunch {
397
597
  holderBase?: string;
398
598
 
399
599
  baseMint?: string;
600
+
601
+ seatAgency?: { index: number; agency: string };
400
602
  }
401
603
 
402
604
  export function claimInstructionV2(p: {
@@ -439,9 +641,37 @@ export function claimInstructionV2(p: {
439
641
  if ((p.types & CLAIM_TRADER_REF) !== 0 && p.refOwed) payers.push(p.refOwed);
440
642
  rest.push(...quoteHookBlock(p.quoteMint, p.wallet, payers, p));
441
643
  }
644
+
645
+ if ((p.types & CLAIM_TEAM_SLOT) !== 0) {
646
+ for (const l of p.launches) if (l.seatAgency && l.teamSlot) rest.push(...seatAgencyBlock(l.launch, l.seatAgency.index, l.seatAgency.agency, p.quoteMint, p.quoteTokenProgram, !!p.quoteIsLaunch, p));
647
+ }
442
648
  return { ...base, accounts: [...base.accounts, ...rest] };
443
649
  }
444
650
 
651
+ export function seatAgencyPda(launch: string, index: number, programId = FLOOR_AMM_PROGRAM_ID): Pda {
652
+ if (!Number.isInteger(index) || index < 0 || index >= MEMBERS_MAX) throw new RangeError(`seat index in 0..${MEMBERS_MAX}`);
653
+ return findProgramAddress(["seat_agency", k(launch), Uint8Array.of(index)], programId);
654
+ }
655
+
656
+ export function seatAgencyBlock(launch: string, index: number, agency: string, quoteMint: string, quoteTokenProgram: string, quoteIsLaunch: boolean, p: Ctx = {}): AccountMeta[] {
657
+ const b = [R(seatAgencyPda(launch, index, pid(p))[0]), R(agency), W(associatedTokenAddress(agency, quoteMint, quoteTokenProgram))];
658
+ if (quoteIsLaunch) b.push(W(holderPositionPda(launchPda(quoteMint, pid(p))[0], agency, hid(p))[0]));
659
+ return b;
660
+ }
661
+
662
+ export const SEAT_AGENCY_BPS_MAX = 3_000;
663
+
664
+ export function teamSlotAddDealV3Instruction(p: { creator: string; launch: string; key: string; kind: number; amount: bigint; dealFeeBps: number; agency?: string; agencyBps: number; index: number; teamSlot?: string; config?: string; seatAgency?: string; rest?: AccountMeta[] } & Ctx): Instruction {
665
+ if (!Number.isInteger(p.dealFeeBps) || p.dealFeeBps < 0 || p.dealFeeBps > 0xffff) throw new RangeError("team_slot_add_deal_v3: deal_fee_bps is a u16");
666
+ const agency = p.agency ?? SYSTEM_PROGRAM_ID;
667
+ if (!Number.isInteger(p.agencyBps) || p.agencyBps < 0 || p.agencyBps > SEAT_AGENCY_BPS_MAX || (agency !== SYSTEM_PROGRAM_ID) !== p.agencyBps > 0) throw new RangeError("team_slot_add_deal_v3: an agency needs 1..=3000 bps, none needs 0 (DealEscrowAgency)");
668
+ if (p.amount <= 0n) throw new RangeError("team_slot_add_deal_v3: amount > 0 (NothingToDo)");
669
+ const g = pid(p);
670
+ const accounts = [WS(p.creator), W(p.launch), W(p.teamSlot ?? teamSlotPda(p.launch, g)[0]), R(p.config ?? configPda(g)[0]), W(p.seatAgency ?? seatAgencyPda(p.launch, p.index, g)[0]), R(SYSTEM_PROGRAM_ID)];
671
+ const base = ix("team_slot_add_deal_v3", accounts, (w) => w.pubkey(p.key).u8(p.kind).u64(p.amount).u16(p.dealFeeBps).pubkey(agency).u16(p.agencyBps), p);
672
+ return { ...base, accounts: [...base.accounts, ...(p.rest ?? [])] };
673
+ }
674
+
445
675
  export function setGenesisConvertBandInstruction(p: { authority: string; solPxMin: bigint; solPxMax: bigint; usdcPxMin: bigint; usdcPxMax: bigint; config?: string; genesisRaise?: string; convertBand?: string } & Ctx): Instruction {
446
676
  for (const v of [p.solPxMin, p.solPxMax, p.usdcPxMin, p.usdcPxMax]) if (v <= 0n || v >> 128n !== 0n) throw new RangeError("set_genesis_convert_band: each price is a u128 > 0");
447
677
  if (p.solPxMin > p.solPxMax || p.usdcPxMin > p.usdcPxMax) throw new RangeError("set_genesis_convert_band: min ≤ max");
@@ -74,6 +74,8 @@ export function solanaSettleInputsV2(l: LaunchV2Account, opts: { mintSupply?: bi
74
74
  nC: l.nC, bandF: [...l.bandF], bandFClaim: [...l.bandFClaim], ckAtF: l.ckAtF, ckFloorTokens: l.ckFloorTokens,
75
75
 
76
76
  kpot: l.kpot !== 0, kAtF: l.kAtF, kFloorTokens: l.kFloorTokens,
77
+
78
+ ...(l.kKept[0] | (l.kKept[1] << 8) | (l.kKept[2] << 16) ? { kKept: l.kKept[0] | (l.kKept[1] << 8) | (l.kKept[2] << 16) } : {}),
77
79
  feePpm: l.feePpm.map(n), feeStartPpm: l.feeStartPpm.map(n), sqrtFeeA: l.sqrtFeeA, sqrtFeeB: l.sqrtFeeB,
78
80
  graduated: l.graduated !== 0, nRanges: l.nRanges, ranges,
79
81