Skip to content

Commit 5aef7ae

Browse files
authored
Merge pull request #10163 from BitGo/mukesh/CSHLD-2160-ton-verify-memo
cshld-2160: bind ton transfer comment to memoId in verifyTransaction
2 parents 9ca732b + 3bacce9 commit 5aef7ae

9 files changed

Lines changed: 589 additions & 25 deletions

File tree

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

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import type { ParsedTransaction as WasmParsedTransaction } from '@bitgo/wasm-ton';
1010
import { TransactionExplanation } from './iface';
11+
import { SINGLE_NOMINATOR_WITHDRAW_ALL_COMMENT } from './constants';
1112

1213
/**
1314
* @bitgo/wasm-ton is loaded lazily (not via a static top-level import) so this
@@ -39,25 +40,39 @@ function extractOutputs(
3940
parsed: WasmParsedTransaction,
4041
toAddressBounceable: boolean
4142
): {
42-
outputs: { address: string; amount: string }[];
43+
outputs: { address: string; amount: string; memo?: string }[];
4344
outputAmount: string;
4445
withdrawAmount: string | undefined;
4546
} {
46-
const outputs: { address: string; amount: string }[] = [];
47+
const outputs: { address: string; amount: string; memo?: string }[] = [];
4748
let withdrawAmount: string | undefined;
4849

4950
for (const action of parsed.sendActions) {
5051
if (action.jettonTransfer) {
5152
outputs.push({
5253
address: action.jettonTransfer.destination,
5354
amount: String(action.jettonTransfer.amount),
55+
// the jetton forward comment — the memo exchanges use to credit token deposits
56+
...(action.memo !== undefined && action.memo !== '' ? { memo: action.memo } : {}),
5457
});
5558
} else {
5659
// destinationBounceable is always EQ... (bounceable)
5760
// destination respects the original bounce flag (UQ... when bounce=false)
61+
// The comment is exposed as memo only for plain sends, mirroring the TonWeb
62+
// parser: op-0 comments that are whales/single-nominator protocol text
63+
// classify the transaction as a staking type, not a user memo.
64+
const memo =
65+
action.memo !== undefined &&
66+
action.memo !== '' &&
67+
action.memo !== 'Deposit' &&
68+
action.memo !== 'Withdraw' &&
69+
action.memo !== SINGLE_NOMINATOR_WITHDRAW_ALL_COMMENT
70+
? action.memo
71+
: undefined;
5872
outputs.push({
5973
address: toAddressBounceable ? action.destinationBounceable : action.destination,
6074
amount: String(action.amount),
75+
...(memo !== undefined ? { memo } : {}),
6176
});
6277
}
6378

‎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: 61 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,18 @@ 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+
loadRef(): CommentSlice;
28+
}
29+
1830
export class Transaction extends BaseTransaction {
1931
public recipient: Recipient;
2032
public bounceable: boolean;
@@ -235,7 +247,14 @@ export class Transaction extends BaseTransaction {
235247
explainTransaction(): TransactionExplanation {
236248
const displayOrder = ['id', 'outputs', 'outputAmount', 'changeOutputs', 'changeAmount', 'fee', 'withdrawAmount'];
237249

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

317+
/**
318+
* Decode a comment cell chain per the TON snake format (TL-B SnakeData: raw bytes
319+
* per cell, refs chain to continuations with no length prefix), mirroring the
320+
* standard reader (@ton/core readBuffer) exactly: byte-aligned cells, at most one
321+
* ref per cell, whole-cell text concatenated across the chain. Binding the memo to
322+
* the full text means a prebuild cannot carry the declared memoId in its first
323+
* cell while chain readers credit a longer, different comment, nor smuggle an
324+
* undeclared comment past verification as no comment. Violations fail closed
325+
* (throw) exactly where the standard reader throws.
326+
*/
327+
private loadComment(slice: CommentSlice): string {
328+
const freeBits = slice.getFreeBits();
329+
const remainingRefs = slice.refs.length - slice.refCursor;
330+
if (freeBits % 8 !== 0 || (remainingRefs !== 0 && remainingRefs !== 1)) {
331+
throw new Error('invalid snake-format comment');
332+
}
333+
let text = new TextDecoder().decode(slice.loadBits(freeBits));
334+
if (remainingRefs === 1) {
335+
text += this.loadComment(slice.loadRef());
336+
}
337+
return text;
338+
}
339+
298340
private parseTransactionBody(slice: any): any {
299341
const signature = Buffer.from(slice.loadBits(512)).toString('hex');
300342
// signing message
@@ -354,8 +396,7 @@ export class Transaction extends BaseTransaction {
354396
if (order.getFreeBits() > 32) {
355397
const opcode = order.loadUint(32).toNumber();
356398
if (opcode === 0) {
357-
const payloadBytes = order.loadBits(order.getFreeBits());
358-
payload = new TextDecoder().decode(payloadBytes);
399+
payload = this.loadComment(order);
359400
if (payload === 'Deposit') {
360401
this.transactionType = TransactionType.TonWhalesVestingDeposit;
361402
} else if (payload === 'Withdraw') {
@@ -382,18 +423,32 @@ export class Transaction extends BaseTransaction {
382423
const forwarderAddress = order.loadAddress();
383424
if (!forwarderAddress) throw new Error('invalid forwarderAddress');
384425

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

387434
const forwardTonAmount = order.loadCoins();
388435
if (!forwardTonAmount.gt(new BN(0))) throw new Error('invalid forwardTonAmount');
389436

390437
let message = '';
391438
if (order.loadBit()) {
392439
order = order.loadRef();
440+
// the ref may be an empty cell — TokenTransferBuilder always writes a forward
441+
// payload ref, empty when the transfer carries no comment
442+
if (order.getFreeBits() > 0) {
443+
const messageOpcode = order.loadUint(32).toNumber();
444+
if (messageOpcode !== 0) throw new Error('invalid message opcode');
445+
message = this.loadComment(order);
446+
}
447+
} else if (order.getFreeBits() > 32) {
448+
// Either bit 0: the forward payload is inline in the remaining bits
393449
const messageOpcode = order.loadUint(32).toNumber();
394450
if (messageOpcode !== 0) throw new Error('invalid message opcode');
395-
const messageBytes = order.loadBits(order.getFreeBits());
396-
message = new TextDecoder().decode(messageBytes);
451+
message = this.loadComment(order);
397452
}
398453

399454
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)