Skip to content
Open
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
14 changes: 14 additions & 0 deletions modules/sdk-core/src/bitgo/baseCoin/iBaseCoin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,20 @@ export interface TransactionParams {
stakingRequestId?: string;
/** ERC-7984 shield intent (`type: 'wrapApprove' | 'wrap'`): wrapper coin name and exact amount. */
wrapParams?: { tokenName: string; amount: string };
/**
* DeFi vault intent parameters (`type: 'defiApprove' | 'defiDeposit' | 'defiWithdraw'`):
* vault the operation targets and the exact amount (share amount for defiWithdraw).
* Reconstructed from the flattened intent on no-txParams signing paths
* (see resolveEffectiveTxParams) so the coin verifier's DeFi calldata checks still run.
* Shape matches the existing EthTransactionParams.defiParams redeclaration
* (DefiIntentParams) — keep the fields required or the optional-to-required
* variance breaks EthLike verifyTransaction assignability (sdk-coin-flr).
*/
defiParams?: {
vaultId: string;
amount: string;
operationId?: string;
};
/** External settlement executor party ID for Canton standing delegation intents. */
executorPartyId?: string;
/** Canton split (fanout): number of equal-value holdings the selected unspents are split into. */
Expand Down
54 changes: 52 additions & 2 deletions modules/sdk-core/src/bitgo/utils/tss/recipientUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import { PopulatedIntent, TxRequest } from './baseTypes';
* ECDSA types: acceleration, fillNonce, transferToken, tokenApproval, consolidate,
* bridgeFunds, enableToken, customTx, wrapApprove, wrap, unwrap,
* finalizeUnwrap, contractCall
* BSC/BNB delegation-based staking: delegate, undelegate, switchValidator
* DeFi vault operations: defiApprove, defiDeposit, defiWithdraw (camelCase
* only — resolveEffectiveTxParams normalizes the kebab-case
* intentType WP persists)
* CELO/ETH lock-based staking: stake, unstake, stakeWithCallData, unstakeWithCallData,
* transferStake, increaseStake, goUnstake
* Claim rewards (BSC, CELO — TRX/SOL use EdDSA and are unaffected): claim, stakeClaimRewards
Expand All @@ -29,7 +31,15 @@ export const NO_RECIPIENT_TX_TYPES = new Set([
'disableToken',
'disabletoken',
'customTx',
// DeFi vault operations — recipients/calldata built server-side from defiParams
// DeFi vault operations — recipients/calldata built server-side from defiParams.
// Registered only in the camelCase txParams.type spelling: WP persists the
// intentType kebab-case ('defi-approve' etc.), and resolveEffectiveTxParams
// normalizes that persisted spelling to the camelCase type before any
// consumer of this set sees it — so the no-txParams signing path
// (pendingApproval.approve() → recreateTxRequest() → signTxRequest())
// matches here AND reaches the coin verifier's dedicated DeFi calldata
// checks, which also key on the camelCase type. The normalization is the
// single bridge; do not rely on dual registration here.
'defiApprove',
'defiDeposit',
'defiWithdraw',
Expand Down Expand Up @@ -105,6 +115,16 @@ export const NO_RECIPIENT_TX_TYPES = new Set([
'authorize',
]);

/**
* DeFi vault intents: the kebab-case intentType WP persists → the camelCase
* txParams.type that the coin verifier's dedicated DeFi calldata checks key on
* (abstractEthLikeNewCoins.verifyTssTransaction).
*/
const DEFI_INTENT_TYPE_TO_TX_TYPE: Record<string, 'defiApprove' | 'defiDeposit' | 'defiWithdraw'> = {
'defi-approve': 'defiApprove',
'defi-deposit': 'defiDeposit',
'defi-withdraw': 'defiWithdraw',
};
/**
* The SDK persists intent recipient addresses as `{ address }`, but txRequests created by other clients
* (e.g. the retail UI's Canton split) store a plain string. Accept both.
Expand Down Expand Up @@ -165,6 +185,36 @@ export function resolveEffectiveTxParams(
recipients: txParams?.recipients?.length ? txParams.recipients : intentRecipients,
};

// DeFi vault intents: WP persists intentType kebab-case ('defi-approve',
// 'defi-deposit', 'defi-withdraw') with the defiParams flattened onto the
// intent by createIntent (vaultId/amount, shareTokenAmount for defi-withdraw).
// Signing paths that carry no txParams — pendingApproval.approve() →
// recreateTxRequest() → signTxRequest() — must still reach the coin
// verifier's dedicated DeFi calldata checks, which key on the camelCase
// txParams.type and read txParams.defiParams (abstractEthLikeNewCoins
// verifyTssTransaction). Normalize the type and reconstruct defiParams from
// the flattened intent, mirroring the wrapApprove wrapParams propagation
// below. A malformed intent (non-string amount fields) reconstructs nothing
// and the coin verifier then rejects the sign with 'missing required intent
// parameters' — fail closed.
const defiIntent = txRequest.intent as PopulatedIntent | undefined;
const defiTxType = defiIntent ? DEFI_INTENT_TYPE_TO_TX_TYPE[defiIntent.intentType] : undefined;
if (defiTxType && defiIntent) {
if (!effectiveTxParams.type) {
effectiveTxParams.type = defiTxType;
}
if (!effectiveTxParams.defiParams) {
const amount = defiIntent.intentType === 'defi-withdraw' ? defiIntent.shareTokenAmount : defiIntent.amount;
if (typeof defiIntent.vaultId === 'string' && typeof amount === 'string') {
effectiveTxParams.defiParams = {
vaultId: defiIntent.vaultId,
amount,
...(typeof defiIntent.operationId === 'string' && { operationId: defiIntent.operationId }),
};
}
}
}

// Fall back to intent.intentType when txParams.type is not explicitly set.
// Staking wallets call signTransaction without txParams, so the type lives only in the intent.
const txType = effectiveTxParams.type ?? (txRequest.intent as PopulatedIntent)?.intentType ?? '';
Expand Down
100 changes: 100 additions & 0 deletions modules/sdk-core/test/unit/bitgo/utils/tss/ecdsa/ecdsaMPCv2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
EcdsaMPCv2KeyGenCallbacks,
IBaseCoin,
IWallet,
IRequestTracer,
RequestTracer,
SignatureShareRecord,
SignatureShareType,
Expand Down Expand Up @@ -836,6 +837,105 @@ describe('ECDSA MPC v2', async () => {
});
});

// Regression test for DEFI-1356: WP persists DeFi vault intentTypes kebab-case with the
// defiParams flattened onto the intent (vaultId/amount, shareTokenAmount for withdraw —
// see mpcUtils.createIntent). The coin verifier's dedicated DeFi calldata checks
// (abstractEthLikeNewCoins.verifyTssTransaction) key on the camelCase txParams.type and
// read txParams.defiParams, so a no-txParams sign must normalize the type and reconstruct
// defiParams — otherwise the PA-approved leg skips DeFi verification entirely (only the
// warnTssVerificationIncomplete warning fires). Pin it through the real signRequestBase()
// -> resolveEffectiveTxParams() -> verifyTransaction() wiring, mirroring the wrap-native
// regression above: pendingApproval.approve() -> recreateTxRequest() -> signTxRequest()
// carries no txParams at all, so the intent is the only source of type and defiParams.
['defi-approve', 'defi-deposit', 'defi-withdraw'].forEach((intentType) => {
it(`signRequestBase should hand the verifier a camelCase type and defiParams for a no-txParams ${intentType} intent`, async () => {
const serializedTxHex = 'f86c808504a817c80082520894' + '00'.repeat(20) + '80808080';
const signableHex = serializedTxHex;
const derivationPath = 'm/0';

const mockBgWithPost = {} as BitGoBase;
mockBgWithPost.getEnv = sinon.stub().returns('test');
mockBgWithPost.setRequestTracer = sinon.stub();
mockBgWithPost.encrypt = sinon.stub().resolves('encrypted');
mockBgWithPost.decrypt = sinon.stub().resolves('decrypted');
mockBgWithPost.post = sinon.stub().returns({
send: sinon.stub().returnsThis(),
set: sinon.stub().returnsThis(),
result: sinon.stub().rejects(new Error('mock: HTTP not available')),
});

const verifyTransactionSpy = sinon.stub().resolves(true);
const mockCoinForDefi = {
getHashFunction: sinon.stub().callsFake(() => createKeccakHash('keccak256') as Hash),
verifyTransaction: verifyTransactionSpy,
getMPCAlgorithm: sinon.stub().returns('ecdsa'),
getChain: sinon.stub().returns('hteth'),
getConfig: sinon.stub().returns({ family: 'hteth' }),
} as unknown as IBaseCoin;

const mockWallet = {
id: sinon.stub().returns(walletID),
multisigType: sinon.stub().returns('tss'),
multisigTypeVersion: sinon.stub().returns('MPCv2'),
};

const defiUtils = new EcdsaMPCv2Utils(mockBgWithPost, mockCoinForDefi, mockWallet as unknown as IWallet);
sinon
.stub(defiUtils as unknown as Record<string, unknown>, 'pickBitgoPubGpgKeyForSigning')
.resolves(bitgoGpgKey.public);

// The persisted intent shape from mpcUtils.createIntent: flattened DefiIntentFields,
// no defiParams container. No recipients anywhere — the calldata is built server-side.
const txRequest = {
txRequestId: `defi-test-${intentType}`,
apiVersion: 'full',
walletId: walletID,
intent: {
intentType,
vaultId: 'vlt-galaxy-usdc',
amount: '1000000',
shareTokenAmount: '900000',
},
transactions: [
{
unsignedTx: { derivationPath, signableHex, serializedTxHex },
signatureShares: [],
},
],
} as unknown as TxRequest;

try {
await defiUtils.signTxRequest({
txRequest,
// No txParams at all — mirrors pendingApproval.approve() -> recreateTxRequest() ->
// signTxRequest(), the one signing path that only ever sees the kebab-case intentType.
txParams: undefined,
prv: userShare.toString('base64'),
reqId: { inc: sinon.stub(), toString: sinon.stub().returns('test-req') } as unknown as IRequestTracer,
});
} catch (e) {}

assert.strictEqual(
verifyTransactionSpy.callCount,
1,
'verifyTransaction must be reached: resolveEffectiveTxParams must not throw for a no-recipients ' +
`${intentType} intent`
);
const verifyCallArgs = verifyTransactionSpy.firstCall.args[0];
const camelCaseType = {
'defi-approve': 'defiApprove',
'defi-deposit': 'defiDeposit',
'defi-withdraw': 'defiWithdraw',
}[intentType];
assert.strictEqual(verifyCallArgs.txParams.type, camelCaseType);
assert.strictEqual(verifyCallArgs.txParams.recipients, undefined);
assert.deepStrictEqual(verifyCallArgs.txParams.defiParams, {
vaultId: 'vlt-galaxy-usdc',
amount: intentType === 'defi-withdraw' ? '900000' : '1000000',
});
});
});

it('should still apply keccak256 for regular FLR EVM transactions', async () => {
// Regular EVM transaction on FLR (e.g. token transfer, not cross-chain).
// serializedTxHex starts with 'f8' (RLP prefix), NOT '0000'.
Expand Down
107 changes: 106 additions & 1 deletion modules/sdk-core/test/unit/bitgo/utils/tss/recipientUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ describe('recipientUtils', function () {
'defiApprove',
'defiDeposit',
'defiWithdraw',
// DeFi vault operations are registered in the camelCase spelling only:
// resolveEffectiveTxParams normalizes the kebab-case intentType WP
// persists, so the no-txParams PA path matches the camelCase entries.
// The normalization tests below pin that contract.
// Native wrap/unwrap — registered in both spellings on purpose
'wrapNative',
'wrap-native',
Expand Down Expand Up @@ -82,7 +86,7 @@ describe('recipientUtils', function () {
});

it('does not contain value-transfer types', function () {
['payment', 'fanout', 'vote', 'defi-deposit', 'defi-redeem'].forEach((t) => {
['payment', 'fanout', 'vote', 'transfer'].forEach((t) => {
assert.ok(!NO_RECIPIENT_TX_TYPES.has(t), `${t} must NOT be in NO_RECIPIENT_TX_TYPES`);
});
});
Expand Down Expand Up @@ -389,6 +393,107 @@ describe('recipientUtils', function () {
});
});

describe('DeFi vault intent propagation (kebab-case persisted intentTypes)', function () {
// WP persists defi intentTypes kebab-case with the defiParams flattened onto the
// intent by createIntent (vaultId/amount; shareTokenAmount for defi-withdraw —
// see mpcUtils.createIntent). pendingApproval.approve() → recreateTxRequest() →
// signTxRequest() carries no txParams, so the intent is the ONLY source of both
// the type and the defiParams. The coin verifier's dedicated DeFi calldata checks
// (abstractEthLikeNewCoins.verifyTssTransaction) key on the camelCase txParams.type
// and read txParams.defiParams, so the type must be normalized and defiParams
// reconstructed — otherwise the PA-approved leg skips DeFi verification entirely.
const kebabToCamel: Record<string, string> = {
'defi-approve': 'defiApprove',
'defi-deposit': 'defiDeposit',
'defi-withdraw': 'defiWithdraw',
};

it('does not throw for kebab-case DeFi intents signed without txParams (PA approve path)', function () {
for (const intentType of Object.keys(kebabToCamel)) {
const txRequest = makeTxRequest({ intent: { intentType } as PopulatedIntent });
const result = resolveEffectiveTxParams(txRequest, undefined);
assert.strictEqual(result.type, kebabToCamel[intentType]);
assert.strictEqual(result.recipients, undefined);
}
});

it('reconstructs defiParams from the flattened intent (vaultId/amount, shareTokenAmount for withdraw)', function () {
for (const intentType of Object.keys(kebabToCamel)) {
const txRequest = makeTxRequest({
intent: {
intentType,
vaultId: 'vlt-galaxy-usdc',
amount: '1000000',
shareTokenAmount: '900000',
} as PopulatedIntent,
});
const result = resolveEffectiveTxParams(txRequest, undefined);
assert.strictEqual(result.type, kebabToCamel[intentType]);
assert.deepStrictEqual(result.defiParams, {
vaultId: 'vlt-galaxy-usdc',
amount: intentType === 'defi-withdraw' ? '900000' : '1000000',
});
}
});

it('propagates operationId from the intent onto the reconstructed defiParams', function () {
const txRequest = makeTxRequest({
intent: {
intentType: 'defi-deposit',
vaultId: 'vlt-galaxy-usdc',
amount: '1000000',
operationId: 'op-123',
} as PopulatedIntent,
});
const result = resolveEffectiveTxParams(txRequest, undefined);
assert.deepStrictEqual(result.defiParams, {
vaultId: 'vlt-galaxy-usdc',
amount: '1000000',
operationId: 'op-123',
});
});

it('does not overwrite defiParams supplied by the caller', function () {
const callerDefiParams = { vaultId: 'vlt-caller', amount: '5' };
const txRequest = makeTxRequest({
intent: { intentType: 'defi-approve', vaultId: 'vlt-galaxy-usdc', amount: '1000000' } as PopulatedIntent,
});
const result = resolveEffectiveTxParams(txRequest, { type: 'defiApprove', defiParams: callerDefiParams });
assert.deepStrictEqual(result.defiParams, callerDefiParams);
});

it('does not derive defiParams for non-defi intents', function () {
const txRequest = makeTxRequest({ intent: { intentType: 'consolidate' } as PopulatedIntent });
const result = resolveEffectiveTxParams(txRequest, undefined);
assert.strictEqual(result.defiParams, undefined);
});

it('reconstructs nothing (fail closed) when the flattened intent fields are malformed', function () {
// Non-string amount/shareTokenAmount or a missing/non-string vaultId ⇒ no
// defiParams reach the coin verifier, which then rejects the sign with
// 'missing required intent parameters' — fail closed (see the analogous
// wrapParams non-string-amount test above).
const malformedIntents: PopulatedIntent[] = [
{ intentType: 'defi-deposit', vaultId: 'vlt-galaxy-usdc', amount: { value: '1000000' } } as PopulatedIntent,
// Deliberately malformed shapes — the double cast is the point of the test.
{
intentType: 'defi-withdraw',
vaultId: 'vlt-galaxy-usdc',
shareTokenAmount: 900000,
} as unknown as PopulatedIntent,
{ intentType: 'defi-approve', amount: '1000000' } as PopulatedIntent,
];
for (const intent of malformedIntents) {
const txRequest = makeTxRequest({ intent });
const result = resolveEffectiveTxParams(txRequest, undefined);
// The type still normalizes so the verifier routes into its DeFi
// calldata checks — but with no defiParams to check against.
assert.strictEqual(result.type, kebabToCamel[intent.intentType]);
assert.strictEqual(result.defiParams, undefined);
}
});
});

it('does not throw when buildParams.type is PascalCase but intent.intentType is lowercase', function () {
// signTransactionTss passes txPrebuild.buildParams as txParams. Prebuild uses
// type: 'Import' while WP stores intentType: 'import' on the txRequest.
Expand Down
Loading