Skip to content

Commit 49037e8

Browse files
mukeshspclaude
andcommitted
fix(sdk-coin-ton): bind transfer comment to memoId in verifyTransaction
Ton.verifyTransaction compared only (address, amount) and stripped the ?memoId= suffix, so a prebuild whose on-chain comment differed from the intended memoId verified successfully, enabling exchange-deposit redirection. Verification now binds the parsed transfer comment (plain-send body comment and jetton forward comment) to the declared memoId on both the tton WASM and mainnet TonWeb paths, rejecting different, missing, and extra comments. Explanations expose the comment as outputs[].memo, and the TonWeb jetton parser now accepts the empty forward-payload cell the builder writes for comment-less transfers. Ticket: CSHLD-2160 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 6aef749 commit 49037e8

9 files changed

Lines changed: 509 additions & 25 deletions

File tree

‎modules/sdk-coin-ton/src/lib/explainTransactionWasm.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,25 +39,29 @@ function extractOutputs(
3939
parsed: WasmParsedTransaction,
4040
toAddressBounceable: boolean
4141
): {
42-
outputs: { address: string; amount: string }[];
42+
outputs: { address: string; amount: string; memo?: string }[];
4343
outputAmount: string;
4444
withdrawAmount: string | undefined;
4545
} {
46-
const outputs: { address: string; amount: string }[] = [];
46+
const outputs: { address: string; amount: string; memo?: string }[] = [];
4747
let withdrawAmount: string | undefined;
4848

4949
for (const action of parsed.sendActions) {
5050
if (action.jettonTransfer) {
5151
outputs.push({
5252
address: action.jettonTransfer.destination,
5353
amount: String(action.jettonTransfer.amount),
54+
// the jetton forward comment — the memo exchanges use to credit token deposits
55+
...(action.memo !== undefined && action.memo !== '' ? { memo: action.memo } : {}),
5456
});
5557
} else {
5658
// destinationBounceable is always EQ... (bounceable)
5759
// destination respects the original bounce flag (UQ... when bounce=false)
5860
outputs.push({
5961
address: toAddressBounceable ? action.destinationBounceable : action.destination,
6062
amount: String(action.amount),
63+
// plain text comment (body opcode 0) — absent for protocol payload bodies
64+
...(action.memo !== undefined && action.memo !== '' ? { memo: action.memo } : {}),
6165
});
6266
}
6367

‎modules/sdk-coin-ton/src/lib/tokenTransaction.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,13 @@ export class TokenTransaction extends Transaction {
104104
explainTransaction(): TransactionExplanation {
105105
const displayOrder = ['id', 'outputs', 'outputAmount', 'changeOutputs', 'changeAmount', 'fee', 'withdrawAmount'];
106106

107-
const outputs: TransactionRecipient[] = [this.recipient];
107+
// `message` is the jetton forward comment — the memo exchanges use to credit token deposits
108+
const outputs: TransactionRecipient[] = [
109+
{
110+
...this.recipient,
111+
...(this.message ? { memo: this.message } : {}),
112+
},
113+
];
108114
const outputAmount = this.recipient.amount;
109115
const withdrawAmount = this.withdrawAmount;
110116
return {

‎modules/sdk-coin-ton/src/lib/transaction.ts‎

Lines changed: 63 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,19 @@ import {
1515
SINGLE_NOMINATOR_WITHDRAW_ALL_COMMENT,
1616
} from './constants';
1717

18+
/**
19+
* The subset of the tonweb Slice API the comment decoders rely on. tonweb ships no
20+
* type definitions for Slice, so this structural type documents the access pattern.
21+
*/
22+
interface CommentSlice {
23+
refs: unknown[];
24+
refCursor: number;
25+
getFreeBits(): number;
26+
loadBits(bits: number): Uint8Array;
27+
loadUint(bits: number): { toNumber(): number };
28+
loadRef(): CommentSlice;
29+
}
30+
1831
export class Transaction extends BaseTransaction {
1932
public recipient: Recipient;
2033
public bounceable: boolean;
@@ -235,7 +248,14 @@ export class Transaction extends BaseTransaction {
235248
explainTransaction(): TransactionExplanation {
236249
const displayOrder = ['id', 'outputs', 'outputAmount', 'changeOutputs', 'changeAmount', 'fee', 'withdrawAmount'];
237250

238-
const outputs: TransactionRecipient[] = [this.recipient];
251+
// Only a plain send's body comment is a user memo; the other transaction types carry
252+
// protocol payloads (e.g. withdraw opcodes) in `message`, which must not be exposed as memo.
253+
const outputs: TransactionRecipient[] = [
254+
{
255+
...this.recipient,
256+
...(this.type === TransactionType.Send && this.message ? { memo: this.message } : {}),
257+
},
258+
];
239259
const outputAmount = this.recipient.amount;
240260
const withdrawAmount = this.withdrawAmount;
241261
return {
@@ -295,6 +315,30 @@ export class Transaction extends BaseTransaction {
295315
};
296316
}
297317

318+
/**
319+
* Decode a comment cell per the TON comment standard: the current cell holds the
320+
* text, and each ref is a snake-format continuation cell (8-bit byte count, then
321+
* that many bytes). Standard chain readers concatenate the whole chain, so the
322+
* memo must be the full text — otherwise a prebuild could carry the declared
323+
* memoId in its first cell while chain readers credit a longer, different
324+
* comment, or smuggle an undeclared comment past verification as no comment.
325+
* A malformed continuation fails closed (throws) rather than exposing partial
326+
* text.
327+
*/
328+
private loadComment(slice: CommentSlice): string {
329+
const decoder = new TextDecoder();
330+
let text = decoder.decode(slice.loadBits(slice.getFreeBits()));
331+
while (slice.refs.length - slice.refCursor > 0) {
332+
slice = slice.loadRef();
333+
const byteCount = slice.loadUint(8).toNumber();
334+
if (byteCount * 8 > slice.getFreeBits()) {
335+
throw new Error('invalid snake-format comment');
336+
}
337+
text += decoder.decode(slice.loadBits(byteCount * 8));
338+
}
339+
return text;
340+
}
341+
298342
private parseTransactionBody(slice: any): any {
299343
const signature = Buffer.from(slice.loadBits(512)).toString('hex');
300344
// signing message
@@ -354,8 +398,7 @@ export class Transaction extends BaseTransaction {
354398
if (order.getFreeBits() > 32) {
355399
const opcode = order.loadUint(32).toNumber();
356400
if (opcode === 0) {
357-
const payloadBytes = order.loadBits(order.getFreeBits());
358-
payload = new TextDecoder().decode(payloadBytes);
401+
payload = this.loadComment(order);
359402
if (payload === 'Deposit') {
360403
this.transactionType = TransactionType.TonWhalesVestingDeposit;
361404
} else if (payload === 'Withdraw') {
@@ -382,18 +425,32 @@ export class Transaction extends BaseTransaction {
382425
const forwarderAddress = order.loadAddress();
383426
if (!forwarderAddress) throw new Error('invalid forwarderAddress');
384427

385-
order.loadBit(); // skip bit
428+
const hasCustomPayload = order.loadBit();
429+
if (hasCustomPayload) {
430+
// consume the custom_payload ref (TEP-74): BitGo builders never write one,
431+
// but a prebuild that sets it shifts the ref cursor so the forward payload
432+
// would otherwise be decoded from the wrong cell
433+
order.loadRef();
434+
}
386435

387436
const forwardTonAmount = order.loadCoins();
388437
if (!forwardTonAmount.gt(new BN(0))) throw new Error('invalid forwardTonAmount');
389438

390439
let message = '';
391440
if (order.loadBit()) {
392441
order = order.loadRef();
442+
// the ref may be an empty cell — TokenTransferBuilder always writes a forward
443+
// payload ref, empty when the transfer carries no comment
444+
if (order.getFreeBits() > 0) {
445+
const messageOpcode = order.loadUint(32).toNumber();
446+
if (messageOpcode !== 0) throw new Error('invalid message opcode');
447+
message = this.loadComment(order);
448+
}
449+
} else if (order.getFreeBits() > 32) {
450+
// Either bit 0: the forward payload is inline in the remaining bits
393451
const messageOpcode = order.loadUint(32).toNumber();
394452
if (messageOpcode !== 0) throw new Error('invalid message opcode');
395-
const messageBytes = order.loadBits(order.getFreeBits());
396-
message = new TextDecoder().decode(messageBytes);
453+
message = this.loadComment(order);
397454
}
398455

399456
payload = {

‎modules/sdk-coin-ton/src/ton.ts‎

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,16 @@ export class Ton extends BaseCoin {
119119
}
120120
}
121121

122+
/**
123+
* Verifies that the prebuilt transaction matches the user's intent.
124+
*
125+
* Compares (bounceable address, amount, memo) per output against txParams.recipients, plus the
126+
* total amount. TON custodial deposits are credited by the transfer's text comment (or the
127+
* jetton forward comment for token transfers), which BitGo models as a `?memoId=` suffix on
128+
* the recipient address. The parsed comment is bound to the intended memoId: a prebuild whose
129+
* comment differs from, is missing from, or is extra to the declared memo fails verification
130+
* on both the tton WASM and the mainnet TonWeb paths.
131+
*/
122132
async verifyTransaction(params: VerifyTransactionOptions): Promise<boolean> {
123133
const { txPrebuild: txPrebuild, txParams: txParams } = params;
124134
const rawTx = txPrebuild.txHex;
@@ -132,15 +142,21 @@ export class Ton extends BaseCoin {
132142
const explainedTx = await explainTonTransaction({ txBase64 });
133143
if (txParams.recipients !== undefined) {
134144
const filteredRecipients = await Promise.all(
135-
txParams.recipients.map(async (recipient) => ({
136-
address: await toBounceable(recipient.address),
137-
amount: BigInt(recipient.amount),
138-
}))
145+
txParams.recipients.map(async (recipient) => {
146+
const { address, memoId } = this.getAddressDetails(recipient.address);
147+
const memo = this.resolveExpectedMemo(memoId, recipient.memo);
148+
return {
149+
address: await toBounceable(address),
150+
amount: BigInt(recipient.amount),
151+
...(memo !== undefined ? { memo } : {}),
152+
};
153+
})
139154
);
140155
const filteredOutputs = await Promise.all(
141156
explainedTx.outputs.map(async (output) => ({
142157
address: await toBounceable(output.address),
143158
amount: BigInt(output.amount),
159+
...(output.memo !== undefined && output.memo !== '' ? { memo: output.memo } : {}),
144160
}))
145161
);
146162
if (!_.isEqual(filteredOutputs, filteredRecipients)) {
@@ -163,16 +179,19 @@ export class Ton extends BaseCoin {
163179
const explainedTx = transaction.explainTransaction();
164180
if (txParams.recipients !== undefined) {
165181
const filteredRecipients = txParams.recipients?.map((recipient) => {
166-
const destination = this.getAddressDetails(recipient.address);
182+
const { address, memoId } = this.getAddressDetails(recipient.address);
183+
const memo = this.resolveExpectedMemo(memoId, recipient.memo);
167184
return {
168-
address: new TonWeb.Address(destination.address).toString(true, true, true),
185+
address: new TonWeb.Address(address).toString(true, true, true),
169186
amount: BigInt(recipient.amount),
187+
...(memo !== undefined ? { memo } : {}),
170188
};
171189
});
172190
const filteredOutputs = explainedTx.outputs.map((output) => {
173191
return {
174192
address: new TonWeb.Address(output.address).toString(true, true, true),
175193
amount: BigInt(output.amount),
194+
...(output.memo !== undefined && output.memo !== '' ? { memo: output.memo } : {}),
176195
};
177196
});
178197
if (!_.isEqual(filteredOutputs, filteredRecipients)) {
@@ -189,6 +208,20 @@ export class Ton extends BaseCoin {
189208
return true;
190209
}
191210

211+
/**
212+
* Resolve the memo a recipient's intent declares. Declared sources are the `?memoId=` suffix
213+
* of the recipient address (see getAddressDetails) and `recipient.memo`; empty strings mean
214+
* "no memo", and conflicting distinct declarations are rejected as ambiguous intent.
215+
* Returns undefined when no memo is declared anywhere.
216+
*/
217+
private resolveExpectedMemo(memoId: string | undefined, recipientMemo: string | undefined): string | undefined {
218+
const declaredMemos = [memoId, recipientMemo].filter((memo): memo is string => memo !== undefined && memo !== '');
219+
if (declaredMemos.some((memo) => memo !== declaredMemos[0])) {
220+
throw new Error('Tx outputs does not match with expected txParams recipients');
221+
}
222+
return declaredMemos[0];
223+
}
224+
192225
async isWalletAddress(params: TssVerifyAddressOptions): Promise<boolean> {
193226
const { keychains, address: newAddress, index } = params;
194227

0 commit comments

Comments
 (0)