@b3dotfun/sdk 0.0.40-alpha.5 → 0.0.40-alpha.6

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.
@@ -0,0 +1,373 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BondkitSwapService = void 0;
4
+ const viem_1 = require("viem");
5
+ const chains_1 = require("viem/chains");
6
+ const constants_1 = require("./constants");
7
+ // Minimal ABIs needed for swap functionality
8
+ const UNIVERSAL_ROUTER_ABI = [
9
+ {
10
+ inputs: [
11
+ { name: "commands", type: "bytes" },
12
+ { name: "inputs", type: "bytes[]" },
13
+ { name: "deadline", type: "uint256" },
14
+ ],
15
+ name: "execute",
16
+ outputs: [],
17
+ stateMutability: "payable",
18
+ type: "function",
19
+ },
20
+ ];
21
+ const QUOTER_ABI = [
22
+ {
23
+ inputs: [
24
+ {
25
+ components: [
26
+ {
27
+ components: [
28
+ { internalType: "Currency", name: "currency0", type: "address" },
29
+ { internalType: "Currency", name: "currency1", type: "address" },
30
+ { internalType: "uint24", name: "fee", type: "uint24" },
31
+ { internalType: "int24", name: "tickSpacing", type: "int24" },
32
+ { internalType: "contract IHooks", name: "hooks", type: "address" },
33
+ ],
34
+ internalType: "struct PoolKey",
35
+ name: "poolKey",
36
+ type: "tuple",
37
+ },
38
+ { internalType: "bool", name: "zeroForOne", type: "bool" },
39
+ { internalType: "uint128", name: "exactAmount", type: "uint128" },
40
+ { internalType: "bytes", name: "hookData", type: "bytes" },
41
+ ],
42
+ internalType: "struct IV4Quoter.QuoteExactSingleParams",
43
+ name: "params",
44
+ type: "tuple",
45
+ },
46
+ ],
47
+ name: "quoteExactInputSingle",
48
+ outputs: [
49
+ { internalType: "uint256", name: "amountOut", type: "uint256" },
50
+ { internalType: "uint256", name: "gasEstimate", type: "uint256" },
51
+ ],
52
+ stateMutability: "nonpayable",
53
+ type: "function",
54
+ },
55
+ ];
56
+ const ERC20_ABI = [
57
+ {
58
+ inputs: [
59
+ { name: "spender", type: "address" },
60
+ { name: "amount", type: "uint256" },
61
+ ],
62
+ name: "approve",
63
+ outputs: [{ name: "", type: "bool" }],
64
+ stateMutability: "nonpayable",
65
+ type: "function",
66
+ },
67
+ {
68
+ inputs: [
69
+ { name: "owner", type: "address" },
70
+ { name: "spender", type: "address" },
71
+ ],
72
+ name: "allowance",
73
+ outputs: [{ name: "", type: "uint256" }],
74
+ stateMutability: "view",
75
+ type: "function",
76
+ },
77
+ ];
78
+ const PERMIT2_ABI = [
79
+ {
80
+ inputs: [
81
+ { name: "token", type: "address" },
82
+ { name: "spender", type: "address" },
83
+ { name: "amount", type: "uint160" },
84
+ { name: "expiration", type: "uint48" },
85
+ ],
86
+ name: "approve",
87
+ outputs: [],
88
+ stateMutability: "nonpayable",
89
+ type: "function",
90
+ },
91
+ {
92
+ inputs: [
93
+ { name: "owner", type: "address" },
94
+ { name: "token", type: "address" },
95
+ { name: "spender", type: "address" },
96
+ ],
97
+ name: "allowance",
98
+ outputs: [
99
+ { name: "amount", type: "uint160" },
100
+ { name: "expiration", type: "uint48" },
101
+ { name: "nonce", type: "uint48" },
102
+ ],
103
+ stateMutability: "view",
104
+ type: "function",
105
+ },
106
+ ];
107
+ const TOKEN_V4_CONFIG_ABI = [
108
+ {
109
+ inputs: [],
110
+ name: "v4Hook",
111
+ outputs: [{ internalType: "address", name: "", type: "address" }],
112
+ stateMutability: "view",
113
+ type: "function",
114
+ },
115
+ {
116
+ inputs: [],
117
+ name: "v4PoolFee",
118
+ outputs: [{ internalType: "uint24", name: "", type: "uint24" }],
119
+ stateMutability: "view",
120
+ type: "function",
121
+ },
122
+ {
123
+ inputs: [],
124
+ name: "v4TickSpacing",
125
+ outputs: [{ internalType: "int24", name: "", type: "int24" }],
126
+ stateMutability: "view",
127
+ type: "function",
128
+ },
129
+ ];
130
+ // Command and action constants
131
+ const COMMANDS = {
132
+ V4_SWAP: "0x10",
133
+ };
134
+ const V4_ACTIONS = {
135
+ SWAP_EXACT_IN_SINGLE: 6,
136
+ TAKE_ALL: 15,
137
+ SETTLE_ALL: 12,
138
+ };
139
+ /**
140
+ * Internal swap service for handling Uniswap V4 swaps between trading token and bondkit token
141
+ */
142
+ class BondkitSwapService {
143
+ constructor(bondkitTokenAddress) {
144
+ this.v4Config = null;
145
+ this.configInitialized = false;
146
+ this.bondkitTokenAddress = bondkitTokenAddress;
147
+ this.publicClient = (0, viem_1.createPublicClient)({
148
+ chain: chains_1.base,
149
+ transport: (0, viem_1.http)(constants_1.BaseMainnetRpcUrl),
150
+ });
151
+ }
152
+ /**
153
+ * Initialize V4 pool configuration from bondkit token contract
154
+ */
155
+ async initializeV4Config() {
156
+ if (this.configInitialized) {
157
+ return;
158
+ }
159
+ try {
160
+ const tokenContract = (0, viem_1.getContract)({
161
+ address: this.bondkitTokenAddress,
162
+ abi: TOKEN_V4_CONFIG_ABI,
163
+ client: this.publicClient,
164
+ });
165
+ const [hook, fee, tickSpacing] = await Promise.all([
166
+ tokenContract.read.v4Hook(),
167
+ tokenContract.read.v4PoolFee(),
168
+ tokenContract.read.v4TickSpacing(),
169
+ ]);
170
+ this.v4Config = {
171
+ hook: hook,
172
+ fee: Number(fee),
173
+ tickSpacing: Number(tickSpacing),
174
+ };
175
+ this.configInitialized = true;
176
+ }
177
+ catch (error) {
178
+ console.warn("Failed to initialize V4 configuration:", error);
179
+ // Use fallback configuration
180
+ this.v4Config = {
181
+ hook: "0xB36f4A2FB18b745ef8eD31452781a463d2B3f0cC",
182
+ fee: 30000,
183
+ tickSpacing: 60,
184
+ };
185
+ this.configInitialized = true;
186
+ }
187
+ }
188
+ /**
189
+ * Get V4 pool configuration
190
+ */
191
+ async getV4Config() {
192
+ await this.initializeV4Config();
193
+ return this.v4Config;
194
+ }
195
+ /**
196
+ * Handle token approvals for swap
197
+ */
198
+ async handleTokenApprovals(tokenAddress, amountIn, walletClient, deadline) {
199
+ // Skip approvals for ETH
200
+ if (tokenAddress === "0x0000000000000000000000000000000000000000") {
201
+ return;
202
+ }
203
+ const userAddress = walletClient.account?.address;
204
+ if (!userAddress) {
205
+ throw new Error("No user address found");
206
+ }
207
+ const erc20Contract = (0, viem_1.getContract)({
208
+ address: tokenAddress,
209
+ abi: ERC20_ABI,
210
+ client: walletClient,
211
+ });
212
+ const permit2Contract = (0, viem_1.getContract)({
213
+ address: constants_1.Permit2Address,
214
+ abi: PERMIT2_ABI,
215
+ client: walletClient,
216
+ });
217
+ // Check ERC20 allowance to Permit2
218
+ const currentAllowance = (await erc20Contract.read.allowance([userAddress, constants_1.Permit2Address]));
219
+ const requiredAmount = BigInt(amountIn);
220
+ if (currentAllowance < requiredAmount) {
221
+ await erc20Contract.write.approve([constants_1.Permit2Address, BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")], {
222
+ account: userAddress,
223
+ chain: chains_1.base,
224
+ });
225
+ }
226
+ // Check Permit2 allowance for Universal Router
227
+ const permit2Allowance = (await permit2Contract.read.allowance([
228
+ userAddress,
229
+ tokenAddress,
230
+ constants_1.UniversalRouterAddress,
231
+ ]));
232
+ const [currentPermit2Amount, expiration] = permit2Allowance;
233
+ const currentTime = Math.floor(Date.now() / 1000);
234
+ const isExpired = expiration <= currentTime;
235
+ if (currentPermit2Amount < requiredAmount || isExpired) {
236
+ await permit2Contract.write.approve([tokenAddress, constants_1.UniversalRouterAddress, BigInt("0xffffffffffffffffffffffffffffffffffffff"), Number(deadline)], {
237
+ account: userAddress,
238
+ chain: chains_1.base,
239
+ });
240
+ }
241
+ }
242
+ /**
243
+ * Get swap quote
244
+ */
245
+ async getSwapQuote(params) {
246
+ try {
247
+ const { tokenIn, tokenOut, amountIn, tokenInDecimals, tokenOutDecimals, slippageTolerance } = params;
248
+ const v4Config = await this.getV4Config();
249
+ const amountInWei = (0, viem_1.parseUnits)(amountIn, tokenInDecimals);
250
+ // Determine token order for pool
251
+ const currency0 = tokenIn.toLowerCase() < tokenOut.toLowerCase() ? tokenIn : tokenOut;
252
+ const currency1 = tokenIn.toLowerCase() < tokenOut.toLowerCase() ? tokenOut : tokenIn;
253
+ const zeroForOne = tokenIn.toLowerCase() === currency0.toLowerCase();
254
+ const poolKey = {
255
+ currency0: currency0,
256
+ currency1: currency1,
257
+ fee: v4Config.fee,
258
+ tickSpacing: v4Config.tickSpacing,
259
+ hooks: v4Config.hook,
260
+ };
261
+ const quoteParams = {
262
+ poolKey,
263
+ zeroForOne,
264
+ exactAmount: BigInt(amountInWei.toString()),
265
+ hookData: "0x",
266
+ };
267
+ const { result } = await this.publicClient.simulateContract({
268
+ address: constants_1.QuoterAddress,
269
+ abi: QUOTER_ABI,
270
+ functionName: "quoteExactInputSingle",
271
+ args: [quoteParams],
272
+ });
273
+ const [amountOut] = result;
274
+ const amountOutRaw = (0, viem_1.formatUnits)(amountOut, tokenOutDecimals);
275
+ const amountOutFormatted = parseFloat(amountOutRaw).toFixed(Math.min(6, tokenOutDecimals));
276
+ // Calculate minimum amount out with slippage
277
+ const slippageMultiplier = (100 - slippageTolerance) / 100;
278
+ const amountOutMinRaw = parseFloat(amountOutFormatted) * slippageMultiplier;
279
+ const amountOutMin = amountOutMinRaw.toFixed(tokenOutDecimals);
280
+ // Simple execution price calculation
281
+ const rate = parseFloat(amountOutFormatted) / parseFloat(amountIn);
282
+ const executionPrice = `1 = ${rate.toFixed(6)}`;
283
+ return {
284
+ amountOut: amountOutFormatted,
285
+ amountOutMin,
286
+ priceImpact: "0.0", // Simplified
287
+ executionPrice,
288
+ fee: (v4Config.fee / 10000).toString(),
289
+ };
290
+ }
291
+ catch (error) {
292
+ console.warn("Error getting swap quote:", error);
293
+ return null;
294
+ }
295
+ }
296
+ /**
297
+ * Execute swap transaction
298
+ */
299
+ async executeSwap(params, walletClient) {
300
+ try {
301
+ const { tokenIn, tokenOut, amountIn, tokenInDecimals, tokenOutDecimals, deadline } = params;
302
+ const swapDeadline = deadline || Math.floor(Date.now() / 1000) + 3600;
303
+ if (!walletClient.account) {
304
+ throw new Error("Wallet client must have an account");
305
+ }
306
+ const amountInWei = (0, viem_1.parseUnits)(amountIn, tokenInDecimals);
307
+ // Handle token approvals
308
+ await this.handleTokenApprovals(tokenIn, amountInWei.toString(), walletClient, swapDeadline);
309
+ // Get quote for minimum amount out
310
+ const quote = await this.getSwapQuote(params);
311
+ if (!quote) {
312
+ throw new Error("Unable to get swap quote");
313
+ }
314
+ const amountOutMinimum = (0, viem_1.parseUnits)(quote.amountOutMin, tokenOutDecimals);
315
+ const v4Config = await this.getV4Config();
316
+ // Determine token order
317
+ const currency0 = tokenIn.toLowerCase() < tokenOut.toLowerCase() ? tokenIn : tokenOut;
318
+ const currency1 = tokenIn.toLowerCase() < tokenOut.toLowerCase() ? tokenOut : tokenIn;
319
+ const zeroForOne = tokenIn.toLowerCase() === currency0.toLowerCase();
320
+ const poolKey = [currency0, currency1, v4Config.fee, v4Config.tickSpacing, v4Config.hook];
321
+ // Encode V4 actions
322
+ const actions = [
323
+ {
324
+ type: V4_ACTIONS.SWAP_EXACT_IN_SINGLE,
325
+ params: [poolKey, zeroForOne, amountInWei, amountOutMinimum, "0x"],
326
+ },
327
+ {
328
+ type: V4_ACTIONS.TAKE_ALL,
329
+ params: [(zeroForOne ? currency1 : currency0), BigInt(0)],
330
+ },
331
+ {
332
+ type: V4_ACTIONS.SETTLE_ALL,
333
+ params: [(zeroForOne ? currency0 : currency1), amountInWei],
334
+ },
335
+ ];
336
+ // Encode actions
337
+ const actionTypes = actions.map(action => action.type);
338
+ const actionsBytes = ("0x" + actionTypes.map(type => type.toString(16).padStart(2, "0")).join(""));
339
+ const actionParams = actions.map(action => {
340
+ switch (action.type) {
341
+ case V4_ACTIONS.SWAP_EXACT_IN_SINGLE:
342
+ return (0, viem_1.encodeAbiParameters)((0, viem_1.parseAbiParameters)("((address,address,uint24,int24,address),bool,uint128,uint128,bytes)"), [action.params]);
343
+ case V4_ACTIONS.TAKE_ALL:
344
+ return (0, viem_1.encodeAbiParameters)((0, viem_1.parseAbiParameters)("address,uint256"), action.params);
345
+ case V4_ACTIONS.SETTLE_ALL:
346
+ return (0, viem_1.encodeAbiParameters)((0, viem_1.parseAbiParameters)("address,uint256"), action.params);
347
+ default:
348
+ return "0x00";
349
+ }
350
+ });
351
+ const v4SwapInput = (0, viem_1.encodeAbiParameters)((0, viem_1.parseAbiParameters)("bytes,bytes[]"), [actionsBytes, actionParams]);
352
+ const commands = COMMANDS.V4_SWAP;
353
+ const inputs = [v4SwapInput];
354
+ // Execute swap
355
+ const universalRouter = (0, viem_1.getContract)({
356
+ address: constants_1.UniversalRouterAddress,
357
+ abi: UNIVERSAL_ROUTER_ABI,
358
+ client: walletClient,
359
+ });
360
+ const txHash = await universalRouter.write.execute([commands, inputs, BigInt(swapDeadline)], {
361
+ account: walletClient.account,
362
+ chain: chains_1.base,
363
+ value: tokenIn === "0x0000000000000000000000000000000000000000" ? amountInWei : BigInt(0),
364
+ });
365
+ return txHash;
366
+ }
367
+ catch (error) {
368
+ console.warn("Error executing swap:", error);
369
+ return null;
370
+ }
371
+ }
372
+ }
373
+ exports.BondkitSwapService = BondkitSwapService;
@@ -49,10 +49,9 @@ export type DexMigrationEventArgs = {
49
49
  ethForFeeRecipient: bigint;
50
50
  };
