Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // The following is a snippet of JS extracted from a variety of components built out for a recent vue.js project.
- // Followed by a few endpoints found in the corresponding API.
- // Crypto.js
- import { mapState } from 'vuex';
- import { validationMixin } from 'vuelidate';
- import { required } from 'vuelidate/lib/validators';
- import { general } from '@/utils';
- import VueQrcode from '@xkeshi/vue-qrcode';
- import CreateBtsAccount from './CreateBtsAccount';
- import AddBtsAccount from './AddBtsAccount';
- export default {
- components: { qrcode: VueQrcode, CreateBtsAccount, AddBtsAccount },
- mixins: [validationMixin, general],
- props: {
- open: Boolean,
- token: Object,
- },
- data: () => ({
- active: 'bitcoin',
- tabs: ['bitcoin', 'bitcoincash', 'ethereum', 'litecoin', 'bitshares'],
- currencies: {
- bitcoin: {
- title: 'BTC',
- address: null,
- },
- bitcoincash: {
- title: 'BCC',
- address: null,
- },
- ethereum: {
- title: 'ETH',
- address: null,
- },
- litecoin: {
- title: 'LTC',
- address: null,
- },
- },
- page: 1,
- codeOptions: {
- size: 200,
- backgroundAlpha: 0,
- },
- accountname: null,
- title: null,
- description: null,
- address: null,
- loading: true,
- adding: false,
- creating: false,
- }),
- methods: {
- postBitsharesAccount() {
- this.$store.dispatch('bitshares/postBitsharesAccount', {
- accountname: this.accountname,
- title: this.title,
- description: this.description,
- });
- },
- setAddresses(data) {
- const keys = Object.keys(data);
- for (let i = 0; i < keys.length; i += 1) {
- this.currencies[keys[i]].address = data[keys[i]];
- }
- this.loading = false;
- },
- },
- watch: {
- open(val) {
- this.loading = true;
- if (!this.token) return null;
- const { name } = this.token;
- if (!this.addresses[name]) {
- this.$store.dispatch('crypto/getAddresses', this.token)
- .then(({ data }) => {
- this.setAddresses(data);
- }).catch(() => {
- this.loading = false;
- });
- } else {
- this.setAddresses(this.addresses[name]);
- }
- return val;
- },
- },
- computed: {
- ...mapState({
- bitshares: ({ bitshares }) => !!bitshares.accounts.filter(acct => !!acct.verified).length,
- addresses: ({ crypto }) => crypto.addresses,
- }),
- step: {
- get() {
- return this.bitshares ? 2 : this.page;
- },
- set(val) {
- this.page = val;
- },
- },
- accountErrors() {
- const errors = [];
- if (!this.$v.accountname.$dirty) return errors;
- !this.$v.accountname.noSpace && errors.push('Account Name cannot contain white spaces');
- !this.$v.accountname.required && errors.push('Account Name is required');
- !this.$v.accountname.isUnique && errors.push('This account name is taken');
- !this.$v.accountname.isBitshares && errors.push('This account name is not in bitshares');
- return errors;
- },
- titleErrors() {
- const errors = [];
- if (!this.$v.title.$dirty) return errors;
- !this.$v.title.required && errors.push('Title is required');
- return errors;
- },
- },
- validations: {
- accountname: {
- required,
- isBitshares(value) {
- if (value === '') return true;
- if (this.bitsharesaccountajax) {
- this.bitsharesaccountajax.abort();
- }
- this.bitsharesaccountajax = $.ajax({
- url: `api/bitshares/bitshares_accounts/${value}`,
- success: result => result,
- });
- return this.bitsharesaccountajax;
- },
- isUnique(value) {
- if (value === '') return true;
- if (this.uniqueaccountajax) {
- this.uniqueaccountajax.abort();
- }
- this.uniqueaccountajax = $.ajax({
- url: `api/bitshares/duplicates/${value}`,
- success: result => result,
- });
- return this.uniqueaccountajax;
- },
- noSpace(value) {
- return !/\s/g.test(value);
- },
- },
- description: { required },
- title: { required },
- },
- };
- // Payment.js
- import { mapState, mapGetters } from 'vuex';
- import { math } from '@/utils';
- export default {
- props: {
- open: Boolean,
- id: Number,
- },
- mixins: [math],
- data: () => ({
- loading: false,
- passing: false,
- failing: false,
- delivering: false,
- deliverLoading: false,
- details: null,
- headers: [
- { align: 'left', value: 'status' },
- { align: 'right', value: 'date' },
- { align: 'right', value: 'details' },
- ],
- }),
- watch: {
- id(id) {
- this.loading = true;
- this.$store.dispatch('accounts/getPayment', id)
- .then(() => {
- this.loading = false;
- });
- },
- },
- methods: {
- dispute() {
- console.log('Disputing');
- },
- capitalize(value) {
- if (!value) return '';
- value = value.toString();
- return value.charAt(0).toUpperCase() + value.slice(1);
- },
- passPayment() {
- if (this.pass === 'delivery') {
- this.delivering = true;
- } else {
- this.passing = true;
- this.update({ id: this.payment.id, action: this.pass })
- .then(() => this.$store.dispatch('accounts/getPayment', this.payment.id))
- .then(() => { this.passing = false; })
- .catch(() => { this.passing = false; });
- }
- },
- failPayment() {
- this.failing = true;
- this.update({ id: this.payment.id, action: this.fail })
- .then(() => this.$store.dispatch('accounts/getPayment', this.payment.id))
- .then(() => { this.failing = false; })
- .catch(() => { this.failing = false; });
- },
- delivery() {
- this.deliverLoading = true;
- this.update({ id: this.payment.id, action: 'delivery', details: this.details })
- .then(() => this.$store.dispatch('accounts/getPayment', this.payment.id))
- .then(() => {
- this.deliverLoading = false;
- this.delivering = false;
- })
- .catch(() => {
- this.deliverLoading = false;
- this.delivering = false;
- });
- },
- update(data) {
- return this.$store.dispatch('accounts/updatePayment', data);
- },
- },
- computed: {
- ...mapState({
- payment: ({ accounts }) => accounts.payment,
- }),
- ...mapGetters({ username: 'user/username' }),
- pass() {
- const { status, to, escrow_settlement: escrow } = this.payment;
- if (status === 'requested' && to !== this.username && escrow) {
- return 'accept';
- }
- if ((status === 'requested' && to !== this.username && !escrow)
- || (status === 'delivered' && to !== this.username)) {
- return 'settle';
- }
- if (status === 'funded' && to === this.username) {
- return 'delivery';
- }
- return false;
- },
- fail() {
- const { status, to } = this.payment;
- if (status === 'requested' && to !== this.username) {
- return 'reject';
- }
- if (status === 'funded' && to === this.username) {
- return 'cancel';
- }
- if (status === 'delivered' && to !== this.username) {
- return 'dispute';
- }
- return false;
- },
- },
- };
- // AccountDetails.js
- import { math } from '@/utils';
- import { mapState, mapGetters } from 'vuex';
- import {
- Order,
- Deposit,
- Withdrawal,
- Payment,
- } from '@/components/Modals';
- export default {
- components: {
- Order,
- Deposit,
- Withdrawal,
- Payment,
- },
- mixins: [math],
- data: () => ({
- order: {},
- deposit: {},
- withdrawal: {},
- payment: {},
- loading: false,
- pagination: {
- sortBy: 'date',
- descending: true,
- },
- headers: [
- { align: 'left', value: 'date' },
- { align: 'right', value: 'amount' },
- { align: 'right', value: 'fee' },
- { align: 'right', value: 'usd' },
- { align: 'right', value: 'type' },
- { align: 'right', value: 'info' },
- { align: 'right', value: 'status' },
- ],
- }),
- watch: {
- pagination: {
- handler() {
- this.loading = true;
- this.$store.dispatch('accounts/getDetails', this.pagination)
- .then(() => {
- this.loading = false;
- });
- },
- deep: true,
- },
- },
- methods: {
- parsePayment(info) {
- if (!info) return '';
- if (info[0] === 'c' || !isNaN(info)) return 'Card';
- if (info[0] === 'p') return 'Bank';
- if (info.match(/[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}/g)
- || info === 'BitShares') return 'Crypto';
- return info;
- },
- capitalize(value) {
- if (!value) return '';
- value = value.toString();
- return value.charAt(0).toUpperCase() + value.slice(1);
- },
- open(item) {
- this[item.type.toLowerCase()] = {
- open: true,
- id: item.id,
- };
- },
- },
- computed: {
- ...mapState({
- details: ({ accounts }) => accounts.details,
- total: ({ accounts }) => accounts.totalDetails,
- }),
- ...mapGetters({
- account: 'accounts/selected',
- }),
- },
- };
- // EXPRESS/NODEJS API
- // payments.js
- // Dependencies
- const router = require('express').Router();
- const { coinbase, mail, authy } = require('../../lib');
- const { Payment, User, Account } = require('../../models');
- /**
- * POST api.quintric.com/app/payments
- * Initiate a payment to another user based on username
- *
- * Body: {
- * Integer token: id of token sending,
- * String username: username of account sending to,
- * String description: description of goods/services,
- * Integer amount: amount to send,
- * Integer fee: fee (calculated on component),
- * }
- *
- * Response: 201
- */
- router.post('', async (req, res, next) => {
- const body = req.body;
- let from;
- let to;
- let escrow;
- Account.getByUserId(req.user.id, body.token)
- .then((account) => {
- from = account;
- return Account.getByUserId(10, body.token);
- })
- .then((account) => {
- escrow = account;
- return User.get(body.username);
- })
- .then((user) => {
- if (user) return Account.getByUserId(user.id, body.token);
- else return { id: -1 };
- })
- .then((user) => {
- to = user.id < 0 ? false : user;
- return Payment.create({
- ...body,
- from: from.id,
- to: user.id,
- })
- })
- .then(payment => payment.addStatus('sent', body.username.toLowerCase()))
- .then(() => from.subtractBalance(+body.amount))
- .then(() => escrow.addBalance(+body.fee))
- .then(() => !!to ? to.addBalance((+body.amount) - (+body.fee)) : null)
- .then(() => mail.send(`payments/${!!to ? 'invite' : 'sent'}`, body.username, {}))
- .then(() => res.status(201).json({ message: 'Payment has been sent' }))
- .catch(err => next(err));
- });
- /**
- * POST api.quintric.com/app/payments/request
- * Request a payment from another user based on username
- *
- * Body: {
- * Integer token: id of token sending,
- * String username: username of account requesting from,
- * Integer amount: amount to send,
- * String description: description of goods/services,
- * Boolean escrow: true for net 30 terms,
- * Integer fee: fee (calculated on component),
- * }
- *
- * Response: 201
- */
- router.post('/request', async (req, res, next) => {
- const body = req.body;
- const to = await Account.getByUserId(req.user.id, body.token);
- const from = await Account.getByUsername(body.username, body.token);
- const options = {
- ...body,
- from: from.id,
- to: to.id,
- };
- Payment.create(options)
- .then(payment => payment.addStatus('requested', body.username))
- .then(() => to.username())
- .then((user) => mail.send('paymentRequested', user, {}))
- .then(() => res.status(201).json({ message: 'Payment has been requested' }))
- .catch(err => next(err));
- });
- /**
- * POST api.quintric.com/app/payments/token
- * Create and settle a payment request verified with Authy Soft Token
- *
- * Body: {
- * Integer token: id of token sending,
- * String username: username of account requesting from,
- * Integer amount: amount to send,
- * String description: description of goods/services,
- * String softToken: soft token verifying counterpary compliance,
- * }
- *
- * Response: 201
- */
- router.post('/token', async (req, res, next) => {
- const { softToken, token, username, amount, description } = req.body;
- const to = await Account.getByUserId(req.user.id, token);
- const from = await Account.getByUsername(username, token);
- const escrow = await Account.getByUserId(10, token);
- let fee = amount * .01;
- fee = fee < 5 ? fee : 5;
- const options = {
- amount,
- description,
- fee,
- from: from.id,
- to: to.id,
- };
- User.get(username)
- .then(user => user.getAuthyId())
- .then(authyId => authy.verifyToken(authyId, softToken))
- .then(() => Payment.create(options))
- .then(payment => payment.addStatus('settled', 'Token Verification'))
- .then(() => to.addBalance(amount - fee))
- .then(() => escrow.addBalance(fee))
- .then(() => from.subtractBalance(amount))
- .then(() => to.username())
- .then((user) => mail.send('paymentRequested', user, {}))
- .then(() => res.status(201).json({ message: 'Payment successfully settled.' }))
- .catch(err => next(err));
- });
- /**
- * GET api.quintric.com/app/address
- * Get list of addresses attached to current user for account funding
- *
- * Query: {
- * Integer token: id of token sending,
- * }
- *
- * Response: 200
- */
- router.get('/address', (req, res, next) => {
- const chargeData = {
- 'name': 'Quintric',
- 'metadata': {
- 'token': req.query.token,
- 'user': req.user.getId(),
- },
- 'description': 'Account Funding',
- 'pricing_type': 'no_price'
- };
- coinbase.Charge.create(chargeData, (err, response) => {
- if (err) return next(err)
- return res.send(response.addresses);
- });
- });
- module.exports = router;
Add Comment
Please, Sign In to add comment