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

Receive via NFC #1251

Merged
merged 3 commits into from
Jan 12, 2023
Merged
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
1 change: 1 addition & 0 deletions locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"general.request": "Request",
"general.scan": "Scan",
"general.enableNfc": "Enable NFC",
"general.receiveNfc": "Receive via NFC",
"general.confirm": "Confirm",
"general.cancel": "Cancel",
"general.warning": "Warning",
Expand Down
136 changes: 134 additions & 2 deletions views/Receive.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,23 @@ import {
StyleSheet,
Text,
TouchableOpacity,
View
View,
Platform
} from 'react-native';
import BigNumber from 'bignumber.js';
import { LNURLWithdrawParams } from 'js-lnurl';
import { ButtonGroup, Header, Icon } from 'react-native-elements';
import { inject, observer } from 'mobx-react';
import _map from 'lodash/map';

import NfcManager, {
NfcEvents,
TagEvent,
Ndef
} from 'react-native-nfc-manager';

import handleAnything from './../utils/handleAnything';

import Success from '../assets/images/GIF/Success.gif';

import Amount from './../components/Amount';
Expand All @@ -37,6 +46,7 @@ import UnitsStore, { SATS_PER_BTC } from './../stores/UnitsStore';

import { localeString } from './../utils/LocaleUtils';
import BackendUtils from './../utils/BackendUtils';
import NFCUtils from './../utils/NFCUtils';
import { themeColor } from './../utils/ThemeUtils';

interface ReceiveProps {
Expand Down Expand Up @@ -75,7 +85,7 @@ export default class Receive extends React.Component<
routeHints: false
};

componentDidMount() {
async componentDidMount() {
const { navigation, InvoicesStore } = this.props;
const { reset } = InvoicesStore;

Expand All @@ -100,12 +110,32 @@ export default class Receive extends React.Component<
}

if (autoGenerate) this.autoGenerateInvoice(this.getSatAmount(amount));

if (Platform.OS === 'android') {
await this.enableNfc();
}
}

componentWillUnmount() {
if (this.listener && this.listener.stop) this.listener.stop();
}

UNSAFE_componentWillReceiveProps(nextProps: any) {
const { navigation, InvoicesStore } = nextProps;
const { reset } = InvoicesStore;

reset();
const lnurl: LNURLWithdrawParams | undefined =
navigation.getParam('lnurlParams');

if (lnurl) {
this.setState({
memo: lnurl.defaultDescription,
value: (lnurl.maxWithdrawable / 1000).toString()
});
}
}

autoGenerateInvoice = (amount?: string) => {
const { InvoicesStore } = this.props;
const { createUnifiedInvoice } = InvoicesStore;
Expand All @@ -123,6 +153,88 @@ export default class Receive extends React.Component<
).then((rHash: string) => this.subscribeInvoice(rHash));
};

disableNfc = () => {
NfcManager.setEventListener(NfcEvents.DiscoverTag, null);
NfcManager.setEventListener(NfcEvents.SessionClosed, null);
};

enableNfc = async () => {
this.disableNfc();
await NfcManager.start().catch((e) => console.warn(e.message));

return new Promise((resolve: any) => {
let tagFound: TagEvent | null = null;

NfcManager.setEventListener(
NfcEvents.DiscoverTag,
(tag: TagEvent) => {
tagFound = tag;
const bytes = new Uint8Array(
tagFound.ndefMessage[0].payload
);

let str;
const decoded = Ndef.text.decodePayload(bytes);
if (decoded.match(/^(https?|lnurl)/)) {
str = decoded;
} else {
str = NFCUtils.nfcUtf8ArrayToStr(bytes) || '';
}
resolve(this.validateAddress(str));
NfcManager.unregisterTagEvent().catch(() => 0);
}
);

NfcManager.setEventListener(NfcEvents.SessionClosed, () => {
if (!tagFound) {
resolve();
}
});

NfcManager.registerTagEvent();
});
};

validateAddress = (text: string) => {
const { navigation, InvoicesStore } = this.props;
const { createUnifiedInvoice } = InvoicesStore;
const amount = this.getSatAmount(navigation.getParam('amount'));

handleAnything(text, amount.toString())
.then((response) => {
try {
const [route, props] = response;
const { lnurlParams } = props;
const { memo } = lnurlParams.defaultDescription;

// if an amount was entered on the keypad screen before scanning
// we will automatically create an invoice and attempt to withdraw
// otherwise we present the user with the create invoice screen
if (Number(amount) > 0) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great job on this decision here. would be nice to have a comment explaining this though

have we tested this against lnurl-w's with ranges?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added comment in there and also cleaned up the commit history to squash prettier commit

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested against a card with a rang of 1-362560 and a card with 1.1-1.1

createUnifiedInvoice(
memo,
amount.toString(),
'3600',
lnurlParams
)
.then((rHash: string) => {
navigation.setParam;
this.subscribeInvoice(rHash);
})
.catch(() => {
navigation.navigate(route, {
amount,
...props
});
});
} else {
navigation.navigate(route, props);
}
} catch (e) {}
})
.catch();
};

subscribeInvoice = (rHash: string) => {
const { InvoicesStore, SettingsStore } = this.props;
const { implementation } = SettingsStore;
Expand Down Expand Up @@ -552,6 +664,26 @@ export default class Receive extends React.Component<
textBottom
/>
)}
{Platform.OS === 'ios' && (
<View
style={[
styles.button,
{ paddingTop: 0 }
]}
>
<Button
title={localeString(
'general.receiveNfc'
)}
icon={{
name: 'nfc',
size: 25
}}
onPress={() => this.enableNfc()}
secondary
/>
</View>
)}
{!belowDustLimit && haveUnifiedInvoice && (
<ButtonGroup
onPress={this.updateIndex}
Expand Down