Skip to content

Commit

Permalink
Payment Handler, crawl and clean migration (#616)
Browse files Browse the repository at this point in the history
* Validator Api calls made with js sdk, Fixed config types and test

* add memo

* memo to tables

* fixed all errors with updated sdk

* included comment for payment handler

Co-authored-by: Justin Kim <[email protected]>
  • Loading branch information
tomijaga and angle943 authored Apr 12, 2021
1 parent 2de4304 commit f2cd300
Show file tree
Hide file tree
Showing 16 changed files with 174 additions and 162 deletions.
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@
"resolve-url-loader": "^3.1.2",
"semver": "7.3.2",
"terser-webpack-plugin": "^4.2.3",
"thenewboston": "^1.1.0-alpha.1",
"thenewboston": "^1.1.0-alpha.3",
"ts-pnp": "^1.2.0",
"tweetnacl": "^1.0.3",
"typeface-roboto": "^0.0.75",
Expand Down
4 changes: 4 additions & 0 deletions src/renderer/containers/Account/AccountTransactions/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ enum TableKeys {
senderAccountNumber,
recipientAccountNumber,
amount,
memo,
balanceKey,
signature,
dateCreated,
Expand Down Expand Up @@ -44,6 +45,7 @@ const AccountTransactions: FC = () => {
[TableKeys.amount]: bankTransaction.amount,
[TableKeys.balanceKey]: <ExpandableText expanded={expanded} text={bankTransaction.block.balance_key} />,
[TableKeys.dateCreated]: formatDate(bankTransaction.block.created_date),
[TableKeys.memo]: <ExpandableText expanded={expanded} text={bankTransaction.memo || '-'} />,
[TableKeys.recipientAccountNumber]: (
<AccountLink accountNumber={bankTransaction.recipient} expanded={expanded} />
),
Expand All @@ -62,6 +64,7 @@ const AccountTransactions: FC = () => {
[TableKeys.amount]: 'Amount',
[TableKeys.balanceKey]: 'Balance Key',
[TableKeys.dateCreated]: 'Date Created',
[TableKeys.memo]: 'Memo',
[TableKeys.recipientAccountNumber]: 'Recipient',
[TableKeys.senderAccountNumber]: 'Sender',
[TableKeys.signature]: 'Signature',
Expand All @@ -70,6 +73,7 @@ const AccountTransactions: FC = () => {
TableKeys.senderAccountNumber,
TableKeys.recipientAccountNumber,
TableKeys.amount,
TableKeys.memo,
TableKeys.balanceKey,
TableKeys.signature,
TableKeys.dateCreated,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import './SendCoinsModalFields.scss';

export interface FormValues {
coins: string;
memo?: string;
recipientAccountNumber: string;
senderAccountNumber: string;
}
Expand Down Expand Up @@ -98,6 +99,7 @@ const SendCoinsModalFields: FC<ComponentProps> = ({submitting}) => {
options={getToOptions}
required
/>
<FormInput disabled={submitting} label="Memo" name="memo" placeholder="What is it for?" />
<table className="SendCoinsModalFields__table">
<tbody>
<tr>
Expand Down
22 changes: 14 additions & 8 deletions src/renderer/containers/Account/SendCoinsModal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,22 +52,24 @@ const SendCoinsModal: FC<ComponentProps> = ({close, initialRecipient, initialSen
const initialValues = useMemo(
() => ({
coins: '',
memo: '',
recipientAccountNumber: initialRecipient,
senderAccountNumber: initialSender,
}),
[initialRecipient, initialSender],
);

const handleSubmit = async ({coins, recipientAccountNumber, senderAccountNumber}: FormValues): Promise<void> => {
const handleSubmit = async ({
coins,
memo,
recipientAccountNumber,
senderAccountNumber,
}: FormValues): Promise<void> => {
try {
setSubmitting(true);
await sendBlock(
activeBank,
primaryValidator,
managedAccounts[senderAccountNumber].signing_key,
senderAccountNumber,
[{accountNumber: recipientAccountNumber, amount: parseInt(coins, 10)}],
);
await sendBlock(activeBank, managedAccounts[senderAccountNumber].signing_key, [
{amount: parseInt(coins, 10), memo, recipient: recipientAccountNumber},
]);
await Promise.all([
dispatch(fetchAccountBalance(senderAccountNumber)),
dispatch(fetchAccountBalance(recipientAccountNumber)),
Expand Down Expand Up @@ -112,6 +114,10 @@ const SendCoinsModal: FC<ComponentProps> = ({close, initialRecipient, initialSen
.lessThan(COIN_AMOUNT_CEILING, `Coins must be less than ${COIN_AMOUNT_CEILING.toLocaleString()}`)
.integer('Coins cannot be a decimal')
.required('Coins is a required field'),
memo: yup
.string()
.matches(/^[a-zA-Z0-9_ ]*$/, 'Memo can only contain alphanumeric characters, spaces, and underscores')
.max(64, 'Memo cannot exceed 64 characters'),
recipientAccountNumber: yup
.string()
.notEqualTo(senderAccountNumberRef, MATCH_ERROR)
Expand Down
12 changes: 11 additions & 1 deletion src/renderer/containers/Bank/BankTransactions/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ enum TableKeys {
sender,
recipient,
amount,
memo,
}

const BankTransactions: FC = () => {
Expand All @@ -34,6 +35,7 @@ const BankTransactions: FC = () => {
[TableKeys.amount]: bankTransaction.amount,
[TableKeys.block]: <ExpandableText expanded={expanded} text={bankTransaction.block.id} />,
[TableKeys.id]: <ExpandableText expanded={expanded} text={bankTransaction.id} />,
[TableKeys.memo]: <ExpandableText expanded={expanded} text={bankTransaction.memo || '-'} />,
[TableKeys.recipient]: <AccountLink accountNumber={bankTransaction.recipient} expanded={expanded} />,
[TableKeys.sender]: <AccountLink accountNumber={bankTransaction.block.sender} expanded={expanded} />,
})) || [],
Expand All @@ -47,10 +49,18 @@ const BankTransactions: FC = () => {
[TableKeys.amount]: 'Amount',
[TableKeys.block]: 'Block',
[TableKeys.id]: 'ID',
[TableKeys.memo]: 'Memo',
[TableKeys.recipient]: 'Recipient',
[TableKeys.sender]: 'Sender',
},
orderedKeys: [TableKeys.id, TableKeys.block, TableKeys.sender, TableKeys.recipient, TableKeys.amount],
orderedKeys: [
TableKeys.id,
TableKeys.block,
TableKeys.sender,
TableKeys.recipient,
TableKeys.amount,
TableKeys.memo,
],
}),
[bankBankTransactionsTableData],
);
Expand Down
34 changes: 28 additions & 6 deletions src/renderer/containers/EditTrustModal/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import React, {FC, useMemo, useState} from 'react';
import axios from 'axios';
import {Account} from 'thenewboston';
import {Account, Bank, ConfirmationValidator} from 'thenewboston';

import {FormInput} from '@renderer/components/FormComponents';
import Modal from '@renderer/components/Modal';
import {useNavigationalHistory} from '@renderer/hooks';
import {ManagedNode} from '@renderer/types';
import {ManagedNode, NodeType} from '@renderer/types';
import {formatAddressFromNode} from '@renderer/utils/address';
import yup from '@renderer/utils/forms/yup';
import {displayToast} from '@renderer/utils/toast';
Expand Down Expand Up @@ -35,10 +34,33 @@ const EditTrustModal: FC<ComponentProps> = ({close, requestingNode, targetIdenti
const handleSubmit = async (values: FormValues): Promise<void> => {
try {
setSubmitting(true);

const networkIdKeyPair = new Account(requestingNode.nid_signing_key);
const requestData = networkIdKeyPair.createSignedMessage(values);
const address = `${formatAddressFromNode(requestingNode)}/${targetType}/${targetIdentifier}`;
await axios.patch(address, requestData);
const address = formatAddressFromNode(requestingNode);

let node: Bank | ConfirmationValidator;

node = new Bank(address);
const nodeConfig = await node.getConfig();

if (nodeConfig.node_type === NodeType.bank) {
if (targetType === 'accounts') {
node.updateAccountTrust(targetIdentifier, Number(values.trust), networkIdKeyPair);
} else if (targetType === 'banks') {
node.updateBankTrust(targetIdentifier, Number(values.trust), networkIdKeyPair);
} else {
node.updateValidatorTrust(targetIdentifier, Number(values.trust), networkIdKeyPair);
}
} else {
node = new ConfirmationValidator(address);

if (targetType === 'banks') {
node.updateBankTrust(targetIdentifier, Number(values.trust), networkIdKeyPair);
} else {
node.updateValidatorTrust(targetIdentifier, Number(values.trust), networkIdKeyPair);
}
}

reload();
} catch (error) {
displayToast('An error occurred');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import React, {FC, useEffect, useMemo, useReducer, useState} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import {Account} from 'thenewboston';

import Modal from '@renderer/components/Modal';
import {fetchBankConfig} from '@renderer/dispatchers/banks';
import {getActiveBankConfig, getPrimaryValidatorConfig} from '@renderer/selectors';
import {getActiveBankConfig} from '@renderer/selectors';
import {AppDispatch, ManagedNode} from '@renderer/types';
import {formatAddressFromNode} from '@renderer/utils/address';
import {sendBlock} from '@renderer/utils/blocks';
Expand All @@ -23,7 +22,6 @@ interface ComponentProps {
const BulkPurchaseConfirmationServicesModal: FC<ComponentProps> = ({bank, close, selectedValidators}) => {
const dispatch = useDispatch<AppDispatch>();
const activeBankConfig = useSelector(getActiveBankConfig)!;
const primaryValidator = useSelector(getPrimaryValidatorConfig)!;

const [submitting, setSubmitting] = useState<boolean>(false);
const [formValues, dispatchFormValues] = useReducer(
Expand All @@ -45,19 +43,18 @@ const BulkPurchaseConfirmationServicesModal: FC<ComponentProps> = ({bank, close,
const handleSubmit = async (): Promise<void> => {
try {
setSubmitting(true);
const {accountNumberHex: bankAccountNumber} = new Account(bank.account_signing_key);
const recipients = Object.entries(formValues)
const transactions = Object.entries(formValues)
.map(([nodeIdentifier, {amount}]) => {
const validatorData = selectedValidators[nodeIdentifier];
return {
accountNumber: validatorData.account_number,
amount: parseInt(amount, 10),
recipient: validatorData.account_number,
};
})
.filter(({amount}) => !!amount);

await sendBlock(activeBankConfig, primaryValidator, bank.account_signing_key, bankAccountNumber, recipients);
displayToast(`You have purchased ${recipients.length} services`, 'success');
await sendBlock(activeBankConfig, bank.account_signing_key, transactions);
displayToast(`You have purchased ${transactions.length} services`, 'success');
close();
} catch (error) {
displayErrorToast(error);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,8 @@ const PurchaseConfirmationServicesModal: FC<ComponentProps> = ({close, initialBa
try {
setSubmitting(true);
const selectedBank = authenticatedBanks[bankAddress];
const {accountNumberHex: bankAccountNumber} = new Account(selectedBank.account_signing_key);
await sendBlock(activeBankConfig, activePrimaryValidator, selectedBank.account_signing_key, bankAccountNumber, [
{accountNumber: validator.account_number, amount: parseInt(amount, 10)},
await sendBlock(activeBankConfig, selectedBank.account_signing_key, [
{amount: parseInt(amount, 10), recipient: validator.account_number},
]);
displayToast('Your payment has been sent', 'success');
close();
Expand Down
49 changes: 13 additions & 36 deletions src/renderer/containers/PurchaseConfirmationServices/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import axios from 'axios';
import omit from 'lodash/omit';
import {Account} from 'thenewboston';
import {Account, Bank, ConfirmationValidator} from 'thenewboston';

import {AXIOS_TIMEOUT_MS} from '@renderer/config';
import {BaseValidator, ManagedNode} from '@renderer/types';
import {formatAddressFromNode} from '@renderer/utils/address';

Expand Down Expand Up @@ -62,55 +60,34 @@ export const checkConnectionBankToValidator = async (
validator: BaseValidator,
): Promise<void> => {
const bankAddress = formatAddressFromNode(managedBank);
const bank = new Bank(bankAddress);

try {
await axios.get(`${bankAddress}/validators/${validator.node_identifier}`, {timeout: AXIOS_TIMEOUT_MS});
await bank.getValidator(validator.node_identifier);
} catch (error) {
if (!managedBank.nid_signing_key) throw new Error('No NID SK');
const bankNetworkKeyPair = new Account(managedBank.nid_signing_key);
const validatorData = {
account_number: validator.account_number,
daily_confirmation_rate: validator.daily_confirmation_rate,
ip_address: validator.ip_address,
node_identifier: validator.node_identifier,
protocol: validator.protocol,
root_account_file: validator.root_account_file,
root_account_file_hash: validator.root_account_file_hash,
trust: 0,
version: validator.version,
};
const signedMessage = bankNetworkKeyPair.createSignedMessage(validatorData);
await axios.post(`${bankAddress}/validators`, signedMessage, {
headers: {
'Content-Type': 'application/json',
},
});
const {ip_address: ipAddress, port, protocol} = validator;
await bank.sendConnectionRequest(ipAddress, port, protocol, bankNetworkKeyPair);
}
};

export const checkConnectionValidatorToBank = async (
managedBank: ManagedNode,
managedValidator: ManagedNode,
validator: BaseValidator,
bankNodeIdentifier: string,
): Promise<void> => {
const validatorAddress = formatAddressFromNode(validator);
const validatorNode = new ConfirmationValidator(validatorAddress);

try {
await axios.get(`${validatorAddress}/banks/${bankNodeIdentifier}`, {timeout: AXIOS_TIMEOUT_MS});
await validatorNode.getBank(bankNodeIdentifier);
} catch (error) {
if (!managedBank.nid_signing_key) throw new Error('No NID SK');
const validatorNetworkKeyPair = new Account(managedBank.nid_signing_key);
const connectionRequestData = {
ip_address: managedBank.ip_address,
port: managedBank.port,
protocol: managedBank.protocol,
};
const signedMessage = validatorNetworkKeyPair.createSignedMessage(connectionRequestData);
await axios.post(`${validatorAddress}/connection_requests`, signedMessage, {
headers: {
'Content-Type': 'application/json',
},
});
if (!managedValidator.nid_signing_key) throw new Error('No NID SK');
const validatorNetworkKeyPair = new Account(managedValidator.nid_signing_key);

const {ip_address: ipAddress, port, protocol} = managedValidator;
await validatorNode.sendConnectionRequest(ipAddress, port, protocol, validatorNetworkKeyPair);
}
};

Expand Down
Loading

0 comments on commit f2cd300

Please sign in to comment.