Skip to content

Commit

Permalink
Initial commit for basic gateway package
Browse files Browse the repository at this point in the history
  • Loading branch information
otherview committed Oct 23, 2023
1 parent 8f89805 commit fcedafe
Show file tree
Hide file tree
Showing 9 changed files with 13,678 additions and 0 deletions.
39 changes: 39 additions & 0 deletions .github/workflows/build-gateway-lib.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: Build JS libs

on:
pull_request:
paths:
- '.github/'
- 'tools/gateway-js/'
branches:
- main

jobs:
build-and-publish:
runs-on: ubuntu-latest

steps:
# Check out the repository
- name: Checkout Repository
uses: actions/checkout@v3

# Set up Node.js
- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '18'

# Install dependencies
- name: Install Dependencies
run: npm install

# Build the project (assuming you have a script named "build" in package.json)
- name: Build
run: npm run lint && npm run test

# Deploy to GitHub Pages using the 'gh-pages' branch
- name: Deploy to GitHub Pages
uses: JamesIves/[email protected]
with:
branch: gh-pages
folder: dist
39 changes: 39 additions & 0 deletions .github/workflows/deploy-gateway-lib.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: Publish JS for External Consumption and GitHub Pages

on:
push:
paths:
- '.github/'
- 'tools/gateway-js/'
branches:
- main

jobs:
build-and-publish:
runs-on: ubuntu-latest

steps:
# Check out the repository
- name: Checkout Repository
uses: actions/checkout@v3

# Set up Node.js
- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '18'

# Install dependencies
- name: Install Dependencies
run: npm install

# Build the project (assuming you have a script named "build" in package.json)
- name: Build
run: npm run build

# Deploy to GitHub Pages using the 'gh-pages' branch
- name: Deploy to GitHub Pages
uses: JamesIves/[email protected]
with:
branch: gh-pages
folder: dist
34 changes: 34 additions & 0 deletions tools/gateway-js/gateway-lib/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
module.exports = {
"env": {
"browser": true,
"es2021": true,
"node": true,
"jest": true,
},
"extends": "eslint:recommended",
"overrides": [
{
"env": {
"node": true
},
"files": [
".eslintrc.{js,cjs}"
],
"parserOptions": {
"sourceType": "script"
}
}
],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"ignorePatterns": [
"node_modules/",
"dist/",
"*.config.*"
],
"rules": {
"no-unused-vars": "off"
}
}
1 change: 1 addition & 0 deletions tools/gateway-js/gateway-lib/dist/gateway.bundle.js

Large diffs are not rendered by default.

76 changes: 76 additions & 0 deletions tools/gateway-js/gateway-lib/gateway.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
const axios = require("axios");

const obscuroGatewayVersion = "v1";
const pathJoin = obscuroGatewayVersion + "/join/";
const pathAuthenticate = obscuroGatewayVersion + "/authenticate/";

class Gateway {
constructor(httpURL, wsURL, provider) {
this.httpURL = httpURL;
this.wsURL = wsURL;
this.userId = '';
this.provider = provider;
}

async join() {
try {
const response = await axios.get(`${this.httpURL}${pathJoin}`);
if (response.status !== 200) {
throw new Error(`Failed to get userID. Status code: ${response.status}`);
}
this.userID = response.data;
} catch (error) {
throw new Error(`Failed to get userID. ${error}`);
}
}

async registerAccount(privateKey, address) {
const message = `Register ${this.userID} for ${address.toLowerCase()}`;
let signature = ""

try {
signature = await this.provider.request({
method: "personal_sign",
params: [message, address]
})
} catch (err) {
throw new Error(`Failed to signe message. ${err}`);
}

if (signature === -1) {
return "Signing failed"
}

try {
const authenticateUserURL = pathAuthenticate+"?u="+this.userID()
const authenticateFields = {"signature": signature, "message": message}
const authenticateResp = await fetch(
authenticateUserURL, {
method: "post",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(authenticateFields)
}
);
return await authenticateResp.text()
} catch (error) {
throw new Error(`Failed to register account. ${error}`);
}
}

userID() {
return this.userId;
}

http() {
return `${this.httpURL}/v1/?u=${this.userId}`;
}

ws() {
return `${this.wsURL}/v1/?u=${this.userId}`;
}
}

module.exports = Gateway;
58 changes: 58 additions & 0 deletions tools/gateway-js/gateway-lib/gateway.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const axios = require('axios');
const Gateway = require('./gateway.js');

// Mocking axios module
jest.mock('axios');

// Mocking the global fetch function
global.fetch = jest.fn();

describe('Gateway', () => {
let gateway;
const httpURL = 'http://example.com';
const wsURL = 'ws://example.com';
const provider = {}; // Placeholder for the provider if it's needed in future tests.

beforeEach(() => {
gateway = new Gateway(httpURL, wsURL, provider);
});

it('should join successfully', async () => {
axios.get.mockResolvedValue({
status: 200,
data: 'testUserID',
});

await gateway.join();

expect(gateway.userID).toBe('testUserID');
});

it('should throw error on unsuccessful join', async () => {
axios.get.mockRejectedValue(new Error('Network error'));

await expect(gateway.join()).rejects.toThrow('Failed to get userID. Error: Network error');
});

it('should register account successfully', async () => {
global.fetch.mockResolvedValue({
text: jest.fn().mockResolvedValue('Account registered'),
});

gateway = new Gateway("", "", {
request: jest.fn().mockResolvedValue("mockSignature")
})

const result = await gateway.registerAccount('privateKey', 'address');

expect(result).toBe('Account registered');
});

it('should throw error on unsuccessful account registration', async () => {
gateway = new Gateway("", "", {
request: jest.fn().mockRejectedValue(new Error('Signature error')),
})

await expect(gateway.registerAccount('privateKey', 'address')).rejects.toThrow('Failed to signe message. Error: Signature error');
});
});
Loading

0 comments on commit fcedafe

Please sign in to comment.