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: Add NFC support #183

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
6 changes: 6 additions & 0 deletions app.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@
},
"assetBundlePatterns": ["**/*"],
"plugins": [
[
"./plugins/withReactNativeHce",
{
"appIds": ["D2760000850101"]
}
],
[
"expo-local-authentication",
{
Expand Down
5 changes: 4 additions & 1 deletion components/Icons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
TriangleAlert,
LogOut,
ArchiveRestore,
Nfc,
} from "lucide-react-native";
import { cssInterop } from "nativewind";

Expand Down Expand Up @@ -95,6 +96,7 @@ interopIcon(CircleCheck);
interopIcon(TriangleAlert);
interopIcon(LogOut);
interopIcon(ArchiveRestore);
interopIcon(Nfc);

export {
AlertCircle,
Expand Down Expand Up @@ -136,5 +138,6 @@ export {
CircleCheck,
TriangleAlert,
LogOut,
ArchiveRestore
ArchiveRestore,
Nfc,
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"react-dom": "18.2.0",
"react-native": "0.74.5",
"react-native-get-random-values": "^1.9.0",
"react-native-hce": "^0.2.0",
"react-native-qrcode-svg": "^6.3.1",
"react-native-reanimated": "~3.10.1",
"react-native-safe-area-context": "4.10.5",
Expand Down
108 changes: 97 additions & 11 deletions pages/receive/Receive.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { Link, router } from "expo-router";
import { Share, TouchableOpacity, View } from "react-native";
import { Share, TouchableOpacity, View, Platform } from "react-native";
import { Button } from "~/components/ui/button";
import * as Clipboard from "expo-clipboard";
import React from "react";
import { useAppStore } from "~/lib/state/appStore";
import { Input } from "~/components/ui/input";
import { Text } from "~/components/ui/text";
import { ArchiveRestore, Copy, Share2, ZapIcon } from "~/components/Icons";
import {
ArchiveRestore,
Copy,
Share2,
ZapIcon,
Nfc,
X,
} from "~/components/Icons";
import Toast from "react-native-toast-message";
import { errorToast } from "~/lib/errorToast";
import { Nip47Transaction } from "@getalby/sdk/dist/NWCClient";
Expand All @@ -16,6 +23,11 @@ import { useGetFiatAmount } from "~/hooks/useGetFiatAmount";
import QRCode from "~/components/QRCode";
import Screen from "~/components/Screen";
import DismissableKeyboardView from "~/components/DismissableKeyboardView";
import {
HCESession,
NFCTagType4NDEFContentType,
NFCTagType4,
} from "react-native-hce";

export function Receive() {
const getFiatAmount = useGetFiatAmount();
Expand All @@ -25,10 +37,13 @@ export function Receive() {
const [amount, setAmount] = React.useState("");
const [comment, setComment] = React.useState("");
const [enterCustomAmount, setEnterCustomAmount] = React.useState(false);
const [hceInstance, setHceInstance] = React.useState<HCESession | null>(null);
const [hceEnabled, setHceEnabled] = React.useState(false);
const selectedWalletId = useAppStore((store) => store.selectedWalletId);
const wallets = useAppStore((store) => store.wallets);
const lightningAddress = wallets[selectedWalletId].lightningAddress;
const nwcCapabilities = wallets[selectedWalletId].nwcCapabilities;
const hceSupported = Platform.OS === "android";

function setInvoice(invoice: string) {
_setInvoice(invoice);
Expand Down Expand Up @@ -100,7 +115,7 @@ export function Receive() {
polling &&
pollCount > 0 &&
receivedTransaction.payment_hash !==
prevTransaction?.payment_hash
prevTransaction?.payment_hash
) {
if (
!invoiceRef.current ||
Expand Down Expand Up @@ -142,6 +157,7 @@ export function Receive() {
!invoiceRef.current ||
notification.notification.invoice === invoiceRef.current
) {
setHceEnabled(false);
router.dismissAll();
router.navigate({
pathname: "/receive/success",
Expand All @@ -158,6 +174,64 @@ export function Receive() {
};
}, []);

React.useEffect(() => {
(async () => {
const hce = await HCESession.getInstance();
setHceInstance(hce);
})();
}, []);

React.useEffect(() => {
if (!hceInstance) {
return;
}
hceInstance.setEnabled(hceEnabled);
}, [hceEnabled]);

function sendNdefMessage() {
const text = invoice || lightningAddress;
if (!text) {
errorToast(new Error("Nothing to send via NFC"));
return;
}

const lnurl = "lightning:" + text;

const tag = new NFCTagType4({
type: NFCTagType4NDEFContentType.URL,
content: lnurl,
writable: false,
});

if (!hceInstance) {
errorToast(new Error("NFC is not available"));
return;
}

if (hceEnabled) {
setHceEnabled(false);
}

console.log("NFC: starting to send Ndef");

hceInstance.setApplication(tag);
setHceEnabled(true);
}

function toggleNFC() {
if (!hceInstance) {
errorToast(new Error("NFC is not available"));
return;
}

if (hceEnabled) {
console.log("NFC: disabled");
setHceEnabled(false);
} else {
sendNdefMessage();
}
}

async function share() {
const message = invoice || lightningAddress;
try {
Expand All @@ -175,10 +249,7 @@ export function Receive() {

return (
<>
<Screen
title="Receive"
animation="slide_from_left"
/>
<Screen title="Receive" animation="slide_from_left" />
{!enterCustomAmount && !invoice && !lightningAddress && (
<>
<View className="flex-1 h-full flex flex-col items-center justify-center gap-5">
Expand Down Expand Up @@ -253,7 +324,22 @@ export function Receive() {
<Share2 className="text-muted-foreground" />
<Text>Share</Text>
</Button>
{!enterCustomAmount && invoice &&
{hceSupported && (
<Button
variant="secondary"
onPress={toggleNFC}
className="flex-1 flex flex-col gap-2"
disabled={!hceInstance}
>
{hceEnabled ? (
<X className="text-muted-foreground" />
) : (
<Nfc className="text-muted-foreground" />
)}
<Text>NFC</Text>
</Button>
)}
{!enterCustomAmount && invoice && (
<Button
variant="secondary"
onPress={copy}
Expand All @@ -262,7 +348,7 @@ export function Receive() {
<Copy className="text-muted-foreground" />
<Text>Copy</Text>
</Button>
}
)}
{!enterCustomAmount && !invoice && (
<Button
variant="secondary"
Expand All @@ -273,7 +359,7 @@ export function Receive() {
<Text>Invoice</Text>
</Button>
)}
{!enterCustomAmount && !invoice &&
{!enterCustomAmount && !invoice && (
<Button
variant="secondary"
className="flex-1 flex flex-col gap-2"
Expand All @@ -284,7 +370,7 @@ export function Receive() {
<ArchiveRestore className="text-muted-foreground" />
<Text>Withdraw</Text>
</Button>
}
)}
</View>
</>
)}
Expand Down
128 changes: 128 additions & 0 deletions plugins/withReactNativeHce.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
const {
AndroidConfig,
XML,
withAndroidManifest,
} = require("expo/config-plugins");
const { mkdirSync } = require("fs");

const NfcHceServiceXml = `
<service
android:name="com.reactnativehce.services.CardService"
android:exported="true"
android:enabled="false"
android:permission="android.permission.BIND_NFC_SERVICE">
<intent-filter>
<action
android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
<meta-data
android:name="android.nfc.cardemulation.host_apdu_service"
android:resource="@xml/aid_list"/>
</service>`;

function addNfcHceHardwareFeatureToManifest(androidManifest) {
// Add `<uses-feature android:name="android.hardware.nfc.hce" android:required="true" />` to the AndroidManifest.xml
if (!Array.isArray(androidManifest.manifest["uses-feature"])) {
androidManifest.manifest["uses-feature"] = [];
}

if (
!androidManifest.manifest["uses-feature"].find(
(item) => item.$["android:name"] === "android.hardware.nfc.hce",
)
) {
androidManifest.manifest["uses-feature"].push({
$: {
"android:name": "android.hardware.nfc.hce",
"android:required": "true",
},
});
}
return androidManifest;
}

async function addNfcHceServiceToManifest(androidManifest) {
const { manifest } = androidManifest;

const NfcHceService = await XML.parseXMLAsync(NfcHceServiceXml);

if (!Array.isArray(manifest["application"])) {
console.warn("withReactNativeHce: No manifest.application array?");
return androidManifest;
}

const application = manifest["application"].find(
(item) => item.$["android:name"] === ".MainApplication",
);
if (!application) {
console.warn("withReactNativeHce: No .MainApplication?");
return androidManifest;
}

let services = application["service"];
if (!Array.isArray(services)) {
services = [];
application["service"] = services;
}

if (
!services.find(
(item) =>
item.$["android:name"] === "com.reactnativehce.services.CardService",
)
) {
services.push(NfcHceService.service);
}

return androidManifest;
}

function aidFilters(appIds) {
return appIds.map((appId) => ({ $: { "android:name": appId } }));
}

function aidGroup(appIds) {
return [
{
$: {
"android:category": "other",
"android:description": "@string/app_name",
},
"aid-filter": aidFilters(appIds),
},
];
}

function hostApduService(appIds) {
return {
"host-apdu-service": {
$: {
"xmlns:android": "http://schemas.android.com/apk/res/android",
"android:description": "@string/app_name",
"android:requireDeviceUnlock": "false",
},
"aid-group": aidGroup(appIds),
},
};
}

async function writeAidList(appIds) {
const obj = hostApduService(appIds);
const dir = "android/app/src/main/res/xml";

mkdirSync(dir, { recursive: true });
await XML.writeXMLAsync({ path: `${dir}/aid_list.xml`, xml: obj });
}

module.exports = function withNfcHceAndroidManifest(config, { appIds }) {
config = withAndroidManifest(config, async (config) => {
config.modResults = addNfcHceHardwareFeatureToManifest(config.modResults);
config.modResults = await addNfcHceServiceToManifest(config.modResults);
writeAidList(appIds);
return config;
});
return AndroidConfig.Permissions.withPermissions(config, [
"android.permission.NFC",
]);
};
Loading