From b2a340683684a5579d0d5dd67e6c1ec8c76419ee Mon Sep 17 00:00:00 2001 From: Mikhail Gladchenko Date: Tue, 19 Mar 2024 09:09:03 +0000 Subject: [PATCH 01/18] feat: added new method getExchangeContractWalletBalance --- package.json | 2 +- src/services/BlockchainService/index.ts | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 8d2b156..471d681 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.73", + "version": "0.20.74-rc0", "description": "Orion Protocol SDK", "main": "./lib/index.cjs", "module": "./lib/index.js", diff --git a/src/services/BlockchainService/index.ts b/src/services/BlockchainService/index.ts index 16d5e59..ceacbcb 100644 --- a/src/services/BlockchainService/index.ts +++ b/src/services/BlockchainService/index.ts @@ -114,6 +114,7 @@ class BlockchainService { this.getRedeemOrderBySecretHash = this.getRedeemOrderBySecretHash.bind(this); this.claimOrder = this.claimOrder.bind(this); this.getGasLimits = this.getGasLimits.bind(this); + this.getExchangeContractWalletBalance = this.getExchangeContractWalletBalance.bind(this); } get basicAuthHeaders() { @@ -495,6 +496,12 @@ class BlockchainService { z.record(z.number()), { headers: this.basicAuthHeaders } ); + + getExchangeContractWalletBalance = (exchangeContractAddress: string) => fetchWithValidation( + `${this.apiUrl}/api/broker/getWalletBalance/${exchangeContractAddress}`, + z.record(z.string()), + { headers: this.basicAuthHeaders } + ); } export * as schemas from './schemas/index.js'; From 1e45222a43e3dd400a44e690c6c278fb18e1da66 Mon Sep 17 00:00:00 2001 From: Mikhail Gladchenko Date: Thu, 28 Mar 2024 12:04:29 +0000 Subject: [PATCH 02/18] Update package.json --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 690319a..cb7a74f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.74-rc0", + "version": "0.20.74-rc1", "description": "Orion Protocol SDK", "main": "./lib/index.cjs", "module": "./lib/index.js", From d17fed1e9e0005b6512427b05faf4c8f64c0def8 Mon Sep 17 00:00:00 2001 From: Mikhail Gladchenko Date: Thu, 28 Mar 2024 12:09:01 +0000 Subject: [PATCH 03/18] Update package.json --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index cb7a74f..ee8c258 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.74-rc1", + "version": "0.20.78", "description": "Orion Protocol SDK", "main": "./lib/index.cjs", "module": "./lib/index.js", From b0873ab04c7b570426a97d5d9141fea2434b8018 Mon Sep 17 00:00:00 2001 From: KS Date: Fri, 29 Mar 2024 07:26:15 +0300 Subject: [PATCH 04/18] added PMM-sample.md , fixed order schema --- PMM-sample.md | 288 +++++++++++++++++++++++++++++++ package.json | 2 +- src/Unit/Pmm/index.ts | 2 +- src/Unit/Pmm/schemas/order.ts | 2 +- src/services/Aggregator/index.ts | 3 +- 5 files changed, 292 insertions(+), 5 deletions(-) create mode 100644 PMM-sample.md diff --git a/PMM-sample.md b/PMM-sample.md new file mode 100644 index 0000000..ad1eb45 --- /dev/null +++ b/PMM-sample.md @@ -0,0 +1,288 @@ + + +
+ Orion Protocol SDK logo +

PMM example

