Skip to content
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
20 changes: 20 additions & 0 deletions packages/solana/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,23 @@ a second read. Missing or changed headers, pruned history, an inclusion or a
window that does not reach the bound remains unknown. The selected RPC is a trust
boundary; this observation is not a cryptographic light-client proof. A missing
transaction or elapsed deadline alone never proves non-inclusion.

## Solana Privacy Ring assets and receipts

Use `getSolanaRingAssetSupport` to check whether the finalized mainnet Ring has
the registry and vault for a token. Registration alone does not establish
swap support.

Use `verifySolanaRingDeposit` to verify a finalized, proofless deposit of one SPL
token into the default Solana mainnet Ring. Supply the signature from the
reviewed provider execution, its expected Solana depositor, the recipient's
public address and owner hash resolved from the Ring registry, the token and
the minimum amount in atomic units. Supply a trusted RPC that returns the
`result` values for `getGenesisHash` and raw JSON `getTransaction`, with
transaction version 1 enabled.

A finalized receipt confirms the deposit into the Ring. The recipient syncs
its private balance separately. The deposit exposes the depositor, recipient,
token and amount. The default Ring encrypts asset and amount for later Ring
transfers, while wallet addresses remain visible.
[Helius deposit guide](https://www.helius.dev/docs/privacy/guides/deposit)
3 changes: 3 additions & 0 deletions packages/solana/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ export type { JupiterIntent, PreparedSolanaSwap } from './jupiter';

export { proveSolanaNotIncluded } from './settlement';
export type { SolanaNonInclusionProof } from './settlement';

export { SOLANA_PRIVACY_RING_PROGRAM, getSolanaRingAssetSupport, verifySolanaRingDeposit } from './privacy-ring';
export type { SolanaRingDepositExpectation, SolanaRingRead } from './privacy-ring';
150 changes: 150 additions & 0 deletions packages/solana/src/privacy-ring.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import bs58 from 'bs58';
import { PublicKey } from '@solana/web3.js';
import { z } from 'zod';
import { AtomicAmountSchema, SolanaAddressSchema, SolanaTokenSchema } from './tokens';

const MAINNET_GENESIS = '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d';
export const SOLANA_PRIVACY_RING_PROGRAM = 'ring1GaLCuJnkUMVkX2JeZLTTX17wKsV4fZmPVzXANW';
const program = new PublicKey(SOLANA_PRIVACY_RING_PROGRAM);
const encoder = new TextEncoder();
const [defaultTree] = PublicKey.findProgramAddressSync([encoder.encode('tree'), Uint8Array.of(0, 0)], program);
const signatureSchema = z.string().min(64).max(88)
.refine(value => bs58.decodeUnsafe(value)?.length === 64, 'Invalid Solana signature');
const addressList = z.array(SolanaAddressSchema).max(256);
const accountIndex = z.number().int().min(0).max(255);
const transactionSchema = z.object({
version: z.union([z.literal('legacy'), z.literal(0), z.literal(1)]),
slot: z.number().int().safe().positive(),
transaction: z.object({
signatures: z.array(signatureSchema).min(1),
message: z.object({
accountKeys: addressList,
instructions: z.array(z.object({
programIdIndex: accountIndex,
accounts: z.array(accountIndex).max(256),
data: z.string().max(2048),
})),
}),
}),
meta: z.object({
err: z.unknown(),
loadedAddresses: z.object({ writable: addressList, readonly: addressList }).optional(),
}).nullable(),
});

export type SolanaRingRead = (
request:
| { method: 'getGenesisHash'; params: [] }
| { method: 'getTransaction'; params: [string, {
commitment: 'finalized';
encoding: 'json';
maxSupportedTransactionVersion: 1;
}] }
| { method: 'getMultipleAccounts'; params: [[string, string], {
commitment: 'finalized';
encoding: 'base64';
dataSlice: { offset: 0; length: 0 };
}] },
) => Promise<unknown>;

function ringAssetVault(mint: PublicKey) {
return PublicKey.findProgramAddressSync([encoder.encode('spl_asset_vault'), mint.toBytes()], program);
}

async function requireMainnet(read: SolanaRingRead) {
const genesis = await read({ method: 'getGenesisHash', params: [] });
if (genesis !== MAINNET_GENESIS) throw new Error('Ring queries require Solana mainnet.');
}

const accountOwnerSchema = z.object({ owner: SolanaAddressSchema, executable: z.literal(false) }).nullable();
const assetAccountsSchema = z.object({ value: z.tuple([accountOwnerSchema, accountOwnerSchema]) });

/** Read the default Ring's finalized SPL registration and vault. This checks token setup only. */
export async function getSolanaRingAssetSupport(read: SolanaRingRead, expected: z.input<typeof SolanaTokenSchema>) {
const token = SolanaTokenSchema.parse(expected);
const mint = new PublicKey(token.mint);
const [registry] = PublicKey.findProgramAddressSync([encoder.encode('spl_asset_registry'), mint.toBytes()], program);
const [vault] = ringAssetVault(mint);

await requireMainnet(read);
const raw = await read({
method: 'getMultipleAccounts',
params: [[registry.toBase58(), vault.toBase58()], {
commitment: 'finalized', encoding: 'base64', dataSlice: { offset: 0, length: 0 },
}],
});
const { value: [registryAccount, vaultAccount] } = assetAccountsSchema.parse(raw);
if (registryAccount?.owner !== SOLANA_PRIVACY_RING_PROGRAM || vaultAccount?.owner !== token.program) {
return { kind: 'unavailable' as const };
}
return { kind: 'registered' as const };
}

export interface SolanaRingDepositExpectation {
/** Destination signature independently bound to the reviewed provider execution. */
signature: string;
/** The bridge's expected Solana deposit signer. */
depositor: string;
/** Public Solana address of the registered Ring recipient. */
recipient: string;
/** Base58-encoded owner hash resolved from the recipient's trusted Ring registry record. */
ownerHash: string;
token: z.input<typeof SolanaTokenSchema>;
minimumAmount: string;
}

/**
* Verify a finalized single-token proofless deposit into the default Ring.
* The transport must return JSON-RPC result values from a trusted Solana RPC.
* This verifies the public deposit. The recipient still syncs its private balance.
*/
export async function verifySolanaRingDeposit(read: SolanaRingRead, expected: SolanaRingDepositExpectation) {
const signature = signatureSchema.parse(expected.signature);
const depositor = SolanaAddressSchema.parse(expected.depositor);
const recipient = SolanaAddressSchema.parse(expected.recipient);
const ownerHash = SolanaAddressSchema.parse(expected.ownerHash);
const token = SolanaTokenSchema.parse(expected.token);
const minimum = BigInt(AtomicAmountSchema.parse(expected.minimumAmount));
if (minimum === 0n) throw new Error('Ring deposit minimum must be positive.');

await requireMainnet(read);

const raw = await read({
method: 'getTransaction',
params: [signature, { commitment: 'finalized', encoding: 'json', maxSupportedTransactionVersion: 1 }],
});
if (raw === null) return { kind: 'pending' as const };

const receipt = transactionSchema.parse(raw);
if (receipt.meta?.err !== null || receipt.transaction.signatures[0] !== signature) {
throw new Error('Successful finalized Ring transaction is unavailable.');
}
const { accountKeys, instructions } = receipt.transaction.message;
const loaded = receipt.meta.loadedAddresses;
const keys = [...accountKeys, ...(loaded?.writable ?? []), ...(loaded?.readonly ?? [])];
const [vault, bump] = ringAssetVault(new PublicKey(token.mint));
const vaultAddress = vault.toBase58();

let amount: bigint | undefined;
for (const { programIdIndex, accounts, data } of instructions) {
if (keys[programIdIndex] !== SOLANA_PRIVACY_RING_PROGRAM || accounts.length !== 7) continue;
const [tree, signer, pool, tokenProgram, mint, source, tokenVault] = accounts.map(index => keys[index]);
if (tree !== defaultTree.toBase58() || signer !== depositor || pool !== SOLANA_PRIVACY_RING_PROGRAM
|| tokenProgram !== token.program || mint !== token.mint || source === undefined
|| source === vaultAddress || tokenVault !== vaultAddress) continue;

// The proofless single-SPL format has one asset, one output and no memo.
// Protocol layout: @heliuslabs/spr 0.9.0-alpha, encodeDepositInstructionData.
const bytes = bs58.decodeUnsafe(data);
if (!bytes || bytes.length !== 79 || bytes[0] !== 15 || bytes[1] !== 1
|| bytes[2] !== 1 || bytes[3] !== bump || bytes[4] !== 1 || bytes[5] !== 0
|| bytes[78] !== 0 || bs58.encode(bytes.subarray(6, 38)) !== recipient
|| bs58.encode(bytes.subarray(38, 70)) !== ownerHash) continue;

if (amount !== undefined) throw new Error('Ring deposit receipt is ambiguous.');
amount = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getBigUint64(70, true);
}
if (amount === undefined || amount < minimum) throw new Error('Finalized Ring deposit did not match the reviewed delivery.');

return { kind: 'finalized' as const, signature, slot: receipt.slot, amount: amount.toString() };
}
111 changes: 111 additions & 0 deletions packages/solana/test/privacy-ring.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import bs58 from 'bs58';
import { getSolanaRingAssetSupport, SOLANA_PRIVACY_RING_PROGRAM, SOLANA_USDC, verifySolanaRingDeposit } from '../src/index';
import type { SolanaRingRead } from '../src/index';

const genesis = '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d';
const expected = {
signature: '2UYGWAmS5nRYs84vEquoH75SRKLtDeMnq6u4945bM4iuHUCQLEZXX7XdZtYj9N51k61NThjRHbx8d4cq1Bjxdjne',
depositor: '5QJSupDFJWqEmiXSxVMP8isABpW6Rs192kP8eLFrDqnd',
recipient: 'DK9wGq1cbMjHKzGaKtB4LZwmWhz7LvqoFgSCAh1imG6c',
ownerHash: '3iaA1s3x7RdMiJHEw7XHRRZ3HMAUZf8YixAn1EonQrvk',
token: SOLANA_USDC,
minimumAmount: '299000000',
};
const tree = '777pvSGe5LaBd9nCczvE2FXEauiwtfGJ5XRpjKyniGor';
const vault = 'H4RD4XSWp8TLmrNYCLmV74a5ixude5s9gGqpCFjXkBLQ';

function receipt(err: unknown = null) {
const data = Buffer.concat([
Buffer.from([15, 1, 1, 250, 1, 0]),
bs58.decode(expected.recipient),
bs58.decode(expected.ownerHash),
Buffer.from('00a3e1110000000000', 'hex'),
]);
return {
version: 1,
slot: 471244421,
transaction: {
signatures: [expected.signature],
message: {
accountKeys: [expected.depositor, SOLANA_PRIVACY_RING_PROGRAM, tree, SOLANA_USDC.program,
SOLANA_USDC.mint, 'B6DPLFC2vm9QCAaAt6XZsQCM7gziabeMaekvcbh1E8KD'],
instructions: [{ programIdIndex: 1, accounts: [2, 0, 1, 3, 4, 5, 6], data: bs58.encode(data) }],
},
},
meta: { err, loadedAddresses: { writable: [vault], readonly: [] } },
};
}

function readResult(result: unknown): SolanaRingRead {
return async request => request.method === 'getGenesisHash' ? genesis : result;
}

test('checks finality on mainnet and resolves version 1 lookup accounts to verify Ring delivery', async () => {
const requests: Parameters<SolanaRingRead>[0][] = [];
const result = await verifySolanaRingDeposit(request => {
requests.push(request);
return readResult(receipt())(request);
}, expected);
assert.deepEqual(result, { kind: 'finalized', signature: expected.signature, slot: 471244421, amount: '300000000' });
assert.deepEqual(requests, [
{ method: 'getGenesisHash', params: [] },
{ method: 'getTransaction', params: [expected.signature, { commitment: 'finalized', encoding: 'json', maxSupportedTransactionVersion: 1 }] },
]);
});

test('an unknown receipt stays pending and a different chain fails closed', async () => {
assert.deepEqual(await verifySolanaRingDeposit(readResult(null), expected), { kind: 'pending' });
await assert.rejects(verifySolanaRingDeposit(async () => 'other chain', expected), /require Solana mainnet/);
});

test('rejects a public payout and a finalized deposit with mismatched signing, assets or recipient', async () => {
const publicPayout = receipt();
publicPayout.transaction.message.instructions[0]!.programIdIndex = 3;
await assert.rejects(verifySolanaRingDeposit(readResult(publicPayout), expected), /did not match/);
const wrongVault = receipt();
wrongVault.meta.loadedAddresses.writable[0] = tree;
await assert.rejects(verifySolanaRingDeposit(readResult(wrongVault), expected), /did not match/);
for (const change of [
{ ownerHash: tree },
{ recipient: tree },
{ depositor: tree },
{ token: { ...SOLANA_USDC, mint: tree } },
{ minimumAmount: '300000001' },
]) {
await assert.rejects(verifySolanaRingDeposit(readResult(receipt()), { ...expected, ...change }), /did not match/);
}
});

test('rejects failed, wrong-signature and ambiguous receipts', async () => {
const failed = receipt({ InstructionError: [0, 'InvalidInstructionData'] });
await assert.rejects(verifySolanaRingDeposit(readResult(failed), expected), /Successful finalized/);

const wrongSignature = receipt();
wrongSignature.transaction.signatures[0] = bs58.encode(new Uint8Array(64).fill(3));
await assert.rejects(verifySolanaRingDeposit(readResult(wrongSignature), expected), /Successful finalized/);

const duplicate = receipt();
duplicate.transaction.message.instructions.push(...duplicate.transaction.message.instructions);
await assert.rejects(verifySolanaRingDeposit(readResult(duplicate), expected), /ambiguous/);
});

test('checks finalized mint registration and the canonical token vault for Ring asset readiness', async () => {
const registryAccount = { owner: SOLANA_PRIVACY_RING_PROGRAM, executable: false };
const vaultAccount = { owner: SOLANA_USDC.program, executable: false };
const result = await getSolanaRingAssetSupport(request => {
if (request.method === 'getGenesisHash') return Promise.resolve(genesis);
assert.deepEqual(request, {
method: 'getMultipleAccounts',
params: [['J85i28ZES8pHqDa21YsmLSbUh2FR56c9WW5GCfQXUeHB', vault], {
encoding: 'base64', commitment: 'finalized', dataSlice: { offset: 0, length: 0 },
}],
});
return Promise.resolve({ value: [registryAccount, vaultAccount] });
}, SOLANA_USDC);
assert.deepEqual(result, { kind: 'registered' });
for (const accounts of [[null, vaultAccount], [registryAccount, null], [registryAccount, registryAccount]]) {
assert.deepEqual(await getSolanaRingAssetSupport(readResult({ value: accounts }), SOLANA_USDC), { kind: 'unavailable' });
}
});
10 changes: 10 additions & 0 deletions packages/swaps/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,13 @@ review; review, execute and submit/retry boundaries also enforce the limit.
Intermediate funds remain in the wallet when the limit is reached. Finalized
history is never truncated, and one legacy in-flight overflow can still record
its final receipt.

## Aurora Intents Connect catalog

`getAuroraRingAssetSupport` checks the live bridge-in catalog for native Zcash
and canonical USDC on Solana. Wrapped ZEC on NEAR or Solana cannot meet the
native source requirement. When both assets are listed, qualify a quote that
binds the Ring deposit instruction and the expected recipient, token, minimum
and refund before committing a payment. Use `verifySolanaRingDeposit` from
`@z-stack/solana` to check its finalized deposit receipt.
[Aurora's Ring demo](https://github.com/aurora-is-near/intents-rings-demo)
35 changes: 35 additions & 0 deletions packages/swaps/src/aurora-ring.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { SOLANA_USDC } from '@z-stack/solana';
import { z } from 'zod';

const CATALOG = 'https://intents-connect-api.aurora.dev/api/v1/supported_tokens?flow=inOperation';
const catalogToken = z.object({
assetId: z.string().min(1),
blockchain: z.string().min(1),
symbol: z.string().min(1),
contractAddress: z.string().optional(),
decimals: z.number().int().nonnegative(),
});
const catalogSchema = z.object({
result: z.object({ in: z.array(catalogToken), out: z.array(catalogToken) }),
});

/** Discovery only. Listing both assets does not qualify a route or authorize a payment. */
export async function getAuroraRingAssetSupport(options: { fetch?: typeof fetch; signal?: AbortSignal } = {}) {
const response = await (options.fetch ?? fetch)(CATALOG, {
signal: options.signal,
redirect: 'error',
headers: { accept: 'application/json' },
});
if (!response.ok) throw new Error('Aurora Intents Connect asset catalog is unavailable.');
const { result } = catalogSchema.parse(await response.json());
const nativeZec = result.in.find(asset =>
(asset.blockchain === 'zec' || asset.blockchain === 'zcash') && asset.symbol === 'ZEC' && asset.decimals === 8,
);
if (!nativeZec) return { kind: 'native-zec-unavailable' as const };

const usdc = result.out.find(asset =>
asset.blockchain === 'sol' && asset.contractAddress === SOLANA_USDC.mint && asset.decimals === SOLANA_USDC.decimals,
);
if (!usdc) return { kind: 'solana-usdc-unavailable' as const };
return { kind: 'assets-listed' as const, sourceAssetId: nativeZec.assetId, destinationAssetId: usdc.assetId };
}
2 changes: 2 additions & 0 deletions packages/swaps/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,3 +240,5 @@ export function createTwoLegController(options: { owner: RouteOwner; store: TwoL
});
}
export type TwoLegController = ReturnType<typeof createTwoLegController>;

export { getAuroraRingAssetSupport } from './aurora-ring';
40 changes: 40 additions & 0 deletions packages/swaps/test/aurora-ring.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { getAuroraRingAssetSupport } from '../src/index';

const usdc = {
assetId: 'nep141:sol-5ce3bf3a31af18be40ba30f721101b4341690186.omft.near',
blockchain: 'sol',
symbol: 'USDC',
contractAddress: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
decimals: 6,
};
const zec = { assetId: 'nep141:zec.omft.near', blockchain: 'zec', symbol: 'ZEC', decimals: 8 };

test('wrapped ZEC entries cannot enable native ZEC Ring delivery', async () => {
const result = await getAuroraRingAssetSupport({
fetch: async url => {
assert.equal(url, 'https://intents-connect-api.aurora.dev/api/v1/supported_tokens?flow=inOperation');
return Response.json({ result: {
in: [
{ ...zec, blockchain: 'near', assetId: '1cs_v1:near:nep141:zec.omft.near' },
{ ...zec, blockchain: 'sol', assetId: '1cs_v1:sol:spl:A7bdiYdS5GjqGFtxf17ppRHtDKPkkRqbKtR27dxvQXaS' },
],
out: [usdc],
} });
},
});
assert.deepEqual(result, { kind: 'native-zec-unavailable' });
});

test('requires the canonical Solana USDC mint and only reports catalog support', async () => {
const fetchCatalog = (out: unknown[]) => async () => Response.json({ result: { in: [zec], out } });
assert.deepEqual(await getAuroraRingAssetSupport({
fetch: fetchCatalog([{ ...usdc, contractAddress: 'other-asset' }]),
}), { kind: 'solana-usdc-unavailable' });
assert.deepEqual(await getAuroraRingAssetSupport({ fetch: fetchCatalog([usdc]) }), {
kind: 'assets-listed',
sourceAssetId: zec.assetId,
destinationAssetId: usdc.assetId,
});
});
Loading
Loading