import { Buffer } from 'buffer'; import { base58 } from '@metaplex-foundation/umi/serializers'; import { ComputeBudgetProgram, Connection, PublicKey, SendTransactionError, SystemProgram, SYSVAR_CLOCK_PUBKEY, Message, Transaction, TransactionInstruction, VersionedTransaction, } from '@solana/web3.js'; import { ALL_APPS, AUDIENCE, LEGACY_MAIL, grantAudience } from './partners.mjs'; import { PYTH_RECEIVER, quoteServiceFee, SERVICE_LIMIT_LAMPORTS, SOL_USD_PRICE_ACCOUNT } from './fees.mjs'; export { AUDIENCE }; export const DEVNET_RPC = 'https://api.devnet.solana.com'; export const V1_REGISTRY = Object.freeze({ version:1, programId:'FX2zKgkTSrmUpQcfNsrahQN7Mer5gfPo6Ec8FLX3SuaR', digest:'9fdcd1f09c0910a6318eb8f5fd9f963a622d4453987d8c815da9466cc17163f1', size:9216, }); export const V2_REGISTRY = Object.freeze({ version:2, programId:'Buy7tbE811fDp4CEdW3r1ypHDVb55J9PQ2RbXMjbbB2a', digest:'36fdf43afef7f2138bb38661f53f4b2898afb7937118c7354b865aad066fa22c', size:14328, }); // Deployment pins must be filled together from a verified V3 release before new grants are enabled. export const V3_REGISTRY = Object.freeze({version:3,programId:'G4bHFvQwwjtaZwx7jv6vCRScEBSRrdKxTHNMwCoM8zSR', digest:'e76e793ea0d374e1f01a812d751fa8f9f350c016e3a43220827cba5f42048f3d',size:13816, deploymentSignature:'5Lr1ZsPJavgxiWZ5hDft11RUfqF8gv21WAhSyac4heercNDxz5HGuM2ghRPPomHwNyXChuaN8g1AxftvpVRNpowi'}); export const DEVNET_PROGRAM_ID = V3_REGISTRY.programId; export const DEVNET_GENESIS = 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG'; export const GRANT_SIZE = 146; export const STATE_SIZE = 41; export const YEAR = 366 * 86400; const upgradeableLoader = new PublicKey('BPFLoaderUpgradeab1e11111111111111111111111'); const zero = Buffer.alloc(32); const ascii = s => Buffer.from(s, 'utf8'); function reviewChanged(message) {const error=Error(message);error.code='SOLBOUND_REVIEW_CHANGED';return error;} export function isAddress(value) { if (typeof value !== 'string' || !/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(value)) return false; try { return new PublicKey(value).toBase58() === value; } catch { return false; } } export function normalizedGrant(owner, draft, nowSeconds) { const delegate = String(draft.delegate ?? '').trim(); const scope = draft.scope; const asset = scope === 'wallet' ? null : String(draft.asset ?? '').trim(); if (!isAddress(owner) || !isAddress(delegate) || !PublicKey.isOnCurve(new PublicKey(delegate).toBytes()) || delegate === SystemProgram.programId.toBase58()) { throw new Error('Enter a valid signing wallet address for the delegate.'); } if (owner === delegate) throw new Error('Choose a different wallet as your delegate.'); if (!['wallet','asset','collection'].includes(scope)) throw new Error('Choose a wallet, collection or asset.'); if (scope !== 'wallet' && (!isAddress(asset) || asset === SystemProgram.programId.toBase58())) { throw new Error('Enter the full Solana asset address.'); } const end = Math.floor(new Date(draft.expiresAt).getTime() / 1000); if (!Number.isSafeInteger(end) || end <= nowSeconds || end > nowSeconds + YEAR) { throw new Error('Choose a future expiry within 366 days.'); } return {owner,delegate,scope,asset,expiresAt:new Date(end * 1000).toISOString(), audience:grantAudience(draft.audience)}; } export async function audienceBytes(origin = ALL_APPS, scope = 'wallet') { if (grantAudience(origin) !== origin) throw new Error('Audience must be a canonical HTTPS origin or the all-apps permission.'); const domain = scope === 'collection' ? 'urn:solmate:verified-collection:v1:' + origin : origin; return Buffer.from(await globalThis.crypto.subtle.digest('SHA-256', ascii(domain))); } export function vaultPda(program, vault) { return PublicKey.findProgramAddressSync([ascii('vault'),new PublicKey(vault).toBuffer()],program)[0]; } export function grantPda(program, vault, delegate, audience, scope, asset) { if (!['wallet','asset','collection'].includes(scope)) throw new Error('Unsupported asset scope.'); const assetBytes = scope === 'wallet' ? zero : new PublicKey(asset).toBuffer(); return PublicKey.findProgramAddressSync([ ascii('grant'),new PublicKey(vault).toBuffer(),new PublicKey(delegate).toBuffer(), audience,Buffer.from([scope === 'wallet' ? 0 : 1]),assetBytes ],program)[0]; } const meta = (pubkey,isSigner,isWritable) => ({pubkey:new PublicKey(pubkey),isSigner,isWritable}); export function configPda(program) { return PublicKey.findProgramAddressSync([ascii('config')],program)[0]; } const reservedRecipients=new Set([ SystemProgram.programId.toBase58(),ComputeBudgetProgram.programId.toBase58(),upgradeableLoader.toBase58(), V1_REGISTRY.programId,V2_REGISTRY.programId,V3_REGISTRY.programId,SYSVAR_CLOCK_PUBKEY.toBase58(),SOL_USD_PRICE_ACCOUNT,PYTH_RECEIVER, ]); export function checkTreasuryWallet(address,account) { if(!isAddress(address) || reservedRecipients.has(address) || !PublicKey.isOnCurve(new PublicKey(address).toBytes())) { throw Error('Enter an ordinary Solana wallet address for the treasury. Program addresses and token accounts cannot receive service payments through this console.'); } if(account && (account.executable || !account.owner.equals(SystemProgram.programId) || account.data.length!==0)) { throw Error('The treasury must be a wallet that can receive SOL. Choose a wallet address instead of a program, token or nonce account.'); } } function checkConfigValues({treasury,feeUsdCents,feeLamports,paused},version=2) { if (!isAddress(treasury) || treasury===SystemProgram.programId.toBase58()) throw Error('Enter a valid treasury address.'); if(version===3) { if(!Number.isSafeInteger(feeLamports) || feeLamports<0 || feeLamports>SERVICE_LIMIT_LAMPORTS) throw Error('Enter a fee between 0 and 1 SOL, with no more than nine decimal places.'); } else if (!Number.isSafeInteger(feeUsdCents) || feeUsdCents<0 || feeUsdCents>10_000) throw Error('Enter a fee between 0 and 10,000 US cents.'); if (typeof paused!=='boolean') throw Error('Choose whether new delegations are paused.'); } export function readConfig(program,info) { // Callers fetch only configPda(program) from the selected registry. const version=registryProfile(program.toBase58()).version; if(version===1) throw Error('The legacy registry has no fee configuration.'); const data=recordBytes(info,program,version===3?4:3,82); if(data[73]>1 || data.readBigUInt64LE(74)===0n) throw Error('Invalid registry configuration.'); const config={authority:addressAt(data,1),treasury:addressAt(data,33),[version===3?'feeLamports':'feeUsdCents']:Number(data.readBigUInt64LE(65)), paused:data[73]===1,configVersion:data.readBigUInt64LE(74).toString()}; checkConfigValues(config,version); return config; } export function updateConfigIx(program,config,changes) { const version=registryProfile(program.toBase58()).version; if(version===1) throw Error('Choose a configured Solbound v2 or v3 devnet registry.'); checkConfigValues(changes,version); const data=Buffer.alloc(50); data[0]=4; data.writeBigUInt64LE(BigInt(config.configVersion),1); data.writeBigUInt64LE(BigInt(version===3?changes.feeLamports:changes.feeUsdCents),9); new PublicKey(changes.treasury).toBuffer().copy(data,17); data[49]=Number(changes.paused); return new TransactionInstruction({programId:program,keys:[meta(config.authority,true,false),meta(configPda(program),false,true)],data}); } export function createGrantIx(program, grant, audience, quote) { const fixed=!!V3_REGISTRY.programId && program.toBase58()===V3_REGISTRY.programId; if (!quote || !Number.isSafeInteger(quote.serviceMaxLamports) || quote.serviceMaxLamports < 0 || quote.serviceMaxLamports > SERVICE_LIMIT_LAMPORTS || (!fixed && !Number.isSafeInteger(Date.parse(quote.quoteExpiresAt)/1000)) || (fixed && (quote.feeMode!=='fixedSOL' || quote.serviceFeeLamports!==quote.serviceMaxLamports))) { throw new Error('Review a valid capped service fee before creating a delegation.'); } // The V2 encoder remains for historical fixtures. The public wallet creates only on V3. if (!fixed && program.toBase58()!==V2_REGISTRY.programId) throw Error('Grant instructions require a pinned v2 or v3 registry.'); registryProfile(program.toBase58()); const data = Buffer.alloc(fixed?122:130); data[0] = fixed?6:3; data[1] = grant.scope === 'wallet' ? 0 : 1; new PublicKey(grant.delegate).toBuffer().copy(data,2); Buffer.from(audience).copy(data,34); if (grant.scope !== 'wallet') new PublicKey(grant.asset).toBuffer().copy(data,66); data.writeBigInt64LE(BigInt(Date.parse(grant.expiresAt)/1000),98); data.writeBigUInt64LE(BigInt(quote.serviceMaxLamports),106); if(!fixed) data.writeBigInt64LE(BigInt(Date.parse(quote.quoteExpiresAt)/1000),114); data.writeBigUInt64LE(BigInt(quote.configVersion),fixed?114:122); const state = vaultPda(program,grant.owner); const id = grantPda(program,grant.owner,grant.delegate,audience,grant.scope,grant.asset); return new TransactionInstruction({programId:program,keys:[ meta(grant.owner,true,true),meta(state,false,true),meta(id,false,true),meta(SystemProgram.programId,false,false), meta(quote.serviceTreasury,false,true),...(!fixed?[meta(SOL_USD_PRICE_ACCOUNT,false,false)]:[]),meta(configPda(program),false,false) ],data}); } export function revokeIx(program, owner, grantId) { return new TransactionInstruction({programId:program,keys:[meta(owner,true,true),meta(grantId,false,true)],data:Buffer.from([1])}); } export function revokeAllIx(program, owner) { return new TransactionInstruction({programId:program,keys:[meta(owner,true,false),meta(vaultPda(program,owner),false,true)],data:Buffer.from([2])}); } function recordBytes(info, program, tag, size) { if (!info || !info.owner.equals(program) || info.executable) throw new Error('Invalid or missing registry record.'); const bytes = Buffer.from(info.data); if (bytes.length !== size || bytes[0] !== tag) throw new Error('Unsupported registry record.'); return bytes; } const addressAt = (bytes,offset) => new PublicKey(bytes.subarray(offset,offset+32)).toBase58(); export function readState(program, vault, info) { const bytes = recordBytes(info,program,1,STATE_SIZE); if(addressAt(bytes,1)!==vault) throw new Error('Vault state belongs to a different address.'); return bytes.readBigUInt64LE(33); } export function readGrant(program, address, info) { const data = recordBytes(info,program,2,GRANT_SIZE); const owner = addressAt(data,1), delegate = addressAt(data,33); const audienceHash = data.subarray(65,97); const scope = data[97] === 0 ? 'wallet' : data[97] === 1 ? 'asset' : null; if (!scope || (scope === 'wallet' && !data.subarray(98,130).equals(zero))) throw new Error('Malformed grant scope.'); const asset = scope === 'asset' ? addressAt(data,98) : null; const id = grantPda(program,owner,delegate,audienceHash,scope,asset).toBase58(); if (id !== new PublicKey(address).toBase58()) throw new Error('Non-canonical registry record.'); const epoch = data.readBigUInt64LE(130), expiry = Number(data.readBigInt64LE(138)); if (!Number.isSafeInteger(expiry) || !Number.isFinite(new Date(expiry*1000).getTime())) throw new Error('Invalid grant expiry.'); return {owner,delegate,scope,asset,id,audienceHash,epoch,expiry,expiresAt:new Date(expiry*1000).toISOString()}; } export function readClock(info) { const data = info && Buffer.from(info.data); if (!data || data.length < 40 || info.owner.toBase58() !== 'Sysvar1111111111111111111111111111111111111') throw new Error('Could not verify the Solana clock.'); const seconds = Number(data.readBigInt64LE(32)); if (!Number.isSafeInteger(seconds) || seconds < 1) throw new Error('Invalid Solana clock.'); return seconds; } export function grantStatus(record,epoch,time) { if (epoch !== record.epoch) return 'revoked'; return record.expiry <= time ? 'expired' : 'active'; } export function registryProfile(address) { const profile = [V1_REGISTRY,V2_REGISTRY,V3_REGISTRY].find(p=>p.programId && p.programId===address && p.digest && p.size); if (!profile) throw Error('Use a program ID pinned in this Solbound devnet release.'); return profile; } export function openDevnet(programAddress,endpoint = DEVNET_RPC) { if (!programAddress) throw new Error('The devnet registry is awaiting deployment. Use a sample wallet to explore.'); registryProfile(programAddress); if (new URL(endpoint).protocol !== 'https:') throw new Error('Use an HTTPS devnet RPC.'); return {connection:new Connection(endpoint,'finalized'),program:new PublicKey(programAddress)}; } export async function checkDeployment({connection,program}) { const profile = registryProfile(program.toBase58()); if (await connection.getGenesisHash() !== DEVNET_GENESIS) throw new Error('Wallet actions are restricted to Solana devnet.'); const info = await connection.getAccountInfo(program,'finalized'); if (!info?.executable || !info.owner.equals(upgradeableLoader) || info.data.length !== 36 || Buffer.from(info.data).readUInt32LE(0) !== 2) { throw new Error('The configured devnet registry is unavailable.'); } const code = new PublicKey(info.data.subarray(4)); const canonicalCode = PublicKey.findProgramAddressSync([program.toBuffer()],upgradeableLoader)[0]; if (!code.equals(canonicalCode)) throw new Error('The registry has an invalid deployment address.'); const stored = await connection.getAccountInfo(code,'finalized'); if (!stored || stored.executable || !stored.owner.equals(upgradeableLoader) || stored.data.length <= 45 || Buffer.from(stored.data).readUInt32LE(0) !== 3) { throw new Error('The configured devnet program has no live program data.'); } const digest = await globalThis.crypto.subtle.digest('SHA-256', stored.data.subarray(45)); if (stored.data.length !== 45 + profile.size || Buffer.from(digest).toString('hex') !== profile.digest) { throw new Error('The deployed devnet code has changed. A verified Solbound release is required.'); } } export async function listChainGrants(client, address, direction='outgoing', knownOrigins=[]) { const {connection,program} = client; await checkDeployment(client); const found = await connection.getProgramAccounts(program,{commitment:'finalized',filters:[ {dataSize:GRANT_SIZE},{memcmp:{offset:direction==='incoming'?33:1,bytes:address}} ],dataSlice:{offset:0,length:0},withContext:true}); const rows = []; const names = new Map(); for (const origin of new Set([ALL_APPS,AUDIENCE,LEGACY_MAIL,...knownOrigins])) { for (const kind of ['wallet','collection']) names.set((await audienceBytes(origin,kind)).toString('hex'),{origin,kind}); } // Discover addresses first. Grant, revocation counter and clock below are read at a common slot. for (let i=0;iv.pubkey); const discovery = await connection.getMultipleAccountsInfoAndContext(keys,{commitment:'finalized',minContextSlot:found.context.slot}); const live = keys.flatMap((key,j)=>discovery.value[j]?[{key,owner:readGrant(program,key,discovery.value[j]).owner}]:[]); if (!live.length) continue; const states = live.map(v=>vaultPda(program,v.owner)); const bundle = await connection.getMultipleAccountsInfoAndContext([...live.map(v=>v.key),...states,SYSVAR_CLOCK_PUBKEY],{commitment:'finalized',minContextSlot:discovery.context.slot}); const time = readClock(bundle.value.at(-1)); live.forEach(({key,owner},j)=>{ if(!bundle.value[j]) return; const grant = readGrant(program,key,bundle.value[j]); if ((direction==='incoming'?grant.delegate:grant.owner)!==address) return; const status = grantStatus(grant,readState(program,owner,bundle.value[live.length+j]),time); const hash=grant.audienceHash.toString('hex'), label=names.get(hash); rows.push({id:grant.id,owner,delegate:grant.delegate,scope:label?.kind==='collection'?'collection':grant.scope,asset:grant.asset,expiresAt:grant.expiresAt,status, audience:label?.origin ?? 'SHA-256 '+hash,mode:'devnet', registryProgram:program.toBase58(),registryVersion:registryProfile(program.toBase58()).version}); }); } return rows.sort((a,b)=>b.expiresAt.localeCompare(a.expiresAt)); } export async function buildTransaction(client,owner,ix) { const {connection} = client; const latest = await connection.getLatestBlockhash('confirmed'); // Specify the budget before review so wallets can sign without adding their own fee. // At 1 micro-lamport per unit, the 200,000-unit limit costs one lamport after rounding. const tx = new Transaction({feePayer:new PublicKey(owner),...latest}).add( ComputeBudgetProgram.setComputeUnitLimit({units:200_000}), ComputeBudgetProgram.setComputeUnitPrice({microLamports:1}), ...(Array.isArray(ix)?ix:[ix]), ); return simulateEnvelope(client,tx,latest); } async function simulateEnvelope({connection},tx,latest) { const msg = tx.compileMessage(); const fee = await connection.getFeeForMessage(msg,'confirmed'); if (!Number.isSafeInteger(fee.value) || fee.value < 0) throw new Error('Fee unavailable. Please review again.'); const sim = await connection.simulateTransaction(new VersionedTransaction(msg),{commitment:'confirmed',sigVerify:false}); if (sim.value.err) { const failure=sim.value.err.InstructionError; const failedIx=Array.isArray(failure) ? tx.instructions[failure[0]] : null; if ([V2_REGISTRY.programId,V3_REGISTRY.programId].includes(failedIx?.programId.toBase58())) { const hint={ 101:'The grant has expired. Choose another expiry.', 107:'The configured treasury cannot receive this service fee. A treasury cannot pay itself.', 108:'The on-chain SOL/USD price account could not be verified. Try a new review later.', 109:'The SOL/USD feed is stale or its confidence range is too wide. Review again after the price updates.', 110:'The fee quote expired. Review the delegation again.', 111:'The service fee differs from the approved amount. Review the current fee.', 113:'The fee settings changed. Review the updated settings.', 114:'New delegations and renewals are paused. Existing grants can still be revoked.', 115:'Only the configuration authority can approve this update.', }[failure[1]?.Custom]; if(hint) throw [101,111,113,114].includes(failure[1]?.Custom)?reviewChanged(hint):Error(hint); } throw new Error('Devnet simulation failed. Check the wallet balance and transaction details, then review again.'); } return {tx,latest,feeLamports:fee.value,bytes:Buffer.from(tx.serializeMessage())}; } export async function refreshPreparedTransaction(client,prepared) { // Decode the saved message, not the mutable Transaction previously handed to a wallet. const tx=Transaction.populate(Message.from(prepared.bytes)); const latest=await client.connection.getLatestBlockhash('confirmed'); tx.recentBlockhash=latest.blockhash; const current=await simulateEnvelope(client,tx,latest); if(current.feeLamports>prepared.feeLamports) throw reviewChanged('The network fee increased. Review the updated fee before approving.'); return {...prepared,...current}; } export async function sendPrepared(client,prepared,sign,checkSession = () => {},options={}) { const {connection} = client; const termKeys=prepared.configVersion===undefined?[]:[configPda(client.program),SYSVAR_CLOCK_PUBKEY]; const paid=prepared.quoteDeadline!==undefined && prepared.serviceMaxLamports>0; if(paid) termKeys.push(new PublicKey(SOL_USD_PRICE_ACCOUNT)); if(prepared.newTreasury) termKeys.push(new PublicKey(prepared.newTreasury)); async function checkValidity() { const [height,records] = await Promise.all([ connection.getBlockHeight('confirmed'), termKeys.length ? connection.getMultipleAccountsInfo(termKeys,'confirmed') : null, ]); const config=records && readConfig(client.program,records[0]); if (config && config.configVersion !== prepared.configVersion) { throw reviewChanged('The registry settings changed. Review the new settings and fee before signing again.'); } if(prepared.serviceFeeLamports!==undefined && (config.paused || config.feeLamports!==prepared.serviceFeeLamports || config.treasury!==prepared.serviceTreasury)) throw reviewChanged('The registry fee or treasury changed. Review the updated settings before approving.'); if(prepared.grantExpiresAt!==undefined && readClock(records[1])>=prepared.grantExpiresAt) throw reviewChanged('The grant has expired. Choose another expiry.'); if (prepared.quoteDeadline !== undefined) { const chainTime=readClock(records[1]); if(chainTime>=prepared.quoteDeadline) throw Error('The service fee quote expired. Review the delegation again.'); if(paid && quoteServiceFee(termKeys[2],records[2],chainTime,config).serviceEstimateLamports>prepared.serviceMaxLamports) { throw Error('The current SOL service fee exceeds your approved maximum. Review the current price and fee before signing again.'); } } if(prepared.newTreasury) checkTreasuryWallet(prepared.newTreasury,records.at(-1)); if (!Number.isSafeInteger(height) || !Number.isSafeInteger(prepared.latest.lastValidBlockHeight)) { throw new Error('Could not verify this transaction’s block height. Review the transaction again.'); } if (height > prepared.latest.lastValidBlockHeight) throw new Error('This review expired. Review the transaction again.'); } await checkValidity(); checkSession(); options.onProgress?.({stage:'awaiting-wallet'}); const returned = await sign(prepared.tx); checkSession(); // Verify locally, including for injected wallets that return their own Transaction object. let signed; try { signed = Transaction.from(returned.serialize({requireAllSignatures:false,verifySignatures:false})); } catch { throw new Error('Solbound could not read the signed transaction. Reconnect your vault wallet and review again.'); } if (!Buffer.from(signed.serializeMessage()).equals(prepared.bytes)) { throw new Error('The wallet changed the reviewed transaction. Solbound stopped before sending. Review again using the displayed network fee.'); } if (!signed.verifySignatures()) { throw new Error('The vault signature could not be verified. Select the same vault account in your wallet and review again.'); } const wire = signed.serialize(); // The first verified signature identifies these exact bytes, including when the RPC reply is lost. const [signature] = base58.deserialize(signed.signature); function inspect(message, cause) { const error = new Error(message + ' Check this devnet transaction before retrying: ' + signature, {cause}); error.signature = signature; return error; } // Hardware confirmation can outlast the reviewed blockhash. Never refresh and sign on the user's behalf. await checkValidity(); checkSession(); if(options.beforeBroadcast) { await options.beforeBroadcast({signature,...prepared.latest}); try {checkSession();} catch(error) {await options.onNotSent?.();throw error;} } let receipt; try { options.onProgress?.({stage:'sending',signature}); receipt = await connection.sendRawTransaction(wire,{skipPreflight:false,preflightCommitment:'confirmed',maxRetries:3}); } catch (cause) { if (cause instanceof SendTransactionError && /^Transaction simulation failed: (Error processing Instruction \d+:|Blockhash not found|insufficient funds)/i.test(cause.transactionError.message)) { await options.onNotSent?.(); throw new Error('Devnet preflight rejected this transaction. Check the vault balance and grant details, then review again.', {cause}); } throw inspect('The RPC did not confirm submission.',cause); } if (receipt !== signature) throw inspect('The RPC returned a different transaction ID.'); options.onProgress?.({stage:'confirming',signature}); let result; try { result = options.confirm ? await options.confirm({...prepared.latest,signature}) : await connection.confirmTransaction({...prepared.latest,signature},'finalized'); } catch (cause) { throw inspect('Finalization could not be confirmed.',cause); } if (result.value.err) { const error=inspect('The transaction finalized with an error.');error.finalized=true;error.transactionError=result.value.err; throw error; } options.onProgress?.({stage:'finalized',signature}); return {signature,finalized:true}; }