Skip to content
Closed
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
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,21 @@ VITE_WALLETCONNECT_PROJECT_ID=Your Project ID can be obtained from https://dashb
```
> ⚠️ **Security Note:** Never commit `.env` files to version control. Keep your private keys secure.

### Relay configuration

Invoice payloads travel encrypted over a [ThruBox](https://github.com/AOSSIE-Org/ThruBox-Server) relay, configured with:

```env
VITE_RELAY_URL=http://localhost:3000
VITE_RELAY_API_KEY=
VITE_RELAY_TIMEOUT_MS=
```

- **`VITE_RELAY_URL`** — in development this is the target the Vite dev server proxies `/relay` to, so the browser stays same-origin. In production, either an absolute `https://` URL (which requires CORS on the relay) or a path such as `/relay` that your host rewrites to it (Vercel rewrites, Netlify redirects, nginx `proxy_pass`), which avoids CORS entirely.
- **`VITE_RELAY_API_KEY`** — only needed if the relay sets `security.api_key`. **This is not a secret:** Vite inlines every `VITE_`-prefixed variable into the built JavaScript, so any visitor can read it. Treat it as a spam speed-bump, not access control. To keep a relay key private, proxy relay calls server-side and inject it there.
- **`VITE_RELAY_TIMEOUT_MS`** — request timeout, default `15000`. Raise it (around `60000`) on hosts that suspend idle instances: a cold start can take most of a minute, and sends are deliberately not retried, so a timeout means an undelivered invoice.


## Deployed Contracts
### v1 (Mainnet Deployment — Jan 1)
- Ethereum Sepolia (11155111)
Expand Down
23 changes: 23 additions & 0 deletions frontend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,26 @@ VITE_CONTRACT_ADDRESS_61=0xD044A85a5daC307217B9bF313A90E8a60AF7DdCe
VITE_CONTRACT_ADDRESS_137=0xD044A85a5daC307217B9bF313A90E8a60AF7DdCe

VITE_WALLETCONNECT_PROJECT_ID=

# ThruBox relay — transport for encrypted invoice payloads.
# In development this is the target the Vite dev server proxies /relay to.
#
# In production, either:
# - an absolute URL (https://relay.example.com) — needs CORS on the relay, or
# - a path (/relay) — the host rewrites it to the relay, so the browser stays
# same-origin and no CORS is needed. Works with Vercel rewrites, Netlify
# redirects, or an nginx proxy_pass.
VITE_RELAY_URL=http://localhost:3000

# Only needed if the relay is configured with security.api_key. Leave blank otherwise.
#
# NOT A SECRET. Vite inlines every VITE_-prefixed variable into the built
# JavaScript, so anyone can read this out of the bundle. Treat it as a spam
# speed-bump, not access control — it cannot restrict the relay to this app.
# To keep a relay key private, proxy relay calls server-side (see VITE_RELAY_URL
# above) and inject the key there instead of shipping it to the browser.
VITE_RELAY_API_KEY=
Comment thread
coderabbitai[bot] marked this conversation as resolved.

# Request timeout in ms (default 15000). Raise it on hosts that suspend idle
# instances — a cold start can take ~60s, and sends are not retried.
VITE_RELAY_TIMEOUT_MS=
14 changes: 14 additions & 0 deletions frontend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,20 @@ VITE_CONTRACT_ADDRESS_137=0xD044A85a5daC307217B9bF313A90E8a60AF7DdCe
VITE_WALLETCONNECT_PROJECT_ID=
```

### Relay configuration

Invoice payloads travel encrypted over a [ThruBox](https://github.com/AOSSIE-Org/ThruBox-Server) relay, configured with:

```env
VITE_RELAY_URL=http://localhost:3000
VITE_RELAY_API_KEY=
VITE_RELAY_TIMEOUT_MS=
```

- **`VITE_RELAY_URL`** — in development this is the target the Vite dev server proxies `/relay` to, so the browser stays same-origin. In production, either an absolute `https://` URL (which requires CORS on the relay) or a path such as `/relay` that your host rewrites to it (Vercel rewrites, Netlify redirects, nginx `proxy_pass`), which avoids CORS entirely.
- **`VITE_RELAY_API_KEY`** — only needed if the relay sets `security.api_key`. **This is not a secret:** Vite inlines every `VITE_`-prefixed variable into the built JavaScript, so any visitor can read it. Treat it as a spam speed-bump, not access control. To keep a relay key private, proxy relay calls server-side and inject it there.
- **`VITE_RELAY_TIMEOUT_MS`** — request timeout, default `15000`. Raise it (around `60000`) on hosts that suspend idle instances: a cold start can take most of a minute, and sends are deliberately not retried, so a timeout means an undelivered invoice.

To enable Web3 wallet functionality, create a free WalletConnect Project ID from the Reown dashboard:

