apinow-sdk 0.9.1 → 0.11.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/README.md CHANGED
@@ -1,14 +1,13 @@
1
1
  # ApiNow SDK
2
2
 
3
- A TypeScript SDK for interacting with ApiNow endpoints, supporting Ethereum (including Base), and Solana chains. Designed to work in Node.js, browsers, and edge environments like Cloudflare Workers.
3
+ A TypeScript SDK for interacting with ApiNow endpoints, supporting Ethereum and Base chains. Designed to work in Node.js, browsers, and edge environments like Cloudflare Workers.
4
4
 
5
5
  ## Features
6
6
 
7
- - Multi-chain support (Ethereum, Base, Solana)
8
- - Native and Token transfers (ERC20 on ETH/Base, SPL on Solana)
7
+ - Multi-chain support (Ethereum, Base)
8
+ - Native and ERC20 token transfers
9
9
  - Environment Agnostic: Uses global `fetch` for broad compatibility.
10
10
  - Optional RPC URL: Uses public RPCs by default, allows override.
11
- - Fast mode for quicker transaction processing (skips confirmation wait).
12
11
  - TypeScript types for better development experience.
13
12
 
14
13
  ## Installation
@@ -27,11 +26,12 @@ yarn add apinow-sdk
27
26
  import apiNow from 'apinow-sdk';
28
27
 
29
28
  const ENDPOINT_URL = 'https://apinow.fun/api/endpoints/your-endpoint';
30
- const YOUR_WALLET_PRIVATE_KEY = '0x...'; // Or Solana base58 private key
29
+ const YOUR_WALLET_PRIVATE_KEY = '0x...';
31
30
 
32
31
  // 1. Get endpoint info (payment details)
33
32
  const info = await apiNow.info(ENDPOINT_URL);
34
33
  // info will contain: { requiredAmount, walletAddress, httpMethod, tokenAddress, chain }
34
+ // Note: chain will be 'eth' or 'base'
35
35
  console.log('Payment required:', info);
36
36
 
37
37
  // 2. Send payment and get the API response in one step
@@ -40,7 +40,7 @@ try {
40
40
  ENDPOINT_URL,
41
41
  YOUR_WALLET_PRIVATE_KEY
42
42
  // Optional: Add RPC URL override here if needed
43
- // Optional: Add options like { fastMode: true } here
43
+ // Optional: Add options like { fastMode: true } here (Note: fastMode currently has no effect)
44
44
  );
45
45
  console.log('API Response:', response);
