import test from 'node:test'; import assert from 'node:assert/strict'; import { base58 } from '@metaplex-foundation/umi/serializers'; import { ComputeBudgetProgram, Keypair, PublicKey, SendTransactionError, SystemProgram, Transaction } from '@solana/web3.js'; import { openWallet, walletChoices } from '../lib/browser-wallets.mjs'; import { audienceBytes, buildTransaction, createGrantIx, V2_REGISTRY, revokeAllIx, sendPrepared } from '../lib/registry.mjs'; const DEVNET_PROGRAM_ID=V2_REGISTRY.programId; // These compatibility cases exercise the preserved V2 transaction encoder. test('an independently named Wallet Standard wallet signs the reviewed legacy transaction and exact sign-in message',async()=>{ const signer=Keypair.generate(); const account={address:signer.publicKey.toBase58(),chains:['solana:devnet'],features:['solana:signTransaction','solana:signMessage']}; const standard={name:'Independent wallet',accounts:[account],chains:account.chains,features:{ 'standard:connect':{connect:async()=>({accounts:[account]})}, 'solana:signTransaction':{supportedTransactionVersions:['legacy'],signTransaction:async input=>{ assert.equal(input.account,account);assert.equal(input.chain,'solana:devnet'); const tx=Transaction.from(input.transaction);tx.sign(signer);return [{signedTransaction:tx.serialize()}]; }}, 'solana:signMessage':{signMessage:async input=>[{signedMessage:input.message,signature:new Uint8Array(64)}]}, }}; const registry={get:()=>[standard]}; const choice=walletChoices(registry,'signTransaction',{}).find(option=>option.standard===standard); const wallet=await openWallet(choice,'signTransaction'); const tx=new Transaction({recentBlockhash:Keypair.generate().publicKey.toBase58(),feePayer:signer.publicKey}) .add(SystemProgram.transfer({fromPubkey:signer.publicKey,toPubkey:Keypair.generate().publicKey,lamports:1})); assert.ok((await wallet.signTransaction(tx)).verifySignatures()); const message=new TextEncoder().encode('one-time sign-in'); assert.equal((await wallet.signMessage(message)).length,64); standard.features['solana:signMessage'].signMessage=async()=>[{signedMessage:new Uint8Array(1),signature:new Uint8Array(64)}]; await assert.rejects(wallet.signMessage(message),/message changed/); standard.accounts=[];assert.equal(wallet.address,undefined); await assert.rejects(wallet.signTransaction(tx),/changed/); }); test('the wallet signs the grant and fee that were simulated and reviewed',async()=>{ const vault=Keypair.generate(); const delegate=Keypair.generate().publicKey; const latest={blockhash:Keypair.generate().publicKey.toBase58(),lastValidBlockHeight:100}; const grant={owner:vault.publicKey,delegate,scope:'wallet',expiresAt:'2030-01-01T00:00:00Z'}; const ix=createGrantIx(new PublicKey(DEVNET_PROGRAM_ID),grant,await audienceBytes(),{ serviceMaxLamports:30_030_000,quoteExpiresAt:new Date(2_000_000_000_000).toISOString(), serviceTreasury:Keypair.generate().publicKey.toBase58(),configVersion:'1', }); let quoted, simulated, sent=0; const connection={ getLatestBlockhash:async()=>latest, getFeeForMessage:async msg=>{quoted=Buffer.from(msg.serialize());return {value:5001};}, simulateTransaction:async tx=>{simulated=Buffer.from(tx.message.serialize());return {value:{err:null}};}, getBlockHeight:async()=>99, sendRawTransaction:async wire=>{ const tx=Transaction.from(wire); assert.deepEqual(tx.serializeMessage(),quoted); assert.ok(tx.verifySignatures()); sent++; return base58.deserialize(tx.signature)[0]; }, confirmTransaction:async()=>({value:{err:null}}), }; const prepare=()=>buildTransaction({connection},vault.publicKey,ix); const prepared=await prepare(); assert.deepEqual(quoted,simulated); assert.equal(prepared.feeLamports,5001); const roundTrip=tx=>Transaction.from(tx.serialize({requireAllSignatures:false})); const signWithAutomaticFee=async tx=>{ const returned=roundTrip(tx); if (!returned.instructions.some(i=>i.programId.equals(ComputeBudgetProgram.programId))) { returned.add(ComputeBudgetProgram.setComputeUnitPrice({microLamports:1000})); } returned.sign(vault); return returned; }; assert.equal((await sendPrepared({connection},prepared,signWithAutomaticFee)).finalized,true); for (const change of [ tx=>tx.add(ComputeBudgetProgram.setComputeUnitPrice({microLamports:1000})), tx=>tx.add(SystemProgram.transfer({fromPubkey:vault.publicKey,toPubkey:delegate,lamports:1})), tx=>{tx.recentBlockhash=Keypair.generate().publicKey.toBase58();}, ]) { await assert.rejects(sendPrepared({connection},await prepare(),async tx=>{ const changed=roundTrip(tx);change(changed);changed.sign(vault);return changed; }),/changed/i); } await assert.rejects(sendPrepared({connection},await prepare(),async tx=>roundTrip(tx)),/signature/i); assert.equal(sent,1); }); function transactionFor(signer,latest) { const program=new PublicKey(DEVNET_PROGRAM_ID); return new Transaction({...latest,feePayer:signer.publicKey}).add(revokeAllIx(program,signer.publicKey)); } test('transaction-only injected Phantom uses its selected vault, never requests a message or delegates broadcasting',async()=>{ const signer=Keypair.generate(), other=Keypair.generate(); let reads=0, connected=0, signed=0; const listeners=new Map(); const provider={ publicKey:signer.publicKey, connect:async()=>{connected++;return {publicKey:signer.publicKey};}, signTransaction:async tx=>{signed++;tx.sign(signer);return tx;}, on:(event,fn)=>listeners.set(event,fn), removeListener:(event,fn)=>{if(listeners.get(event)===fn) listeners.delete(event);}, }; const standard={name:'Phantom',chains:['solana:devnet'],features:{ 'standard:connect':{connect:async()=>{reads++;throw Error('Unexpected connector');}}, 'solana:signTransaction':{supportedTransactionVersions:['legacy'],signTransaction:async()=>{}}, }}; const registry={get:()=>[standard]},host={phantom:{solana:provider}}; const phantoms=walletChoices(registry,'signTransaction',host).filter(w=>w.name==='Phantom'); assert.equal(phantoms.length,1); assert.equal(phantoms[0].provider,provider); assert.equal(walletChoices(registry,'signMessage',host).find(w=>w.name==='Phantom').available,false); const wallet=await openWallet(phantoms[0],'signTransaction'); assert.equal(wallet.address,signer.publicKey.toBase58());assert.equal(wallet.signMessage,undefined); const tx=transactionFor(signer,{blockhash:other.publicKey.toBase58(),lastValidBlockHeight:80}); assert.ok((await wallet.signTransaction(tx)).verifySignatures()); let changes=0; const remove=wallet.watch(()=>changes++); listeners.get('accountChanged')(signer.publicKey);assert.equal(changes,0); provider.publicKey=other.publicKey;listeners.get('accountChanged')(other.publicKey); assert.equal(changes,1);assert.equal(wallet.address,undefined);remove();assert.equal(listeners.size,0); await assert.rejects(wallet.signTransaction(tx),/changed/); assert.deepEqual([connected,signed,reads],[1,1,0]); const sendOnly={phantom:{solana:{connect:provider.connect,signAndSendTransaction:async()=>assert.fail('unexpected')}}}; assert.equal(walletChoices({get:()=>[]},'signTransaction',sendOnly).find(w=>w.id==='phantom').available,false); }); test('Standard transaction-only vaults require an explicit choice among authorized accounts, then follow capability and chain changes',async()=>{ const chain='solana:devnet', capability='solana:signTransaction'; const signers=[Keypair.generate(),Keypair.generate()]; const accounts=signers.map(signer=>({address:signer.publicKey.toBase58(),features:[capability],chains:[chain]})); let changes=0,connects=0, notify; const features={ 'standard:connect':{connect:async()=>{connects++;return {accounts};}}, 'standard:events':{on:(event,fn)=>{assert.equal(event,'change');notify=fn;return ()=>{notify=null;};}}, [capability]:{supportedTransactionVersions:['legacy'], signTransaction:async input=>{ assert.equal(input.account,accounts[1]);assert.equal(input.chain,chain); const tx=Transaction.from(input.transaction);tx.sign(signers[1]);return [{signedTransaction:tx.serialize()}]; }}, }; const standard={name:'Multi-account device wallet',chains:[chain],features,accounts}; const choice=walletChoices({get:()=>[standard]},'signTransaction',{}).find(item=>item.standard===standard); await assert.rejects(openWallet(choice,'signTransaction'),error=>{ assert.equal(error.code,'SOLBOUND_ACCOUNT_SELECTION_REQUIRED');assert.deepEqual(error.accounts,accounts.map(a=>a.address));return true; }); await assert.rejects(openWallet(choice,'signTransaction',Keypair.generate().publicKey.toBase58()),/no longer available/); const wallet=await openWallet(choice,'signTransaction',accounts[1].address); assert.equal(connects,1);assert.equal(wallet.address,accounts[1].address);assert.equal(wallet.signMessage,undefined); const stop=wallet.watch(()=>{changes++;}); const tx=transactionFor(signers[1],{blockhash:signers[0].publicKey.toBase58(),lastValidBlockHeight:100}); assert.ok((await wallet.signTransaction(tx)).verifySignatures()); notify({accounts:[...accounts].reverse()});assert.equal(changes,0); notify({chains:['solana:mainnet']}); notify({features:{...features,[capability]:{...features[capability],supportedTransactionVersions:[0]}}}); notify({accounts:[accounts[0],{...accounts[1],features:[]}]}); assert.equal(changes,3); standard.accounts=[accounts[0],{...accounts[1],chains:['solana:mainnet']}]; assert.equal(wallet.address,undefined);await assert.rejects(wallet.signTransaction(tx),/changed/); stop();assert.equal(notify,null); }); test('a loaded vault session ignores closures from superseded providers and never resurrects a cancelled connection',async(t)=>{ const {connectWallet,disconnectWallet,getWalletSession}=await import('../lib/wallet.mjs'); const prior=Object.getOwnPropertyDescriptor(globalThis,'window'); const first=Keypair.generate(), second=Keypair.generate(); let onDisconnect, triggerConnect, confirmConnect; const provider={ publicKey:first.publicKey, connect:async()=>({publicKey:provider.publicKey}), disconnect:async()=>{}, signTransaction:async()=>assert.fail('Connect should never sign'), on:(evt,fn)=>{if(evt==='disconnect')onDisconnect=fn;},removeListener:()=>{}, }; const emitter=new EventTarget();emitter.phantom={solana:provider}; Object.defineProperty(globalThis,'window',{value:emitter,configurable:true}); t.after(async()=>{await disconnectWallet();if(prior) Object.defineProperty(globalThis,'window',prior);else delete globalThis.window;}); const firstSession=await connectWallet('phantom'); assert.equal(firstSession.address,first.publicKey.toBase58());const staleEvent=onDisconnect; await disconnectWallet();provider.publicKey=second.publicKey;const next=await connectWallet('phantom'); staleEvent();assert.equal(getWalletSession(),next); await disconnectWallet(); const opening=new Promise(resolve=>{triggerConnect=resolve;}); provider.connect=()=>{triggerConnect();return new Promise(resolve=>{confirmConnect=resolve;});}; const pending=connectWallet('phantom'); await opening;await disconnectWallet();confirmConnect({publicKey:provider.publicKey}); await assert.rejects(pending,/connection changed/);assert.equal(getWalletSession(),null); }); test('rechecks device delays, blockhash boundaries and live session before broadcast without rebuilding or repeating approval',async()=>{ const key=Keypair.generate(); const latest={blockhash:Keypair.generate().publicKey.toBase58(),lastValidBlockHeight:100}; for (const outcome of ['already expired','device expiry','prompt disconnect','last read disconnect','boundary']) { const tx=transactionFor(key,latest); const prepared={tx,latest,bytes:Buffer.from(tx.serializeMessage())}; let current=true,reads=0,signs=0,broadcasts=0; const connection={ getBlockHeight:async()=>{ reads++; if(outcome==='last read disconnect' && reads===2) current=false; return (outcome==='device expiry' && reads===2)||outcome==='already expired'?101:100; }, sendRawTransaction:async wire=>{ broadcasts++;const signed=Transaction.from(wire);assert.deepEqual(signed.serializeMessage(),prepared.bytes); return base58.deserialize(signed.signature)[0]; }, confirmTransaction:async()=>({value:{err:null}}), }; const result=sendPrepared({connection},prepared,async message=>{ signs++;message.sign(key); if(outcome==='prompt disconnect') current=false; return message; },()=>{if(!current) throw Error('Wallet session changed');}); if(outcome==='boundary') {assert.equal((await result).finalized,true);assert.equal(broadcasts,1);} else { await assert.rejects(result,outcome.includes('disconnect')?/session changed/:/expired/); assert.equal(broadcasts,0); } assert.equal(signs,outcome==='already expired'?0:1); assert.equal(reads,outcome==='already expired'||outcome==='prompt disconnect'?1:2); } }); test('an uncertain submission keeps the local signature for inspection and never resubmits or signs again',async()=>{ const key=Keypair.generate(),latest={blockhash:Keypair.generate().publicKey.toBase58(),lastValidBlockHeight:10}; for (const outcome of ['timeout','mismatch','confirmation outage','finalized failure','preflight rejection']) { const tx=transactionFor(key,latest), prepared={tx,latest,bytes:Buffer.from(tx.serializeMessage())}; let signs=0,submissions=0,confirms=0,expected; const connection={ getBlockHeight:async()=>9, sendRawTransaction:async(wire,options)=>{ submissions++;assert.equal(options.skipPreflight,false);assert.equal(options.maxRetries,3); const signed=Transaction.from(wire); assert.deepEqual(signed.serializeMessage(),prepared.bytes);assert.ok(signed.verifySignatures()); expected=base58.deserialize(signed.signature)[0]; if(outcome==='timeout') throw Error('Transport timeout'); if(outcome==='preflight rejection') throw new SendTransactionError({action:'simulate',signature:'', transactionMessage:'Transaction simulation failed: Blockhash not found',logs:[]}); return outcome==='mismatch'?'unrelated-remote-response':expected; }, confirmTransaction:async strategy=>{ confirms++;assert.equal(strategy.signature,expected); if(outcome==='confirmation outage')throw Error('RPC unavailable'); return {value:{err:{InstructionError:[0,'Custom']}}}; }, }; await assert.rejects(sendPrepared({connection},prepared,async input=>{signs++;input.sign(key);return input;}),error=>{ if(outcome==='preflight rejection') {assert.equal(error.signature,undefined);assert.match(error.message,/preflight rejected/);} else {assert.equal(error.signature,expected);assert.ok(error.message.includes(expected));assert.match(error.message,/before retrying/);} assert.ok(!error.message.includes('unrelated-remote-response')); return true; }); assert.equal(signs,1);assert.equal(submissions,1); assert.equal(confirms,outcome==='confirmation outage'||outcome==='finalized failure'?1:0); } }); test('a slow vault prompt cannot broadcast when its signed price deadline or settings revision has changed',async()=>{ const key=Keypair.generate(), program=new PublicKey(DEVNET_PROGRAM_ID); const latest={blockhash:Keypair.generate().publicKey.toString(),lastValidBlockHeight:10}; for(const scenario of ['price expired','settings changed','expired before prompt']){ let prompts=0; const config=Buffer.alloc(82),clock=Buffer.alloc(40); config[0]=3;key.publicKey.toBuffer().copy(config,1);key.publicKey.toBuffer().copy(config,33); config.writeBigUInt64LE(250n,65);config.writeBigUInt64LE(5n,74); clock.writeBigInt64LE(scenario==='expired before prompt'?100n:99n,32); const treasury=Keypair.generate().publicKey.toString(), delegate=Keypair.generate().publicKey.toString(); const ix=createGrantIx(program,{owner:key.publicKey.toString(),scope:'wallet',delegate,expiresAt:'2030-01-01T00:00:00Z'},await audienceBytes(), {serviceMaxLamports:30_000_000,serviceTreasury:treasury,configVersion:'5',quoteExpiresAt:new Date(100_000).toISOString()}); const tx=new Transaction({...latest,feePayer:key.publicKey}).add(ix); const prepared={tx,latest,bytes:Buffer.from(tx.serializeMessage()),configVersion:'5',quoteDeadline:100}; const connection={ getBlockHeight:async()=>9,getMultipleAccountsInfo:async()=>[{owner:program,data:config},{owner:new PublicKey('Sysvar1111111111111111111111111111111111111'),data:clock}], sendRawTransaction:async()=>assert.fail('Expired or changed terms must never reach the RPC'), }; await assert.rejects(sendPrepared({connection,program},prepared,async input=>{ prompts++;input.sign(key); if(scenario==='price expired')clock.writeBigInt64LE(100n,32); if(scenario==='settings changed')config.writeBigUInt64LE(6n,74); return input; }),scenario==='settings changed'?/settings changed/:/quote expired/); assert.equal(prompts,scenario==='expired before prompt'?0:1); } });