apinow-sdk 0.1.0

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 ADDED
@@ -0,0 +1,105 @@
1
+ # ApiNow SDK
2
+
3
+ The endpoint vending machine - SDK for interacting with ApiNow endpoints.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install apinow-sdk
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```ts
14
+ import apiNow from 'apinow-sdk';
15
+
16
+ // One-shot purchase and response
17
+ const response = await apiNow.infoBuyResponse(
18
+ 'https://apinow.fun/api/endpoints/my-endpoint',
19
+ '0x123...private-key',
20
+ 'https://eth-mainnet.g.alchemy.com/v2/YOUR-API-KEY'
21
+ );
22
+ ```
23
+
24
+ ## API Reference
25
+
26
+ ### info(endpoint)
27
+ Fetches endpoint metadata like required ETH amount and wallet address.
28
+
29
+ ```ts
30
+ const info = await apiNow.info('https://apinow.fun/api/endpoints/my-endpoint');
31
+ // Returns: {
32
+ // requiredEth: "0.1",
33
+ // walletAddress: "0x123...",
34
+ // httpMethod: "POST"
35
+ // }
36
+ ```
37
+
38
+ ### buy(walletAddress, amount, privateKey, rpcUrl)
39
+ Sends an ETH transaction to purchase endpoint access.
40
+
41
+ ```ts
42
+ const txHash = await apiNow.buy(
43
+ "0x123...wallet", // Destination wallet
44
+ ethers.parseEther("0.1"), // Amount in ETH
45
+ "0x456...private-key", // Your private key
46
+ "https://eth-mainnet.g.alchemy.com/v2/YOUR-API-KEY" // RPC URL
47
+ );
48
+ ```
49
+
50
+ ### txResponse(endpoint, txHash, options?)
51
+ Gets the API response using your transaction hash.
52
+
53
+ ```ts
54
+ const response = await apiNow.txResponse(
55
+ "https://apinow.fun/api/endpoints/my-endpoint",
56
+ "0x789...txhash",
57
+ {
58
+ method: "POST", // Optional, defaults to GET
59
+ data: { foo: "bar" } // Optional request body
60
+ }
61
+ );
62
+ ```
63
+
64
+ ### infoBuyResponse(endpoint, privateKey, rpcUrl, options?)
65
+ Combines all steps: fetches info, sends payment, and gets response.
66
+
67
+ ```ts
68
+ // Complete example with all parameters
69
+ const response = await apiNow.infoBuyResponse(
70
+ "https://apinow.fun/api/endpoints/my-endpoint",
71
+ "0x123...private-key",
72
+ "https://eth-mainnet.g.alchemy.com/v2/YOUR-API-KEY",
73
+ {
74
+ method: "POST", // Optional, defaults to endpoint's httpMethod
75
+ data: { // Optional request body
76
+ query: "example",
77
+ limit: 10
78
+ }
79
+ }
80
+ );
81
+ ```
82
+
83
+ ## License
84
+
85
+ MIT
86
+
87
+ Copyright (c) 2024 Your Name
88
+
89
+ Permission is hereby granted, free of charge, to any person obtaining a copy
90
+ of this software and associated documentation files (the "Software"), to deal
91
+ in the Software without restriction, including without limitation the rights
92
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
93
+ copies of the Software, and to permit persons to whom the Software is
94
+ furnished to do so, subject to the following conditions:
95
+
96
+ The above copyright notice and permission notice shall be included in all
97
+ copies or substantial portions of the Software.
98
+
99
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
100
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
101
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
102
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
103
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
104
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
105
+ SOFTWARE.
@@ -0,0 +1,17 @@
1
+ interface TxResponseOptions {
2
+ method?: string;
3
+ data?: any;
4
+ }
5
+ interface InfoResponse {
6
+ requiredEth: string;
7
+ walletAddress: string;
8
+ httpMethod: string;
9
+ }
10
+ declare class ApiNow {
11
+ info(endpoint: string): Promise<InfoResponse>;
12
+ buy(walletAddress: string, amount: bigint, pkey: string, rpc: string): Promise<string>;
13
+ txResponse(endpoint: string, txHash: string, opts?: TxResponseOptions): Promise<any>;
14
+ infoBuyResponse(endpoint: string, pkey: string, rpc: string, opts?: TxResponseOptions): Promise<any>;
15
+ }
16
+ declare const _default: ApiNow;
17
+ export default _default;
package/dist/index.js ADDED
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const ethers_1 = require("ethers");
7
+ const node_fetch_1 = __importDefault(require("node-fetch"));
8
+ class ApiNow {
9
+ async info(endpoint) {
10
+ if (!endpoint.startsWith('https://apinow.fun/api/endpoints/')) {
11
+ throw new Error('Invalid endpoint URL format');
12
+ }
13
+ console.log(`Fetching info from ${endpoint}`);
14
+ const response = await (0, node_fetch_1.default)(`${endpoint}`);
15
+ if (!response.ok) {
16
+ throw new Error(`Failed to fetch endpoint info: ${response.status}`);
17
+ }
18
+ return response.json();
19
+ }
20
+ async buy(walletAddress, amount, pkey, rpc) {
21
+ if (!rpc || typeof rpc !== 'string') {
22
+ throw new Error('Invalid RPC URL');
23
+ }
24
+ if (!walletAddress || !ethers_1.ethers.isAddress(walletAddress)) {
25
+ throw new Error('Invalid wallet address');
26
+ }
27
+ const provider = new ethers_1.ethers.JsonRpcProvider(rpc);
28
+ const wallet = new ethers_1.ethers.Wallet(pkey, provider);
29
+ try {
30
+ await provider.getNetwork();
31
+ const balance = await provider.getBalance(wallet.address);
32
+ console.log('Sender balance:', ethers_1.ethers.formatEther(balance), 'ETH');
33
+ const nonce = await provider.getTransactionCount(wallet.address, 'latest');
34
+ const gasLimit = wallet.address.toLowerCase() === walletAddress.toLowerCase()
35
+ ? 30000
36
+ : 21000;
37
+ const tx = await wallet.sendTransaction({
38
+ to: walletAddress,
39
+ value: amount,
40
+ type: 2,
41
+ maxFeePerGas: ethers_1.ethers.parseUnits('0.1', 'gwei'),
42
+ maxPriorityFeePerGas: ethers_1.ethers.parseUnits('0.1', 'gwei'),
43
+ gasLimit,
44
+ nonce
45
+ });
46
+ console.log('tx:', JSON.stringify(tx));
47
+ console.log('Transaction sent:', tx.hash);
48
+ return tx.hash;
49
+ }
50
+ catch (error) {
51
+ console.error('Detailed error:', error);
52
+ throw new Error(`Transaction failed: ${error instanceof Error ? error.message : String(error)}`);
53
+ }
54
+ }
55
+ async txResponse(endpoint, txHash, opts = {}) {
56
+ if (!endpoint.startsWith('https://apinow.fun/api/endpoints/')) {
57
+ throw new Error('Invalid endpoint URL format');
58
+ }
59
+ console.log('txResponse:', { endpoint, txHash, ...opts });
60
+ const options = {
61
+ method: opts.method || 'GET',
62
+ headers: {
63
+ 'x-transaction-hash': txHash,
64
+ ...(opts.data && { 'Content-Type': 'application/json' })
65
+ },
66
+ ...(opts.data && { body: JSON.stringify(opts.data) })
67
+ };
68
+ const response = await (0, node_fetch_1.default)(endpoint, options);
69
+ if (!response.ok) {
70
+ throw new Error(`API request failed: ${response.status}`);
71
+ }
72
+ return response.json();
73
+ }
74
+ async infoBuyResponse(endpoint, pkey, rpc, opts = {}) {
75
+ const info = await this.info(endpoint);
76
+ const amount = ethers_1.ethers.parseEther(info.requiredEth);
77
+ const txHash = await this.buy(info.walletAddress, amount, pkey, rpc);
78
+ console.log('infoBuyResponse:', { endpoint, txHash, ...opts });
79
+ const response = await this.txResponse(endpoint, txHash, {
80
+ method: opts.method || info.httpMethod,
81
+ data: opts.data
82
+ });
83
+ console.log('response:', response);
84
+ return response;
85
+ }
86
+ }
87
+ exports.default = new ApiNow();
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "apinow-sdk",
3
+ "version": "0.1.0",
4
+ "description": "ApiNow SDK · The endpoint vending machine",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "scripts": {
11
+ "build": "tsc",
12
+ "test": "jest",
13
+ "prepare": "npm run build"
14
+ },
15
+ "keywords": [
16
+ "api",
17
+ "ethereum",
18
+ "web3"
19
+ ],
20
+ "author": "Your Name",
21
+ "license": "MIT",
22
+ "dependencies": {
23
+ "ethers": "^6.13.5",
24
+ "node-fetch": "^3.3.2"
25
+ },
26
+ "devDependencies": {
27
+ "@types/jest": "^29.5.12",
28
+ "@types/node": "^20.11.24",
29
+ "jest": "^29.7.0",
30
+ "ts-jest": "^29.1.2",
31
+ "typescript": "^5.3.3"
32
+ }
33
+ }