46
46
  } catch (error) {
@@ -50,10 +50,10 @@ try {
50
50
 
51
51
  ### Providing a Custom RPC URL
52
52
 
53
- If you need to use a specific RPC node:
53
+ If you need to use a specific RPC node (e.g., for Base):
54
54
 
55
55
  ```typescript
56
- const CUSTOM_RPC_URL = 'https://your-custom-node.com';
56
+ const CUSTOM_RPC_URL = 'https://mainnet.base.org';
57
57
 
58
58
  const response = await apiNow.infoBuyResponse(
59
59
  ENDPOINT_URL,
@@ -64,24 +64,22 @@ const response = await apiNow.infoBuyResponse(
64
64
 
65
65
  ### Fast Mode
66
66
 
67
- Fast mode skips waiting for transaction confirmation. This provides faster responses but relies on the transaction being accepted by the network (mempool/leader inclusion).
67
+ *Note: `fastMode` is currently included for potential future use but does not affect Ethereum/Base transaction confirmation behavior in this version.*
68
68
 
69
69
  ```typescript
70
70
  const response = await apiNow.infoBuyResponse(
71
71
  ENDPOINT_URL,
72
72
  YOUR_WALLET_PRIVATE_KEY,
73
73
  undefined, // Use default RPC
74
- { fastMode: true } // Enable fast mode
74
+ { fastMode: true } // Option included, but no effect yet
75
75
  );
76
76
  ```
77
77
 
78
78
  ### Manual Payment (Separate Steps)
79
79
 
80
- You can also perform the payment manually if needed.
81
-
82
80
  ```typescript
83
81
  import apiNow from 'apinow-sdk';
84
- import { ethers } from 'ethers'; // For amount conversion if needed
82
+ import { ethers } from 'ethers';
85
83
 
86
84
  const ENDPOINT_URL = 'https://apinow.fun/api/endpoints/your-endpoint';
87
85
  const YOUR_WALLET_PRIVATE_KEY = '0x...';
@@ -91,7 +89,7 @@ const YOUR_CUSTOM_RPC_URL = 'https://your-node.com'; // Optional
91
89
  const info = await apiNow.info(ENDPOINT_URL);
92
90
  const { requiredAmount, walletAddress, chain, tokenAddress } = info;
93
91
 
94
- // Convert requiredAmount (string) to bigint (smallest unit: wei/lamports)
92
+ // Convert requiredAmount (string) to bigint (wei)
95
93
  const amountBigInt = BigInt(requiredAmount);
96
94
 
97
95
  // 2. Send Payment
@@ -99,15 +97,14 @@ const txHash = await apiNow.buy(
99
97
  walletAddress,
100
98
  amountBigInt,
101
99
  YOUR_WALLET_PRIVATE_KEY,
102
- chain, // Specify the chain from info
100
+ chain, // 'eth' or 'base'
103
101
  YOUR_CUSTOM_RPC_URL, // Optional: override RPC
104
- tokenAddress, // Optional: specify token if required by endpoint
105
- false // Optional: fastMode (defaults to false)
102
+ tokenAddress // Optional: specify ERC20 token if required
103
+ // fastMode param exists but is unused by handler
106
104
  );
107
105
  console.log(`Payment sent: ${txHash}`);
108
106
 
109
- // 3. Get API Response (after waiting for confirmation if not fastMode)
110
- // Add a delay here if needed
107
+ // 3. Get API Response (add delay as needed)
111
108
  await new Promise(resolve => setTimeout(resolve, 5000)); // Example 5s delay
112
109
 
113
110
  const apiResponse = await apiNow.txResponse(
@@ -123,15 +120,15 @@ console.log('API Response:', apiResponse);
123
120
 
124
121
  Gets payment requirement information about an ApiNow endpoint.
125
122
 
126
- ### `buy(walletAddress: string, amount: bigint, userWalletPrivateKey: string, chain: 'eth' | 'sol' | 'base', rpcUrl?: string, tokenAddress?: string, fastMode?: boolean): Promise<string>`
123
+ ### `buy(walletAddress: string, amount: bigint, userWalletPrivateKey: string, chain: 'eth' | 'base', rpcUrl?: string, tokenAddress?: string, fastMode?: boolean): Promise<string>`
127
124
 
128
125
  Sends the required payment transaction to the specified address.
129
- - `amount`: The required amount in the smallest unit (wei for ETH/Base, lamports for SOL).
126
+ - `amount`: The required amount in the smallest unit (wei).
130
127
  - `userWalletPrivateKey`: The private key of the wallet sending the funds.
131
- - `chain`: The blockchain target ('eth', 'sol', 'base').
128
+ - `chain`: The blockchain target ('eth' or 'base').
132
129
  - `rpcUrl` (Optional): Overrides the default public RPC URL.
133
- - `tokenAddress` (Optional): The contract address if paying with an ERC20/SPL token.
134
- - `fastMode` (Optional): If true, returns the transaction hash immediately without waiting for confirmation.
130
+ - `tokenAddress` (Optional): The contract address if paying with an ERC20 token.
131
+ - `fastMode` (Optional): Parameter exists but currently has no effect.
135
132
 
136
133
  Returns the transaction hash.
137
134
 
@@ -139,16 +136,16 @@ Returns the transaction hash.
139
136
 
140
137
  Fetches the final API response from the endpoint after a successful payment.
141
138
  - `txHash`: The hash of the payment transaction.
142
- - `opts` (Optional): Options like `{ method: 'POST', data: {...} }` to be passed to the underlying endpoint API call if needed (usually configured by the endpoint itself).
139
+ - `opts` (Optional): Options like `{ method: 'POST', data: {...} }`.
143
140
 
144
141
  Returns the endpoint's API response.
145
142
 
146
143
  ### `infoBuyResponse(endpoint: string, userWalletPrivateKey: string, rpcUrl?: string, opts?: TxResponseOptions & { fastMode?: boolean }): Promise<any>`
147
144
 
148
- Combines `info`, `buy`, and `txResponse` into a single call for convenience.
145
+ Combines `info`, `buy`, and `txResponse` into a single call.
149
146
  - `userWalletPrivateKey`: The private key of the wallet sending the funds.
150
147
  - `rpcUrl` (Optional): Overrides the default public RPC URL for the payment.
151
- - `opts` (Optional): Contains `fastMode` boolean and any `TxResponseOptions`.
148
+ - `opts` (Optional): Contains `fastMode` boolean (currently no effect) and any `TxResponseOptions`.
152
149
 
153
150
  Returns the final API response.
154
151
 
@@ -157,16 +154,16 @@ Returns the final API response.
157
154
  ```typescript
158
155
  // Defined in the SDK
159
156
  interface InfoResponse {
160
- requiredAmount: string; // Amount in smallest unit (string)
157
+ requiredAmount: string; // Amount in wei (string)
161
158
  walletAddress: string;
162
- httpMethod: string; // Usually GET or POST for txResponse
163
- tokenAddress?: string;
164
- chain: 'eth' | 'sol' | 'base';
159
+ httpMethod: string;
160
+ tokenAddress?: string; // ERC20 address
161
+ chain: 'eth' | 'base';
165
162
  }
166
163
 
167
164
  interface TxResponseOptions {
168
- method?: string; // HTTP method for txResponse call
169
- data?: any; // Body data for txResponse call
165
+ method?: string;
166
+ data?: any;
170
167
  }
171
168
  ```
172
169
 
@@ -174,7 +171,6 @@ interface TxResponseOptions {
174
171
 
175
172
  - **Ethereum:** `https://rpc.ankr.com/eth`
176
173
  - **Base:** `https://mainnet.base.org`
177
- - **Solana:** `https://api.mainnet-beta.solana.com`
178
174
 
179
175
  You can override these by providing the `rpcUrl` parameter to `buy` or `infoBuyResponse`.
180
176
 
package/dist/index.d.ts CHANGED
@@ -7,17 +7,14 @@ interface InfoResponse {
7
7
  walletAddress: string;
8
8
  httpMethod: string;
9
9
  tokenAddress?: string;
10
- chain: 'eth' | 'sol' | 'base';
10
+ chain: 'eth' | 'base';
11
11
  }
12
12
  declare class ApiNow {
13
13
  private handlers;
14
14
  info(endpoint: string): Promise<InfoResponse>;
15
- buy(walletAddress: string, amount: bigint, userWalletPrivateKey: string, chain: 'eth' | 'sol' | 'base', // Chain is now required to choose handler
16
- rpcUrl?: string, // Optional RPC URL
17
- tokenAddress?: string, fastMode?: boolean): Promise<string>;
15
+ buy(walletAddress: string, amount: bigint, userWalletPrivateKey: string, chain: 'eth' | 'base', rpcUrl?: string, tokenAddress?: string, fastMode?: boolean): Promise<string>;
18
16
  txResponse(endpoint: string, txHash: string, opts?: TxResponseOptions): Promise<any>;
19
- infoBuyResponse(endpoint: string, userWalletPrivateKey: string, rpcUrl?: string, // Optional RPC URL
20
- opts?: TxResponseOptions & {
17
+ infoBuyResponse(endpoint: string, userWalletPrivateKey: string, rpcUrl?: string, opts?: TxResponseOptions & {
21
18
  fastMode?: boolean;
22
19
  }): Promise<any>;
23
20
  }
package/dist/index.js CHANGED
@@ -1,12 +1,8 @@
1
1
  import { ethers, Wallet, isAddress } from 'ethers';
2
- import { Connection, PublicKey, Transaction, SystemProgram, Keypair, ComputeBudgetProgram } from '@solana/web3.js';
3
- import { createTransferInstruction, getAssociatedTokenAddress } from '@solana/spl-token';
4
- import bs58 from 'bs58';
5
2
  // Default RPC URLs
6
- const DEFAULT_ETH_RPC = 'https://rpc.ankr.com/eth'; // Example public RPC
7
- const DEFAULT_SOL_RPC = 'https://api.mainnet-beta.solana.com'; // Example public RPC
8
- const DEFAULT_BASE_RPC = 'https://mainnet.base.org'; // Example public RPC
9
- // --- Helper function for fetch ---
3
+ const DEFAULT_ETH_RPC = 'https://rpc.ankr.com/eth';
4
+ const DEFAULT_BASE_RPC = 'https://mainnet.base.org';
5
+ // --- Helper function for fetch (Keep this) ---
10
6
  async function fetchJson(url, options) {
11
7
  const response = await fetch(url, options);
12
8
  if (!response.ok) {
@@ -15,7 +11,7 @@ async function fetchJson(url, options) {
15
11
  }
16
12
  return response.json();
17
13
  }
18
- // --- Helper function for RPC calls ---
14
+ // --- Helper function for RPC calls (Keep this) ---
19
15
  async function sendJsonRpc(rpcUrl, method, params) {
20
16
  const response = await fetch(rpcUrl, {
21
17
  method: 'POST',
@@ -40,52 +36,46 @@ async function sendJsonRpc(rpcUrl, method, params) {
40
36
  return jsonResponse.result;
41
37
  }
42
38
  class EthereumHandler {
43
- async buy(walletAddress, amount, userWalletPrivateKey, rpcUrl, tokenAddress, fastMode) {
44
- const rpc = rpcUrl || (rpcUrl && rpcUrl.includes('base') ? DEFAULT_BASE_RPC : DEFAULT_ETH_RPC); // Determine default based on presence/content of rpcUrl or use general ETH
39
+ async buy(walletAddress, amount, userWalletPrivateKey, rpcUrl, tokenAddress) {
40
+ const rpc = rpcUrl || (rpcUrl && rpcUrl.includes('base') ? DEFAULT_BASE_RPC : DEFAULT_ETH_RPC);
45
41
  if (!walletAddress || !isAddress(walletAddress)) {
46
42
  throw new Error('Invalid recipient wallet address');
47
43
  }
48
44
  const wallet = new Wallet(userWalletPrivateKey);
49
45
  const senderAddress = wallet.address;
50
46
  try {
51
- // Get nonce manually
52
47
  const nonce = await sendJsonRpc(rpc, 'eth_getTransactionCount', [senderAddress, 'latest']);
53
- // Get gas price suggestion (EIP-1559)
54
- const feeData = await sendJsonRpc(rpc, 'eth_gasPrice', []); // Using legacy gasPrice for simplicity, could fetch EIP-1559 fees
48
+ const feeData = await sendJsonRpc(rpc, 'eth_gasPrice', []);
55
49
  let txRequest;
56
50
  if (tokenAddress) {
57
51
  if (!isAddress(tokenAddress)) {
58
52
  throw new Error('Invalid token address');
59
53
  }
60
- // ERC20 Transfer
61
54
  const abi = ["function transfer(address to, uint256 amount)"];
62
55
  const iface = new ethers.Interface(abi);
63
56
  const data = iface.encodeFunctionData("transfer", [walletAddress, amount]);
64
57
  txRequest = {
65
58
  to: tokenAddress,
66
59
  nonce: parseInt(nonce, 16),
67
- gasPrice: feeData, // Use fetched gas price
68
- // Estimate gas manually if needed, or use a standard limit
69
- gasLimit: 100000, // Adjust as necessary for ERC20 transfers
60
+ gasPrice: feeData,
61
+ gasLimit: 100000,
70
62
  data: data,
71
- chainId: (await sendJsonRpc(rpc, 'eth_chainId', [])), // Fetch chainId
63
+ chainId: (await sendJsonRpc(rpc, 'eth_chainId', [])),
72
64
  };
73
65
  }
74
66
  else {
75
- // Native ETH/Base Transfer
76
67
  txRequest = {
77
68
  to: walletAddress,
78
69
  value: amount,
79
70
  nonce: parseInt(nonce, 16),
80
- gasPrice: feeData, // Use fetched gas price
81
- gasLimit: 21000, // Standard limit for native transfers
82
- chainId: (await sendJsonRpc(rpc, 'eth_chainId', [])), // Fetch chainId
71
+ gasPrice: feeData,
72
+ gasLimit: 21000,
73
+ chainId: (await sendJsonRpc(rpc, 'eth_chainId', [])),
83
74
  };
84
75
  }
85
76
  const signedTx = await wallet.signTransaction(txRequest);
86
77
  const txHash = await sendJsonRpc(rpc, 'eth_sendRawTransaction', [signedTx]);
87
- // TODO: Optionally wait for confirmation if fastMode is false
88
- // This would involve polling eth_getTransactionReceipt
78
+ console.log(`Transaction sent: ${txHash}. Confirmation check not implemented.`);
89
79
  return txHash;
90
80
  }
91
81
  catch (error) {
@@ -94,125 +84,13 @@ class EthereumHandler {
94
84
  }
95
85
  }
96
86
  }
97
- class SolanaHandler {
98
- // Keep using Connection for some helpers, but sendRawTransaction manually
99
- async getConnection(rpcUrl) {
100
- const rpc = rpcUrl || DEFAULT_SOL_RPC;
101
- return new Connection(rpc, {
102
- commitment: 'processed',
103
- confirmTransactionInitialTimeout: 10000 // Used by getMint etc.
104
- });
105
- }
106
- async buy(walletAddress, amount, userWalletPrivateKey, rpcUrl, tokenAddress, fastMode) {
107
- const rpc = rpcUrl || DEFAULT_SOL_RPC;
108
- const connection = await this.getConnection(rpc); // Still useful for some reads
109
- try {
110
- const recipientPubkey = new PublicKey(walletAddress);
111
- const senderKeypair = Keypair.fromSecretKey(bs58.decode(userWalletPrivateKey));
112
- const transaction = new Transaction();
113
- // Add priority fee instruction
114
- transaction.add(ComputeBudgetProgram.setComputeUnitPrice({
115
- microLamports: 50000 // Example fee, adjust as needed
116
- }));
117
- // Add compute unit limit if necessary, e.g., for token transfers
118
- transaction.add(ComputeBudgetProgram.setComputeUnitLimit({
119
- units: tokenAddress ? 200000 : 50000 // Higher limit for token ops
120
- }));
121
- if (tokenAddress) {
122
- const mint = new PublicKey(tokenAddress);
123
- // Use connection helpers for these reads
124
- const senderATA = await getAssociatedTokenAddress(mint, senderKeypair.publicKey);
125
- const recipientATA = await getAssociatedTokenAddress(mint, recipientPubkey);
126
- // Check if recipient ATA exists, if not, add instruction to create it
127
- const recipientATAInfo = await connection.getAccountInfo(recipientATA);
128
- if (!recipientATAInfo) {
129
- // This part needs @solana/spl-token's createAssociatedTokenAccountInstruction
130
- // Import: import { createAssociatedTokenAccountInstruction } from '@solana/spl-token';
131
- // transaction.add(
132
- // createAssociatedTokenAccountInstruction(
133
- // senderKeypair.publicKey, // Payer
134
- // recipientATA,
135
- // recipientPubkey,
136
- // mint
137
- // )
138
- // );
139
- console.warn("Recipient Associated Token Account does not exist. Auto-creation commented out. Ensure recipient has the ATA.");
140
- // For now, we'll proceed assuming it exists or will be created elsewhere.
141
- // Production code should handle this creation properly.
142
- }
143
- transaction.add(createTransferInstruction(senderATA, recipientATA, senderKeypair.publicKey, Number(amount) // SPL transfer amount expects number
144
- ));
145
- }
146
- else {
147
- // SOL transfer
148
- transaction.add(SystemProgram.transfer({
149
- fromPubkey: senderKeypair.publicKey,
150
- toPubkey: recipientPubkey,
151
- lamports: Number(amount) // SystemProgram.transfer expects number
152
- }));
153
- }
154
- // Get blockhash manually
155
- const { blockhash, lastValidBlockHeight } = await sendJsonRpc(rpc, 'getLatestBlockhash', [{ 'commitment': 'processed' }]);
156
- transaction.recentBlockhash = blockhash;
157
- transaction.feePayer = senderKeypair.publicKey;
158
- transaction.sign(senderKeypair);
159
- const rawTx = transaction.serialize();
160
- const base64Tx = Buffer.from(rawTx).toString('base64');
161
- // Send transaction manually via RPC
162
- const signature = await sendJsonRpc(rpc, 'sendTransaction', [
163
- base64Tx,
164
- {
165
- encoding: 'base64',
166
- skipPreflight: false, // Usually false
167
- preflightCommitment: 'processed',
168
- maxRetries: 2
169
- }
170
- ]);
171
- // Optionally confirm transaction if not in fastMode
172
- if (!fastMode) {
173
- console.log('Waiting for Solana confirmation (up to 30s)... Signature:', signature);
174
- try {
175
- // Ensure blockhash is defined before confirming
176
- if (!transaction.recentBlockhash) {
177
- throw new Error("Transaction recentBlockhash is missing, cannot confirm.");
178
- }
179
- await connection.confirmTransaction({
180
- signature,
181
- blockhash: transaction.recentBlockhash, // Now confirmed non-undefined
182
- lastValidBlockHeight // Use the height we got
183
- }, 'processed'); // or 'confirmed'/'finalized'
184
- console.log('Solana transaction confirmed!');
185
- }
186
- catch (confirmError) {
187
- console.error(`Solana confirmation failed for ${signature}:`, confirmError);
188
- // Don't necessarily throw here, tx might still succeed eventually
189
- // Consider returning signature but warning about confirmation failure
190
- }
191
- }
192
- return signature;
193
- }
194
- catch (error) {
195
- console.error('Detailed SOL error:', error);
196
- // Try to provide more specific error info if possible
197
- if (error instanceof Error && error.message.includes('AccountNotFound')) {
198
- throw new Error(`Solana transaction failed: Source token account might not exist or have funds. ${error.message}`);
199
- }
200
- if (error instanceof Error && error.message.includes('Invalid private key')) {
201
- throw new Error(`Solana transaction failed: Invalid private key provided. ${error.message}`);
202
- }
203
- throw new Error(`Solana transaction failed: ${error instanceof Error ? error.message : String(error)}`);
204
- }
205
- }
206
- }
207
87
  class ApiNow {
208
88
  constructor() {
209
89
  this.handlers = {
210
90
  eth: new EthereumHandler(),
211
- sol: new SolanaHandler(),
212
- base: new EthereumHandler() // Base uses Ethereum handler
91
+ base: new EthereumHandler()
213
92
  };
214
93
  }
215
- // Use helper function
216
94
  async info(endpoint) {
217
95
  if (!endpoint || typeof endpoint !== 'string') {
218
96
  throw new Error('Invalid endpoint URL');
@@ -225,10 +103,7 @@ class ApiNow {
225
103
  throw new Error(`Could not get endpoint info: ${error instanceof Error ? error.message : String(error)}`);
226
104
  }
227
105
  }
228
- // Updated to accept optional rpcUrl
229
- async buy(walletAddress, amount, userWalletPrivateKey, chain, // Chain is now required to choose handler
230
- rpcUrl, // Optional RPC URL
231
- tokenAddress, fastMode) {
106
+ async buy(walletAddress, amount, userWalletPrivateKey, chain, rpcUrl, tokenAddress, fastMode) {
232
107
  const handler = this.handlers[chain];
233
108
  if (!handler) {
234
109
  throw new Error(`Unsupported chain: ${chain}`);
@@ -236,10 +111,8 @@ class ApiNow {
236
111
  if (amount <= 0n) {
237
112
  throw new Error('Amount must be positive.');
238
113
  }
239
- // Pass rpcUrl to the handler
240
- return handler.buy(walletAddress, amount, userWalletPrivateKey, rpcUrl, tokenAddress, fastMode);
114
+ return handler.buy(walletAddress, amount, userWalletPrivateKey, rpcUrl, tokenAddress);
241
115
  }
242
- // Use helper function
243
116
  async txResponse(endpoint, txHash, opts = {}) {
244
117
  if (!endpoint || typeof endpoint !== 'string') {
245
118
  throw new Error('Invalid endpoint URL');
@@ -248,12 +121,11 @@ class ApiNow {
248
121
  throw new Error('Invalid transaction hash');
249
122
  }
250
123
  const url = new URL(endpoint);
251
- // Append txHash respecting existing query params
252
124
  url.searchParams.append('txHash', txHash);
253
125
  try {
254
126
  return await fetchJson(url.toString(), {
255
- method: opts.method || 'GET', // Default to GET if not specified
256
- headers: { 'Content-Type': 'application/json' }, // Assume JSON body if data exists
127
+ method: opts.method || 'GET',
128
+ headers: { 'Content-Type': 'application/json' },
257
129
  body: opts.data ? JSON.stringify(opts.data) : undefined
258
130
  });
259
131
  }
@@ -262,21 +134,16 @@ class ApiNow {
262
134
  throw new Error(`Could not get transaction response: ${error instanceof Error ? error.message : String(error)}`);
263
135
  }
264
136
  }
265
- // Updated to accept optional rpcUrl
266
- async infoBuyResponse(endpoint, userWalletPrivateKey, rpcUrl, // Optional RPC URL
267
- opts = {}) {
137
+ async infoBuyResponse(endpoint, userWalletPrivateKey, rpcUrl, opts = {}) {
268
138
  console.log(`Starting infoBuyResponse for endpoint: ${endpoint}`);
269
- // 1. Get Info
270
139
  const info = await this.info(endpoint);
271
140
  console.log("Received info:", info);
272
141
  const { requiredAmount, walletAddress, chain, tokenAddress } = info;
273
142
  if (!chain || !this.handlers[chain]) {
274
143
  throw new Error(`Unsupported chain specified by endpoint: ${chain}`);
275
144
  }
276
- // Convert required amount string (assuming decimals handled by endpoint info) to bigint
277
145
  let amountBigInt;
278
146
  try {
279
- // Assume requiredAmount is in native smallest units (wei, lamports)
280
147
  amountBigInt = BigInt(requiredAmount);
281
148
  if (amountBigInt <= 0n) {
282
149
  throw new Error('Required amount must be positive.');
@@ -286,16 +153,13 @@ class ApiNow {
286
153
  throw new Error(`Invalid requiredAmount format: ${requiredAmount}`);
287
154
  }
288
155
  console.log(`Attempting payment: Chain=${chain}, To=${walletAddress}, Amount=${amountBigInt.toString()}, Token=${tokenAddress || 'Native'}`);
289
- // 2. Perform Buy (Payment)
290
156
  const txHash = await this.buy(walletAddress, amountBigInt, userWalletPrivateKey, chain, rpcUrl, tokenAddress, opts.fastMode);
291
157
  console.log(`Transaction sent: ${txHash}`);
292
- // 3. Get Tx Response
293
- // Add a small delay before fetching the response, especially for non-fast mode
294
158
  if (!opts.fastMode) {
295
- await new Promise(resolve => setTimeout(resolve, 3000)); // 3-second delay
159
+ await new Promise(resolve => setTimeout(resolve, 3000));
296
160
  }
297
161
  else {
298
- await new Promise(resolve => setTimeout(resolve, 500)); // Shorter delay for fast mode
162
+ await new Promise(resolve => setTimeout(resolve, 500));
299
163
  }
300
164
  console.log(`Fetching response for tx: ${txHash}`);
301
165
  return this.txResponse(endpoint, txHash, opts);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apinow-sdk",
3
- "version": "0.9.1",
3
+ "version": "0.11.1",
4
4
  "description": "ApiNow SDK · The endpoint vending machine",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -21,9 +21,6 @@
21
21
  "author": "ApiNow.fun",
22
22
  "license": "MIT",
23
23
  "dependencies": {
24
- "@solana/spl-token": "^0.4.12",
25
- "@solana/web3.js": "^1.98.0",
26
- "bs58": "^6.0.0",
27
24
  "ethers": "^6.13.5"
28
25
  },
29
26
  "devDependencies": {