51
51
  export declare enum TokenStatus {
52
- Inactive = 0,// Assuming mapping from ABI, verify actual enum values if specified elsewhere
53
- BondingPhase = 1,
54
- DexPhase = 2,
55
- Migrated = 3
52
+ Uninitialized = 0,
53
+ Bonding = 1,
54
+ Dex = 2
56
55
  }
57
56
  export interface GetTransactionHistoryOptions {
58
57
  userAddress?: Address;
@@ -80,3 +79,10 @@ export interface TransactionResponse {
80
79
  skip: number;
81
80
  data: Transaction[];
82
81
  }
82
+ export interface SwapQuote {
83
+ amountOut: string;
84
+ amountOutMin: string;
85
+ priceImpact: string;
86
+ executionPrice: string;
87
+ fee: string;
88
+ }
@@ -1,11 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.TokenStatus = void 0;
4
- // Enum for Status (used in BondkitToken ABI)
4
+ // Enum for Status (matches contract Status enum exactly)
5
5
  var TokenStatus;
6
6
  (function (TokenStatus) {
7
- TokenStatus[TokenStatus["Inactive"] = 0] = "Inactive";
8
- TokenStatus[TokenStatus["BondingPhase"] = 1] = "BondingPhase";
9
- TokenStatus[TokenStatus["DexPhase"] = 2] = "DexPhase";
10
- TokenStatus[TokenStatus["Migrated"] = 3] = "Migrated";
7
+ TokenStatus[TokenStatus["Uninitialized"] = 0] = "Uninitialized";
8
+ TokenStatus[TokenStatus["Bonding"] = 1] = "Bonding";
9
+ TokenStatus[TokenStatus["Dex"] = 2] = "Dex";
11
10
  })(TokenStatus || (exports.TokenStatus = TokenStatus = {}));
@@ -1,6 +1,7 @@
1
1
  import type { Address, EIP1193Provider, GetContractReturnType, Hex, PublicClient, WalletClient } from "viem";
2
2
  import { BondkitTokenABI } from "./abis";
3
- import type { BondkitTokenInitializationConfig, GetTransactionHistoryOptions, TokenDetails, TokenStatus, TransactionResponse } from "./types";
3
+ import type { BondkitTokenInitializationConfig, GetTransactionHistoryOptions, SwapQuote, TokenDetails, TransactionResponse } from "./types";
4
+ import { TokenStatus } from "./types";
4
5
  type ExecuteWriteOptions = {
5
6
  value?: bigint;
6
7
  gas?: bigint;
@@ -18,6 +19,7 @@ export declare class BondkitToken {
18
19
  private walletClientInstance;
19
20
  private connectedProvider?;
20
21
  private tradingToken?;
22
+ private swapService?;
21
23
  constructor(contractAddress: string, walletKey?: string, rpcUrl?: string);
22
24
  connect(provider?: EIP1193Provider): boolean;
23
25
  /**
@@ -69,5 +71,38 @@ export declare class BondkitToken {
69
71
  migrateToDex(options?: ExecuteWriteOptions): Promise<Hex | undefined>;
70
72
  transferTokenOwnership(newOwner: Address, options?: ExecuteWriteOptions): Promise<Hex | undefined>;
71
73
  renounceTokenOwnership(options?: ExecuteWriteOptions): Promise<Hex | undefined>;
74
+ /**
75
+ * Get the swap service instance (lazy initialization)
76
+ */
77
+ private getSwapService;
78
+ /**
79
+ * Check if DEX swapping is available (token must be in Dex phase)
80
+ */
81
+ isSwapAvailable(): Promise<boolean | undefined>;
82
+ /**
83
+ * Get swap quote for trading token → bondkit token
84
+ */
85
+ getSwapQuoteForBondkitToken(amountTradingTokenIn: string, slippageTolerance?: number): Promise<SwapQuote | undefined>;
86
+ /**
87
+ * Get swap quote for bondkit token → trading token
88
+ */
89
+ getSwapQuoteForTradingToken(amountBondkitTokenIn: string, slippageTolerance?: number): Promise<SwapQuote | undefined>;
90
+ /**
91
+ * Swap trading token for bondkit token
92
+ */
93
+ swapTradingTokenForBondkitToken(amountTradingTokenIn: string, slippageTolerance?: number, options?: ExecuteWriteOptions): Promise<Hex | undefined>;
94
+ /**
95
+ * Swap bondkit token for trading token
96
+ */
97
+ swapBondkitTokenForTradingToken(amountBondkitTokenIn: string, slippageTolerance?: number, options?: ExecuteWriteOptions): Promise<Hex | undefined>;
98
+ /**
99
+ * Helper method to get trading token decimals
100
+ */
101
+ private getTradingTokenDecimals;
102
+ /**
103
+ * Get trading token symbol
104
+ * @param tradingTokenAddress Optional trading token address to avoid fetching it again
105
+ */
106
+ getTradingTokenSymbol(tradingTokenAddress?: Address): Promise<string | undefined>;
72
107
  }
73
108
  export {};