```text
Expand Down
3 changes: 3 additions & 0 deletions frontend/jest.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ module.exports = {
collectCoverageFrom: [
"src/utils/invoiceCalculations.js",
"src/utils/invoiceValidation.js",
"src/services/relay/invoiceCrypto.js",
"src/services/relay/invoiceHashUtils.js",
"src/services/relay/relayInvoiceMessaging.js",
],
coverageDirectory: "<rootDir>/coverage",
};
2 changes: 2 additions & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
},
"dependencies": {
"@aossie-org/idb-backup": "^1.0.0",
"@aossie-org/thrubox-client": "1.0.2",
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.0",
"@mui/icons-material": "^6.4.6",
Expand All @@ -31,6 +32,7 @@
"clsx": "^2.1.1",
"crypto-convert": "^2.1.7",
"date-fns": "^3.6.0",
"eciesjs": "0.5.0",
"ethers": "^6.13.5",
"framer-motion": "^12.23.12",
"html2canvas": "^1.4.1",
Expand Down
229 changes: 229 additions & 0 deletions frontend/src/hooks/useRelayKeys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
import { useState, useCallback, useEffect, useRef } from 'react';
import { useAccount, useWalletClient } from 'wagmi';
import { BrowserProvider, Contract } from 'ethers';
import { ChainvoiceABI } from '../contractsABI/ChainvoiceABI.js';
import {
deriveRelayKeyPair,
registerPublicKeyOnChain,
fetchPublicKeyFromChain,
bytesToHex,
getCachedKeyPair,
clearCachedKeys,
} from '../services/relay/relayKeyManager.js';

/**
* React hook for managing the user's ECIES messaging keypair.
* Handles derivation from a wallet signature, session caching,
* and on-chain registration status.
*/
export function useRelayKeys() {
const { data: walletClient } = useWalletClient();
const { address, chainId } = useAccount();
const [keys, setKeys] = useState(null);
const [hasKeys, setHasKeys] = useState(false);
const [isRegistered, setIsRegistered] = useState(false);
const [isUnsupportedNetwork, setIsUnsupportedNetwork] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
// Persist to sessionStorage by default. Without this the private key lives
// only in module memory, so a page reload silently loses it and anything
// gated on key availability — like polling the relay for new invoices —
// never starts again. sessionStorage still dies with the tab.
const [rememberSession, setRememberSession] = useState(true);

// Always the address of the currently connected account, readable from
// inside in-flight async work to tell whether its result is still wanted.
// Written in an effect rather than during render: a render can be discarded
// without committing (StrictMode double-renders, for one), and recording an
// address the committed tree never used would make the staleness check
// discard results that are actually current.
const activeAddressRef = useRef(address);
useEffect(() => {
activeAddressRef.current = address;
}, [address]);

// Reset account-scoped state and republish any already-derived key in one
// pass. Reads the cache directly rather than going through
// deriveRelayKeyPair, which would fall through to signMessage when the cache
// is empty or corrupt and pop an unexplained signature prompt on page load.
useEffect(() => {
setIsRegistered(false);
setError(null);

const cached = address ? getCachedKeyPair(address) : null;
setKeys(cached);
setHasKeys(cached !== null);
}, [address]);

// Drop the stored key for an account the user has actually left — a
// disconnect, or a switch to a different account.
//
// Deliberately not an effect cleanup: cleanups also run on unmount, which
// would wipe the key on every route change, on any second consumer of this
// hook unmounting, and once immediately in StrictMode — throwing away the
// key the effect above had just restored, and defeating the reason for
// persisting it at all.
const previousAddressRef = useRef(address);
useEffect(() => {
const previous = previousAddressRef.current;
previousAddressRef.current = address;
if (previous && previous !== address) {
clearCachedKeys(previous);
}
}, [address]);

const getContract = useCallback(async () => {
if (!walletClient || !chainId) return null;
const provider = new BrowserProvider(walletClient);
const signer = await provider.getSigner();
const contractAddress = import.meta.env[`VITE_CONTRACT_ADDRESS_${chainId}`];
if (!contractAddress) return null;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
return new Contract(contractAddress, ChainvoiceABI, signer);
}, [walletClient, chainId]);
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/** Derive keys from wallet signature without registering on-chain. */
const deriveKeysOnly = useCallback(
async (remember) => {
if (!walletClient || !address) throw new Error('Wallet not connected');
const requestedAddress = address;
const provider = new BrowserProvider(walletClient);
const signer = await provider.getSigner();
const shouldRemember = remember !== undefined ? remember : rememberSession;
const keyPair = await deriveRelayKeyPair(signer, requestedAddress, shouldRemember);
// Signing takes as long as the user takes, so the account may have
// changed underneath us; publishing then would attach one account's key
// to another.
if (activeAddressRef.current !== requestedAddress) return keyPair;
setKeys(keyPair);
setHasKeys(true);
return keyPair;
},
[walletClient, address, rememberSession]
);

/** Check if the user's public key is registered on-chain. */
const checkRegistration = useCallback(async () => {
const requestedAddress = address;
// Reading the registry is an async chain call. If the user switches
// accounts while it is in flight, the resolved value describes the old
// account — applying it would report the previous account's registration
// state for the current one, and could skip the setup step for an address
// that has no key on chain.
const isStale = () => activeAddressRef.current !== requestedAddress;

// "No contract on this chain" is not the same as "not registered", and
// registering cannot fix it — report it separately so callers can say so
// rather than offering a setup step that is guaranteed to fail.
const unsupported =
Boolean(chainId) && !import.meta.env[`VITE_CONTRACT_ADDRESS_${chainId}`];
if (!isStale()) setIsUnsupportedNetwork(unsupported);
if (unsupported) {
if (!isStale()) setIsRegistered(false);
return false;
}

const contract = await getContract();
if (!contract || !requestedAddress) {
if (!isStale()) setIsRegistered(false);
return false;
}
try {
const pubKey = await fetchPublicKeyFromChain(contract, requestedAddress);
const registered = pubKey !== null && pubKey.length > 0;
if (!isStale()) setIsRegistered(registered);
return registered;
} catch (err) {
// A transient RPC failure is indistinguishable from "not registered" in
// the returned value, so leave a trace of which one it was.
console.warn('[useRelayKeys] Registry read failed:', err);
if (!isStale()) setIsRegistered(false);
return false;
}
}, [getContract, address, chainId]);

/** Derive keys AND register the public key on-chain (if not already). */
const deriveAndRegister = useCallback(
async (remember) => {
const requestedAddress = address;
// Abort rather than publish if the account changes mid-flow: the signer,
// the key being compared and the key being registered must all describe
// the same account.
const assertSameAccount = () => {
if (activeAddressRef.current !== requestedAddress) {
throw new Error('Account changed during key registration');
}
};

try {
setIsLoading(true);
setError(null);

const keyPair = await deriveKeysOnly(remember);
assertSameAccount();

const contract = await getContract();
if (!contract) throw new Error('Contract not available on this network');
assertSameAccount();

// Skip the transaction if the same key is already registered
const existingKey = await fetchPublicKeyFromChain(contract, requestedAddress);
assertSameAccount();
if (existingKey && existingKey.length > 0) {
if (bytesToHex(existingKey) === bytesToHex(keyPair.publicKey)) {
setIsRegistered(true);
return;
}
}

await registerPublicKeyOnChain(contract, keyPair.publicKey);
assertSameAccount();
setIsRegistered(true);
} catch (err) {
console.error('[useRelayKeys] Failed to derive/register keys:', err);
// The rejection value is whatever the wallet provider threw, which is
// not guaranteed to be an Error. Reading .message off a string or null
// would throw from inside this catch, losing the real failure and
// never running setError.
const rawMessage =
typeof err?.message === 'string' ? err.message : String(err ?? '');
const code = err?.code;
let errMsg = rawMessage || 'Failed to register messaging keys';
if (
errMsg.toLowerCase().includes('user rejected') ||
errMsg.toLowerCase().includes('rejected the request') ||
code === 'ACTION_REJECTED' ||
code === 4001
) {
errMsg =
'Signature request rejected. You must sign the message to enable encrypted invoices.';
}
setError(errMsg);
throw err;
} finally {
setIsLoading(false);
}
},
[deriveKeysOnly, getContract, address]
);

// Check registration status when wallet/chain changes
useEffect(() => {
if (address && walletClient && chainId) {
checkRegistration().catch(() => {});
}
}, [address, walletClient, chainId, checkRegistration]);

return {
keys,
hasKeys,
isRegistered,
isUnsupportedNetwork,
isLoading,
error,
rememberSession,
setRememberSession,
deriveAndRegister,
deriveKeysOnly,
checkRegistration,
};
}
30 changes: 30 additions & 0 deletions frontend/src/services/relay/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export {
getRelayClient,
resetRelayClient,
isRelayHealthy,
RELAY_PROXY_PATH,
} from './relayClient.js';
export {
deriveRelayKeyPair,
registerPublicKeyOnChain,
fetchPublicKeyFromChain,
clearCachedKeys,
hasCachedKeys,
getCachedKeyPair,
hexToBytes,
bytesToHex,
DERIVATION_MESSAGE,
} from './relayKeyManager.js';
export {
encryptPayload,
decryptPayload,
tryDecryptPayload,
} from './invoiceCrypto.js';
export {
sendEncryptedInvoice,
fetchInvoiceMessages,
pollInvoiceMessages,
toMailboxAddress,
DEFAULT_POLL_INTERVAL_MS,
} from './relayInvoiceMessaging.js';
export { computeInvoiceHash, verifyInvoiceHash, stableStringify } from './invoiceHashUtils.js';
Loading
Loading