Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: backend service #68

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/offline-pay-with-crypto-backend/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
COIN_MARKET_API_KEY=
COIN_API_KEY=
COIN_MARKET_TEST_API_KEY=
2 changes: 2 additions & 0 deletions packages/offline-pay-with-crypto-backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
build
31 changes: 26 additions & 5 deletions packages/offline-pay-with-crypto-backend/README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,32 @@
# `offline-pay-with-crypto-backend`
## `offline-pay-with-celo-backend`

> TODO: description
This project handles currency exchange on the `offline-pay-with-celo-widget` application.

## Usage
## Getting Started

### Run


```
yarn
```

### Rename
```
.env.example to .env

```
const offlinePayWithCryptoBackend = require('offline-pay-with-crypto-backend');

// TODO: DEMONSTRATE API
#### Update config to the .env file

### Available Scripts

```
npm run dev
```
Runs the app in the development mode.

```
npm build
```
Builds minified version for production mode
19 changes: 18 additions & 1 deletion packages/offline-pay-with-crypto-backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,34 @@
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
"start": "npm run build && node ./build/app.js",
"dev": "nodemon --exec babel-node ./src/app.js",
"clean": "rm -rf build && mkdir build",
"build-babel": "babel -d ./build ./src -s",
"build": "npm run clean && npm run build-babel"
},
"dependencies": {
"@babel/cli": "^7.16.8",
"@babel/core": "^7.16.10",
"@celo/contractkit": "^1.3.3",
"axios": "^0.25.0",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"morgan": "~1.9.1",
"node-fetch": "^3.1.0",
"web3": "^1.6.0"
},
"devDependencies": {
"@babel/node": "^7.16.8",
"@babel/plugin-transform-runtime": "^7.16.10",
"@babel/polyfill": "^7.12.1",
"@babel/preset-env": "^7.16.11",
"@babel/runtime": "^7.16.7",
"dotenv": "^14.2.0",
"nodemon": "^2.0.15"
}
}
Original file line number Diff line number Diff line change
@@ -1,30 +1,34 @@
var createError = require('http-errors')
var express = require('express')
var path = require('path')
var cors = require('cors')
var cookieParser = require('cookie-parser')
var logger = require('morgan')

var indexRouter = require('./routes/index')
require('dotenv').config()
var indexRouter = require('./routes')
var celoSubscriptions = require('./services/celo/subscribe')
var celoTnxCreateRouter = require('./routes/celo/transaction-create')
var celoTnxVerifyRouter = require('./routes/celo/transaction-verify')
var getExchange = require('./routes/rate');


var app = express()

// view engine setup
app.set('view engine', 'jade')
// app.set('view engine', 'jade')

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))
app.use(cors())
// app.use(express.static(path.join(__dirname, 'public')))

app.use('/', indexRouter)

// Celo Endpoints
app.use('/celo/transaction/create', celoTnxCreateRouter)
app.use('/celo/transaction/verify', celoTnxVerifyRouter)
app.use('/rate', getExchange)


// NEAR Endpoints

Expand All @@ -34,10 +38,13 @@ const celoAddress1 = '0x363f932743599EBc88C85A35C201615dA4f2Bc5E'
const celoAddress2 = '0x6D2cFcdB9FD34E01c65527397B6DDE8b2E9EE711'
celoSubscriptions(celoAddress1)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404))
})

app.get("/", indexRouter);

const PORT = process.env.PORT || 3200;
app.listen(PORT, () => {
console.log("server up and running");
});

// error handler
app.use(function (err, req, res, next) {
Expand All @@ -47,7 +54,7 @@ app.use(function (err, req, res, next) {

// render the error page
res.status(err.status || 500)
res.render('error')
res.send('error')
})

module.exports = app
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ var router = express.Router();

/* POST create transaction. */
router.post('/', function(req, res, next) {
res.render('index', { title: 'Express' });
res.send('index', { title: 'Express' });
});

module.exports = router;
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ var router = express.Router();

/* POST verify payment. */
router.post('/', function(req, res, next) {
res.render('index', { title: 'Express' });
res.send('index', { title: 'Express' });
});

module.exports = router;
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
res.status(200).json({
message: "offline pay with celo api:powered by chimoney ",
status: "success",
});

});

module.exports = router;
36 changes: 36 additions & 0 deletions packages/offline-pay-with-crypto-backend/src/routes/rate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
var express = require('express');
const coinApi = require('../services/coin-api');
const CoinMarketAPI = require('../services/coinmarket');
var router = express.Router();

router.get('/', async (req, res, next) => {

const { code } = req.query;

if (!code) {
return res.status(400).json({
message: 'code is required',
rate: null,
error: true
})
}

let result = [];

const data = await CoinMarketAPI.getExchange(code);

if (data?.[code]?.error === false) {
result.push(data);
} else {
// fallback support api
const coinAPIData = await coinApi.getExchange(code);

result.push(coinAPIData);
}
return res.status(200).json({
data: result[0]
})

});

module.exports = router;
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
var axios = require('axios');

const apiKey = process.env.COIN_API_KEY

const axiosApiInstance = axios.create({
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'X-CoinAPI-Key': apiKey,
},
})

axiosApiInstance.defaults.baseURL = 'https://rest.coinapi.io'

const coinApi = {
getExchange: async (code) => {
try {

let data = {}
const result = await axiosApiInstance.get(
`/v1/exchangerate/${code}/USD`
)

data[code] = {
rate: result?.data?.rate,
error: false,
}

return data
} catch (err){
let data = {};
data[`${code}`] = {
rate: null,
error: true,
err: err.message,
}

return data;
}
}
}

module.exports = coinApi;
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
var axios = require('axios');
require('dotenv').config()
const apiKey = process.env.COIN_MARKET_API_KEY;
const testApiKey = process.env.COIN_MARKET_TEST_API_KEY;

const isDev = process.env.NODE_ENV === 'development';

let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
}

if (isDev) {
headers['X-CMC_PRO_API_KEY'] = testApiKey;
} else {
headers['X-CMC_PRO_API_KEY'] = apiKey
}
const baseURL = isDev ? 'https://sandbox-api.coinmarketcap.com' : 'https://pro-api.coinmarketcap.com';
const axiosApiInstance = axios.create({
headers
})

axiosApiInstance.defaults.baseURL = baseURL;

const CoinMarketAPI = {
getExchange: async (code) => {
try {

const result = await axiosApiInstance.get(`/v1/tools/price-conversion?amount=1&symbol=${code}`);
let data = {};

const rate = isDev ? result?.data?.data[`${code}`].quote['USD'].price : result?.data?.data?.quote['USD'].price;

if (result.status === 200) {
data[`${code}`] = {
rate,
error: false
}
}

return data;
} catch (err) {
let data = {};
data[`${code}`] = {
rate: null,
error: true,
err: err.message,
}

return data;
}


}
}

module.exports = CoinMarketAPI;
Loading