+
+ +## Overview + +This is special example which shows how to use PMM liquidity without using SDK, only using few libraries + +```ts +import {ethers, Wallet} from "ethers"; +import {z} from "zod"; +import hmacSHA256 from "crypto-js/hmac-sha256"; +import Hex from "crypto-js/enc-hex"; + +/////////////////////////////// +/////////////////////////////// +const pmmOrderQuotationSchema = z.object({ + info: z.string().default(''), + makerAsset: z.string().default(''), + takerAsset: z.string().default(''), + maker: z.string().default(''), + allowedSender: z.string().default(''), + makingAmount: z.string().default(''), + takingAmount: z.string().default(''), +}); + +const pmmOrderSchema = z.object({ + order: pmmOrderQuotationSchema.default({}), + signature: z.string().default(''), + success: z.boolean().default(false), + error: z.string().default(''), +}); + +const orionRFQContractABI = + [ + { + "inputs": [ + { + "components": [ + { + "internalType": "uint256", + "name": "info", + "type": "uint256" + }, + { + "internalType": "address", + "name": "makerAsset", + "type": "address" + }, + { + "internalType": "address", + "name": "takerAsset", + "type": "address" + }, + { + "internalType": "address", + "name": "maker", + "type": "address" + }, + { + "internalType": "address", + "name": "allowedSender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "makingAmount", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "takingAmount", + "type": "uint256" + } + ], + "internalType": "struct OrderRFQLib.OrderRFQ", + "name": "order", + "type": "tuple" + }, + { + "internalType": "bytes", + "name": "signature", + "type": "bytes" + }, + { + "internalType": "uint256", + "name": "flagsAndAmount", + "type": "uint256" + } + ], + "name": "fillOrderRFQ", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } + ]; + +function encode_utf8(s : string) { + return unescape(encodeURIComponent(s)); +} +function sign(message : string, key: string) { + return hmacSHA256( + encode_utf8(message), + encode_utf8(key) + ).toString(Hex); +} + +function generateHeaders(body : any, method : string, path : string, timestamp : number, apiKey : string, secretKey : string) { + const sortedBody = Object.keys(body) + .sort() + .map((key) => ( + `${key}=${body[key]}` + )).join('&'); + + const payload = timestamp + method.toUpperCase() + path + sortedBody; + + const signature = sign(payload, secretKey); + + const httpOptions = { + headers: { + 'API-KEY': apiKey, + 'ACCESS-TIMESTAMP': timestamp.toString(), + 'ACCESS-SIGN': signature + } + }; + return httpOptions; +} + +// +async function RFQOrder( + tokenFrom: string, + tokenTo: string, + fromTokenAmount: string, + apiKey: string, // + secretKey: string, + wallet: string +) : Promise> { + + // NB: replace with correct URL for networks + const apiUrl = 'https://testing.orion.xyz/bsc-testnet/backend' + // const apiUrl = 'https://trade.orion.xyz/bsc-mainnet/backend' + , path = '/rfq' + , url = `${apiUrl}/api/v1/integration/pmm`+path + , headers = { + 'Content-Type': 'application/json', + } + , data = { + "baseToken":tokenFrom, // USDT + "quoteToken":tokenTo, // ORN + "amount": fromTokenAmount, // 100 + "taker": wallet, + "feeBps": 0 + } + , method = 'POST' + , timestamp = Date.now() + , signatureHeaders = generateHeaders(data, method, path, timestamp, apiKey, secretKey) + , compiledHeaders = {...headers, ...signatureHeaders.headers, } + , body = JSON.stringify(data) + ; + + let res = pmmOrderSchema.parse({}); + + try { + const result = await fetch(url,{ + headers: compiledHeaders, + method, + body + }); + + // const data = await result.text(); + // console.log(data); + + const json = await result.json(); + console.log(json); + const parseResult = pmmOrderSchema.safeParse(json); + + if(!parseResult.success) { + // Try to parse error answer + const errorSchema = z.object({error: z.object({code: z.number(), reason: z.string()})}); + + const errorParseResult = errorSchema.safeParse(json); + + if(!errorParseResult.success) + throw Error(`Unrecognized answer from aggregator: ${json}`); + + throw Error(errorParseResult.data.error.reason); + } + + res.order = parseResult.data.order; + res.signature = parseResult.data.signature; + res.error = ''; + res.success = true; + } + catch(err) { + res.error = `${err}`; + } + return res; +} + + +(async() => { + const apiKey = '958153f1-b8b9-3ec4-84eb-2147429105d9'; + const secretKey = 'secretKey'; + + // BNB testnet tokens and router + const assetORN = '0xf223eca06261145b3287a0fefd8cfad371c7eb34'; + const assetUSDT = '0xcb2951e90d8dcf16e1fa84ac0c83f48906d6a744'; + const router = '0x89357522C0ed6E557D39dC75290859246077bdfC'; + + // BNB mainnet tokens and router + // const assetORN = '0xe4ca1f75eca6214393fce1c1b316c237664eaa8e'; + // const assetUSDT = '0x55d398326f99059ff775485246999027b3197955'; + // const router = '0xcb2D40EabC4f4c92Ee993Eb3D67f7717bE476E76'; + + const rfqOrder = await RFQOrder( + assetORN, // Spending asset + assetUSDT, // Receiving asset + '1000000000', // Amount in "satoshi" of spending asset + apiKey, + secretKey, + '0x61Eed69c0d112C690fD6f44bB621357B89fBE67F' // Can be any address, ignored for now + ); + + if(!rfqOrder.success) { + console.log(rfqOrder.error); + return; + } + + // ... here you can check order prices, etc. + console.log(rfqOrder); + + // Calldata according to provided rfqOrder + const contractInterface = new ethers.Interface(orionRFQContractABI); + const calldata = contractInterface.encodeFunctionData("fillOrderRFQ", [rfqOrder.order, rfqOrder.signature, 0]); + console.log('Calldata = ', calldata); + + // Call router with this data + // Replace with your private key + const yourWalletPrivateKey = '0xf1.......'; + + const tx = { + to: router, + data: calldata + } + + const provider = new ethers.JsonRpcProvider("https://data-seed-prebsc-1-s1.binance.org:8545/"); + const signer = new ethers.Wallet(yourWalletPrivateKey, provider); + console.log('Address = ', signer.address); + const transactionResponse = await signer.sendTransaction(tx); + console.log("Transaction hash:", transactionResponse.hash); + await transactionResponse.wait(); +})(); +``` + +RFQ order response example description (`rfqOrder` from example above): + +``` + { + quotation: { + info: '31545611720730315633520017429', + makerAsset: '0xcb2951e90d8dcf16e1fa84ac0c83f48906d6a744', + takerAsset: '0xf223eca06261145b3287a0fefd8cfad371c7eb34', + maker: '0x1ff516e5ce789085cff86d37fc27747df852a80a', + allowedSender: '0x0000000000000000000000000000000000000000', + makingAmount: '193596929', + takingAmount: '10000000000' + }, + signature: '0x8a2f9140a3c3a5734eda763a19c54c5ac909d8a03db37d9804af9115641fd1d35896b66ca6e136c1c89e0478fb7382a4b875d0f74529c1e83601f9383d310dde1b', + success: true, + error: '' + } +``` + + +* info - can be ignored +* makerAsset - your RECEIVING asset (what you expect to receive from contract, in this case USDT) +* takerAsset - your SPENDING asset (what you're giving to contract, in this case ORN) +* maker - can be ignored for now; +* allowedSender - can be ignored for now; +* makingAmount - how much you will RECEIVE (in receiving asset's precision) +* takingAmount - how much you should SPEND (in spending asset's precision) \ No newline at end of file diff --git a/package.json b/package.json index cec14eb..a307337 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.68-rc1", + "version": "0.20.79-rc1", "description": "Orion Protocol SDK", "main": "./lib/index.cjs", "module": "./lib/index.js", diff --git a/src/Unit/Pmm/index.ts b/src/Unit/Pmm/index.ts index cb41136..d4f1c57 100644 --- a/src/Unit/Pmm/index.ts +++ b/src/Unit/Pmm/index.ts @@ -79,6 +79,6 @@ export default class Pmm { const contract = new ethers.Contract(this.contractAddress, orionRFQContractABI, signer); // @ts-ignore - return contract.fillOrderRFQ(order.quotation, order.signature, BigInt(0)); + return contract.fillOrderRFQ(order.order, order.signature, BigInt(0)); } } \ No newline at end of file diff --git a/src/Unit/Pmm/schemas/order.ts b/src/Unit/Pmm/schemas/order.ts index 2651660..a9727e4 100644 --- a/src/Unit/Pmm/schemas/order.ts +++ b/src/Unit/Pmm/schemas/order.ts @@ -11,7 +11,7 @@ export const pmmOrderQuotationSchema = z.object({ }); export const pmmOrderSchema = z.object({ - quotation: pmmOrderQuotationSchema.default({}), + order: pmmOrderQuotationSchema.default({}), signature: z.string().default(''), success: z.boolean().default(false), error: z.string().default(''), diff --git a/src/services/Aggregator/index.ts b/src/services/Aggregator/index.ts index f04e4c5..1077a53 100644 --- a/src/services/Aggregator/index.ts +++ b/src/services/Aggregator/index.ts @@ -461,11 +461,10 @@ class Aggregator { throw Error(errorParseResult.data.error.reason); } - res.quotation = parseResult.data.quotation; + res.order = parseResult.data.order; res.signature = parseResult.data.signature; res.error = ''; res.success = true; - // return result; } catch(err) { res.error = `${err}`; From ddc8acde7ca6004da69e94cc3ffcabc9d0bb1137 Mon Sep 17 00:00:00 2001 From: KS Date: Fri, 29 Mar 2024 07:27:52 +0300 Subject: [PATCH 05/18] fixed PMM-sample.md --- PMM-sample.md | 30 +----------------------------- 1 file changed, 1 insertion(+), 29 deletions(-) diff --git a/PMM-sample.md b/PMM-sample.md index ad1eb45..344788e 100644 --- a/PMM-sample.md +++ b/PMM-sample.md @@ -257,32 +257,4 @@ async function RFQOrder( console.log("Transaction hash:", transactionResponse.hash); await transactionResponse.wait(); })(); -``` - -RFQ order response example description (`rfqOrder` from example above): - -``` - { - quotation: { - info: '31545611720730315633520017429', - makerAsset: '0xcb2951e90d8dcf16e1fa84ac0c83f48906d6a744', - takerAsset: '0xf223eca06261145b3287a0fefd8cfad371c7eb34', - maker: '0x1ff516e5ce789085cff86d37fc27747df852a80a', - allowedSender: '0x0000000000000000000000000000000000000000', - makingAmount: '193596929', - takingAmount: '10000000000' - }, - signature: '0x8a2f9140a3c3a5734eda763a19c54c5ac909d8a03db37d9804af9115641fd1d35896b66ca6e136c1c89e0478fb7382a4b875d0f74529c1e83601f9383d310dde1b', - success: true, - error: '' - } -``` - - -* info - can be ignored -* makerAsset - your RECEIVING asset (what you expect to receive from contract, in this case USDT) -* takerAsset - your SPENDING asset (what you're giving to contract, in this case ORN) -* maker - can be ignored for now; -* allowedSender - can be ignored for now; -* makingAmount - how much you will RECEIVE (in receiving asset's precision) -* takingAmount - how much you should SPEND (in spending asset's precision) \ No newline at end of file +``` \ No newline at end of file From 9e493457715ed3cc45d02202b05e2d0178fe4881 Mon Sep 17 00:00:00 2001 From: Kirill Litvinov Date: Tue, 2 Apr 2024 15:07:26 +0300 Subject: [PATCH 06/18] 0.20.79-rc1 --- package-lock.json | 4 +- package.json | 2 +- src/Orion/index.ts | 9 ++- src/Unit/index.ts | 8 ++- src/services/Aggregator/index.ts | 98 ++++++++++++++--------------- src/services/Aggregator/ws/index.ts | 26 +++++--- 6 files changed, 83 insertions(+), 64 deletions(-) diff --git a/package-lock.json b/package-lock.json index 9cc7fbb..f02c880 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.73", + "version": "0.20.79-rc1", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@orionprotocol/sdk", - "version": "0.20.73", + "version": "0.20.79-rc1", "hasInstallScript": true, "license": "ISC", "dependencies": { diff --git a/package.json b/package.json index ee8c258..48979e1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.78", + "version": "0.20.79-rc1", "description": "Orion Protocol SDK", "main": "./lib/index.cjs", "module": "./lib/index.js", diff --git a/src/Orion/index.ts b/src/Orion/index.ts index 7245c00..8ddf534 100644 --- a/src/Orion/index.ts +++ b/src/Orion/index.ts @@ -21,10 +21,15 @@ export default class Orion { // TODO: get tradable pairs (aggregated) + public logger: ((message: string) => void) | undefined; + constructor( envOrConfig: KnownEnv | EnvConfig = 'production', - overrides?: DeepPartial + overrides?: DeepPartial, + logger?: ((message: string) => void) | undefined ) { + this.logger = logger; + let config: EnvConfig; if (typeof envOrConfig === 'string') { const envConfig = envs[envOrConfig]; @@ -92,7 +97,7 @@ export default class Orion { // api: networkConfig.api, nodeJsonRpc: networkConfig.nodeJsonRpc, services: networkConfig.services, - }); + }, logger); return { ...acc, [chainId]: unit, diff --git a/src/Unit/index.ts b/src/Unit/index.ts index 85d7052..9b504cc 100644 --- a/src/Unit/index.ts +++ b/src/Unit/index.ts @@ -41,7 +41,10 @@ export default class Unit { public readonly contracts: Record; - constructor(config: KnownConfig | VerboseUnitConfig) { + public logger: ((message: string) => void) | undefined; + + constructor(config: KnownConfig | VerboseUnitConfig, logger?: ((message: string) => void) | undefined) { + this.logger = logger; if ('env' in config) { const staticConfig = envs[config.env]; if (!staticConfig) { @@ -118,7 +121,8 @@ export default class Unit { this.aggregator = new Aggregator( this.config.services.aggregator.http, this.config.services.aggregator.ws, - this.config.basicAuth + this.config.basicAuth, + logger, ); this.priceFeed = new PriceFeed( this.config.services.priceFeed.api, diff --git a/src/services/Aggregator/index.ts b/src/services/Aggregator/index.ts index f04e4c5..2cbc6c5 100644 --- a/src/services/Aggregator/index.ts +++ b/src/services/Aggregator/index.ts @@ -19,9 +19,9 @@ import httpToWS from '../../utils/httpToWS.js'; import { ethers } from 'ethers'; import orderSchema from './schemas/orderSchema.js'; import { fetchWithValidation } from 'simple-typed-fetch'; -import hmacSHA256 from "crypto-js/hmac-sha256"; -import Hex from "crypto-js/enc-hex"; -import {pmmOrderSchema} from "../../Unit/Pmm/schemas/order"; +import hmacSHA256 from 'crypto-js/hmac-sha256'; +import Hex from 'crypto-js/enc-hex'; +import { pmmOrderSchema } from '../../Unit/Pmm/schemas/order'; class Aggregator { private readonly apiUrl: string; @@ -34,11 +34,16 @@ class Aggregator { return this.apiUrl; } + public logger: ((message: string) => void) | undefined; + constructor( httpAPIUrl: string, wsAPIUrl: string, - basicAuth?: BasicAuthCredentials + basicAuth?: BasicAuthCredentials, + logger?: ((message: string) => void) | undefined ) { + this.logger = logger; + // const oaUrl = new URL(apiUrl); // const oaWsProtocol = oaUrl.protocol === 'https:' ? 'wss' : 'ws'; // const aggregatorWsUrl = `${oaWsProtocol}://${oaUrl.host + (oaUrl.pathname === '/' @@ -46,7 +51,7 @@ class Aggregator { // : oaUrl.pathname)}/v1`; this.apiUrl = httpAPIUrl; - this.ws = new AggregatorWS(httpToWS(wsAPIUrl)); + this.ws = new AggregatorWS(httpToWS(wsAPIUrl), undefined, logger); this.basicAuth = basicAuth; this.getHistoryAtomicSwaps = this.getHistoryAtomicSwaps.bind(this); @@ -373,24 +378,23 @@ class Aggregator { return fetchWithValidation(url.toString(), atomicSwapHistorySchema, { headers: this.basicAuthHeaders }); }; - - private encode_utf8(s : string) { + private encode_utf8(s: string) { return unescape(encodeURIComponent(s)); } - private sign(message : string, key: string) { + private sign(message: string, key: string) { return hmacSHA256( - this.encode_utf8(message), - this.encode_utf8(key) + this.encode_utf8(message), + this.encode_utf8(key) ).toString(Hex); } - private generateHeaders(body : any, method : string, path : string, timestamp : number, apiKey : string, secretKey : string) { + private generateHeaders(body: any, method: string, path: string, timestamp: number, apiKey: string, secretKey: string) { const sortedBody = Object.keys(body) - .sort() - .map((key) => ( - `${key}=${body[key]}` - )).join('&'); + .sort() + .map((key) => ( + `${key}=${body[key]}` + )).join('&'); const payload = timestamp + method.toUpperCase() + path + sortedBody; @@ -407,40 +411,38 @@ class Aggregator { } public async RFQOrder( - tokenFrom: string, - tokenTo: string, - fromTokenAmount: string, - apiKey: string, // - secretKey: string, - wallet: string - ) : Promise> { - + tokenFrom: string, + tokenTo: string, + fromTokenAmount: string, + apiKey: string, // + secretKey: string, + wallet: string + ): Promise> { // Making the order structure const - path = '/rfq' - , url = `${this.apiUrl}/api/v1/integration/pmm`+path - , headers = { - 'Content-Type': 'application/json', - } - , data = { - "baseToken":tokenFrom, // USDT - "quoteToken":tokenTo, // ORN - "amount": fromTokenAmount, // 100 - "taker": wallet, - "feeBps": 0 - } - , method = 'POST' - , timestamp = Date.now() - , signatureHeaders = this.generateHeaders(data, method, path, timestamp, apiKey, secretKey) - , compiledHeaders = {...headers, ...signatureHeaders.headers, } - , body = JSON.stringify(data) + path = '/rfq'; + const url = `${this.apiUrl}/api/v1/integration/pmm` + path; + const headers = { + 'Content-Type': 'application/json', + }; + const data = { + baseToken: tokenFrom, // USDT + quoteToken: tokenTo, // ORN + amount: fromTokenAmount, // 100 + taker: wallet, + feeBps: 0 + }; + const method = 'POST'; + const timestamp = Date.now(); + const signatureHeaders = this.generateHeaders(data, method, path, timestamp, apiKey, secretKey); + const compiledHeaders = { ...headers, ...signatureHeaders.headers, }; + const body = JSON.stringify(data) ; - - let res = pmmOrderSchema.parse({}); + const res = pmmOrderSchema.parse({}); try { - const result = await fetch(url,{ + const result = await fetch(url, { headers: compiledHeaders, method, body @@ -449,14 +451,13 @@ class Aggregator { const json = await result.json(); const parseResult = pmmOrderSchema.safeParse(json); - if(!parseResult.success) { + if (!parseResult.success) { // Try to parse error answer - const errorSchema = z.object({error: z.object({code: z.number(), reason: z.string()})}); + const errorSchema = z.object({ error: z.object({ code: z.number(), reason: z.string() }) }); const errorParseResult = errorSchema.safeParse(json); - if(!errorParseResult.success) - throw Error(`Unrecognized answer from aggregator: ${json}`); + if (!errorParseResult.success) { throw Error(`Unrecognized answer from aggregator: ${json}`); } throw Error(errorParseResult.data.error.reason); } @@ -466,8 +467,7 @@ class Aggregator { res.error = ''; res.success = true; // return result; - } - catch(err) { + } catch (err) { res.error = `${err}`; } return res; diff --git a/src/services/Aggregator/ws/index.ts b/src/services/Aggregator/ws/index.ts index 69d214c..ab6f6c5 100644 --- a/src/services/Aggregator/ws/index.ts +++ b/src/services/Aggregator/ws/index.ts @@ -66,10 +66,11 @@ type PairConfigSubscription = { type AggregatedOrderbookSubscription = { payload: string + dc?: number callback: ( asks: OrderbookItem[], bids: OrderbookItem[], - pair: string + pair: string, ) => void errorCb?: (message: string) => void } @@ -195,9 +196,10 @@ class AggregatorWS { readonly basicAuth?: BasicAuthCredentials | undefined; - constructor(wsUrl: string, basicAuth?: BasicAuthCredentials) { + constructor(wsUrl: string, basicAuth?: BasicAuthCredentials, logger?: ((message: string) => void) | undefined) { this.wsUrl = wsUrl; this.basicAuth = basicAuth; + this.logger = logger; } private messageQueue: BufferLike[] = []; @@ -252,7 +254,7 @@ class AggregatorWS { subscription: Subscription[T], prevSubscriptionId?: string ) { - const id = type === 'aobus' + const id = type === SubscriptionType.AGGREGATED_ORDER_BOOK_UPDATES_SUBSCRIBE ? ((subscription as any).payload as string) // TODO: Refactor!!! : uuidv4(); @@ -261,6 +263,14 @@ class AggregatorWS { const subRequest: Json = {}; subRequest['T'] = type; subRequest['id'] = id; + // test + if ('dc' in subscription) { + if (typeof subscription.dc === 'number') { + subRequest['dc'] = subscription.dc; + } + } + + this.logger?.('test'); if ('payload' in subscription) { if (typeof subscription.payload === 'string') { @@ -369,11 +379,11 @@ class AggregatorWS { delete this.subscriptions[SubscriptionType.ASSET_PAIR_CONFIG_UPDATES_SUBSCRIBE]?.[newestSubId]; // !!! swap info subscription is uuid that contains hyphen } else if (isOrderBooksSubscription(newestSubId)) { // is pair name(AGGREGATED_ORDER_BOOK_UPDATE) - const aobSubscriptions = this.subscriptions[SubscriptionType.AGGREGATED_ORDER_BOOK_UPDATES_SUBSCRIBE]; - if (aobSubscriptions) { - const targetAobSub = Object.entries(aobSubscriptions).find(([, value]) => value?.payload === newestSubId); - if (targetAobSub) { - const [key] = targetAobSub; + const aobusSubscriptions = this.subscriptions[SubscriptionType.AGGREGATED_ORDER_BOOK_UPDATES_SUBSCRIBE]; + if (aobusSubscriptions) { + const targetAobusSub = Object.entries(aobusSubscriptions).find(([, value]) => value?.payload === newestSubId); + if (targetAobusSub) { + const [key] = targetAobusSub; delete this.subscriptions[SubscriptionType.AGGREGATED_ORDER_BOOK_UPDATES_SUBSCRIBE]?.[key]; } } From 57cffe5eff92d976ef9a5e169eed93f7c3bee645 Mon Sep 17 00:00:00 2001 From: Kirill Litvinov Date: Tue, 2 Apr 2024 15:09:57 +0300 Subject: [PATCH 07/18] 0.20.80-rc1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 48979e1..14d3066 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.79-rc1", + "version": "0.20.80-rc1", "description": "Orion Protocol SDK", "main": "./lib/index.cjs", "module": "./lib/index.js", From 84a0fe7a86fb9646a65602b507f0a53c3482df37 Mon Sep 17 00:00:00 2001 From: Kirill Litvinov Date: Tue, 2 Apr 2024 15:18:35 +0300 Subject: [PATCH 08/18] fix: remove test logger --- package.json | 2 +- src/services/Aggregator/ws/index.ts | 3 --- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/package.json b/package.json index 14d3066..d19b27e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.80-rc1", + "version": "0.20.80-rc2", "description": "Orion Protocol SDK", "main": "./lib/index.cjs", "module": "./lib/index.js", diff --git a/src/services/Aggregator/ws/index.ts b/src/services/Aggregator/ws/index.ts index ab6f6c5..55c875e 100644 --- a/src/services/Aggregator/ws/index.ts +++ b/src/services/Aggregator/ws/index.ts @@ -263,15 +263,12 @@ class AggregatorWS { const subRequest: Json = {}; subRequest['T'] = type; subRequest['id'] = id; - // test if ('dc' in subscription) { if (typeof subscription.dc === 'number') { subRequest['dc'] = subscription.dc; } } - this.logger?.('test'); - if ('payload' in subscription) { if (typeof subscription.payload === 'string') { subRequest['S'] = subscription.payload; From c204ebf0b3c6ce3487822ad2ce7cd2586c37e2ac Mon Sep 17 00:00:00 2001 From: Kirill Litvinov Date: Tue, 2 Apr 2024 16:19:36 +0300 Subject: [PATCH 09/18] fix: space --- src/services/Aggregator/ws/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/services/Aggregator/ws/index.ts b/src/services/Aggregator/ws/index.ts index 55c875e..f0f0e8f 100644 --- a/src/services/Aggregator/ws/index.ts +++ b/src/services/Aggregator/ws/index.ts @@ -263,6 +263,7 @@ class AggregatorWS { const subRequest: Json = {}; subRequest['T'] = type; subRequest['id'] = id; + if ('dc' in subscription) { if (typeof subscription.dc === 'number') { subRequest['dc'] = subscription.dc; From 6b95e76a83c8a49b867f5f936c69f6ad018c2177 Mon Sep 17 00:00:00 2001 From: Kirill Litvinov Date: Tue, 2 Apr 2024 16:29:23 +0300 Subject: [PATCH 10/18] bump version --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index f02c880..9e4bc27 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.79-rc1", + "version": "0.20.79", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@orionprotocol/sdk", - "version": "0.20.79-rc1", + "version": "0.20.79", "hasInstallScript": true, "license": "ISC", "dependencies": { diff --git a/package.json b/package.json index d19b27e..b9093ae 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.80-rc2", + "version": "0.20.80-rc3", "description": "Orion Protocol SDK", "main": "./lib/index.cjs", "module": "./lib/index.js", From 201a177938f98eb709c4aaa847ca04d145b77ce2 Mon Sep 17 00:00:00 2001 From: Kirill Litvinov Date: Tue, 2 Apr 2024 16:30:24 +0300 Subject: [PATCH 11/18] bump version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index b9093ae..986ea3e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.80-rc3", + "version": "0.20.79", "description": "Orion Protocol SDK", "main": "./lib/index.cjs", "module": "./lib/index.js", From 8f840aede201d641e9ef7228edad726739a8e85e Mon Sep 17 00:00:00 2001 From: Mikhail Gladchenko Date: Tue, 2 Apr 2024 15:10:28 +0100 Subject: [PATCH 12/18] feat: updated readme file --- README.md | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index b06f8c3..0fec57d 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,8 @@ +[//]: # ( Orion Protocol SDK logo)
- Orion Protocol SDK logo -

