Skip to content
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@
"peerDependencies": {
"@craftzdog/react-native-buffer": "^6.1.0",
"@react-native-async-storage/async-storage": "^2.2.0",
"@scure/base": "^1.2.0",
"@tetherto/pear-wrk-wdk": "^1.0.0-beta.4",
"@tetherto/wdk-secret-manager": "^1.0.0-beta.3",
"b4a": "^1.7.2",
Expand Down
331 changes: 331 additions & 0 deletions src/contexts/ocp-context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,331 @@
import type { ReactNode } from 'react';
import { createContext, useContext, useReducer } from 'react';
import { OcpError, ocpService } from '../services/ocp';
import { WDKService } from '../services/wdk-service';
import type { NetworkType } from '../services/wdk-service/types';
import { AssetTicker } from '../services/wdk-service/types';
import type {
OcpDetection,
OcpPaymentDetails,
OcpStatus,
OcpSubmitResult,
OcpTransactionDetails,
} from '../services/ocp/types';

// Mappings

const OCP_METHOD_TO_NETWORK: Record<string, NetworkType> = {
Bitcoin: 'bitcoin' as NetworkType,
Ethereum: 'ethereum' as NetworkType,
Arbitrum: 'arbitrum' as NetworkType,
Polygon: 'polygon' as NetworkType,
Lightning: 'lightning' as NetworkType,
Solana: 'solana' as NetworkType,
Tron: 'tron' as NetworkType,
};

const OCP_ASSET_TO_TICKER: Record<string, AssetTicker> = {
BTC: AssetTicker.BTC,
USDT: AssetTicker.USDT,
XAUT: AssetTicker.XAUT,
};

const SUPPORTED_METHODS = Object.keys(OCP_METHOD_TO_NETWORK);

// State

interface OcpState {
status: OcpStatus;
detection: OcpDetection | null;
paymentDetails: OcpPaymentDetails | null;
transactionDetails: OcpTransactionDetails | null;
txHash: string | null;
result: OcpSubmitResult | null;
error: string | null;
}

const INITIAL_STATE: OcpState = {
status: 'idle',
detection: null,
paymentDetails: null,
transactionDetails: null,
txHash: null,
result: null,
error: null,
};

// Actions

type OcpAction =
| { type: 'SET_STATUS'; payload: OcpStatus }
| { type: 'SET_DETECTION'; payload: OcpDetection }
| { type: 'SET_PAYMENT_DETAILS'; payload: OcpPaymentDetails }
| { type: 'SET_TRANSACTION_DETAILS'; payload: OcpTransactionDetails }
| { type: 'SET_TX_HASH'; payload: string }
| { type: 'SET_RESULT'; payload: OcpSubmitResult }
| { type: 'SET_ERROR'; payload: string }
| { type: 'RESET' };

function reducer(state: OcpState, action: OcpAction): OcpState {
switch (action.type) {
case 'SET_STATUS':
return { ...state, status: action.payload };

case 'SET_DETECTION':
return { ...state, detection: action.payload, error: null };

case 'SET_PAYMENT_DETAILS':
return {
...state,
paymentDetails: action.payload,
status: 'ready',
};

case 'SET_TRANSACTION_DETAILS':
return { ...state, transactionDetails: action.payload };

case 'SET_TX_HASH':
return { ...state, txHash: action.payload };

case 'SET_RESULT':
return { ...state, result: action.payload, status: 'success' };

case 'SET_ERROR':
return { ...state, error: action.payload, status: 'error' };

case 'RESET':
return INITIAL_STATE;

default:
return state;
}
}

// Context

interface OcpContextType extends OcpState {
supportedMethods: string[];
detect: (qrData: string) => OcpDetection | null;
fetchPaymentDetails: (
apiUrl: string,
timeout?: number
) => Promise<OcpPaymentDetails>;
pay: (
method: string,
asset: string,
accountIndex?: number
) => Promise<OcpSubmitResult>;
reset: () => void;
}

const OcpContext = createContext<OcpContextType | undefined>(undefined);

// Provider

export function OcpProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, INITIAL_STATE);

const reset = () => {
dispatch({ type: 'RESET' });
};

const detect = (qrData: string): OcpDetection | null => {
const detection = ocpService.detect(qrData);
if (detection) {
dispatch({ type: 'SET_DETECTION', payload: detection });
}
return detection;
};

const fetchPaymentDetails = async (
apiUrl: string,
timeout?: number
): Promise<OcpPaymentDetails> => {
dispatch({ type: 'SET_STATUS', payload: 'loading' });

try {
const details = await ocpService.getPaymentDetails(apiUrl, timeout);
dispatch({ type: 'SET_PAYMENT_DETAILS', payload: details });
return details;
} catch (e) {
console.error('Failed to fetch payment details:', e);
const msg =
e instanceof Error ? e.message : 'Failed to fetch payment details';
dispatch({ type: 'SET_ERROR', payload: msg });
throw e;
}
};

