diff --git a/modules/sdk-coin-sol/src/lib/utils.ts b/modules/sdk-coin-sol/src/lib/utils.ts index a9283042c5..0a66bac146 100644 --- a/modules/sdk-coin-sol/src/lib/utils.ts +++ b/modules/sdk-coin-sol/src/lib/utils.ts @@ -12,8 +12,6 @@ import { BaseCoin, BaseNetwork, CoinNotDefinedError, coins, SolCoin } from '@bit import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddress, - NATIVE_MINT, - NATIVE_MINT_2022, TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, decodeInstruction, @@ -814,124 +812,3 @@ export function computeTransferFee(amount: string, basisPoints: number, maximumF const cap = BigInt(maximumFee); return (raw < cap ? raw : cap).toString(); } - -/** The System Program AdvanceNonceAccount instruction: u32 little-endian index 4. */ -const SYSTEM_ADVANCE_NONCE_INDEX = 4; -/** Position of the nonce authority in the account list of AdvanceNonceAccount: nonce, recent blockhashes, authority. */ -const ADVANCE_NONCE_AUTHORITY_POSITION = 2; -/** Position of the funder in the account list of an associated-token-account creation. */ -const ATA_CREATE_FUNDER_POSITION = 0; - -function isAdvanceNonceInstruction(instruction: TransactionInstruction): boolean { - return ( - instruction.programId.equals(SystemProgram.programId) && - instruction.data.length >= 4 && - instruction.data.readUInt32LE(0) === SYSTEM_ADVANCE_NONCE_INDEX - ); -} - -function isAtaCreationInstruction(instruction: TransactionInstruction): boolean { - return instruction.programId.equals(ASSOCIATED_TOKEN_PROGRAM_ID); -} - -/** The Token Program Transfer instruction (index 3) names no mint: the destination's owner cannot be told. */ -const TOKEN_TRANSFER_INSTRUCTION_INDEX = 3; - -function isPlainTokenTransfer(instruction: TransactionInstruction): boolean { - return ( - [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID].some((program) => instruction.programId.equals(program)) && - instruction.data.length > 0 && - instruction.data[0] === TOKEN_TRANSFER_INSTRUCTION_INDEX - ); -} - -/** - * The associated token accounts the fee payer owns for the mints a transaction may touch. An instruction names its - * token accounts, not their owners, so a transfer or a pool deposit into an account the fee payer owns cannot be seen - * from the account list alone: the fee payer's account is derived for every account the transaction lists (any of - * them may be a mint, such as a stake pool's mint), for the mints the caller parsed, and for the native mint (a - * transfer of SOL into the fee payer's wrapped-SOL account), under both token programs, and compared. - */ -function feePayerTokenAccounts( - feePayer: PublicKey, - instructions: TransactionInstruction[], - extraMints: string[] -): Set { - const candidates = new Map(); - const consider = (key: PublicKey) => candidates.set(key.toBase58(), key); - instructions.forEach((instruction) => instruction.keys.forEach((meta) => consider(meta.pubkey))); - extraMints.forEach((mint) => consider(new PublicKey(mint))); - consider(NATIVE_MINT); - consider(NATIVE_MINT_2022); - const owned = new Set(); - for (const mint of candidates.values()) { - for (const tokenProgram of [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID]) { - const [address] = PublicKey.findProgramAddressSync( - [feePayer.toBuffer(), tokenProgram.toBuffer(), mint.toBuffer()], - ASSOCIATED_TOKEN_PROGRAM_ID - ); - owned.add(address.toBase58()); - } - } - return owned; -} - -/** - * Whether a fee payer other than the wallet is isolated from the transaction's instructions: it pays the network fee - * and may be the durable-nonce authority or the funder of a token-account creation, and nothing else. It is never a - * source, destination, owner, delegate or authority of any other instruction, and it owns none of the token accounts - * the transaction moves tokens into or out of. - * - * The check runs on the compiled instructions (account lists and data), not on parsed parameters, because the parsers - * drop accounts they do not model: a stake account's staker and withdrawer, or the destination of a pool deposit. - * - * @param feePayer the transaction's fee payer - * @param instructions the compiled instructions of the transaction - * @param extraMints mints the caller knows the transaction moves (parsed token transfers), derived in addition to - * the mints found in the instructions - * @returns true when no instruction references the fee payer outside the two roles above - * - * @obligation MUST reject the fee payer in any account list or inside any instruction data, except as the - * AdvanceNonceAccount authority and as the funder of an associated-token-account creation — consequence: a stake - * whose staker or withdrawer is the fee payer, an approval or authority change to it, or a transfer to it is never - * accepted as sponsored, whichever address the server names as the fee payer - * @obligation MUST reject a token account the fee payer owns (its associated token account for every account the - * transaction lists, for the parsed mints and for the native mint) in any account list — consequence: a token - * transfer, a pool deposit or a transfer of SOL into the fee payer's token account is not accepted - * @obligation MUST reject a plain token Transfer, which names no mint — consequence: a transfer into a token account - * whose owner cannot be derived is never accepted as sponsored (the builders use TransferChecked) - * @edge a token account the fee payer owns that is not its associated token account cannot be recognised without - * reading the chain — consequence: the caller's recipients check (txParams.recipients) is the remaining guard there - * @edge the rent of a closed token account goes to the destination the instruction names; a destination that is the - * fee payer's token account for a mint the transaction never lists is not recognised — consequence: bounded to the - * closed account's rent, and close-ATA transactions skip this check - * @guarantees SHALL return true for a transaction with no instruction — consequence: the caller decides what an - * empty transaction means - */ -export function isFeePayerIsolated( - feePayer: string, - instructions: TransactionInstruction[], - extraMints: string[] = [] -): boolean { - const feePayerKey = new PublicKey(feePayer); - const feePayerBytes = feePayerKey.toBuffer(); - const ownedTokenAccounts = feePayerTokenAccounts(feePayerKey, instructions, extraMints); - return instructions.every((instruction) => { - if (isPlainTokenTransfer(instruction) || instruction.data.includes(feePayerBytes)) { - return false; - } - return instruction.keys.every((meta, position) => { - const address = meta.pubkey.toBase58(); - if (ownedTokenAccounts.has(address)) { - return false; - } - if (address !== feePayer) { - return true; - } - return ( - (isAdvanceNonceInstruction(instruction) && position === ADVANCE_NONCE_AUTHORITY_POSITION) || - (isAtaCreationInstruction(instruction) && position === ATA_CREATE_FUNDER_POSITION) - ); - }); - }); -} diff --git a/modules/sdk-coin-sol/src/sol.ts b/modules/sdk-coin-sol/src/sol.ts index 65095f29eb..1aae1f293c 100644 --- a/modules/sdk-coin-sol/src/sol.ts +++ b/modules/sdk-coin-sol/src/sol.ts @@ -99,7 +99,6 @@ import { getMarinadeUnstakeTransfer, getSolTokenFromAddress, getSolTokenFromTokenName, - isFeePayerIsolated, isValidAddress, isValidBase64, isValidHex, @@ -905,11 +904,10 @@ export class Sol extends BaseCoin { } } - // For non-consolidate transactions the fee payer is one of three things: - // - the wallet's root address: accepted; - // - a fee payer wallet-platform declares as sponsored: it must match exactly, any other address throws (CHALO-1749); - // - a non-root fee payer nothing declares, as when the signing path re-verifies from the transaction request alone: - // accepted only when it is isolated from the instructions (isFeePayerIsolated), otherwise it throws (CHALO-998). + // For non-consolidate transactions, feePayer must be the wallet's root address, + // or — when wallet-platform declares a sponsored fee payer — exactly that address. + // The closed match only accepts the specific fee payer declared for this + // transaction; every other non-root fee payer still throws. (CHALO-1749) const declaredFeePayer = params.feePayer ?? (typeof txParams === 'object' && @@ -929,19 +927,8 @@ export class Sol extends BaseCoin { ); } } else if (transactionJson.feePayer !== walletRootAddress) { - // A fee payer other than the wallet root is a sponsored transaction (the enterprise fee address pays the fee) - // only when it is isolated: it appears in no instruction except as the durable-nonce authority or the payer of - // a token-account creation, so it cannot be the source, destination or authority of anything the wallet signs. - // Anything else keeps today's behavior: the fee payer must be the wallet root. - const feePayer = transactionJson.feePayer; - const parsedTokenMints = transactionJson.instructionsData.flatMap((instruction) => - instruction.type === InstructionBuilderTypes.TokenTransfer && instruction.params.tokenAddress - ? [instruction.params.tokenAddress] - : [] - ); - if (!feePayer || !isFeePayerIsolated(feePayer, transaction.solTransaction.instructions, parsedTokenMints)) { - throw new Error('Tx fee payer is not the wallet root address'); - } + // Today's behavior: fee payer must be the wallet root + throw new Error('Tx fee payer is not the wallet root address'); } } diff --git a/modules/sdk-coin-sol/test/unit/feePayerIsolation.ts b/modules/sdk-coin-sol/test/unit/feePayerIsolation.ts deleted file mode 100644 index f84557d1dd..0000000000 --- a/modules/sdk-coin-sol/test/unit/feePayerIsolation.ts +++ /dev/null @@ -1,195 +0,0 @@ -import should from 'should'; -import { - ASSOCIATED_TOKEN_PROGRAM_ID, - createApproveInstruction, - createAssociatedTokenAccountInstruction, - createReallocateInstruction, - createSetAuthorityInstruction, - createTransferCheckedInstruction, - AuthorityType, - ExtensionType, - NATIVE_MINT, - TOKEN_2022_PROGRAM_ID, - TOKEN_PROGRAM_ID, -} from '@solana/spl-token'; -import { Keypair, PublicKey, StakeProgram, SystemProgram, TransactionInstruction } from '@solana/web3.js'; -import { isFeePayerIsolated } from '../../src/lib/utils'; - -describe('isFeePayerIsolated', function () { - const key = () => Keypair.generate().publicKey; - const feePayer = key(); - const wallet = key(); - const other = key(); - const nonceAccount = key(); - const mint = key(); - const isolated = (instructions: TransactionInstruction[], extraMints: string[] = []) => - isFeePayerIsolated(feePayer.toBase58(), instructions, extraMints); - const ata = (owner: PublicKey, tokenProgram: PublicKey = TOKEN_PROGRAM_ID) => - PublicKey.findProgramAddressSync( - [owner.toBuffer(), tokenProgram.toBuffer(), mint.toBuffer()], - ASSOCIATED_TOKEN_PROGRAM_ID - )[0]; - const advance = (authorizedPubkey: PublicKey) => - SystemProgram.nonceAdvance({ noncePubkey: nonceAccount, authorizedPubkey }); - const transfer = (from: PublicKey, to: PublicKey) => - SystemProgram.transfer({ fromPubkey: from, toPubkey: to, lamports: 1000 }); - - describe('accepted: the fee payer only pays', function () { - it('accepts the fee payer as the durable-nonce authority', function () { - should(isolated([advance(feePayer), transfer(wallet, other)])).equal(true); - }); - - it('accepts a transaction that does not reference the fee payer at all', function () { - should(isolated([transfer(wallet, other)])).equal(true); - }); - - it('accepts the fee payer as the funder of a token-account creation', function () { - const create = createAssociatedTokenAccountInstruction(feePayer, ata(wallet), wallet, mint); - should(isolated([advance(feePayer), create])).equal(true); - }); - - it('accepts a token transfer between accounts the fee payer does not own', function () { - const move = createTransferCheckedInstruction(ata(wallet), mint, ata(other), wallet, 5, 6); - should(isolated([advance(feePayer), move])).equal(true); - }); - - it('returns true for a transaction with no instruction', function () { - should(isolated([])).equal(true); - }); - }); - - describe('rejected: the fee payer is more than a payer', function () { - it('rejects the fee payer as the source or destination of a transfer', function () { - should(isolated([transfer(feePayer, other)])).equal(false); - should(isolated([transfer(wallet, feePayer)])).equal(false); - }); - - it('rejects the fee payer as the owner of a token-account creation, even when it also funds it', function () { - const create = createAssociatedTokenAccountInstruction(feePayer, ata(feePayer), feePayer, mint); - should(isolated([create])).equal(false); - }); - - it('rejects the fee payer as the nonce account of the advance instruction', function () { - const advanceOnFeePayer = SystemProgram.nonceAdvance({ noncePubkey: feePayer, authorizedPubkey: wallet }); - should(isolated([advanceOnFeePayer])).equal(false); - }); - - it('rejects the fee payer as the staker or withdrawer of a new stake account (inside the instruction data)', function () { - const stake = key(); - const initialize = StakeProgram.initialize({ - stakePubkey: stake, - authorized: { staker: wallet, withdrawer: feePayer }, - }); - should(isolated([initialize])).equal(false); - const stakerIsFeePayer = StakeProgram.initialize({ - stakePubkey: stake, - authorized: { staker: feePayer, withdrawer: wallet }, - }); - should(isolated([stakerIsFeePayer])).equal(false); - }); - - it('rejects a stake authority change to the fee payer', function () { - const authorize = StakeProgram.authorize({ - stakePubkey: key(), - authorizedPubkey: wallet, - newAuthorizedPubkey: feePayer, - stakeAuthorizationType: { index: 1 }, - }); - should(isolated([...authorize.instructions])).equal(false); - }); - - it('rejects an approval of the fee payer as a token delegate', function () { - const approve = createApproveInstruction(ata(wallet), feePayer, wallet, 5); - should(isolated([approve])).equal(false); - }); - - it('rejects a token authority change to the fee payer', function () { - const setAuthority = createSetAuthorityInstruction(ata(wallet), wallet, AuthorityType.AccountOwner, feePayer); - should(isolated([setAuthority])).equal(false); - }); - - it('rejects a token transfer into the fee payer token account, classic and Token-2022', function () { - const toClassic = createTransferCheckedInstruction(ata(wallet), mint, ata(feePayer), wallet, 5, 6); - should(isolated([advance(feePayer), toClassic])).equal(false); - const toToken2022 = createTransferCheckedInstruction( - ata(wallet, TOKEN_2022_PROGRAM_ID), - mint, - ata(feePayer, TOKEN_2022_PROGRAM_ID), - wallet, - 5, - 6, - [], - TOKEN_2022_PROGRAM_ID - ); - should(isolated([advance(feePayer), toToken2022])).equal(false); - }); - - it('rejects a token transfer out of the fee payer token account', function () { - const fromFeePayer = createTransferCheckedInstruction(ata(feePayer), mint, ata(other), wallet, 5, 6); - should(isolated([fromFeePayer])).equal(false); - }); - - it('rejects a plain token Transfer, which names no mint, whoever the destination is', function () { - // the sponsored builders use TransferChecked; a plain Transfer into the fee payer's account cannot be recognised - for (const program of [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID]) { - const plain = (destination: PublicKey) => - new TransactionInstruction({ - programId: program, - keys: [ - { pubkey: ata(wallet, program), isSigner: false, isWritable: true }, - { pubkey: destination, isSigner: false, isWritable: true }, - { pubkey: wallet, isSigner: true, isWritable: false }, - ], - data: Buffer.from([3, 5, 0, 0, 0, 0, 0, 0, 0]), - }); - should(isolated([plain(ata(feePayer, program))])).equal(false); - should(isolated([plain(ata(other, program))])).equal(false); - } - }); - - it('rejects a transfer of SOL into the fee payer wrapped-SOL token account', function () { - const wrappedSolAccount = PublicKey.findProgramAddressSync( - [feePayer.toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), NATIVE_MINT.toBuffer()], - ASSOCIATED_TOKEN_PROGRAM_ID - )[0]; - should(isolated([advance(feePayer), transfer(wallet, wrappedSolAccount)])).equal(false); - }); - - it('rejects a pool deposit that mints the pool tokens into the fee payer token account', function () { - // the pool mint is one of the instruction accounts, whichever program the instruction belongs to - const poolProgram = key(); - const poolMint = key(); - const deposit = new TransactionInstruction({ - programId: poolProgram, - keys: [ - { pubkey: key(), isSigner: false, isWritable: true }, - { pubkey: wallet, isSigner: true, isWritable: true }, - { pubkey: ata(feePayer), isSigner: false, isWritable: true }, - { pubkey: poolMint, isSigner: false, isWritable: true }, - ], - data: Buffer.from([14, 1, 0, 0, 0, 0, 0, 0, 0]), - }); - const poolAtaOfFeePayer = PublicKey.findProgramAddressSync( - [feePayer.toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), poolMint.toBuffer()], - ASSOCIATED_TOKEN_PROGRAM_ID - )[0]; - deposit.keys[2].pubkey = poolAtaOfFeePayer; - should(isolated([deposit])).equal(false); - deposit.keys[2].pubkey = ata(other); - should(isolated([deposit])).equal(true); - }); - - it('rejects the fee payer as the payer of a confidential-transfer account reallocation', function () { - // wallet-platform sponsors no confidential-transfer instruction, so none is exempted - const reallocate = createReallocateInstruction( - ata(wallet, TOKEN_2022_PROGRAM_ID), - feePayer, - [ExtensionType.ConfidentialTransferAccount], - wallet, - [], - TOKEN_2022_PROGRAM_ID - ); - should(isolated([reallocate])).equal(false); - }); - }); -}); diff --git a/modules/sdk-coin-sol/test/unit/sol.ts b/modules/sdk-coin-sol/test/unit/sol.ts index f26c7fe991..16ed66510b 100644 --- a/modules/sdk-coin-sol/test/unit/sol.ts +++ b/modules/sdk-coin-sol/test/unit/sol.ts @@ -632,76 +632,6 @@ describe('SOL:', function () { .should.be.rejectedWith('Tx fee payer is not the wallet root address'); }); - // CHALO-998: a sponsored transaction (the enterprise fee address pays the fee) is accepted without a declared fee - // payer when the fee payer is isolated from the instructions the wallet signs; every other non-root fee payer - // still fails. Built with the real transfer builder, no mocks. - describe('sponsored fee payer without a declaration', () => { - const feeAddress = new KeyPair(resources.authAccount2).getKeys().pub; - const nonceAccount = new KeyPair(resources.nonceAccount).getKeys().pub; - const recipient = 'CP5Dpaa42RtJmMuKqCQsLwma5Yh3knuvKsYDFX85F41S'; - - const buildTx = async (opts: { sender: string; feePayer: string; to: string; nonceAuthority?: string }) => { - const txBuilder = factory.getTransferBuilder(); - txBuilder.sender(opts.sender); - txBuilder.feePayer(opts.feePayer); - txBuilder.nonce(blockHash, { - walletNonceAddress: nonceAccount, - authWalletAddress: opts.nonceAuthority ?? opts.feePayer, - }); - txBuilder.send({ address: opts.to, amount: '1000' }); - return (await txBuilder.build()).toBroadcastFormat(); - }; - - const verify = (txBase64: string, params: Record = {}) => - basecoin.verifyTransaction({ - txParams: { recipients: [{ address: recipient, amount: '1000' }] }, - txPrebuild: { txBase64 }, - wallet: walletObj, - ...params, - } as any); - - it('accepts a fee payer that is only the durable-nonce authority', async function () { - const txBase64 = await buildTx({ sender: wallet.pub, feePayer: feeAddress, to: recipient }); - (await verify(txBase64)).should.equal(true); - }); - - it('accepts a sponsored fee payer on a recent-blockhash transaction with no nonce', async function () { - const txBuilder = factory.getTransferBuilder(); - txBuilder.sender(wallet.pub); - txBuilder.feePayer(feeAddress); - txBuilder.nonce(blockHash); - txBuilder.send({ address: recipient, amount: '1000' }); - const txBase64 = (await txBuilder.build()).toBroadcastFormat(); - (await verify(txBase64)).should.equal(true); - }); - - it('rejects a non-root fee payer that is the source of the transfer', async function () { - const txBase64 = await buildTx({ sender: feeAddress, feePayer: feeAddress, to: recipient }); - await verify(txBase64).should.be.rejectedWith('Tx fee payer is not the wallet root address'); - }); - - it('rejects a non-root fee payer that is the destination of the transfer', async function () { - const txBase64 = await buildTx({ sender: wallet.pub, feePayer: feeAddress, to: feeAddress }); - await verify(txBase64, { - txParams: { recipients: [{ address: feeAddress, amount: '1000' }] }, - }).should.be.rejectedWith('Tx fee payer is not the wallet root address'); - }); - - it('still requires the exact declared fee payer when one is declared', async function () { - const txBase64 = await buildTx({ sender: wallet.pub, feePayer: feeAddress, to: recipient }); - await verify(txBase64, { feePayer: recipient }).should.be.rejectedWith( - `Tx fee payer ${feeAddress} does not match the declared sponsored fee payer ${recipient}` - ); - (await verify(txBase64, { feePayer: feeAddress })).should.equal(true); - }); - - it('keeps the wallet root as an accepted fee payer', async function () { - const rootWallet = new Wallet(bitgo, basecoin, { ...walletData, coinSpecific: { rootAddress: wallet.pub } }); - const txBase64 = await buildTx({ sender: wallet.pub, feePayer: wallet.pub, to: recipient }); - (await verify(txBase64, { wallet: rootWallet })).should.equal(true); - }); - }); - // CHALO-1749: sponsored fee-payer bypass — when wallet-platform declares a // fee payer, the transaction's fee payer must match it exactly; when it doesn't, // today's wallet-root check applies. All tests below use the same fixture @@ -1025,14 +955,14 @@ describe('SOL:', function () { coin: 'tsol', }; - // Without a declared feePayer: the tx feePayer (enterprise) ≠ wallet root (sender), but it is isolated (it only - // pays the fee and owns the durable nonce), so it is accepted as a sponsored fee payer (CHALO-998) - const withoutDeclaration = await basecoin.verifyTransaction({ - txParams, - txPrebuild: prebuild, - wallet: senderWallet, - } as unknown as SolVerifyTransactionOptions); - withoutDeclaration.should.equal(true); + // Without the declared feePayer: the tx feePayer (enterprise) ≠ wallet root (sender) → throws + await basecoin + .verifyTransaction({ + txParams, + txPrebuild: prebuild, + wallet: senderWallet, + } as unknown as SolVerifyTransactionOptions) + .should.be.rejectedWith('Tx fee payer is not the wallet root address'); // With the declared feePayer matching the tx's actual fee payer → passes const result = await basecoin.verifyTransaction({ diff --git a/modules/sdk-coin-sol/test/unit/sponsoredIntentsVerify.ts b/modules/sdk-coin-sol/test/unit/sponsoredIntentsVerify.ts deleted file mode 100644 index cf787debd8..0000000000 --- a/modules/sdk-coin-sol/test/unit/sponsoredIntentsVerify.ts +++ /dev/null @@ -1,271 +0,0 @@ -import should from 'should'; -import { TestBitGo, TestBitGoAPI } from '@bitgo/sdk-test'; -import { BitGoAPI } from '@bitgo/sdk-api'; -import { Wallet } from '@bitgo/sdk-core'; -import { PublicKey, StakeProgram } from '@solana/web3.js'; -import { KeyPair, Sol, SolVerifyTransactionOptions, Tsol } from '../../src'; -import { Transaction } from '../../src/lib'; -import * as resources from '../resources/sol'; -import { getBuilderFactory } from './getBuilderFactory'; - -/** - * Every sponsored intent of the SOL fee payer project built with the real builders and verified with - * Sol.verifyTransaction when nothing declares the fee payer (the signing path re-verifies from the transaction alone): - * the enterprise fee address pays the fee and is accepted only while it is isolated from the instructions. - */ -describe('verifyTransaction of every sponsored intent (CHALO-998)', function () { - const factory = getBuilderFactory('tsol'); - const blockHash = resources.blockHashes.validBlockHashes[0]; - const NOT_ROOT_ERROR = 'Tx fee payer is not the wallet root address'; - - const root = new KeyPair(resources.authAccount).getKeys().pub; // the wallet root address - const feeAddress = new KeyPair(resources.authAccount2).getKeys().pub; // the enterprise fee address - const nonceAccount = new KeyPair(resources.nonceAccount).getKeys().pub; - const recipient = new KeyPair({ prv: resources.prvKeys.prvKey1.base58 }).getKeys().pub; - const stakeAccount = new KeyPair(resources.stakeAccount).getKeys().pub; - const validator = resources.validator.pub; - const tokenName = resources.tokenTransfers.nameUSDC; - const mint = resources.associatedTokenAccounts.mint; - const childAddress = new KeyPair(resources.associatedTokenAccounts.accounts[0]).getKeys().pub; // a receive address - - let bitgo: TestBitGoAPI; - let basecoin: Sol; - let walletObj: Wallet; - - before(function () { - bitgo = TestBitGo.decorate(BitGoAPI, { env: 'mock' }); - bitgo.safeRegister('tsol', Tsol.createInstance); - bitgo.initializeTestVars(); - basecoin = bitgo.coin('tsol') as Sol; - walletObj = new Wallet(bitgo, basecoin, { - id: '5b34252f1bf349930e34020a00000000', - coin: 'tsol', - keys: [ - '5b3424f91bf349930e34017500000000', - '5b3424f91bf349930e34017600000000', - '5b3424f91bf349930e34017700000000', - ], - coinSpecific: { rootAddress: root }, - multisigType: 'tss', - }); - }); - - type SponsorableBuilder = { - feePayer: (address: string) => unknown; - nonce: (blockHash: string, durableNonce?: { walletNonceAddress: string; authWalletAddress: string }) => unknown; - }; - - /** Sets the sponsored fee payer, on a durable nonce the fee address owns or on a recent blockhash. */ - const sponsor = (builder: SponsorableBuilder, feePayer: string, useDurableNonce: boolean) => { - builder.feePayer(feePayer); - if (useDurableNonce) { - builder.nonce(blockHash, { walletNonceAddress: nonceAccount, authWalletAddress: feePayer }); - } else { - builder.nonce(blockHash); - } - }; - - const verify = (txBase64: string, txParams: Record = {}) => - basecoin.verifyTransaction({ - txParams, - txPrebuild: { txBase64 }, - wallet: walletObj, - } as unknown as SolVerifyTransactionOptions); - - type Intent = { - name: string; - /** builds the intent's transaction; feePayer is the address that pays and sender the address that signs */ - build: (feePayer: string, sender: string, useDurableNonce: boolean) => Promise; - txParams?: Record; - /** the intent is exempt from the fee payer check, so no rejection case applies */ - exempt?: boolean; - }; - - const intents: Intent[] = [ - { - name: 'payment (native)', - txParams: { recipients: [{ address: recipient, amount: '1000' }] }, - build: async (feePayer, sender, durable) => { - const b = factory.getTransferBuilder(); - sponsor(b, feePayer, durable); - b.sender(sender); - b.send({ address: recipient, amount: '1000' }); - return (await b.build()).toBroadcastFormat(); - }, - }, - { - name: 'payment (SPL token)', - build: async (feePayer, sender, durable) => { - const b = factory.getTokenTransferBuilder(); - sponsor(b, feePayer, durable); - b.sender(sender); - b.send({ address: recipient, amount: '1000', tokenName }); - return (await b.build()).toBroadcastFormat(); - }, - }, - { - name: 'goUnstake (a payment from the wallet)', - txParams: { recipients: [{ address: recipient, amount: '1000' }] }, - build: async (feePayer, sender, durable) => { - const b = factory.getTransferBuilder(); - sponsor(b, feePayer, durable); - b.sender(sender); - b.send({ address: recipient, amount: '1000' }); - return (await b.build()).toBroadcastFormat(); - }, - }, - { - name: 'enableToken', - build: async (feePayer, sender, durable) => { - const b = factory.getAtaInitializationBuilder(); - sponsor(b, feePayer, durable); - b.sender(sender); - b.mint(mint); - b.rentExemptAmount('2039280'); - return (await b.build()).toBroadcastFormat(); - }, - }, - { - name: 'consolidate (native sweep of a receive address)', - build: async (feePayer, sender, durable) => { - const b = factory.getTransferBuilder(); - sponsor(b, feePayer, durable); - b.sender(sender === root ? childAddress : sender); - b.send({ address: root, amount: '1000' }); - return (await b.build()).toBroadcastFormat(); - }, - }, - { - name: 'consolidateToken (token sweep of a receive address)', - build: async (feePayer, sender, durable) => { - const b = factory.getTokenTransferBuilder(); - sponsor(b, feePayer, durable); - b.sender(sender === root ? childAddress : sender); - b.send({ address: root, amount: '1000', tokenName }); - return (await b.build()).toBroadcastFormat(); - }, - }, - { - name: 'stake', - build: async (feePayer, sender, durable) => { - const b = factory.getStakingActivateBuilder(); - sponsor(b, feePayer, durable); - b.sender(sender); - b.stakingAddress(stakeAccount); - b.amount('300000'); - b.validator(validator); - return (await b.build()).toBroadcastFormat(); - }, - }, - { - name: 'unstake / deactivate', - build: async (feePayer, sender, durable) => { - const b = factory.getStakingDeactivateBuilder(); - sponsor(b, feePayer, durable); - b.sender(sender); - b.stakingAddress(stakeAccount); - return (await b.build()).toBroadcastFormat(); - }, - }, - { - name: 'claim (withdraw rewards)', - build: async (feePayer, sender, durable) => { - const b = factory.getStakingWithdrawBuilder(); - sponsor(b, feePayer, durable); - b.sender(sender); - b.stakingAddress(stakeAccount); - b.amount('300000'); - return (await b.build()).toBroadcastFormat(); - }, - }, - { - name: 'delegate', - build: async (feePayer, sender, durable) => { - const b = factory.getStakingDelegateBuilder(); - sponsor(b, feePayer, durable); - b.sender(sender); - b.stakingAddress(stakeAccount); - b.validator(validator); - return (await b.build()).toBroadcastFormat(); - }, - }, - { - name: 'closeAssociatedTokenAccount', - exempt: true, - build: async (feePayer, sender, durable) => { - const b = factory.getCloseAtaInitializationBuilder(); - sponsor(b, feePayer, durable); - b.sender(sender); - b.accountAddress(nonceAccount); - b.destinationAddress(root); - b.authorityAddress(sender); - return (await b.build()).toBroadcastFormat(); - }, - }, - ]; - - for (const intent of intents) { - describe(intent.name, function () { - for (const useDurableNonce of [true, false]) { - const mode = useDurableNonce ? 'on a durable nonce the fee address owns' : 'on a recent blockhash'; - - it(`accepts the fee address as the only fee payer, ${mode}`, async function () { - const txBase64 = await intent.build(feeAddress, root, useDurableNonce); - should(await verify(txBase64, intent.txParams)).equal(true); - }); - - if (!intent.exempt) { - it(`rejects it when the fee address is also the signer of the instructions, ${mode}`, async function () { - const txBase64 = await intent.build(feeAddress, feeAddress, useDurableNonce); - await verify(txBase64, intent.txParams).should.be.rejectedWith(NOT_ROOT_ERROR); - }); - } - } - - it('keeps the wallet root as an accepted fee payer', async function () { - const txBase64 = await intent.build(root, root, true); - const result = await verify(txBase64, intent.txParams).then( - () => true, - (e: Error) => e.message - ); - // an unrelated check of the intent may reject it, but never the fee payer rule - if (result !== true) { - should(result).not.equal(NOT_ROOT_ERROR); - } - }); - }); - } - it('rejects a token payment that sends the tokens to the fee address (its token account)', async function () { - const b = factory.getTokenTransferBuilder(); - sponsor(b, feeAddress, true); - b.sender(root); - b.send({ address: feeAddress, amount: '1000', tokenName }); - const txBase64 = (await b.build()).toBroadcastFormat(); - await verify(txBase64).should.be.rejectedWith(NOT_ROOT_ERROR); - }); - - it('rejects a stake that hands its authority to the fee address', async function () { - // the builder makes the wallet the staker and withdrawer, so the transaction is rebuilt with the fee address as - // withdrawer: the parsed stake instruction does not show it, the raw instruction does - const b = factory.getStakingActivateBuilder(); - sponsor(b, feeAddress, true); - b.sender(root); - b.stakingAddress(stakeAccount); - b.amount('300000'); - b.validator(validator); - const tx = (await b.build()) as Transaction; - const instructions = tx.solTransaction.instructions; - const initialize = instructions.find( - (ix) => ix.programId.equals(StakeProgram.programId) && ix.data.readUInt32LE(0) === 0 - ); - should.exist(initialize); - // overwrite the withdrawer (the second authority of Initialize) with the fee address - const data = Buffer.from(initialize!.data); - new PublicKey(feeAddress).toBuffer().copy(data, 4 + 32); - initialize!.data = data; - const txBase64 = Buffer.from( - tx.solTransaction.serialize({ requireAllSignatures: false, verifySignatures: false }) - ).toString('base64'); - await verify(txBase64).should.be.rejectedWith(NOT_ROOT_ERROR); - }); -});