okex-api
Version:
A modern, asynchronous, and easy-to-use [Okx API](https://www.okx.com/docs-v5) wrapper for Node.js/bun/Web Browser/Cloudflare workers.
59 lines (58 loc) • 2.22 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.APICredentials = void 0;
class Signer {
cryptoKey;
unixTime;
constructor(cryptoKey, unixTime = false) {
this.cryptoKey = cryptoKey;
this.unixTime = unixTime;
}
async sign(path, params = '', method = 'GET') {
const timestamp = this.unixTime ? Date.now() / 1000 : new Date().toISOString();
const message = `${timestamp}${method}${path}${params}`;
const sign = await crypto.subtle.sign('HMAC', this.cryptoKey, new TextEncoder().encode(message));
return { timestamp, sign: btoa(String.fromCharCode(...new Uint8Array(sign))) };
}
static async create(secret, unixTime = false) {
const cryptoKey = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
return new Signer(cryptoKey, unixTime);
}
}
class APICredentials {
apiKey;
signer;
passphrase;
constructor(apiKey, signer, passphrase) {
this.apiKey = apiKey;
this.signer = signer;
this.passphrase = passphrase;
}
async getHttpHeaders(method, path, params = '') {
const { timestamp, sign } = await this.signer.sign(path, params, method);
return {
'OK-ACCESS-KEY': this.apiKey,
'OK-ACCESS-TIMESTAMP': timestamp,
'OK-ACCESS-SIGN': sign,
'OK-ACCESS-PASSPHRASE': this.passphrase,
...method === 'POST' && { 'Content-Type': 'application/json' }
};
}
async getWsLoginMessage() {
const { timestamp, sign } = await this.signer.sign('/users/self/verify');
return JSON.stringify({
op: 'login',
args: [{
apiKey: this.apiKey,
passphrase: this.passphrase,
timestamp,
sign
}]
});
}
static async create(apiKey, apiSecret, passphrase, unixTime = false) {
if (apiKey && apiSecret && passphrase)
return new APICredentials(apiKey, await Signer.create(apiSecret, unixTime), passphrase);
}
}
exports.APICredentials = APICredentials;