const pay = async (
method: string,
asset: string,
accountIndex: number = 0
): Promise<OcpSubmitResult> => {
if (!state.paymentDetails) {
throw new OcpError(
'no_payment',
'No payment details. Call fetchPaymentDetails first.'
);
}

if (state.status === 'paying' || state.status === 'submitting') {
throw new OcpError(
'payment_in_progress',
'A payment is already in progress'
);
}

// Check quote expiration before proceeding
const expiration = new Date(state.paymentDetails.quote.expiration);
if (expiration.getTime() < Date.now()) {
throw new OcpError(
'quote_expired',
'Quote has expired. Fetch new payment details'
);
}

const network = OCP_METHOD_TO_NETWORK[method];
if (!network) {
throw new OcpError(
'unsupported_method',
`Method "${method}" is not supported by WDK`
);
}

const wdkAsset = OCP_ASSET_TO_TICKER[asset];
if (!wdkAsset) {
throw new OcpError(
'unsupported_asset',
`Asset "${asset}" is not supported by WDK`
);
}

const transferMethod = state.paymentDetails.transferAmounts.find(
(t) => t.method === method && t.available
);
if (!transferMethod) {
throw new OcpError(
'method_unavailable',
`Method "${method}" is not available for this payment`
);
}

const transferAsset = transferMethod.assets.find(
(a) => a.asset === asset
);
if (!transferAsset) {
throw new OcpError(
'asset_unavailable',
`Asset "${asset}" is not available for method "${method}"`
);
}

const amount = parseFloat(transferAsset.amount);

try {
// Get transaction details
dispatch({ type: 'SET_STATUS', payload: 'paying' });
const txDetails = await ocpService.getTransactionDetails(
state.paymentDetails.callback,
state.paymentDetails.quote.id,
method,
asset
);
dispatch({ type: 'SET_TRANSACTION_DETAILS', payload: txDetails });

// Send via WDK
const response = await WDKService.sendByNetwork(
network,
accountIndex,
amount,
extractRecipient(txDetails, method),
wdkAsset
);

const txHash = extractTxHash(response);
if (!txHash) {
throw new OcpError(
'no_tx_hash',
'WDK did not return a transaction hash'
);
}

// Persist tx hash so the app can retry submission if it fails
dispatch({ type: 'SET_TX_HASH', payload: txHash });

// Submit tx hash to OCP API
dispatch({ type: 'SET_STATUS', payload: 'submitting' });
const submitResult = await ocpService.submitTxHash(
state.paymentDetails.callback,
state.paymentDetails.quote.id,
state.paymentDetails.quote.payment,
method,
txHash
);

dispatch({ type: 'SET_RESULT', payload: submitResult });
return submitResult;
} catch (e) {
console.error('OCP payment failed:', e);
const msg = e instanceof Error ? e.message : 'Payment failed';
dispatch({ type: 'SET_ERROR', payload: msg });
throw e;
}
};

const value: OcpContextType = {
...state,
supportedMethods: SUPPORTED_METHODS,
detect,
fetchPaymentDetails,
pay,
reset,
};

return <OcpContext.Provider value={value}>{children}</OcpContext.Provider>;
}

// Hook

export function useOcp() {
const context = useContext(OcpContext);
if (context === undefined) {
throw new Error('useOcp must be used within an OcpProvider');
}
return context;
}

// Helpers

function extractRecipient(
txDetails: OcpTransactionDetails,
method: string
): string {
const { uri } = txDetails;
if (!uri) {
throw new OcpError(
'no_uri',
`No payment URI for method "${method}"`
);
}

// ethereum:0x1234...@chainId?value=... | bitcoin:bc1...?amount=...
const match = uri.match(/^[a-zA-Z]+:([^?@/]+)/);
if (!match || !match[1]) {
throw new OcpError('invalid_uri', `Cannot parse recipient from URI: ${uri}`);
}

return match[1] as string;
}

function extractTxHash(response: unknown): string | null {
if (!response) return null;
if (typeof response === 'string') return response;
if (typeof response !== 'object') return null;

const r = response as Record<string, unknown>;
const hash = r.txHash ?? r.hash ?? r.transactionHash ?? r.txId;
return typeof hash === 'string' ? hash : null;
}

export default OcpContext;
19 changes: 19 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,22 @@ export {
AssetTicker,
NetworkType,
} from './services/wdk-service/types';

// Export OpenCryptoPay
export {
useOcp,
default as OcpContext,
OcpProvider,
} from './contexts/ocp-context';
export { OcpService, OcpError, ocpService } from './services/ocp';
export type {
OcpPaymentDetails,
OcpTransactionDetails,
OcpTransferMethod,
OcpTransferAsset,
OcpRecipient,
OcpQuote,
OcpSubmitResult,
OcpDetection,
OcpStatus,
} from './services/ocp/types';
Loading