Orion Protocol SDK

+

Lumia Stream SDK

Use CEX and DEX liquidity without KYC.

@@ -14,16 +10,15 @@ ![npm bundle size (version)](https://img.shields.io/bundlephobia/minzip/@orionprotocol/sdk) [![Downloads](https://img.shields.io/npm/dm/@orionprotocol/sdk.svg)](https://www.npmjs.com/package/@orionprotocol/sdk) -Do you want to integrate the Orion protocol into your application? See [integration guide](./docs/INTEGRATION.md) +Do you want to integrate the Lumia Stream protocol into your application? See [integration guide](./docs/INTEGRATION.md) ## Overview -Orion Software Developer Kit is a set of functions and methods that allow dApp developers connect to the superior aggregated liquidity of Orion Protocol which combines orderbooks of centralized exchanges as well decentralized automatic market makers such as Uniswap or Spookyswap across several supported blockchains. -Through this connection, developers using the SDK can perform a wide range of actions, including swapping selected tokens using Orion’s aggregated liquidity, obtaining relevant market information through subscriptions, add and remove liquidity to Orion’s pools. +Lumia Stream Developer Kit, natively built into Lumia, is a set of functions and methods that allow dApp developers to connect to the superior aggregated liquidity of Lumia Stream which combines orderbooks of centralized exchanges as well as decentralized Automatic Market Makers (AMMs) such as Uniswap, PancakeSwap, and Curve, across several supported blockchains. Through this connection, developers using the SDK can perform a wide range of actions, including swapping selected tokens, obtaining relevant market information through subscriptions, and more. ## API Key -Orion’s SDK is free to use and does not require an API key or registration. Refer to integration examples for more detailed information. +Lumia Stream’s SDK is free to use and does not require an API key or registration. Refer to integration examples for more detailed information. - [Overview](#overview) - [API Key](#api-key) @@ -33,7 +28,7 @@ Orion’s SDK is free to use and does not require an API key or registration. Re - [High level methods](#high-level-methods) - [Get assets](#get-assets) - [Get pairs](#get-pairs) - - [Get Orion Bridge history](#get-orion-bridge-history) + - [Get Lumia Stream Bridge history](#get-lumia-stream-bridge-history) - [Bridge swap](#bridge-swap) - [Withdraw](#withdraw) - [Deposit](#deposit) @@ -145,7 +140,7 @@ const pairs = await orion.getPairs("spot"); // 'spot' // } ``` -### Get Orion Bridge history +### Get Lumia Stream Bridge history ```ts const bridgeHistory = await orion.bridge.getHistory( @@ -722,7 +717,7 @@ switch (data.type) { ``` ## PMM -PMM allows institutional traders to request RFQ orders from Orion and then fill them. +PMM allows institutional traders to request RFQ orders from Lumia Stream and then fill them. RFQ order allows trader to fix the price for a certain time interval (up to 90 seconds, including the order settlement time interval on blockchain). From 9afda4260b5d88d33db063039f8ed01e9480e972 Mon Sep 17 00:00:00 2001 From: KS Date: Thu, 4 Apr 2024 17:32:37 +0300 Subject: [PATCH 13/18] removed crypto-js dependency --- src/services/Aggregator/index.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/services/Aggregator/index.ts b/src/services/Aggregator/index.ts index 1077a53..09966bf 100644 --- a/src/services/Aggregator/index.ts +++ b/src/services/Aggregator/index.ts @@ -19,8 +19,9 @@ import httpToWS from '../../utils/httpToWS.js'; import { ethers } from 'ethers'; import orderSchema from './schemas/orderSchema.js'; import { fetchWithValidation } from 'simple-typed-fetch'; -import hmacSHA256 from "crypto-js/hmac-sha256"; -import Hex from "crypto-js/enc-hex"; +// import hmacSHA256 from "crypto-js/hmac-sha256"; +// import Hex from "crypto-js/enc-hex"; +const crypto = require('crypto') import {pmmOrderSchema} from "../../Unit/Pmm/schemas/order"; class Aggregator { @@ -379,10 +380,9 @@ class Aggregator { } private sign(message : string, key: string) { - return hmacSHA256( - this.encode_utf8(message), - this.encode_utf8(key) - ).toString(Hex); + return crypto.createHmac('sha256', this.encode_utf8(key)) + .update(this.encode_utf8(message)) + .digest('hex'); } private generateHeaders(body : any, method : string, path : string, timestamp : number, apiKey : string, secretKey : string) { From b6370c97aa569f2b36227053db7bb46d255637d6 Mon Sep 17 00:00:00 2001 From: KS Date: Thu, 4 Apr 2024 17:34:53 +0300 Subject: [PATCH 14/18] increased version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index a307337..ace8c14 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.79-rc1", + "version": "0.20.80-rc1", "description": "Orion Protocol SDK", "main": "./lib/index.cjs", "module": "./lib/index.js", From 7b463dc82346e0b95d3cc4ba303a0417f0e93643 Mon Sep 17 00:00:00 2001 From: kigastu Date: Thu, 4 Apr 2024 17:58:03 +0300 Subject: [PATCH 15/18] bump version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 910785d..7b806e5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.80-rc1", + "version": "0.20.80", "description": "Orion Protocol SDK", "main": "./lib/index.cjs", "module": "./lib/index.js", From 5e1922411489bd3292fbb3e38f07173d3e60600a Mon Sep 17 00:00:00 2001 From: Kirill Litvinov Date: Thu, 4 Apr 2024 18:54:33 +0300 Subject: [PATCH 16/18] fix: build --- package-lock.json | 17 ++--------------- package.json | 2 +- src/services/Aggregator/index.ts | 20 +++++++++++--------- 3 files changed, 14 insertions(+), 25 deletions(-) diff --git a/package-lock.json b/package-lock.json index 9e4bc27..3e9a96b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.79", + "version": "0.20.81", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@orionprotocol/sdk", - "version": "0.20.79", + "version": "0.20.81", "hasInstallScript": true, "license": "ISC", "dependencies": { @@ -40,7 +40,6 @@ "@babel/plugin-syntax-import-assertions": "^7.20.0", "@tsconfig/esm": "^1.0.4", "@tsconfig/strictest": "^2.0.1", - "@types/crypto-js": "^4.2.2", "@types/express": "^4.17.17", "@types/jest": "^29.5.1", "@types/node": "^20.5.1", @@ -2547,12 +2546,6 @@ "@types/node": "*" } }, - "node_modules/@types/crypto-js": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-4.2.2.tgz", - "integrity": "sha512-sDOLlVbHhXpAUAL0YHDUUwDZf3iN4Bwi4W6a0W0b+QcAezUbRtH4FVb+9J4h+XFPW7l/gQ9F8qC7P+Ec4k8QVQ==", - "dev": true - }, "node_modules/@types/eslint": { "version": "8.44.2", "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.44.2.tgz", @@ -13617,12 +13610,6 @@ "@types/node": "*" } }, - "@types/crypto-js": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-4.2.2.tgz", - "integrity": "sha512-sDOLlVbHhXpAUAL0YHDUUwDZf3iN4Bwi4W6a0W0b+QcAezUbRtH4FVb+9J4h+XFPW7l/gQ9F8qC7P+Ec4k8QVQ==", - "dev": true - }, "@types/eslint": { "version": "8.44.2", "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.44.2.tgz", diff --git a/package.json b/package.json index 7b806e5..bf41f6f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.80", + "version": "0.20.81", "description": "Orion Protocol SDK", "main": "./lib/index.cjs", "module": "./lib/index.js", diff --git a/src/services/Aggregator/index.ts b/src/services/Aggregator/index.ts index dd8416f..0e505c6 100644 --- a/src/services/Aggregator/index.ts +++ b/src/services/Aggregator/index.ts @@ -19,10 +19,10 @@ import httpToWS from '../../utils/httpToWS.js'; import { ethers } from 'ethers'; import orderSchema from './schemas/orderSchema.js'; import { fetchWithValidation } from 'simple-typed-fetch'; +import { pmmOrderSchema } from '../../Unit/Pmm/schemas/order'; // import hmacSHA256 from "crypto-js/hmac-sha256"; // import Hex from "crypto-js/enc-hex"; -const crypto = require('crypto') -import {pmmOrderSchema} from "../../Unit/Pmm/schemas/order"; +// const crypto = require('crypto') class Aggregator { private readonly apiUrl: string; @@ -379,14 +379,16 @@ class Aggregator { return fetchWithValidation(url.toString(), atomicSwapHistorySchema, { headers: this.basicAuthHeaders }); }; - private encode_utf8(s: string) { - return unescape(encodeURIComponent(s)); - } + // private encode_utf8(s: string) { + // return unescape(encodeURIComponent(s)); + // } - private sign(message : string, key: string) { - return crypto.createHmac('sha256', this.encode_utf8(key)) - .update(this.encode_utf8(message)) - .digest('hex'); + // @ts-expect-error: TODO: please remove this line! + private sign(message: string, key: string) { + // return crypto.createHmac('sha256', this.encode_utf8(key)) + // .update(this.encode_utf8(message)) + // .digest('hex'); + return ''; } private generateHeaders(body: any, method: string, path: string, timestamp: number, apiKey: string, secretKey: string) { From 515888a268b594e6ace470d57301724eb46f3e90 Mon Sep 17 00:00:00 2001 From: Kirill Litvinov Date: Mon, 8 Apr 2024 15:33:45 +0300 Subject: [PATCH 17/18] getStableCoins --- package-lock.json | 4 ++-- package.json | 2 +- src/services/Aggregator/index.ts | 11 +++++++++++ 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 3e9a96b..239694a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.81", + "version": "0.20.82", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@orionprotocol/sdk", - "version": "0.20.81", + "version": "0.20.82", "hasInstallScript": true, "license": "ISC", "dependencies": { diff --git a/package.json b/package.json index bf41f6f..15ace9e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.81", + "version": "0.20.82-rc1", "description": "Orion Protocol SDK", "main": "./lib/index.cjs", "module": "./lib/index.js", diff --git a/src/services/Aggregator/index.ts b/src/services/Aggregator/index.ts index 0e505c6..fd7fec8 100644 --- a/src/services/Aggregator/index.ts +++ b/src/services/Aggregator/index.ts @@ -61,6 +61,7 @@ class Aggregator { this.getPairsList = this.getPairsList.bind(this); this.getSwapInfo = this.getSwapInfo.bind(this); this.getTradeProfits = this.getTradeProfits.bind(this); + this.getStableCoins = this.getStableCoins.bind(this); this.placeAtomicSwap = this.placeAtomicSwap.bind(this); this.placeOrder = this.placeOrder.bind(this); this.cancelOrder = this.cancelOrder.bind(this); @@ -340,6 +341,16 @@ class Aggregator { ); }; + getStableCoins = () => { + const url = new URL(`${this.apiUrl}/api/v1/tokens/stable/`); + return fetchWithValidation( + url.toString(), + z.array(z.string()), + { headers: this.basicAuthHeaders }, + errorSchema, + ); + }; + /** * Placing atomic swap. Placement must take place on the target chain. * @param secretHash Secret hash From b1920c91b9b8d1165775e454d4a3e1678b10a97e Mon Sep 17 00:00:00 2001 From: kigastu Date: Mon, 8 Apr 2024 15:52:32 +0300 Subject: [PATCH 18/18] bump version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 15ace9e..e2cb3dc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@orionprotocol/sdk", - "version": "0.20.82-rc1", + "version": "0.20.82", "description": "Orion Protocol SDK", "main": "./lib/index.cjs", "module": "./lib/index.js",