├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE.txt ├── README.md ├── VERSION ├── index.js ├── lib ├── request.js └── validate.js ├── package.json ├── services ├── balance.js ├── base_tokens.js ├── chains.js ├── device_managers.js ├── devices.js ├── manifest.js ├── price_points.js ├── recovery_owners.js ├── redeemable_skus.js ├── redemptions.js ├── rules.js ├── sessions.js ├── tokens.js ├── transactions.js ├── users.js └── webhooks.js └── test ├── config.json └── index.js /.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | .DS_Store 3 | 4 | # Logs 5 | logs 6 | *.log 7 | log 8 | 9 | # Runtime data 10 | pids 11 | dump.rdb 12 | /.idea 13 | package-lock.json 14 | *.pid 15 | *.seed 16 | nohup.out 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | 24 | # Grunt intermediate storage 25 | .grunt 26 | 27 | # node-waf configuration 28 | .lock-wscript 29 | 30 | # Compiled binary addons 31 | build/Release 32 | 33 | # Dependency directory 34 | node_modules 35 | 36 | # Debug log from npm 37 | npm-debug.log 38 | .vscode 39 | set_env_vars.sh 40 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: trusty 2 | language: node_js 3 | sudo: required 4 | branches: 5 | only: 6 | - develop 7 | - /^release-.*/ 8 | notifications: 9 | email: 10 | recipients: 11 | - ci.report@ost.com 12 | on_success: always 13 | on_failure: always 14 | node_js: 15 | - "10" 16 | - "9" 17 | - "8" 18 | before_install: 19 | - sudo apt-get update 20 | - sudo apt-get install nodejs 21 | - sudo apt-get install npm 22 | install: 23 | - npm install 24 | - npm install -g mocha 25 | before_script: 26 | script: 27 | - mocha --timeout 120000 test/* --exit 28 | after_script: 29 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | [OST Javascript SDK v2.2.3](https://github.com/ostdotcom/ost-sdk-js/tree/v2.2.3) 2 | --- 3 | 4 | * Added redemptions module to call user redemptions management OST APIs. 5 | * Added redeemable SKUs module to call redeemable SKUs OST APIs. 6 | 7 | [OST Javascript SDK v2.2.2](https://github.com/ostdotcom/ost-sdk-js/tree/v2.2.2) 8 | --- 9 | 10 | * Readme changes for documenting new parameters in transactions module. These parameters can help to 11 | get data between specific time interval. 12 | 13 | [OST Javascript SDK v2.2.0](https://github.com/ostdotcom/ost-sdk-js/tree/v2.2.0) 14 | --- 15 | 16 | * Added webhooks module to call webhook management OST APIs. 17 | * Support for verify webhook signature. 18 | 19 | [OST Javascript SDK v2.1.0](https://github.com/ostdotcom/ost-sdk-js/tree/v2.1.0) 20 | --- 21 | 22 | * Added base tokens module to V2 API's 23 | 24 | [OST Javascript SDK v2.0.0](https://github.com/ostdotcom/ost-sdk-js/tree/v2.0.0) 25 | --- 26 | 27 | * OST API V2 interaction layer implementation. 28 | * Removed API V0 and V1 support. 29 | * [README.md](README.md) has API V2 usage instructions 30 | 31 | [OST Javascript SDK v1.1.0](https://github.com/ostdotcom/ost-sdk-js/tree/v1.1.0) 32 | --- 33 | 34 | * Added balance module to v1 API 35 | * Added ledger module to v1 API 36 | 37 | [OST Javascript SDK v1.0.0](https://github.com/ostdotcom/ost-sdk-js/tree/v1.0.0) 38 | --- 39 | 40 | * Added OST API V1 support along with API V0 41 | * Test cases for for both V0 and V1 APIs 42 | * [README.md](README.md) has API V1 usage instructions 43 | * [README_V0.md](README.md) has API V0 usage instructions 44 | 45 | [OST Javascript SDK v0.9.1](https://github.com/ostdotcom/ost-sdk-js/tree/v0.9.1) 46 | --- 47 | Initial release of the official OST Javascript SDK
48 | This release has the OST API V0 interaction layer implementation. 49 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019 OST.com Inc. 2 | 3 | MIT License 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | "Software"), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 20 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 22 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OST Server-Side JavaScript SDK 2 | [![Build Status](https://travis-ci.org/ostdotcom/ost-sdk-js.svg?branch=develop)](https://travis-ci.org/ostdotcom/ost-sdk-js) 3 | 4 | [OST](https://dev.ost.com/) Platform SDK for JavaScript. 5 | 6 | ## Introduction 7 | 8 | OST is a complete technology solution enabling mainstream businesses 9 | to easily launch blockchain based economies without requiring blockchain development. 10 | 11 | Brand Tokens (BTs) are white-label cryptocurrency tokens with utility representations 12 | running on highly-scalable Ethereum-based utility blockchains, 13 | backed by value token (such as OST, USDC) staked on Ethereum mainnet. Within a business`s 14 | token economy, BTs can only be transferred to whitelisted user addresses. 15 | This ensures that they stay within the token economy. 16 | 17 | The OST technology stack is designed to give businesses everything they need 18 | to integrate, test, and deploy BTs. Within the OST suite of products, developers 19 | can use OST Platform to create, test, and launch Brand Tokens. 20 | 21 | OST APIs and server-side SDKs make it simple and easy for developers to 22 | integrate blockchain tokens into their apps. 23 | 24 | For documentation, visit [https://dev.ost.com/](https://dev.ost.com/) 25 | 26 | ## Getting Started 27 | 28 | ### Setup Brand Token 29 | 1. Sign-up on [OST Platform](https://platform.ost.com) and setup your Brand Token. 30 | 2. Obtain your API Key and API Secret from [developers page](https://platform.ost.com/mainnet/developer). 31 | 32 | ### Installation 33 | 34 | The preferred way to install the OST JavaScript SDK is to use the npm package manager for Node.js. Simply type the following into a terminal window: 35 | 36 | ```bash 37 | npm install @ostdotcom/ost-sdk-js 38 | ``` 39 | 40 | ## Usage 41 | * Require the OST JavaScript SDK. 42 | 43 | ```js 44 | const OSTSDK = require('@ostdotcom/ost-sdk-js'); 45 | ``` 46 | 47 | * Initialize the SDK object. 48 | 49 | ```js 50 | // Declare connection parameters. 51 | 52 | // Mandatory API parameters 53 | let apiKey = '__abc'; // OBTAINED FROM DEVELOPER PAGE 54 | 55 | let apiSecret = '_xyz'; // OBTAINED FROM DEVELOPER PAGE 56 | 57 | /* 58 | The valid API endpoints are: 59 | 1. Mainnet: "https://api.ost.com/mainnet/v2/" 60 | 2. Testnet: "https://api.ost.com/testnet/v2/" 61 | */ 62 | let apiEndpoint = 'https://api.ost.com/testnet/v2/'; 63 | 64 | // Optional API parameters 65 | 66 | // This is the timeout in seconds for which the socket connection will remain open. 67 | let timeoutInSeconds = '60'; 68 | let options = { timeout: timeoutInSeconds }; 69 | 70 | // OST server side sdk object. 71 | const ostObj = new OSTSDK({apiKey: apiKey, apiSecret: apiSecret, apiEndpoint: apiEndpoint,config: options}); 72 | ``` 73 | 74 | ### Users Module 75 | 76 | * Initialize Users service object to perform user specific actions. 77 | 78 | ```js 79 | const usersService = ostObj.services.users; 80 | ``` 81 | 82 | * Create User. This creates a unique identifier for each user. 83 | 84 | ```js 85 | usersService.create({}) 86 | .then(function(res) { console.log(JSON.stringify(res)); }) 87 | .catch(function(err) { console.log(JSON.stringify(err)); }); 88 | ``` 89 | 90 | * Get User Detail using the userId obtained in user create. 91 | 92 | ```js 93 | // Mandatory API parameters 94 | 95 | // UserId of user for whom user details needs to be fetched. 96 | let userId = 'c2c__'; 97 | 98 | usersService.get({ user_id: userId }) 99 | .then(function(res) { console.log(JSON.stringify(res)); }) 100 | .catch(function(err) { console.log(JSON.stringify(err)); }); 101 | ``` 102 | 103 | * Get Users List. Pagination is supported by this API. 104 | 105 | ```js 106 | // Mandatory API parameters 107 | // No mandatory parameters. 108 | 109 | // Optional API parameters 110 | 111 | // Array of userIds for which data needs to be fetched. 112 | let userIdsArray = ["c2c__", "d2c__"]; 113 | 114 | // Pagination identifier from the previous API call response. Not needed for page one. 115 | let paginationIdentifier = 'e77y___'; 116 | 117 | // Limit. 118 | let limit = 10; 119 | 120 | usersService.getList({ ids: userIdsArray, limit: limit, pagination_identifier: paginationIdentifier }) 121 | .then(function(res) { console.log(JSON.stringify(res)); }) 122 | .catch(function(err) { console.log(JSON.stringify(err)); }); 123 | ``` 124 | 125 | ### Devices Module 126 | 127 | * Initialize Devices service object to perform device specific actions. 128 | ```js 129 | const devicesService = ostObj.services.devices; 130 | ``` 131 | 132 | * Create a Device for User. 133 | 134 | ```js 135 | // Mandatory API parameters 136 | 137 | // UserId of user for whom device needs to be created. 138 | let userId = 'c2c___'; 139 | 140 | // Device address of user's device. 141 | let deviceAddress = '0x1Ea___'; 142 | 143 | // Device API signer address. 144 | let apiSignerAddress = '0x5F8___'; 145 | 146 | devicesService.create({ 147 | user_id: userId, 148 | address: deviceAddress, 149 | api_signer_address: apiSignerAddress 150 | }).then(function(res) { console.log(JSON.stringify(res)); }) 151 | .catch(function(err) { console.log(JSON.stringify(err)); }); 152 | ``` 153 | 154 | * Get User Device Detail using userId and deviceAddress. 155 | 156 | ```js 157 | // Mandatory API parameters 158 | 159 | // UserId of user for whom device details needs to be fetched. 160 | let userId = 'c2c___'; 161 | 162 | // Device address of user's device. 163 | let deviceAddress = '0x1E___'; 164 | 165 | devicesService.get({ 166 | user_id: userId, 167 | device_address: deviceAddress 168 | }).then(function(res) { console.log(JSON.stringify(res)); }) 169 | .catch(function(err) { console.log(JSON.stringify(err)); }); 170 | ``` 171 | 172 | * Get User Devices List. Pagination is supported by this API. 173 | 174 | ```js 175 | // Mandatory API parameters 176 | 177 | // UserId of user for whom device details needs to be fetched. 178 | let userId = 'c2c6___'; 179 | 180 | // Optional API parameters 181 | 182 | // Pagination identifier from the previous API call response. Not needed for page one. 183 | let paginationIdentifier = 'eyJ___'; 184 | 185 | // Array of device addresses of end user. 186 | let deviceAddressesArray = ['0x59___','0xab___']; 187 | 188 | // Limit. 189 | let limit = 10; 190 | 191 | devicesService.getList({ 192 | user_id: userId, 193 | addresses: deviceAddressesArray, 194 | pagination_identifier: paginationIdentifier, 195 | limit: limit 196 | }).then(function(res) { console.log(JSON.stringify(res)); }) 197 | .catch(function(err) { console.log(JSON.stringify(err)); }); 198 | ``` 199 | 200 | ### Device Managers Module 201 | 202 | * Initialize Device Manager service object to perform device manager specific actions. 203 | 204 | ```js 205 | const deviceManagersService = ostObj.services.device_managers; 206 | ``` 207 | 208 | * Get Device Manager Detail using userId. 209 | 210 | ```js 211 | // Mandatory API parameters 212 | 213 | // UserId of user for whom device manager details needs to be fetched. 214 | let userId = 'c2c___'; 215 | 216 | deviceManagersService.get({ user_id: userId }) 217 | .then(function(res) { console.log(JSON.stringify(res)); }) 218 | .catch(function(err) { console.log(JSON.stringify(err)); }); 219 | ``` 220 | 221 | ### Sessions Module 222 | 223 | * Initialize Sessions service object to perform session specific actions. 224 | 225 | ```js 226 | const sessionsService = ostObj.services.sessions; 227 | ``` 228 | 229 | * Get User Session Detail using userId and session address. 230 | 231 | ```js 232 | // Mandatory API parameters 233 | 234 | // UserId of user for whom session details needs to be fetched. 235 | let userId = 'c2c___'; 236 | 237 | // Session address of user for which details needs to be fetched. 238 | let sessionAddress = '0x1Ea___'; 239 | 240 | sessionsService.get({ 241 | user_id: userId, 242 | session_address: sessionAddress 243 | }).then(function(res) { console.log(JSON.stringify(res)); }) 244 | .catch(function(err) { console.log(JSON.stringify(err)); }); 245 | ``` 246 | 247 | * Get User Sessions List using userId. Pagination is supported by this API. 248 | 249 | ```js 250 | // Mandatory API parameters 251 | 252 | // UserId of user for whom session details needs to be fetched. 253 | let userId = 'c2c___'; 254 | 255 | // Optional API parameters 256 | 257 | // Pagination identifier from the previous API call response. Not needed for page one. 258 | let paginationIdentifier = 'eyJs___'; 259 | 260 | // Array of session addresses of end user. 261 | let sessionAddressesArray = ["0x59___","0xab___"]; 262 | 263 | // Limit. 264 | let limit = 10; 265 | 266 | sessionsService.getList({ 267 | user_id: userId, 268 | addresses: sessionAddressesArray, 269 | pagination_identifier: paginationIdentifier, 270 | limit: limit 271 | }).then(function(res) { console.log(JSON.stringify(res)); }) 272 | .catch(function(err) { console.log(JSON.stringify(err)); }); 273 | ``` 274 | 275 | 276 | ### Executing Transactions 277 | 278 | For executing transactions, you need to understand the 4 modules described below. 279 | 280 | #### Rules Module 281 | 282 | * Initialize Rules service object to perform rules specific actions. 283 | 284 | ```js 285 | const rulesService = ostObj.services.rules; 286 | ``` 287 | 288 | * List Rules. 289 | 290 | ```js 291 | rulesService.getList({}) 292 | .then(function(res) { console.log(JSON.stringify(res)); }) 293 | .catch(function(err) { console.log(JSON.stringify(err)); }); 294 | ``` 295 | 296 | #### Price Points Module 297 | 298 | * Initialize Price Points service object to perform price points specific actions. 299 | 300 | ```js 301 | const pricePoints = ostObj.services.price_points; 302 | ``` 303 | 304 | * Get Price Points Detail. 305 | 306 | ```js 307 | // Mandatory API parameters 308 | 309 | // ChainId of your brand token economy. 310 | let chainId = 2000; 311 | 312 | pricePoints.get({ chain_id: chainId }) 313 | .then(function(res) { console.log(JSON.stringify(res)); }) 314 | .catch(function(err) { console.log(JSON.stringify(err)); }); 315 | ``` 316 | 317 | 318 | #### Transactions Module 319 | 320 | * Initialize Transactions service object to perform transaction specific actions. 321 | 322 | ```js 323 | const transactionsService = ostObj.services.transactions; 324 | ``` 325 | 326 | * DIRECT-TRANSFERS execute transaction should be used to transfer BTs to your end-users. 327 | 328 | ```js 329 | // Mandatory API parameters 330 | 331 | // Token holder address of receiver. 332 | let transferToAddress = '0xa3___'; 333 | 334 | // Amount of tokens to be transferred. 335 | let transferAmount = '1'; 336 | 337 | // Parameters required for rule execution. 338 | let rawCalldata = JSON.stringify({ 339 | method: 'directTransfers', // Rule name which needs to be passed as-is. 340 | parameters: [[transferToAddress],[transferAmount]] 341 | }); 342 | 343 | // Company userId. 344 | let companyUserId = 'ee89___'; 345 | 346 | // Address of DirectTransfer rule. Use list rules API of Rules module to get the address of rules. 347 | // In the rules array which you will get in response, use the address having name "Direct Transfer". 348 | let directTransferRuleAddress = '0xe379___'; 349 | 350 | // Optional API parameters 351 | 352 | // Name of the transaction. Eg. 'like', 'download', etc. 353 | // NOTE: Max length 25 characters (Allowed characters: [A-Za-z0-9_/s]) 354 | let transactionName = 'like'; 355 | 356 | // Transaction type. Possible values: 'company_to_user', 'user_to_user', 'user_to_company'. 357 | let transactionType = 'company_to_user'; 358 | 359 | // Some extra information about transaction. 360 | // NOTE: Max length 125 characters (Allowed characters: [A-Za-z0-9_/s]) 361 | let details = 'lorem_ipsum'; 362 | 363 | // Additional transaction information. There is no dependency between any of the metaProperty keys. 364 | // However, if a key is present, its value cannot be null or undefined. 365 | let metaProperty = { 366 | "name": transactionName, 367 | "type": transactionType, 368 | "details" : details 369 | }; 370 | 371 | transactionsService.execute({ 372 | user_id: companyUserId, 373 | to: directTransferRuleAddress, 374 | raw_calldata: rawCalldata, 375 | meta_property: metaProperty 376 | }) 377 | .then(function(res) { console.log(JSON.stringify(res)); }) 378 | .catch(function(err) { console.log(JSON.stringify(err)); }); 379 | ``` 380 | 381 | * PAY Execute Transaction should be used when transactions of BTs equivalent to some fiat amount need to be executed. 382 | 383 | ```js 384 | // Mandatory API parameters 385 | 386 | // Token holder address of receiver. 387 | let transferToAddress = '0xa31__'; 388 | 389 | // Company token holder address. 390 | let companyTokenHolderAddress = '0xa963___'; 391 | 392 | // Pay currency code. Supported currency codes are 'USD', 'EUR' and 'GBP'. 393 | let payCurrencyCode = 'USD'; 394 | 395 | // In pay transaction, the transfer amounts are in pay currency (fiat currency like USD) which then are converted 396 | // into tokens. Use get price point detail API of Price Points module to get this value. 397 | let pricePoint = 0.020606673; 398 | 399 | // Price point needs to be passed in atto. Multiply the price point with 10^18. Also, this value should be a string. 400 | let intendedPricePointInAtto = String(pricePoint * 10**18); 401 | 402 | // Amount of Fiat to be transferred. 403 | let transferAmountInFiat = 0.1; 404 | 405 | // Transfer amount in wei needs to be passed in atto. Multiply the fiat transfer amount with 10^18. Also, this value should be a string. 406 | let fiatTransferAmountInAtto = String(transferAmountInFiat * 10**18); 407 | 408 | // Parameters required for rule execution. 409 | let rawCalldata = JSON.stringify({ 410 | method: 'pay', // Rule name which needs to be passed as-is. 411 | parameters: [companyTokenHolderAddress, [transferToAddress],[fiatTransferAmountInAtto], payCurrencyCode, intendedPricePointInAtto] 412 | }); 413 | 414 | // Company userId. 415 | let companyUserId = 'ee8___'; 416 | 417 | // Address of Pay rule. Use list rules API to get the address of rules. 418 | // In the rules array which you will get in response, use the address having name "Pricer". 419 | let payRuleAddress = '0xe37___'; 420 | 421 | // Optional API parameters 422 | 423 | // Name of the transaction. Eg. 'like', 'download', etc. 424 | // NOTE: Max length 25 characters (Allowed characters: [A-Za-z0-9_/s]) 425 | let transactionName = 'like'; 426 | 427 | // Transaction type. Possible values: 'company_to_user', 'user_to_user', 'user_to_company'. 428 | let transactionType = 'company_to_user'; 429 | 430 | // Some extra information about transaction. 431 | // NOTE: Max length 125 characters (Allowed characters: [A-Za-z0-9_/s]) 432 | let details = 'lorem_ipsum'; 433 | 434 | // Additional transaction information. There is no dependency between any of the metaProperty keys. 435 | // However, if a key is present, its value cannot be null or undefined. 436 | let metaProperty = { 437 | "name": transactionName, 438 | "type": transactionType, 439 | "details" : details 440 | }; 441 | 442 | transactionsService.execute({ 443 | user_id: companyUserId, 444 | to: payRuleAddress, 445 | raw_calldata: rawCalldata, 446 | meta_property: metaProperty 447 | }).then(function(res) { console.log(JSON.stringify(res)); }) 448 | .catch(function(err) { console.log(JSON.stringify(err)); }); 449 | ``` 450 | 451 | * Get Transaction Detail using userId and transactionId. 452 | 453 | ```js 454 | // Mandatory API parameters 455 | 456 | // UserId of end-user. 457 | let userId = 'ee8___'; 458 | 459 | // Unique identifier of the transaction to be retrieved. 460 | let transactionId = 'f1d___'; 461 | 462 | transactionsService.get({ user_id: userId, transaction_id: transactionId }) 463 | .then(function(res) { console.log(JSON.stringify(res)); }) 464 | .catch(function(err) { console.log(JSON.stringify(err)); }); 465 | ``` 466 | 467 | * Get User Transactions using userId. Pagination is supported by this API. 468 | 469 | ```js 470 | // Mandatory API parameters 471 | 472 | // UserId of end-user. 473 | let userId = 'ee89___'; 474 | 475 | // Optional API parameters 476 | 477 | // Array of status values. 478 | let statusesArray = ['CREATED', 'SUBMITTED', 'SUCCESS', 'FAILED']; 479 | 480 | // To get transactions between a specific time interval, add start timestamp and end timestamp. 481 | let startTime = 1563260786; 482 | let endTime = 1563280786; 483 | 484 | // Name of the transaction. Eg. 'like', 'download', etc. 485 | // NOTE: Max length 25 characters (Allowed characters: [A-Za-z0-9_/s]) 486 | let transactionName = 'like'; 487 | 488 | // Transaction type. Possible values: 'company_to_user', 'user_to_user', 'user_to_company'. 489 | let transactionType = 'company_to_user'; 490 | 491 | // NOTE: Max length 125 characters (Allowed characters: [A-Za-z0-9_/s]) 492 | let details = 'lorem_ipsum'; 493 | 494 | // Additional transaction information. There is no dependency between any of the metaProperty keys. 495 | // However, if a key is present, its value cannot be null or undefined. 496 | let metaPropertiesArray = JSON.stringify([ 497 | { 498 | "name": transactionName, 499 | "type": transactionType, 500 | "details" : details 501 | } 502 | ]); 503 | 504 | // Limit. 505 | let limit = 10; 506 | 507 | // Pagination identifier from the previous API call response. Not needed for page one. 508 | let paginationIdentifier = 'eyJsY___'; 509 | 510 | transactionsService.getList({ 511 | user_id: userId, 512 | start_time: startTime, 513 | end_time: endTime, 514 | statuses: statusesArray, 515 | meta_properties: metaPropertiesArray, 516 | limit: limit, 517 | pagination_identifier: paginationIdentifier 518 | }).then(function(res) { console.log(JSON.stringify(res)); }) 519 | .catch(function(err) { console.log(JSON.stringify(err)); }); 520 | ``` 521 | 522 | 523 | #### Balances Module 524 | 525 | * Initialize Balances service object to perform balances specific actions. 526 | 527 | ```js 528 | const balancesService = ostObj.services.balance; 529 | ``` 530 | 531 | * Get User Balance using userId. 532 | 533 | ```js 534 | // Mandatory API parameters 535 | 536 | // UserId for whom balance needs to be fetched. 537 | let userId = 'c2c6___'; 538 | 539 | balancesService.get({ user_id: userId }) 540 | .then(function(res) { console.log(JSON.stringify(res)); }) 541 | .catch(function(err) { console.log(JSON.stringify(err)); }); 542 | ``` 543 | 544 | 545 | ### Recovery Owners Module 546 | 547 | * Initialize Recovery Owners service object to perform recovery owners specific actions. 548 | 549 | ```js 550 | const recoveryOwnersService = ostObj.services.recovery_owners; 551 | ``` 552 | 553 | * Get Recovery Owner Detail using userId and recovery owner address. 554 | 555 | ```js 556 | // Mandatory API parameters 557 | 558 | // UserId for whom recovery details needs to be fetched. 559 | let userId = 'c2c___'; 560 | 561 | // Recovery address of user. 562 | let recoveryOwnerAddress = '0xe37___'; 563 | 564 | recoveryOwnersService.get({ 565 | user_id: userId, 566 | recovery_owner_address: recoveryOwnerAddress 567 | }).then(function(res) { console.log(JSON.stringify(res)); }) 568 | .catch(function(err) { console.log(JSON.stringify(err)); }); 569 | ``` 570 | 571 | 572 | ### Tokens Module 573 | 574 | * Initialize Tokens service object to perform tokens specific actions. 575 | 576 | ```js 577 | const tokensService = ostObj.services.tokens; 578 | ``` 579 | 580 | * Get Token Detail. 581 | 582 | ```js 583 | tokensService.get({}) 584 | .then(function(res) { console.log(JSON.stringify(res)); }) 585 | .catch(function(err) { console.log(JSON.stringify(err)); }); 586 | ``` 587 | 588 | ### Chains Module 589 | 590 | * Initialize Chains service object to perform chains specific actions. 591 | 592 | ```js 593 | const chainsService = ostObj.services.chains; 594 | ``` 595 | 596 | * Get Chain Detail using chainId. 597 | 598 | ```js 599 | // Mandatory API parameters 600 | 601 | // ChainId for which details needs to be fetched. Only origin chainId and OST-specific auxiliary chainIds are allowed. 602 | let chainId = '2000'; 603 | 604 | chainsService.get({ chain_id: chainId }) 605 | .then(function(res) { console.log(JSON.stringify(res)); }) 606 | .catch(function(err) { console.log(JSON.stringify(err)); }); 607 | ``` 608 | 609 | ### Base Tokens Module 610 | 611 | * Initialize Base Tokens service object to perform base tokens specific actions. 612 | 613 | ```js 614 | const baseTokensService = ostObj.services.base_tokens; 615 | ``` 616 | 617 | * Get Base Tokens Detail. 618 | 619 | ```js 620 | baseTokensService.get({}) 621 | .then(function(res) { console.log(JSON.stringify(res)); }) 622 | .catch(function(err) { console.log(JSON.stringify(err)); }); 623 | ``` 624 | 625 | ### Webhooks Module 626 | 627 | * Initialize Webhooks service object to perform webhooks specific actions. 628 | 629 | ```js 630 | const webhooksService = ostObj.services.webhooks; 631 | ``` 632 | 633 | * Create Webhook using the topics and the subscription url. 634 | 635 | ```js 636 | // Mandatory API parameters 637 | 638 | // Array of topics. 639 | let topicParams = ['transactions/initiate','transactions/success']; 640 | 641 | // URL where you want to receive the event notifications. 642 | let url = 'https://www.testingWebhooks.com'; 643 | 644 | // Optional API parameters 645 | 646 | // Status of a webhook. Possible values are 'active' and 'inactive'. 647 | let status = 'active'; 648 | 649 | webhooksService.create({ topics: topicParams , url: url, status: status}) 650 | .then(function(res) { console.log(JSON.stringify(res)); }) 651 | .catch(function(err) { console.log(JSON.stringify(err)); }); 652 | ``` 653 | 654 | * Update existing Webhook using a webhookId and an array of topics. 655 | 656 | ```js 657 | // Mandatory API parameters 658 | 659 | // Array of topics. 660 | let topicParams = ['transactions/initiate','transactions/success']; 661 | 662 | // Unique identifier for a webhook. 663 | let webhookId = 'a743___'; 664 | 665 | // Optional API parameters 666 | 667 | // Status of a webhook. Possible values are 'active' and 'inactive'. 668 | let status = 'active'; 669 | 670 | webhooksService.update({ webhook_id: webhookId, topics: topicParams, status: status }) 671 | .then(function(res) { console.log(JSON.stringify(res)); }) 672 | .catch(function(err) { console.log(JSON.stringify(err)); }); 673 | ``` 674 | 675 | * Get Webhook using webhookId. 676 | 677 | ```js 678 | // Mandatory API parameters 679 | 680 | let webhookId = 'a743___'; 681 | // Unique identifier for a webhook. 682 | 683 | webhooksService.get({ webhook_id: webhookId }) 684 | .then(function(res) { console.log(JSON.stringify(res)); }) 685 | .catch(function(err) { console.log(JSON.stringify(err)); }); 686 | ``` 687 | 688 | * Get Webhook List. Pagination is supported by this API. 689 | 690 | ```js 691 | // Mandatory API parameters 692 | // No mandatory parameters. 693 | 694 | // Optional API parameters 695 | 696 | // Limit. 697 | let limit = 10; 698 | 699 | // Pagination identifier from the previous API call response. Not needed for page one. 700 | let paginationIdentifier = 'eyJwY___'; 701 | 702 | webhooksService.getList({ limit: limit, pagination_identifier: paginationIdentifier }) 703 | .then(function(res) { console.log(JSON.stringify(res)); }) 704 | .catch(function(err) { console.log(JSON.stringify(err)); }); 705 | ``` 706 | 707 | * Delete Webhook using webhookId. 708 | 709 | ```js 710 | // Mandatory API parameters 711 | 712 | // Unique identifier for a webhook. 713 | let webhookId = 'a743___'; 714 | 715 | webhooksService.deleteWebhook({ webhook_id: webhookId }) 716 | .then(function(res) { console.log(JSON.stringify(res)); }) 717 | .catch(function(err) { console.log(JSON.stringify(err)); }); 718 | ``` 719 | 720 | * Verify webhook request signature. This can be used to validate if the webhook received at your end from OST platform is correctly signed. 721 | 722 | ```js 723 | // Webhook data obtained. 724 | webhookEventData = JSON.stringify({"id":"54e3cd1c-afd7-4dcf-9c78-137c56a53582","topic":"transactions/success","created_at":1560838772,"webhook_id":"0823a4ea-5d87-44cf-8ca8-1e5a31bf8e46","version":"v2","data":{"result_type":"transaction","transaction":{"id":"ddebe817-b94f-4b51-9227-f543fae4715a","transaction_hash":"0x7ee737db22b58dc4da3f4ea4830ca709b388d84f31e77106cb79ee09fc6448f9","from":"0x69a581096dbddf6d1e0fff7ebc1254bb7a2647c6","to":"0xc2f0dde92f6f3a3cb13bfff43e2bd136f7dcfe47","nonce":3,"value":"0","gas_price":"1000000000","gas_used":120558,"transaction_fee":"120558000000000","block_confirmation":24,"status":"SUCCESS","updated_timestamp":1560838699,"block_timestamp":1560838698,"block_number":1554246,"rule_name":"Pricer","meta_property":{},"transfers":[{"from":"0xc2f0dde92f6f3a3cb13bfff43e2bd136f7dcfe47","from_user_id":"acfdea7d-278e-4ffc-aacb-4a21398a280c","to":"0x0a754aaab96d634337aac6556312de396a0ca46a","to_user_id":"7bc8e0bd-6761-4604-8f8e-e33f86f81309","amount":"112325386","kind":"transfer"}]}}}); 725 | 726 | // Get webhoook version from webhook events data. 727 | version = "v2"; 728 | 729 | // Get ost-timestamp from the response received in event. 730 | requestTimestamp = '1559902637'; 731 | 732 | // Get signature from the response received in event. 733 | signature = '2c56c143550c603a6ff47054803f03ee4755c9c707986ae27f7ca1dd1c92a824'; 734 | 735 | stringifiedData = webhookEventData; 736 | webhookSecret = 'mySecret'; 737 | let resp = webhooksService.verifySignature(version, stringifiedData,requestTimestamp, signature, webhookSecret); 738 | console.log(resp); 739 | ``` 740 | 741 | ### Redemption Modules 742 | 743 | Two modules of redemption, "Redeemable SKUs" and "User Redemptions", are described below. 744 | 745 | #### Redeemable SKUs Module 746 | 747 | * Initialize Redeemable SKUs service object to perform redeemable skus specific actions. 748 | 749 | ```js 750 | const redeemableSkusService = ostObj.services.redeemable_skus; 751 | ``` 752 | * Get Redeemable SKU detail using the redeemable sku id. 753 | 754 | ```js 755 | // Mandatory API parameters 756 | 757 | // Fetch details of following redeemable sku. 758 | let redeemableSkuId = 'c2c__'; 759 | 760 | redeemableSkusService.get({ redeemable_sku_id: redeemableSkuId }) 761 | .then(function(res) { console.log(JSON.stringify(res)); }) 762 | .catch(function(err) { console.log(JSON.stringify(err)); }); 763 | ``` 764 | 765 | * Get Redeemable SKUs List. Pagination is supported by this API. 766 | 767 | ```js 768 | // Mandatory API parameters 769 | // NOTE: No mandatory parameters. 770 | 771 | // Optional API parameters 772 | 773 | // Limit. 774 | let limit = 10; 775 | 776 | // Array of redeemable SKU ids. 777 | let redeemableSkuIds = ['1001', '1002']; 778 | 779 | // Pagination identifier from the previous API call response. Not needed for page one. 780 | let paginationIdentifier = 'e77y___'; 781 | 782 | redeemableSkusService.getList({limit: limit, pagination_identifier: paginationIdentifier, redeemable_sku_ids: redeemableSkuIds }) 783 | .then(function(res) { console.log(JSON.stringify(res)); }) 784 | .catch(function(err) { console.log(JSON.stringify(err)); }); 785 | ``` 786 | 787 | #### User Redemptions Module 788 | 789 | * Initialize Redemptions service object to perform user redemption specific actions. 790 | 791 | ```js 792 | const redemptionsService = ostObj.services.redemptions; 793 | ``` 794 | 795 | * Get User redemption details using the userId and redemptionId. 796 | 797 | ```js 798 | // Mandatory API parameters 799 | 800 | // UserId of user for whom redemption details needs to be fetched. 801 | let userId = 'c2c__'; 802 | 803 | // Unique identifier of the redemption of user. 804 | let redemptionId = 'c2c__'; 805 | 806 | redemptionsService.get({ user_id: userId, redemption_id: redemptionId }) 807 | .then(function(res) { console.log(JSON.stringify(res)); }) 808 | .catch(function(err) { console.log(JSON.stringify(err)); }); 809 | ``` 810 | 811 | * Get User Redemptions List. Pagination is supported by this API. 812 | 813 | ```js 814 | // Mandatory API parameters 815 | let userId = 'c2c__'; 816 | 817 | // Optional API parameters 818 | 819 | // Limit. 820 | let limit = 10; 821 | 822 | // Array of user redemption uuids. 823 | let redemptionIds = ['a743___', 'a743___']; 824 | 825 | // Pagination identifier from the previous API call response. Not needed for page one. 826 | let paginationIdentifier = 'e77y___'; 827 | 828 | redemptionsService.getList({ user_id: userId, limit: limit, pagination_identifier: paginationIdentifier, redemption_ids: redemptionIds }) 829 | .then(function(res) { console.log(JSON.stringify(res)); }) 830 | .catch(function(err) { console.log(JSON.stringify(err)); }); 831 | ``` 832 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 2.2.3 2 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /** 4 | * OST Javascript SDK 5 | * 6 | * @module index 7 | */ 8 | 9 | const rootPrefix = "." 10 | , serviceManifestKlass = require(rootPrefix + '/services/manifest') 11 | ; 12 | 13 | const OSTSDK = function (params) { 14 | const oThis = this; 15 | 16 | params = params || {}; 17 | 18 | // Extract API major version 19 | const apiEndpointVersion = ((params.apiEndpoint || '').split("/")[4] || '').toLowerCase(); 20 | if (apiEndpointVersion =="v2"){ 21 | oThis.services = new serviceManifestKlass(params); 22 | } else{ 23 | throw new Error('Api endpoint is invalid'); 24 | } 25 | 26 | }; 27 | 28 | module.exports = OSTSDK; -------------------------------------------------------------------------------- /lib/request.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /** 4 | * Request Manager 5 | * 6 | * @module lib/request 7 | */ 8 | const queryString = require('qs') 9 | , crypto = require('crypto') 10 | , https = require('https') 11 | , http = require('http') 12 | , url = require('url') 13 | , API_SIGNATURE_KIND = "OST1-HMAC-SHA256" 14 | ; 15 | 16 | const rootPrefix = ".." 17 | , validate = require(rootPrefix + '/lib/validate') 18 | , version = require(rootPrefix + '/package.json').version 19 | , httpUserAgent = "ost-sdk-js " + version 20 | ; 21 | 22 | let DEBUG = ("true" === process.env.OST_SDK_DEBUG); 23 | 24 | /** 25 | * Generate query signature 26 | * @param {string} resource - API Resource 27 | * @param {object} queryParams - resource query parameters 28 | * @param {object} _apiCredentials - API credentials 29 | * 30 | * @return {string} - query parameters with signature 31 | * 32 | * @private @static 33 | */ 34 | function signQueryParams(resource, queryParams, _apiCredentials) { 35 | const buff = new Buffer.from(_apiCredentials.secret, 'utf8') 36 | , hmac = crypto.createHmac('sha256', buff); 37 | 38 | hmac.update(resource + "?" + queryParams); 39 | 40 | return queryParams + "&api_signature=" + hmac.digest('hex'); 41 | } 42 | 43 | /** 44 | * Request Manager constructor 45 | * 46 | * @param {object} params 47 | * @param {string} params.apiKey - api key 48 | * @param {string} params.apiSecret - api secret 49 | * @param {string} params.apiEndpoint - version specific api endpoint 50 | * @param {obj} params.config - configurations like timeout 51 | * 52 | * @constructor 53 | */ 54 | const RequestKlass = function (params) { 55 | const oThis = this 56 | , _apiCredentials = {} 57 | ; 58 | 59 | // Validate API key 60 | if (validate.isPresent(params.apiKey)) { 61 | _apiCredentials.key = params.apiKey; 62 | } else { 63 | throw new Error('Api key not present.'); 64 | } 65 | 66 | // Validate API secret 67 | if (validate.isPresent(params.apiSecret)) { 68 | _apiCredentials.secret = params.apiSecret; 69 | } else { 70 | throw new Error('Api secret not present.'); 71 | } 72 | 73 | oThis.apiEndpoint = params.apiEndpoint.replace(/\/$/, ""); 74 | var config = params.config || {}; 75 | oThis.timeOut = config.timeout * 1000 || 60000; 76 | 77 | oThis._formatQueryParams = function (resource, queryParams) { 78 | const oThis = this; 79 | 80 | queryParams.api_key = _apiCredentials.key; 81 | queryParams.api_request_timestamp = parseInt(Math.round((new Date()).getTime() / 1000)); 82 | queryParams.api_signature_kind = API_SIGNATURE_KIND; 83 | 84 | var formattedParams = oThis.formatQueryParams(queryParams); 85 | return signQueryParams(resource, formattedParams, _apiCredentials); 86 | } 87 | }; 88 | 89 | RequestKlass.prototype = { 90 | 91 | /** 92 | * Send get request 93 | * 94 | * @param {string} resource - API Resource 95 | * @param {object} queryParams - resource query parameters 96 | * 97 | * @public 98 | */ 99 | get: function (resource, queryParams) { 100 | const oThis = this; 101 | return oThis._send('GET', resource, queryParams); 102 | }, 103 | 104 | /** 105 | * Send post request 106 | * 107 | * @param {string} resource - API Resource 108 | * @param {object} queryParams - resource query parameters 109 | * 110 | * @public 111 | */ 112 | post: function (resource, queryParams) { 113 | const oThis = this; 114 | return oThis._send('POST', resource, queryParams); 115 | }, 116 | 117 | /** 118 | * Send delete request 119 | * 120 | * @param {string} resource - API Resource 121 | * @param {object} queryParams - resource query parameters 122 | * 123 | * @public 124 | */ 125 | deleteRequest: function (resource, queryParams) { 126 | const oThis = this; 127 | return oThis._send('DELETE', resource, queryParams); 128 | }, 129 | 130 | /** 131 | * Get formatted query params 132 | * 133 | * @param {string} resource - API Resource 134 | * @param {object} queryParams - resource query parameters 135 | * 136 | * @return {string} - query parameters with signature 137 | * 138 | * @private 139 | */ 140 | _formatQueryParams: function (resource, queryParams) { 141 | /** 142 | Note: This is just an empty function body. 143 | The Actual code has been moved to constructor. 144 | Modifying prototype._formatQueryParams will not have any impact. 145 | **/ 146 | }, 147 | 148 | /** 149 | * Get parsed URL 150 | * 151 | * @param {string} resource - API Resource 152 | * 153 | * @return {object} - parsed url object 154 | * 155 | * @private 156 | */ 157 | _parseURL: function (resource) { 158 | const oThis = this; 159 | 160 | return url.parse(oThis.apiEndpoint + resource); 161 | }, 162 | 163 | /** 164 | * Send request 165 | * 166 | * @param {string} requestType - API request type 167 | * @param {string} resource - API Resource 168 | * @param {object} queryParams - resource query parameters 169 | * @private 170 | */ 171 | _send: function (requestType, resource, queryParams) { 172 | const oThis = this 173 | , parsedURL = oThis._parseURL(resource) 174 | , requestData = oThis._formatQueryParams(resource, queryParams); 175 | 176 | const options = { 177 | host: parsedURL.hostname, 178 | port: parsedURL.port, 179 | path: parsedURL.path, 180 | method: requestType, 181 | headers: { 182 | 'Content-Type': 'application/x-www-form-urlencoded', 183 | 'User-Agent': httpUserAgent 184 | } 185 | }; 186 | 187 | if (requestType === 'GET' && validate.isPresent(requestData)) { 188 | options.path = options.path + "?" + requestData; 189 | } 190 | 191 | if (requestType === 'DELETE' && validate.isPresent(requestData)) { 192 | options.path = options.path + "?" + requestData; 193 | } 194 | 195 | if (DEBUG) { 196 | console.log("------------------------------"); 197 | console.log("request OPTIONS \n", JSON.stringify(options)); 198 | console.log("requestData \n", requestData); 199 | } 200 | return new Promise(async function (onResolve, onReject) { 201 | var chunkedResponseData = ''; 202 | 203 | var request = (parsedURL.protocol === 'https:' ? https : http).request(options, function (response) { 204 | 205 | response.setEncoding('utf8'); 206 | 207 | response.on('data', function (chunk) { 208 | chunkedResponseData += chunk; 209 | }); 210 | 211 | response.on('end', function () { 212 | var parsedResponse = oThis._parseResponse(chunkedResponseData, response); 213 | if (DEBUG) { 214 | console.log("parsedResponse \n", JSON.stringify(parsedResponse)); 215 | console.log("------------------------------"); 216 | } 217 | 218 | if (parsedResponse.success) { 219 | onResolve(parsedResponse); 220 | } else { 221 | onReject(parsedResponse); 222 | } 223 | }); 224 | 225 | }); 226 | 227 | request.on('socket', function (socket) { 228 | socket.setTimeout(oThis.timeOut); 229 | socket.on('timeout', function (e) { 230 | onReject({ 231 | "success": false, 232 | "err": {"code": "GATEWAY_TIMEOUT", "internal_id": "TIMEOUT_ERROR", "msg": "", "error_data": []} 233 | }); 234 | }); 235 | }); 236 | 237 | request.on('error', function (e) { 238 | 239 | console.error('OST-SDK: Request error'); 240 | console.error(e); 241 | var parsedResponse = oThis._parseResponse(e); 242 | if (parsedResponse.success) { 243 | onResolve(parsedResponse); 244 | } else { 245 | onReject(parsedResponse); 246 | } 247 | 248 | }); 249 | 250 | // Write data to server 251 | if (requestType === 'POST' && validate.isPresent(requestData)) { 252 | request.write(requestData); 253 | } 254 | 255 | request.end(); 256 | }); 257 | }, 258 | 259 | /** 260 | * Parse response. 261 | * 262 | * @param {string} responseData - Response data 263 | * @param {object} response - Response object 264 | * @private 265 | */ 266 | _parseResponse: function (responseData, response) { 267 | 268 | if (!validate.isPresent(responseData) || (response || {}).statusCode != 200) { 269 | switch ((response || {}).statusCode) { 270 | case 400: 271 | responseData = responseData || '{"success": false, "err": {"code": "BAD_REQUEST", "internal_id": "SDK(BAD_REQUEST)", "msg": "", "error_data":[]}}'; 272 | break; 273 | case 429: 274 | responseData = responseData || '{"success": false, "err": {"code": "TOO_MANY_REQUESTS", "internal_id": "SDK(TOO_MANY_REQUESTS)", "msg": "", "error_data":[]}}'; 275 | break; 276 | case 502: 277 | responseData = responseData || '{"success": false, "err": {"code": "BAD_GATEWAY", "internal_id": "SDK(BAD_GATEWAY)", "msg": "", "error_data":[]}}'; 278 | break; 279 | case 503: 280 | responseData = responseData || '{"success": false, "err": {"code": "SERVICE_UNAVAILABLE", "internal_id": "SDK(SERVICE_UNAVAILABLE)", "msg": "", "error_data":[]}}'; 281 | break; 282 | case 504: 283 | responseData = responseData || '{"success": false, "err": {"code": "GATEWAY_TIMEOUT", "internal_id": "SDK(GATEWAY_TIMEOUT)", "msg": "", "error_data":[]}}'; 284 | break; 285 | default: 286 | responseData = responseData || '{"success": false, "err": {"code": "SOMETHING_WENT_WRONG", "internal_id": "SDK(SOMETHING_WENT_WRONG)", "msg": "", "error_data":[]}}'; 287 | } 288 | } 289 | 290 | try { 291 | var parsedResponse = JSON.parse(responseData); 292 | } catch (e) { 293 | //console.error('OST-SDK: Response parsing error'); 294 | console.error(e); 295 | var parsedResponse = { 296 | "success": false, 297 | "err": { 298 | "code": "SOMETHING_WENT_WRONG", 299 | "internal_id": "SDK(SOMETHING_WENT_WRONG)", 300 | "msg": "Response parsing error", 301 | "error_data": [] 302 | } 303 | }; 304 | } 305 | 306 | return parsedResponse; 307 | }, 308 | 309 | /** 310 | * Sign query params for testing. 311 | * 312 | * @param {string} resource - url endpoint 313 | * @param {object} queryParams - query params 314 | * @param {object} _apiCredentials - credentail 315 | * @private 316 | */ 317 | signQueryParamsTest: function (resource, queryParams, _apiCredentials) { 318 | return signQueryParams(resource, queryParams, _apiCredentials) 319 | }, 320 | 321 | /** 322 | * Format query params. 323 | * 324 | * @param {object} queryParams - query params 325 | * @private 326 | */ 327 | formatQueryParams: function (queryParams) { 328 | return queryString.stringify(queryParams, { 329 | arrayFormat: 'brackets', sort: function (a, b) { 330 | return a.localeCompare(b); 331 | } 332 | }).replace(/%20/g, '+'); 333 | } 334 | 335 | }; 336 | 337 | module.exports = RequestKlass; -------------------------------------------------------------------------------- /lib/validate.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | /** 3 | * Module to validate parameters. 4 | * 5 | * @module lib/validate 6 | */ 7 | 8 | /** 9 | * Validate parameters constructor 10 | * 11 | * @constructor 12 | */ 13 | const ValidateKlass = function () { 14 | }; 15 | 16 | ValidateKlass.prototype = { 17 | 18 | /** 19 | * Check if parameter is present 20 | * 21 | * @param {string} param - parameter value 22 | * 23 | * @public 24 | */ 25 | isPresent: function (param) { 26 | return (typeof param !== 'undefined' && param !== null && String(param).trim() !== ''); 27 | }, 28 | 29 | /** 30 | * Check if parameter is valid. 31 | * 32 | * @param {string} param - parameter value 33 | * @public 34 | */ 35 | isValid: function (param) { 36 | const oThis = this, 37 | regex = /^[a-zA-Z0-9_\.\-]+$/; 38 | return oThis.isPresent(param) && String(param).match(regex); 39 | }, 40 | 41 | /** 42 | * Get id from params. 43 | * 44 | * @param {object} params 45 | */ 46 | getId: function (params) { 47 | const oThis = this; 48 | if (oThis.isValid(params.id)) { 49 | var id = params.id; 50 | delete params.id; 51 | return id; 52 | } else { 53 | throw new Error('id missing or invalid in request params'); 54 | } 55 | }, 56 | 57 | 58 | /** 59 | * Get user id from params. 60 | * 61 | * @param {object} params 62 | */ 63 | getUserId: function (params) { 64 | const oThis = this; 65 | if (oThis.isValid(params.user_id)) { 66 | var userId = params.user_id; 67 | delete params.user_id; 68 | return userId 69 | } else { 70 | throw new Error('user_id missing or invalid in request params'); 71 | } 72 | }, 73 | 74 | /** 75 | * Get redeemable sku id from params. 76 | * 77 | * @param {object} params 78 | * @param {string} params.redeemable_sku_id 79 | */ 80 | getRedeemableSkuId: function (params) { 81 | const oThis = this; 82 | if (oThis.isValid(params.redeemable_sku_id)) { 83 | var redeemableSkuId = params.redeemable_sku_id; 84 | delete params.redeemable_sku_id; 85 | return redeemableSkuId 86 | } else { 87 | throw new Error('redeemable_sku_id missing or invalid in request params'); 88 | } 89 | }, 90 | 91 | /** 92 | * Get redemption uid from params. 93 | * 94 | * @param {object} params 95 | * @param {string} params.redemption_id 96 | */ 97 | getRedemptionId: function (params) { 98 | const oThis = this; 99 | if (oThis.isValid(params.redemption_id)) { 100 | let redemption_id = params.redemption_id; 101 | delete params.redemption_id; 102 | return redemption_id 103 | } else { 104 | throw new Error('redemption_id missing or invalid in request params.'); 105 | } 106 | }, 107 | 108 | 109 | /** 110 | * Get webhook id from params. 111 | * 112 | * @param {object} params 113 | */ 114 | getWebhookId: function (params) { 115 | const oThis = this; 116 | if (oThis.isValid(params.webhook_id)) { 117 | let webhookId = params.webhook_id; 118 | return webhookId 119 | } else { 120 | throw new Error('webhook_id missing or invalid in request params'); 121 | } 122 | }, 123 | 124 | /** 125 | * Get chain id from params 126 | * 127 | * @param {object} params 128 | */ 129 | getChainId: function (params) { 130 | const oThis = this; 131 | if (oThis.isValid(params.chain_id)) { 132 | var chainId = params.chain_id; 133 | delete params.chain_id; 134 | return chainId 135 | } else { 136 | throw new Error('chain_id missing or invalid in request params'); 137 | } 138 | }, 139 | 140 | /** 141 | * Get device address from params 142 | * 143 | * @param {object} params 144 | */ 145 | getDeviceAddress: function (params) { 146 | const oThis = this; 147 | if (oThis.isValid(params.device_address)) { 148 | var deviceAddress = params.device_address; 149 | delete params.device_address; 150 | return deviceAddress; 151 | } else { 152 | throw new Error('device_address missing or invalid in request params'); 153 | } 154 | }, 155 | 156 | /** 157 | * Get session address from params 158 | * 159 | * @param {object} params 160 | */ 161 | getSessionAddress: function (params) { 162 | const oThis = this; 163 | if (oThis.isValid(params.session_address)) { 164 | var sessionAddress = params.session_address; 165 | delete params.session_address; 166 | return sessionAddress; 167 | } else { 168 | throw new Error('session_address missing or invalid in request params'); 169 | } 170 | }, 171 | 172 | /** 173 | * Get transaction id from params 174 | * 175 | * @param {object} params 176 | */ 177 | getTransactionId: function (params) { 178 | const oThis = this; 179 | if (oThis.isValid(params.transaction_id)) { 180 | var TxAddress = params.transaction_id; 181 | delete params.transaction_id; 182 | return TxAddress; 183 | } else { 184 | throw new Error('transaction_id missing or invalid in request params'); 185 | } 186 | }, 187 | 188 | /** 189 | * Get recovery owner address from params 190 | * 191 | * @param {object} params 192 | */ 193 | getRecoveryOwnerAddress: function (params) { 194 | const oThis = this; 195 | if (oThis.isValid(params.recovery_owner_address)) { 196 | 197 | var RecoveryAddress = params.recovery_owner_address; 198 | delete params.recovery_owner_address; 199 | return RecoveryAddress; 200 | } else { 201 | throw new Error('recovery_owner_address missing or invalid in request params'); 202 | } 203 | } 204 | 205 | }; 206 | 207 | module.exports = new ValidateKlass(); 208 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@ostdotcom/ost-sdk-js", 3 | "version": "2.2.3", 4 | "description": "OST Platform SDK for JavaScript.", 5 | "main": "index.js", 6 | "scripts": { 7 | "start": "index.js" 8 | }, 9 | "keywords": [ 10 | "OST", 11 | "JavaScript", 12 | "Node.js", 13 | "SDK", 14 | "SimpleToken", 15 | "OpenST" 16 | ], 17 | "homepage": "https://ost.com", 18 | "author": "OST.com Inc.", 19 | "license": "MIT", 20 | "repository": { 21 | "type": "git", 22 | "url": "https://github.com/ostdotcom/ost-sdk-js.git" 23 | }, 24 | "bugs": { 25 | "url": "https://github.com/ostdotcom/ost-sdk-js/issues" 26 | }, 27 | "dependencies": { 28 | "qs": "6.6.0" 29 | }, 30 | "devDependencies": { 31 | "chai": "4.1.2", 32 | "ink-docstrap": "1.3.2", 33 | "mocha": "5.0.0", 34 | "bignumber.js": "6.0.0" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /services/balance.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Balance Service 3 | * 4 | * @module services/balance 5 | */ 6 | 7 | const rootPrefix = ".." 8 | , validate = require(rootPrefix + '/lib/validate') 9 | ; 10 | 11 | // hide request object 12 | var _requestObj = null; 13 | 14 | /** 15 | * balance service 16 | * 17 | * @constructor 18 | */ 19 | const balance = function (requestObj) { 20 | const oThis = this; 21 | 22 | // Assign request object 23 | _requestObj = requestObj; 24 | 25 | // Define the url prefix 26 | oThis.urlPrefix = '/users'; 27 | oThis.urlSufix = '/balance'; 28 | 29 | return oThis; 30 | }; 31 | 32 | balance.prototype = { 33 | 34 | 35 | /** 36 | * Get balance 37 | * 38 | * @param {object} params 39 | * 40 | * @public 41 | */ 42 | get: function (params) { 43 | const oThis = this; 44 | var params = params || {}; 45 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getUserId(params) + oThis.urlSufix, params); 46 | }, 47 | 48 | }; 49 | 50 | module.exports = balance; -------------------------------------------------------------------------------- /services/base_tokens.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /** 4 | * Base Tokens Service 5 | * 6 | * @module /services/base_tokens 7 | */ 8 | 9 | // Hide request object 10 | var _requestObj = null; 11 | 12 | /** 13 | * Base tokens service constructor. 14 | * 15 | * @constructor 16 | */ 17 | const baseTokens = function (requestObj) { 18 | const oThis = this; 19 | 20 | // Assign request object 21 | _requestObj = requestObj; 22 | 23 | // Define the url prefix 24 | oThis.urlPrefix = '/base-tokens'; 25 | 26 | return oThis; 27 | }; 28 | 29 | baseTokens.prototype = { 30 | 31 | /** 32 | * Get base tokens details. 33 | * 34 | * @param {object} params 35 | * 36 | * @public 37 | */ 38 | get: function (params) { 39 | const oThis = this; 40 | params = params || {}; 41 | 42 | return _requestObj.get(oThis.urlPrefix, params); 43 | } 44 | 45 | }; 46 | 47 | module.exports = baseTokens; -------------------------------------------------------------------------------- /services/chains.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Chains Service 3 | * 4 | * @module services/chains 5 | */ 6 | 7 | const rootPrefix = ".." 8 | , validate = require(rootPrefix + '/lib/validate') 9 | ; 10 | 11 | // hide request object 12 | var _requestObj = null; 13 | 14 | /** 15 | * Chains Service constructor 16 | * 17 | * @constructor 18 | */ 19 | const chains = function (requestObj) { 20 | const oThis = this; 21 | 22 | // Assign request object 23 | _requestObj = requestObj; 24 | 25 | // Define the url prefix 26 | oThis.urlPrefix = '/chains'; 27 | 28 | return oThis; 29 | }; 30 | 31 | chains.prototype = { 32 | 33 | /** 34 | * Get chains details 35 | * 36 | * @param {object} params 37 | * 38 | * @public 39 | */ 40 | get: function (params) { 41 | const oThis = this; 42 | params = params || {}; 43 | 44 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getChainId(params), params); 45 | } 46 | }; 47 | 48 | module.exports = chains; -------------------------------------------------------------------------------- /services/device_managers.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Devices Managers Service 3 | * 4 | * @module services/device_managers 5 | */ 6 | 7 | const rootPrefix = ".." 8 | , validate = require(rootPrefix + '/lib/validate') 9 | ; 10 | 11 | // hide request object 12 | var _requestObj = null; 13 | 14 | /** 15 | * Device Managers Service constructor 16 | * 17 | * @constructor 18 | */ 19 | const device_managers = function (requestObj) { 20 | const oThis = this; 21 | 22 | // Assign request object 23 | _requestObj = requestObj; 24 | 25 | // Define the url prefix 26 | oThis.urlPrefix = '/users'; 27 | oThis.urlSuffix = '/device-managers'; 28 | 29 | return oThis; 30 | }; 31 | 32 | device_managers.prototype = { 33 | 34 | 35 | /** 36 | * Get a device managers 37 | * 38 | * @param {object} params 39 | * 40 | * @public 41 | */ 42 | get: function (params) { 43 | const oThis = this; 44 | var params = params || {}; 45 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getUserId(params) + oThis.urlSuffix, params); 46 | }, 47 | 48 | }; 49 | 50 | module.exports = device_managers; -------------------------------------------------------------------------------- /services/devices.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Devices Service 3 | * 4 | * @module services/devices 5 | */ 6 | 7 | const rootPrefix = ".." 8 | , validate = require(rootPrefix + '/lib/validate') 9 | ; 10 | 11 | // hide request object 12 | var _requestObj = null; 13 | 14 | /** 15 | * Devices Service constructor 16 | * 17 | * @constructor 18 | */ 19 | const devices = function (requestObj) { 20 | const oThis = this; 21 | 22 | // Assign request object 23 | _requestObj = requestObj; 24 | 25 | // Define the url prefix 26 | oThis.urlPrefix = '/users'; 27 | oThis.urlSuffix = '/devices'; 28 | 29 | return oThis; 30 | }; 31 | 32 | devices.prototype = { 33 | 34 | 35 | /** 36 | * Create 37 | * 38 | * @param {object} params 39 | * 40 | * @public 41 | */ 42 | create: function (params) { 43 | const oThis = this; 44 | var params = params || {}; 45 | return _requestObj.post(oThis.urlPrefix + "/" + validate.getUserId(params) + oThis.urlSuffix, params); 46 | }, 47 | 48 | /** 49 | * Get List of devices for user 50 | * 51 | * @param {object} params 52 | * 53 | * @public 54 | */ 55 | getList: function (params) { 56 | const oThis = this; 57 | var params = params || {}; 58 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getUserId(params) + oThis.urlSuffix, params); 59 | }, 60 | 61 | 62 | /** 63 | * Get a devices 64 | * 65 | * @param {object} params 66 | * 67 | * @public 68 | */ 69 | get: function (params) { 70 | const oThis = this; 71 | var params = params || {}; 72 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getUserId(params) + oThis.urlSuffix + 73 | "/" + validate.getDeviceAddress(params), params); 74 | }, 75 | 76 | }; 77 | 78 | module.exports = devices; -------------------------------------------------------------------------------- /services/manifest.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /** 4 | * Service Manifest 5 | * 6 | * @module services/manifest 7 | */ 8 | 9 | const rootPrefix = ".." 10 | , requestKlass = require(rootPrefix + '/lib/request') 11 | , chainsKlass = require(rootPrefix + '/services/chains') 12 | , devicesKlass = require(rootPrefix + '/services/devices') 13 | , pricePointsKlass = require(rootPrefix + '/services/price_points') 14 | , sessionsKlass = require(rootPrefix + '/services/sessions') 15 | , tokensKlass = require(rootPrefix + '/services/tokens') 16 | , usersKlass = require(rootPrefix + '/services/users') 17 | , balanceKlass = require(rootPrefix + '/services/balance') 18 | , deviceManagersKlass = require(rootPrefix + '/services/device_managers') 19 | , recoveryOwnersKlass = require(rootPrefix + '/services/recovery_owners') 20 | , rulesKlass = require(rootPrefix + '/services/rules') 21 | , transactionsKlass = require(rootPrefix + '/services/transactions') 22 | , baseTokensKlass = require(rootPrefix + '/services/base_tokens') 23 | , webhooksKlass = require(rootPrefix + '/services/webhooks') 24 | , redemptionsKlass = require(rootPrefix + '/services/redemptions') 25 | , redeemableSkusKlass = require(rootPrefix + '/services/redeemable_skus') 26 | ; 27 | 28 | // hide request object 29 | var _requestObj = null; 30 | 31 | /** 32 | * Service manifest constructor 33 | * 34 | * @constructor 35 | */ 36 | const manifest = function (params) { 37 | const oThis = this; 38 | 39 | // Create request object 40 | _requestObj = new requestKlass(params); 41 | 42 | // Define services 43 | oThis.chains = new chainsKlass(_requestObj); 44 | oThis.devices = new devicesKlass(_requestObj); 45 | oThis.price_points = new pricePointsKlass(_requestObj); 46 | oThis.sessions = new sessionsKlass(_requestObj); 47 | oThis.tokens = new tokensKlass(_requestObj); 48 | oThis.users = new usersKlass(_requestObj); 49 | oThis.balance = new balanceKlass(_requestObj); 50 | oThis.device_managers = new deviceManagersKlass(_requestObj); 51 | oThis.recovery_owners = new recoveryOwnersKlass(_requestObj); 52 | oThis.rules = new rulesKlass(_requestObj); 53 | oThis.transactions = new transactionsKlass(_requestObj); 54 | oThis.base_tokens = new baseTokensKlass(_requestObj); 55 | oThis.webhooks = new webhooksKlass(_requestObj); 56 | oThis.redemptions = new redemptionsKlass(_requestObj); 57 | oThis.redeemable_skus = new redeemableSkusKlass(_requestObj); 58 | 59 | return oThis; 60 | }; 61 | 62 | manifest.prototype = { 63 | 64 | chains: null, 65 | 66 | devices: null, 67 | 68 | price_points: null, 69 | 70 | sessions: null, 71 | 72 | tokens: null, 73 | 74 | users: null, 75 | 76 | balance: null, 77 | 78 | device_managers: null, 79 | 80 | recovery_owners: null, 81 | 82 | rules: null, 83 | 84 | transactions: null, 85 | 86 | base_tokens: null, 87 | 88 | webhooks: null, 89 | 90 | redemptions: null, 91 | 92 | redeemable_skus: null, 93 | }; 94 | 95 | module.exports = manifest; 96 | -------------------------------------------------------------------------------- /services/price_points.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /** 4 | * Price Points Service 5 | * 6 | * @module services/price_points 7 | */ 8 | 9 | const rootPrefix = ".." 10 | , validate = require(rootPrefix + '/lib/validate') 11 | ; 12 | 13 | // hide request object 14 | var _requestObj = null; 15 | 16 | /** 17 | * Price Points Service constructor 18 | * 19 | * @constructor 20 | */ 21 | const pricePoints = function (requestObj) { 22 | const oThis = this; 23 | 24 | // Assign request object 25 | _requestObj = requestObj; 26 | 27 | // Define the url prefix 28 | oThis.urlPrefix = '/chains'; 29 | oThis.urlSuffix = '/price-points'; 30 | 31 | return oThis; 32 | }; 33 | 34 | pricePoints.prototype = { 35 | 36 | /** 37 | * Get pricePoints details 38 | * 39 | * @param {object} params 40 | * 41 | * @public 42 | */ 43 | get: function (params) { 44 | const oThis = this; 45 | params = params || {}; 46 | 47 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getChainId(params) + oThis.urlSuffix, params); 48 | } 49 | 50 | }; 51 | 52 | module.exports = pricePoints; -------------------------------------------------------------------------------- /services/recovery_owners.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Recovery Owners Service 3 | * 4 | * @module services/recovery_owners 5 | */ 6 | 7 | const rootPrefix = ".." 8 | , validate = require(rootPrefix + '/lib/validate') 9 | ; 10 | 11 | // hide request object 12 | var _requestObj = null; 13 | 14 | /** 15 | * Recovery Owners service 16 | * 17 | * @constructor 18 | */ 19 | const recovery_owners = function (requestObj) { 20 | const oThis = this; 21 | 22 | // Assign request object 23 | _requestObj = requestObj; 24 | 25 | // Define the url prefix 26 | oThis.urlPrefix = '/users'; 27 | oThis.urlSufix = '/recovery-owners'; 28 | 29 | return oThis; 30 | }; 31 | 32 | recovery_owners.prototype = { 33 | 34 | 35 | /** 36 | * Get recovery_owners 37 | * 38 | * @param {object} params 39 | * 40 | * @public 41 | */ 42 | get: function (params) { 43 | const oThis = this; 44 | var params = params || {}; 45 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getUserId(params) + oThis.urlSufix + 46 | "/" + validate.getRecoveryOwnerAddress(params), params); 47 | }, 48 | }; 49 | 50 | module.exports = recovery_owners; -------------------------------------------------------------------------------- /services/redeemable_skus.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /** 4 | * Redeemable SKUs Service 5 | * 6 | * @module services/redeemable_skus 7 | */ 8 | 9 | const rootPrefix = ".." 10 | , validate = require(rootPrefix + '/lib/validate') 11 | ; 12 | 13 | // hide request object 14 | var _requestObj = null; 15 | 16 | /** 17 | * Redeemable SKUs Service constructor. 18 | * 19 | * @constructor 20 | */ 21 | const redeemable_skus = function (requestObj) { 22 | const oThis = this; 23 | 24 | // Assign request object. 25 | _requestObj = requestObj; 26 | 27 | // Define the url prefix. 28 | oThis.urlPrefix = '/redeemable-skus'; 29 | 30 | return oThis; 31 | }; 32 | 33 | redeemable_skus.prototype = { 34 | /** 35 | * Get redeemable skus list. 36 | * 37 | * @param {object} params 38 | * 39 | * @returns {*} 40 | */ 41 | getList: function(params) { 42 | const oThis = this; 43 | 44 | params = params || {}; 45 | 46 | return _requestObj.get(oThis.urlPrefix, params); 47 | }, 48 | 49 | /** 50 | * Get redeemable sku by redeemable sku id. 51 | * 52 | * @param {object} params 53 | * 54 | * @returns {*} 55 | */ 56 | get: function(params) { 57 | const oThis = this; 58 | 59 | params = params || {}; 60 | 61 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getRedeemableSkuId(params), params); 62 | } 63 | 64 | }; 65 | 66 | module.exports = redeemable_skus; 67 | -------------------------------------------------------------------------------- /services/redemptions.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /** 4 | * Redemptions Service 5 | * 6 | * @module services/redemptions 7 | */ 8 | 9 | const rootPrefix = ".." 10 | , validate = require(rootPrefix + '/lib/validate') 11 | ; 12 | 13 | // hide request object 14 | var _requestObj = null; 15 | 16 | /** 17 | * Redemptions Service constructor 18 | * 19 | * @constructor 20 | */ 21 | const redemptions = function (requestObj) { 22 | const oThis = this; 23 | 24 | // Assign request object 25 | _requestObj = requestObj; 26 | 27 | // Define the url prefix 28 | oThis.urlPrefix = '/users'; 29 | oThis.redemptionsUrlPrefix = '/redemptions'; 30 | 31 | return oThis; 32 | }; 33 | 34 | redemptions.prototype = { 35 | /** 36 | * Get user redemptions list. 37 | * 38 | * @param {object} params 39 | * 40 | * @returns {*} 41 | */ 42 | getList: function(params) { 43 | const oThis = this; 44 | 45 | params = params || {}; 46 | 47 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getUserId(params) + oThis.redemptionsUrlPrefix, params); 48 | }, 49 | 50 | /** 51 | * Get user redemption by redemption id. 52 | * 53 | * @param {object} params 54 | * 55 | * @returns {*} 56 | */ 57 | get: function(params) { 58 | const oThis = this; 59 | 60 | params = params || {}; 61 | 62 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getUserId(params) + oThis.redemptionsUrlPrefix + '/' + validate.getRedemptionId(params), params); 63 | } 64 | 65 | }; 66 | 67 | module.exports = redemptions; 68 | -------------------------------------------------------------------------------- /services/rules.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Rules Service 3 | * 4 | * @module services/rules 5 | */ 6 | 7 | const rootPrefix = ".." 8 | , validate = require(rootPrefix + '/lib/validate') 9 | ; 10 | 11 | // hide request object 12 | var _requestObj = null; 13 | 14 | /** 15 | * rules service 16 | * 17 | * @constructor 18 | */ 19 | const rules = function (requestObj) { 20 | const oThis = this; 21 | 22 | // Assign request object 23 | _requestObj = requestObj; 24 | 25 | // Define the url prefix 26 | oThis.urlPrefix = '/rules'; 27 | 28 | return oThis; 29 | }; 30 | 31 | rules.prototype = { 32 | 33 | 34 | /** 35 | * Get rules 36 | * 37 | * @param {object} params 38 | * 39 | * @public 40 | */ 41 | getList: function (params) { 42 | const oThis = this; 43 | var params = params || {}; 44 | return _requestObj.get(oThis.urlPrefix, params); 45 | }, 46 | 47 | }; 48 | 49 | module.exports = rules; -------------------------------------------------------------------------------- /services/sessions.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Sessions Service 3 | * 4 | * @module services/sessions 5 | */ 6 | 7 | const rootPrefix = ".." 8 | , validate = require(rootPrefix + '/lib/validate') 9 | ; 10 | 11 | // hide request object 12 | var _requestObj = null; 13 | 14 | /** 15 | * Sessions Service constructor 16 | * 17 | * @constructor 18 | */ 19 | const sessions = function (requestObj) { 20 | const oThis = this; 21 | 22 | // Assign request object 23 | _requestObj = requestObj; 24 | 25 | // Define the url prefix 26 | oThis.urlPrefix = '/users'; 27 | oThis.urlSuffix = '/sessions'; 28 | 29 | return oThis; 30 | }; 31 | 32 | sessions.prototype = { 33 | 34 | 35 | /** 36 | * Get List of sessions for user 37 | * 38 | * @param {object} params 39 | * 40 | * @public 41 | */ 42 | getList: function (params) { 43 | const oThis = this; 44 | var params = params || {}; 45 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getUserId(params) + oThis.urlSuffix, params); 46 | }, 47 | 48 | 49 | /** 50 | * Get a session 51 | * 52 | * @param {object} params 53 | * 54 | * @public 55 | */ 56 | get: function (params) { 57 | const oThis = this; 58 | var params = params || {}; 59 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getUserId(params) + oThis.urlSuffix + 60 | "/" + validate.getSessionAddress(params), params); 61 | }, 62 | 63 | }; 64 | 65 | module.exports = sessions; -------------------------------------------------------------------------------- /services/tokens.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /** 4 | * Token Service 5 | * 6 | * @module services/tokens 7 | */ 8 | 9 | const rootPrefix = ".." 10 | ; 11 | 12 | // hide request object 13 | var _requestObj = null; 14 | 15 | /** 16 | * tokens Service constructor 17 | * 18 | * @constructor 19 | */ 20 | const tokens = function (requestObj) { 21 | const oThis = this; 22 | 23 | // Assign request object 24 | _requestObj = requestObj; 25 | 26 | // Define the url prefix 27 | oThis.urlPrefix = '/tokens'; 28 | 29 | return oThis; 30 | }; 31 | 32 | tokens.prototype = { 33 | 34 | /** 35 | * Get token details 36 | * 37 | * @param {object} params 38 | * 39 | * @public 40 | */ 41 | get: function (params) { 42 | const oThis = this; 43 | params = params || {}; 44 | 45 | return _requestObj.get(oThis.urlPrefix, params); 46 | } 47 | 48 | }; 49 | 50 | module.exports = tokens; -------------------------------------------------------------------------------- /services/transactions.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Transactions Service 3 | * 4 | * @module services/transactions 5 | */ 6 | 7 | const rootPrefix = ".." 8 | , validate = require(rootPrefix + '/lib/validate') 9 | ; 10 | 11 | // hide request object 12 | var _requestObj = null; 13 | 14 | /** 15 | * Transactions Service constructor 16 | * 17 | * @constructor 18 | */ 19 | const transactions = function (requestObj) { 20 | const oThis = this; 21 | 22 | // Assign request object 23 | _requestObj = requestObj; 24 | 25 | // Define the url prefix 26 | oThis.urlPrefix = '/users'; 27 | oThis.urlSuffix = '/transactions'; 28 | 29 | return oThis; 30 | }; 31 | 32 | transactions.prototype = { 33 | 34 | 35 | /** 36 | * execute company to user transaction 37 | * 38 | * @param {object} params 39 | * 40 | * @public 41 | */ 42 | execute: function (params) { 43 | const oThis = this; 44 | var params = params || {}; 45 | return _requestObj.post(oThis.urlPrefix + "/" + validate.getUserId(params) + oThis.urlSuffix, params); 46 | }, 47 | 48 | /** 49 | * Get List of transactions for user 50 | * 51 | * @param {object} params 52 | * 53 | * @public 54 | */ 55 | getList: function (params) { 56 | const oThis = this; 57 | var params = params || {}; 58 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getUserId(params) + oThis.urlSuffix, params); 59 | }, 60 | 61 | 62 | /** 63 | * Get a transaction 64 | * 65 | * @param {object} params 66 | * 67 | * @public 68 | */ 69 | get: function (params) { 70 | const oThis = this; 71 | var params = params || {}; 72 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getUserId(params) + oThis.urlSuffix + 73 | "/" + validate.getTransactionId(params), params); 74 | }, 75 | 76 | }; 77 | 78 | module.exports = transactions; -------------------------------------------------------------------------------- /services/users.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /** 4 | * Users Service 5 | * 6 | * @module services/users 7 | */ 8 | 9 | const rootPrefix = ".." 10 | , validate = require(rootPrefix + '/lib/validate') 11 | ; 12 | 13 | // hide request object 14 | var _requestObj = null; 15 | 16 | /** 17 | * Users Service constructor 18 | * 19 | * @constructor 20 | */ 21 | const users = function (requestObj) { 22 | const oThis = this; 23 | 24 | // Assign request object 25 | _requestObj = requestObj; 26 | 27 | // Define the url prefix 28 | oThis.urlPrefix = '/users'; 29 | oThis.redemptionsUrlPrefix = '/redemptions'; 30 | 31 | return oThis; 32 | }; 33 | 34 | users.prototype = { 35 | 36 | /** 37 | * Create 38 | * 39 | * @param {object} params 40 | * 41 | * @public 42 | */ 43 | create: function (params) { 44 | const oThis = this; 45 | params = params || {}; 46 | return _requestObj.post(oThis.urlPrefix, params); 47 | }, 48 | 49 | /** 50 | * List 51 | * 52 | * @param {object} params 53 | * 54 | * @public 55 | */ 56 | getList: function (params) { 57 | const oThis = this; 58 | params = params || {}; 59 | 60 | return _requestObj.get(oThis.urlPrefix, params); 61 | }, 62 | 63 | /** 64 | * Get user details 65 | * 66 | * @param {object} params 67 | * 68 | * @public 69 | */ 70 | get: function (params) { 71 | const oThis = this; 72 | params = params || {}; 73 | 74 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getUserId(params), params); 75 | } 76 | }; 77 | 78 | module.exports = users; 79 | -------------------------------------------------------------------------------- /services/webhooks.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /** 4 | * Webhooks service. 5 | * 6 | * @module services/webhooks 7 | */ 8 | const crypto = require('crypto'); 9 | 10 | const rootPrefix = ".." 11 | , validate = require(rootPrefix + '/lib/validate') 12 | ; 13 | 14 | // Hide request object. 15 | let _requestObj = null; 16 | 17 | /** 18 | * Webhooks service constructor. 19 | * 20 | * @constructor 21 | */ 22 | const webhooks = function (requestObj, webhookSecret) { 23 | const oThis = this; 24 | 25 | // Assign request object. 26 | _requestObj = requestObj; 27 | 28 | // Define the url prefix 29 | oThis.urlPrefix = '/webhooks'; 30 | 31 | return oThis; 32 | }; 33 | 34 | webhooks.prototype = { 35 | 36 | /** 37 | * Create webhook. 38 | * 39 | * @param {object} params 40 | * @returns {*} 41 | * @public 42 | */ 43 | create: function (params) { 44 | const oThis = this; 45 | var params = params || {}; 46 | return _requestObj.post(oThis.urlPrefix + "/" , params); 47 | }, 48 | 49 | /** 50 | * Update webhook. 51 | * 52 | * @param {object} params 53 | * @returns {*} 54 | * @public 55 | */ 56 | update: function (params) { 57 | const oThis = this; 58 | var params = params || {}; 59 | return _requestObj.post(oThis.urlPrefix + "/" + validate.getWebhookId(params), params); 60 | }, 61 | 62 | /** 63 | * Get webhook. 64 | * 65 | * @param params 66 | * @returns {*} 67 | * @public 68 | */ 69 | get: function (params) { 70 | const oThis = this; 71 | var params = params || {}; 72 | return _requestObj.get(oThis.urlPrefix + "/" + validate.getWebhookId(params), params); 73 | }, 74 | 75 | /** 76 | * Get list of webhooks. 77 | * 78 | * @param params 79 | * @returns {*} 80 | * @public 81 | */ 82 | getList: function (params) { 83 | const oThis = this; 84 | var params = params || {}; 85 | return _requestObj.get(oThis.urlPrefix + "/" , params); 86 | }, 87 | 88 | /** 89 | * Delete webhook. 90 | * 91 | * @param params 92 | * @returns {*} 93 | * @public 94 | */ 95 | deleteWebhook: function (params) { 96 | const oThis = this; 97 | var params = params || {}; 98 | return _requestObj.deleteRequest(oThis.urlPrefix + "/" + validate.getWebhookId(params), params); 99 | }, 100 | 101 | /** 102 | * Verify signature 103 | * 104 | * @param version 105 | * @param stringifiedData 106 | * @param requestTimestamp 107 | * @param signature 108 | * @param webhookSecret 109 | * @return {boolean} 110 | */ 111 | verifySignature: function (version, stringifiedData, requestTimestamp, signature, webhookSecret) { 112 | if(typeof stringifiedData !== 'string') stringifiedData = JSON.stringify(stringifiedData); 113 | 114 | const buff = new Buffer.from(webhookSecret, 'utf8') 115 | , hmac = crypto.createHmac('sha256', buff); 116 | 117 | hmac.update(`${requestTimestamp}.${version}.${stringifiedData}`); 118 | 119 | let computedSignature = hmac.digest('hex'); 120 | 121 | return signature.indexOf(computedSignature) >= 0; 122 | } 123 | 124 | }; 125 | 126 | module.exports = webhooks; -------------------------------------------------------------------------------- /test/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "testObjForSignature": { 3 | "a": null, 4 | "b": [], 5 | "c": "", 6 | "d": ["", null], 7 | "e": {}, 8 | "k1": 125.45, 9 | "k2": "Tejas", 10 | "aaaaa": {"a": {"a": "L21A", "b": "L21B"}, "b": {"a": "L22A", "b": "L22B"}, "c": {"a": "L23A", "b": "L23B"}}, 11 | "arrayValues": ["Hello", "There", "12345"], 12 | "garbage_str": "~!@#$%^&*()_+-= {}[]:\";'?/<>,. this is garbage" 13 | }, 14 | "testResource": "/api/v2/users", 15 | "signatureExpected": "28664cdbc613b66835d7bcf825dce719fb8e0621992c291ba9bd1767c1c5560d", 16 | "api_secret_for_testing_signature":"a0431203671f42c079b2154066fd04ba" 17 | } -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | const rootPrefix = "..", 3 | 4 | chai = require("chai"), 5 | qs = require("qs"), 6 | assert = chai.assert, 7 | RequestKlass = require(rootPrefix + "/lib/request"), 8 | fs = require("fs"), 9 | configObj = JSON.parse(fs.readFileSync("test/config.json", 'utf8')), 10 | credentialObject = { 11 | apiKey: process.env.OST_KIT_API_KEY, 12 | secret: process.env.OST_KIT_API_SECRET 13 | }, 14 | apiEndpont = process.env.OST_KIT_API_ENDPOINT, 15 | 16 | OSTSDK = require(rootPrefix + "/index"), 17 | //config is optional param, timeout should be given in seconds 18 | ostObj = new OSTSDK({ 19 | apiKey: credentialObject.apiKey, 20 | apiSecret: credentialObject.secret, 21 | apiEndpoint: apiEndpont, 22 | config: {timeout: 100000} 23 | }), 24 | userService = ostObj.services.users, 25 | chainService = ostObj.services.chains, 26 | tokenService = ostObj.services.tokens, 27 | deviceService = ostObj.services.devices, 28 | sessionService = ostObj.services.sessions, 29 | pricePoints = ostObj.services.price_points, 30 | balanceService = ostObj.services.balance, 31 | deviceManagersService = ostObj.services.device_managers, 32 | recoveryOwnersService = ostObj.services.recovery_owners, 33 | rulesService = ostObj.services.rules, 34 | transactionsService = ostObj.services.transactions, 35 | baseTokensService = ostObj.services.base_tokens, 36 | webhooksService = ostObj.services.webhooks, 37 | redemptionsService = ostObj.services.redemptions, 38 | redeemableSkusService = ostObj.services.redeemable_skus, 39 | 40 | 41 | userId = process.env.OST_KIT_USER_ID, 42 | companyUserId = process.env.OST_KIT_COMPANY_USER_ID, 43 | auxChainId = process.env.OST_KIT_AUX_CHAIN_ID, 44 | transactionId = process.env.OST_KIT_TRANSACTION_ID, 45 | deviceAddrs = process.env.OST_KIT_USER_DEVICE_ADDRESS, 46 | sessionAddrs = process.env.OST_KIT_SESSION_ADDRESS, 47 | ruleAddress = process.env.OST_KIT_RULE_ADDRESS, 48 | user2TokenHolderAddress = process.env.OST_KIT_USER2_TOKEN_HOLDER_ADDRESS, 49 | recoveryOwnerAddress = process.env.OST_KIT_RECOVERY_OWNER_ADDRESS, 50 | redemptionId = process.env.OST_KIT_REDEMPTION_ID, 51 | redeemableSkuId = process.env.OST_KIT_REDEEMABLE_SKU_ID 52 | ; 53 | 54 | let webhookId = null; 55 | 56 | 57 | function userList() { 58 | it("test user list", async function () { 59 | let res = await userService.getList().catch(function (err) { 60 | console.log(JSON.stringify(err)); 61 | assert.fail('GET User list testcase is failed'); 62 | }); 63 | assert.equal(res.success, true); 64 | }); 65 | } 66 | 67 | function createUser() { 68 | 69 | it("test create user ", async function () { 70 | let res = await userService.create({}).catch(function (err) { 71 | console.log(JSON.stringify(err)); 72 | assert.fail('create User testcase is failed'); 73 | }); 74 | assert.equal(res.success, true); 75 | }); 76 | 77 | } 78 | 79 | 80 | function getUser() { 81 | 82 | it("test get user ", async function () { 83 | let res = await userService.get({user_id: userId}).catch(function (err) { 84 | console.log(JSON.stringify(err)); 85 | assert.fail('get User testcase is failed'); 86 | }); 87 | assert.equal(res.success, true); 88 | }); 89 | 90 | } 91 | 92 | function getChain() { 93 | 94 | it("test get chain ", async function () { 95 | let res = await chainService.get({chain_id: auxChainId}).catch(function (err) { 96 | console.log(JSON.stringify(err)); 97 | assert.fail('get chain testcase is failed'); 98 | }); 99 | assert.equal(res.success, true); 100 | }); 101 | } 102 | 103 | function getTokenDetails() { 104 | 105 | it("test get token details ", async function () { 106 | let res = await tokenService.get({}).catch(function (err) { 107 | assert.fail('get token details testcase is failed'); 108 | }); 109 | assert.equal(res.success, true); 110 | }); 111 | } 112 | 113 | function createDevice() { 114 | 115 | it("test create device ", function () { 116 | generateRandomAddrs().then(async function (res) { 117 | let resp = await deviceService.create( 118 | { 119 | user_id: userId, 120 | address: res, 121 | api_signer_address: '0x5F860598383868e8E8Ee0ffC5ADD92369Db37455' 122 | }).catch(function (err) { 123 | console.log(JSON.stringify(err)); 124 | assert.fail('create device testcase is failed'); 125 | }); 126 | assert.equal(resp.success, true); 127 | // get device device testcase 128 | 129 | }) 130 | }); 131 | 132 | } 133 | 134 | 135 | function getDevice() { 136 | it("test get device", async function () { 137 | let res = await deviceService.get({ 138 | user_id: userId, 139 | device_address: deviceAddrs 140 | }).catch(function (err) { 141 | console.log(JSON.stringify(err)); 142 | assert.fail('get device testcase is failed'); 143 | }); 144 | assert.equal(res.success, true); 145 | }); 146 | 147 | } 148 | 149 | 150 | function getDeviceList() { 151 | 152 | it("test get device list ", async function () { 153 | let res = await deviceService.getList({ 154 | user_id: userId 155 | }).catch(function (err) { 156 | console.log(JSON.stringify(err)); 157 | assert.fail('get device list testcase is failed'); 158 | }); 159 | assert.equal(res.success, true); 160 | }); 161 | 162 | } 163 | 164 | function getUserSessionList() { 165 | 166 | it("test get user session list", async function () { 167 | let res = await sessionService.getList({ 168 | user_id: userId, 169 | }).catch(function (err) { 170 | console.log(JSON.stringify(err)); 171 | assert.fail('get user session list testcase is failed'); 172 | }); 173 | assert.equal(res.success, true); 174 | }); 175 | 176 | } 177 | 178 | function getUserSession() { 179 | it("test get user session", async function () { 180 | let res = await sessionService.get({ 181 | user_id: userId, 182 | session_address: sessionAddrs 183 | }).catch(function (err) { 184 | console.log(JSON.stringify(err)); 185 | assert.fail('get user session testcase is failed'); 186 | }); 187 | assert.equal(res.success, true); 188 | }); 189 | } 190 | 191 | function getpricePoints() { 192 | 193 | it("test get price points", async function () { 194 | let res = await pricePoints.get({a: [1, 2, 3, "a"], chain_id: auxChainId}).catch(function (err) { 195 | console.log(JSON.stringify(err)); 196 | assert.fail('get price points testcase is failed'); 197 | }); 198 | assert.equal(res.success, true); 199 | }); 200 | 201 | 202 | } 203 | 204 | function getBalance() { 205 | it("test get balance", async function () { 206 | let res = await balanceService.get({ 207 | user_id: userId 208 | }).catch(function (err) { 209 | assert.fail('get balance'); 210 | }); 211 | assert.equal(res.success, true); 212 | }); 213 | } 214 | 215 | 216 | function getDeviceManagers() { 217 | it("test get device managers", async function () { 218 | let res = await deviceManagersService.get({ 219 | user_id: userId, 220 | garbage_str: "~^[]%$#@!&*~,./?~()-_'this is garbage" // This garbage string is for testing 221 | }).catch(function (err) { 222 | console.log(JSON.stringify(err)); 223 | assert.fail('get device managers'); 224 | }); 225 | assert.equal(res.success, true); 226 | }); 227 | } 228 | 229 | 230 | function getRecoveryOwnerAddress() { 231 | it("test get recovery owners", async function () { 232 | let res = await recoveryOwnersService.get({ 233 | user_id: userId, 234 | recovery_owner_address: recoveryOwnerAddress //"0x4e9314f004026F89Fc52790c3357b2D34FBA93b0" 235 | }).catch(function (err) { 236 | console.log(JSON.stringify(err)); 237 | assert.fail('get recovery owners'); 238 | }); 239 | assert.equal(res.success, true); 240 | }); 241 | } 242 | 243 | 244 | function getRules() { 245 | it("test get rules", async function () { 246 | let res = await rulesService.getList({}).catch(function (err) { 247 | console.log(JSON.stringify(err)); 248 | assert.fail('get rules'); 249 | }); 250 | assert.equal(res.success, true); 251 | }); 252 | } 253 | 254 | function executeTransactions() { 255 | it("test execute transaction", async function () { 256 | 257 | let raw_calldata = JSON.stringify({ 258 | method: "directTransfers", 259 | parameters: [[user2TokenHolderAddress], ["1"]] 260 | }); 261 | 262 | let executeParams = { 263 | user_id: companyUserId, 264 | to: ruleAddress, 265 | raw_calldata: raw_calldata 266 | }; 267 | 268 | let res = await transactionsService.execute(executeParams).catch(function (err) { 269 | console.log(JSON.stringify(err)); 270 | assert.fail('execute transaction'); 271 | }); 272 | assert.equal(res.success, true); 273 | }); 274 | } 275 | 276 | 277 | function transactionsList() { 278 | it("test transaction list", async function () { 279 | let res = await transactionsService.getList({ 280 | user_id: userId 281 | }).catch(function (err) { 282 | console.log(JSON.stringify(err)); 283 | assert.fail('list transactions'); 284 | }); 285 | assert.equal(res.success, true); 286 | }); 287 | } 288 | 289 | 290 | function getTransaction() { 291 | it("Test get transaction", async function () { 292 | let res = await transactionsService.get({ 293 | user_id: userId, 294 | transaction_id: transactionId 295 | }).catch(function (err) { 296 | console.log(JSON.stringify(err)); 297 | assert.fail('List transactions'); 298 | }); 299 | assert.equal(res.success, true); 300 | }); 301 | } 302 | 303 | function createWebhook() { 304 | it("Test create webhook.", async function () { 305 | 306 | let webhookParams = { 307 | topics:['transactions/initiate','transactions/success'], 308 | url:`${"https://www.testingWebhooks.com"}/${Date.now()}/${process.version}`, 309 | status:"active" 310 | }; 311 | 312 | let res = await webhooksService.create(webhookParams).catch(function (err) { 313 | console.log(JSON.stringify(err)); 314 | assert.fail('Create webhook.'); 315 | }); 316 | assert.equal(res.success, true); 317 | 318 | webhookId = res.data[[res.data.result_type]].id; 319 | }); 320 | } 321 | 322 | function updateWebhook() { 323 | it("Test update webhook.", async function () { 324 | 325 | let webhookParams = { 326 | webhook_id: webhookId, 327 | topics: ['transactions/initiate','transactions/success','transactions/failure'], 328 | status: "active" 329 | }; 330 | 331 | let res = await webhooksService.update(webhookParams).catch(function (err) { 332 | console.log(JSON.stringify(err)); 333 | assert.fail('Update webhook.'); 334 | }); 335 | assert.equal(res.success, true); 336 | }); 337 | } 338 | 339 | function getWebhook() { 340 | it("Test get webhook.", async function () { 341 | 342 | let webhookParams = { 343 | webhook_id: webhookId 344 | }; 345 | 346 | let res = await webhooksService.get(webhookParams).catch(function (err) { 347 | console.log(JSON.stringify(err)); 348 | assert.fail('Get webhook.'); 349 | }); 350 | assert.equal(res.success, true); 351 | }); 352 | } 353 | 354 | function getWebhookList() { 355 | it("Test get webhook list.", async function () { 356 | 357 | let res = await webhooksService.getList().catch(function (err) { 358 | console.log(JSON.stringify(err)); 359 | assert.fail('Get webhook list.'); 360 | }); 361 | assert.equal(res.success, true); 362 | }); 363 | } 364 | 365 | function deleteWebhook() { 366 | it("Test delete webhook.", async function () { 367 | 368 | let webhookParams = { 369 | webhook_id: webhookId 370 | }; 371 | 372 | let res = await webhooksService.deleteWebhook(webhookParams).catch(function (err) { 373 | console.log(JSON.stringify(err)); 374 | assert.fail('Delete webhook.'); 375 | }); 376 | assert.equal(res.success, true); 377 | }); 378 | } 379 | 380 | 381 | function getRedemption() { 382 | it("Test get user redemption", async function () { 383 | let res = await redemptionsService.get({ 384 | user_id: userId, 385 | redemption_id: redemptionId 386 | }).catch(function (err) { 387 | console.log(JSON.stringify(err)); 388 | assert.fail('Get user redemption.'); 389 | }); 390 | assert.equal(res.success, true); 391 | }); 392 | } 393 | 394 | 395 | function listRedemptions() { 396 | it("Test list user redemptions", async function () { 397 | let res = await redemptionsService.getList({ 398 | user_id: userId 399 | }).catch(function (err) { 400 | console.log(JSON.stringify(err)); 401 | assert.fail('List user redemptions.'); 402 | }); 403 | assert.equal(res.success, true); 404 | }); 405 | } 406 | 407 | function getRedeemableSku() { 408 | it("Test get redeemable SKU by id", async function () { 409 | let res = await redeemableSkusService.get({ 410 | redeemable_sku_id: redeemableSkuId 411 | }).catch(function (err) { 412 | console.log(JSON.stringify(err)); 413 | assert.fail('Get redeemable SKU.'); 414 | }); 415 | assert.equal(res.success, true); 416 | }); 417 | } 418 | 419 | function listRedeemableSkus() { 420 | it("Test list redeemable SKUs", async function () { 421 | let res = await redeemableSkusService.getList({}).catch(function (err) { 422 | console.log(JSON.stringify(err)); 423 | assert.fail('List redeemable SKUs.'); 424 | }); 425 | assert.equal(res.success, true); 426 | }); 427 | } 428 | 429 | 430 | function testWebhookRequestSignature() { 431 | it ("Tests webhook request signature.", async function () { 432 | let version = "2", 433 | requestTimestamp = '1559902637', 434 | signature = '2c56c143550c603a6ff47054803f03ee4755c9c707986ae27f7ca1dd1c92a824', 435 | stringifiedData = JSON.stringify({hello: "hello"}), 436 | webhookSecret = 'mySecret'; 437 | 438 | let res = webhooksService.verifySignature(version, stringifiedData,requestTimestamp, signature, webhookSecret); 439 | assert.equal(res, true); 440 | }) 441 | } 442 | 443 | 444 | function testSignature() { 445 | it("Signature should match with given one", function () { 446 | const requestObj = new RequestKlass({apiKey: '12121', apiSecret: 'dsdsd', apiEndpoint: "endpoint"}), 447 | credentialObjectForSignatureTest = { 448 | secret: configObj['api_secret_for_testing_signature'] 449 | }, 450 | testObjForSignature = configObj["testObjForSignature"], 451 | queryString = requestObj.formatQueryParams(testObjForSignature); 452 | var fullQueryString = requestObj.signQueryParamsTest(configObj["testResource"], queryString, credentialObjectForSignatureTest), 453 | queryStringObj = qs.parse(fullQueryString); 454 | assert.equal(queryStringObj.api_signature, configObj["signatureExpected"]); 455 | }); 456 | } 457 | 458 | function getBaseTokensDetails() { 459 | 460 | it("test get base token details ", async function () { 461 | let res = await baseTokensService.get({}).catch(function (err) { 462 | assert.fail('get base token details testcase is failed'); 463 | }); 464 | assert.equal(res.success, true); 465 | }); 466 | } 467 | 468 | async function generateRandomAddrs() { 469 | let buffer = await require('crypto').randomBytes(20); 470 | return "0x" + buffer.toString("hex"); 471 | } 472 | 473 | 474 | async function testcases() { 475 | getBaseTokensDetails(); 476 | createUser(); 477 | userList(); 478 | getChain(); 479 | getUser(); 480 | getTokenDetails(); 481 | createDevice(); 482 | getDeviceList(); 483 | getUserSession(); 484 | getUserSessionList(); 485 | getpricePoints(); 486 | getBalance(); 487 | getDeviceManagers(); 488 | getRecoveryOwnerAddress(); 489 | getRules(); 490 | executeTransactions(); 491 | getTransaction(); 492 | transactionsList(); 493 | getDevice(); 494 | testSignature(); 495 | await createWebhook(); 496 | await getWebhookList(); 497 | await getWebhook(); 498 | await updateWebhook(); 499 | await deleteWebhook(); 500 | testWebhookRequestSignature(); 501 | getRedemption(); 502 | listRedemptions(); 503 | getRedeemableSku(); 504 | listRedeemableSkus() 505 | } 506 | 507 | testcases(); 508 | 509 | 510 | --------------------------------------------------------------------------------