JavaScript Integration Examples¶
This section provides examples of how to integrate with the API using JavaScript.
Authentication¶
// api-client.js
const crypto = require('crypto');
const axios = require('axios');
class ApiClient {
constructor(baseUrl, accessKey, secretKey) {
this.baseUrl = baseUrl.replace(/\/$/, '');
this.accessKey = accessKey;
this.secretKey = secretKey;
}
getTimestamp() {
return Date.now().toString();
}
generateSignature(path, timestamp, body = '') {
const message = `${this.accessKey}${path}${timestamp}${body}`;
return crypto
.createHmac('sha256', this.secretKey)
.update(message)
.digest('hex');
}
async request(method, endpoint, params = {}, data = null) {
const path = `/api/v1${endpoint}`;
const url = `${this.baseUrl}${path}`;
const timestamp = this.getTimestamp();
const headers = {
'X-Access-Key': this.accessKey,
'X-Timestamp': timestamp,
};
let body = '';
if (['POST', 'PUT', 'PATCH'].includes(method.toUpperCase()) && data !== null) {
body = JSON.stringify(data);
headers['Content-Type'] = 'application/json';
}
headers['X-Signature'] = this.generateSignature(path, timestamp, body);
try {
const response = await axios({
method,
url,
params: method.toUpperCase() === 'GET' ? params : undefined,
data: body || undefined,
headers,
});
return response.data;
} catch (error) {
if (error.response) {
throw new Error(`API Error: ${JSON.stringify(error.response.data)}`);
}
throw error;
}
}
async get(endpoint, params = {}) {
return this.request('GET', endpoint, params);
}
async post(endpoint, data = {}) {
return this.request('POST', endpoint, {}, data);
}
}
module.exports = ApiClient;
Usage Examples¶
Check Server Status¶
// status.js
const axios = require('axios');
const ApiClient = require('./api-client');
async function main() {
try {
// Status endpoint doesn't require authentication
const statusResponse = await axios.get('https://api.001k.world/api/v1/status');
console.log(`Server timestamp: ${statusResponse.data.timestamp}`);
// For authenticated endpoints
const api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');
// ... other examples
} catch (error) {
console.error('Error:', error.message);
}
}
main();
Get Account Balances¶
// balances.js
const ApiClient = require('./api-client');
async function getBalances() {
try {
const api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');
const balances = await api.get('/balance');
balances.forEach(balance => {
console.log(`${balance.currency}: ${balance.available} (available), ${balance.frozen} (frozen)`);
});
} catch (error) {
console.error('Error:', error.message);
}
}
getBalances();
Generate Deposit Address¶
// generate-deposit-address.js
const ApiClient = require('./api-client');
async function generateDepositAddress() {
try {
const api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');
const response = await api.post('/deposit/generate_address', {
currency: 'BTC',
method: 'btc_native',
callback_url: 'https://your-server.com/callbacks/deposits',
custom_id: 'my-deposit-address-123'
});
console.log(`Deposit address: ${response.address}`);
if (response.tag) {
console.log(`Tag: ${response.tag}`);
}
} catch (error) {
console.error('Error:', error.message);
}
}
generateDepositAddress();
Create Withdrawal¶
// create-withdrawal.js
const ApiClient = require('./api-client');
async function createWithdrawal() {
try {
const api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');
const response = await api.post('/withdraw', {
currency: 'BTC',
method: 'btc_native',
amount: '0.01000000',
address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh',
callback_url: 'https://your-server.com/callbacks/withdrawals',
custom_id: 'my-withdrawal-123'
});
console.log(`Withdrawal created: ${response.code}`);
console.log(`Status: ${response.status}`);
} catch (error) {
console.error('Error:', error.message);
}
}
createWithdrawal();
Create Swap¶
// create-swap.js
const ApiClient = require('./api-client');
async function createSwap() {
try {
const api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');
// First, get available swap directions
const directions = await api.get('/swap-directions');
directions.forEach(direction => {
console.log(`${direction.code}: ${direction.spend_currency} -> ${direction.receive_currency} (rate: ${direction.rate})`);
});
// Create a swap
const response = await api.post('/swap/open', {
direction: 'BTC-USDT',
spend_amount: '0.01000000',
callback_url: 'https://your-server.com/callbacks/swaps',
custom_id: 'my-swap-123'
});
console.log(`Swap created: ${response.code}`);
console.log(`Spend: ${response.spend_amount} ${response.spend_currency}`);
console.log(`Receive: ${response.receive_amount} ${response.receive_currency}`);
console.log(`Status: ${response.status}`);
} catch (error) {
console.error('Error:', error.message);
}
}
createSwap();
Create Internal Transfer¶
// create-transfer.js
const ApiClient = require('./api-client');
async function createTransfer() {
try {
const api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');
const response = await api.post('/internal-transfer', {
currency_code: 'BTC',
amount: '0.01000000',
recipient: 'user123',
callback_url: 'https://your-server.com/callbacks/transfers',
custom_id: 'my-transfer-123',
note: 'Payment for services'
});
console.log(`Transfer created: ${response.code}`);
console.log(`Status: ${response.status}`);
} catch (error) {
console.error('Error:', error.message);
}
}
createTransfer();
Create Limit Order¶
// create-limit-order.js
const ApiClient = require('./api-client');
async function createLimitOrder() {
try {
const api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');
// First, get available trading pairs
const pairs = await api.get('/limit-pairs');
pairs.forEach(pair => {
console.log(`${pair.symbol}: ${pair.current_price} (fee: ${pair.fee_percent}%)`);
});
// Create a limit order
const response = await api.post('/limit-order', {
pair: 'BTCUSDT',
side: 'buy',
receive_amount: '0.01000000',
limit_price: '29000.00',
callback_url: 'https://your-server.com/callbacks/orders',
custom_id: 'my-order-123'
});
console.log(`Order created: ${response.code}`);
console.log(`Status: ${response.status}`);
console.log(`Base amount: ${response.base_amount}`);
console.log(`Quote amount: ${response.quote_amount}`);
console.log(`Filled base amount: ${response.filled_base_amount}`);
console.log(`Filled quote amount: ${response.filled_quote_amount}`);
console.log(`Fee currency: ${response.fee_currency}`);
console.log(`Filled fee amount: ${response.filled_fee_amount}`);
console.log(`Created at: ${response.created_at}`);
console.log(`Updated at: ${response.updated_at}`);
console.log(`Done at: ${response.done_at || 'N/A'}`);
} catch (error) {
console.error('Error:', error.message);
}
}
createLimitOrder();
Create AML Check¶
// create-aml-check.js
const ApiClient = require('./api-client');
async function createAmlCheck() {
try {
const api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');
// First, get available plans and tokens
const plans = await api.get('/aml/plan');
const tokens = await api.get('/aml/token');
plans.forEach(plan => {
console.log(`Plan: ${plan.code} - ${plan.name} (price: ${plan.price} ${plan.currency})`);
});
tokens.forEach(token => {
console.log(`Token: ${token.symbol} on ${token.network} (ID: ${token.id})`);
});
// Create an AML check
const response = await api.post('/aml/check', {
direction: 'withdrawal',
token: 1, // Bitcoin
address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh',
callback_url: 'https://your-server.com/callbacks/aml',
custom_id: 'my-aml-check-123'
});
console.log(`AML check created: ${response.code}`);
console.log(`Status: ${response.status}`);
console.log(`Direction: ${response.direction}`);
console.log(`Token: ${response.token}`);
console.log(`Address: ${response.address}`);
console.log(`Transaction: ${response.transaction || 'N/A'}`);
console.log(`Created at: ${response.created_at}`);
console.log(`Updated at: ${response.updated_at}`);
if (response.report) {
console.log(`Report status: ${response.report.status}`);
console.log(`Risk score: ${response.report.riskscore}`);
console.log(`Alert grade: ${response.report.alert_grade}`);
}
} catch (error) {
console.error('Error:', error.message);
}
}
createAmlCheck();
Callback Handling¶
When the status of an operation changes, the API will send a callback to the URL provided in the callback_url parameter. Here's an example of how to handle these callbacks in an Express application:
Important Note: You may not receive callbacks for every intermediate status change or field update if changes occur very rapidly. When operations transition through multiple states quickly, intermediate callbacks may be skipped. However, you will always receive callbacks for the final states of operations. Design your callback handling to be idempotent and not dependent on receiving every single state transition.
// callback-server.js
const express = require('express');
const ApiClient = require('./api-client');
const bodyParser = require('body-parser');
const app = express();
const PORT = process.env.PORT || 3000;
// Your API client
const api = new ApiClient('https://api.001k.world', 'your_access_key', 'your_secret_key');
// IP whitelist for callback security
const ALLOWED_IPS = ['192.168.1.1', '10.0.0.1']; // Replace with actual IPs provided by support
// Verify IP middleware
function verifyIp(req, res, next) {
const clientIp = req.ip || req.connection.remoteAddress;
if (!ALLOWED_IPS.includes(clientIp)) {
return res.status(403).json({ error: 'Unauthorized IP' });
}
next();
}
// Verify data by making an API request
async function verifyData(endpoint, code) {
try {
// Make an authenticated API request to verify the status
const response = await api.get(`${endpoint}/${code}`);
return response;
} catch (error) {
console.error(`Error verifying data: ${error.message}`);
return null;
}
}
// Parse JSON bodies
app.use(bodyParser.json());
// Deposit callbacks
app.post('/callbacks/deposits', verifyIp, async (req, res) => {
const { code, status, custom_id } = req.body;
console.log(`Deposit callback received: ${code} (${custom_id}) - Status: ${status}`);
// Verify the data by making an API request
const verifiedData = await verifyData('/deposit', code);
if (verifiedData && verifiedData.status === status) {
// Process the callback (update database, send notifications, etc.)
console.log("Deposit status verified");
} else {
console.log("Warning: Callback data verification failed!");
}
res.json({ success: true });
});
// Withdrawal callbacks
app.post('/callbacks/withdrawals', verifyIp, async (req, res) => {
const { code, status, custom_id } = req.body;
console.log(`Withdrawal callback received: ${code} (${custom_id}) - Status: ${status}`);
// Verify the data by making an API request
const verifiedData = await verifyData('/withdraw', code);
if (verifiedData && verifiedData.status === status) {
// Process the callback
console.log("Withdrawal status verified");
} else {
console.log("Warning: Callback data verification failed!");
}
res.json({ success: true });
});
// Swap callbacks
app.post('/callbacks/swaps', verifyIp, async (req, res) => {
const { code, status, custom_id } = req.body;
console.log(`Swap callback received: ${code} (${custom_id}) - Status: ${status}`);
// Verify the data by making an API request
const verifiedData = await verifyData('/swap', code);
if (verifiedData && verifiedData.status === status) {
// Process the callback
console.log("Swap status verified");
} else {
console.log("Warning: Callback data verification failed!");
}
res.json({ success: true });
});
// Transfer callbacks
app.post('/callbacks/transfers', verifyIp, async (req, res) => {
const { code, status, custom_id } = req.body;
console.log(`Transfer callback received: ${code} (${custom_id}) - Status: ${status}`);
// Verify the data by making an API request
const verifiedData = await verifyData('/internal-transfer', code);
if (verifiedData && verifiedData.status === status) {
// Process the callback
console.log("Transfer status verified");
} else {
console.log("Warning: Callback data verification failed!");
}
res.json({ success: true });
});
// Order callbacks
app.post('/callbacks/orders', verifyIp, async (req, res) => {
const { code, status, custom_id } = req.body;
console.log(`Order callback received: ${code} (${custom_id}) - Status: ${status}`);
// Verify the data by making an API request
const verifiedData = await verifyData('/limit-order', code);
if (verifiedData && verifiedData.status === status) {
// Process the callback
console.log("Order status verified");
} else {
console.log("Warning: Callback data verification failed!");
}
res.json({ success: true });
});
// AML check callbacks
app.post('/callbacks/aml', verifyIp, async (req, res) => {
const { code, status, custom_id } = req.body;
console.log(`AML check callback received: ${code} (${custom_id}) - Status: ${status}`);
// Verify the data by making an API request
const verifiedData = await verifyData('/aml/check', code);
if (verifiedData && verifiedData.status === status) {
// Process the callback
console.log("AML check status verified");
} else {
console.log("Warning: Callback data verification failed!");
}
res.json({ success: true });
});
app.listen(PORT, () => {
console.log(`Callback server running on port ${PORT}`);
});