From 90244f5175fea15287c030a9c0cb47566988eb1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Friedemann=20F=C3=BCrst?= <59653747+friedemannf@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:41:33 +0100 Subject: [PATCH 1/3] feat(canton): add getFee implementation --- ccip-api-ref/docs-sdk/guides/multi-chain.mdx | 4 +- .../src/canton/clients/ledger-api/client.ts | 25 ++ .../ledger-api/prepared-transaction.test.ts | 149 +++++++++ .../ledger-api/prepared-transaction.ts | 286 ++++++++++++++++++ ccip-sdk/src/canton/get-fee.test.ts | 242 +++++++++++++++ ccip-sdk/src/canton/index.ts | 137 +++++++-- 6 files changed, 816 insertions(+), 27 deletions(-) create mode 100644 ccip-sdk/src/canton/clients/ledger-api/prepared-transaction.test.ts create mode 100644 ccip-sdk/src/canton/clients/ledger-api/prepared-transaction.ts create mode 100644 ccip-sdk/src/canton/get-fee.test.ts diff --git a/ccip-api-ref/docs-sdk/guides/multi-chain.mdx b/ccip-api-ref/docs-sdk/guides/multi-chain.mdx index 6d34f9ac3..8561e0825 100644 --- a/ccip-api-ref/docs-sdk/guides/multi-chain.mdx +++ b/ccip-api-ref/docs-sdk/guides/multi-chain.mdx @@ -318,7 +318,7 @@ const request = await source.sendMessage({ }) ``` -On Canton source, `router` is the **CCIPSender instance id** (e.g. `ccipsender`), not a contract address. `getFee()` returns `0n` — fees are computed on-ledger during send. +On Canton source, `router` is the **CCIPSender instance id** (e.g. `ccipsender`), not a contract address. `getFee()` quotes the fee by exercising the on-ledger `CCIPSender.GetFee` choice via a prepare-only interactive submission — nothing is signed or committed. @@ -428,7 +428,7 @@ Canton source sends use `CantonExtraArgsV1` (not on-wire encoded bytes): ### Fee Model -`getFee()` returns `0n` on Canton — fees are computed on-ledger during the send transaction. Fee tokens are instrument IDs (native Amulet or CCIP LINK). +`getFee()` quotes the real fee on Canton: it exercises the `CCIPSender.GetFee` choice through a **prepare-only** interactive submission — the participant interprets the command and returns the computed fee without anything being signed, sequenced or committed (no wallet prompt, no traffic cost, no ledger effect). The fee covers CCV, token-pool, network and executor costs, denominated in the fee token's smallest units (10 decimals). Fee tokens are instrument IDs (native Amulet or CCIP LINK). ### Unsigned Transactions diff --git a/ccip-sdk/src/canton/clients/ledger-api/client.ts b/ccip-sdk/src/canton/clients/ledger-api/client.ts index 1d1c3195c..3a49686d0 100644 --- a/ccip-sdk/src/canton/clients/ledger-api/client.ts +++ b/ccip-sdk/src/canton/clients/ledger-api/client.ts @@ -71,5 +71,30 @@ export function createLedgerApiClientFromProvider(provider: CantonRpcProvider) { return response as JsGetActiveContractsResponse[] }, + + /** + * Prepare an interactive submission without executing or signing it. + * + * The participant only interprets the commands — read authorization is + * sufficient — and returns the interpreted `preparedTransaction` (base64 + * protobuf) plus its hash for external signing. Nothing is sequenced: no + * signature is requested, no traffic is consumed, and the ledger is + * unchanged. The interpreted transaction's Exercise nodes already contain + * the computed choice results. + */ + async prepareSubmission( + request: JsPrepareSubmissionRequest, + ): Promise { + const response = await provider.request({ + method: 'ledgerApi', + params: { + requestMethod: 'post', + resource: '/v2/interactive-submission/prepare', + body: request, + }, + }) + + return response as JsPrepareSubmissionResponse + }, } } diff --git a/ccip-sdk/src/canton/clients/ledger-api/prepared-transaction.test.ts b/ccip-sdk/src/canton/clients/ledger-api/prepared-transaction.test.ts new file mode 100644 index 000000000..4223f3d58 --- /dev/null +++ b/ccip-sdk/src/canton/clients/ledger-api/prepared-transaction.test.ts @@ -0,0 +1,149 @@ +/** + * Unit tests for {@link findExerciseResult}: navigation of interactive + * submission `PreparedTransaction` protobuf blobs and Daml value decoding. + */ +import assert from 'node:assert/strict' +import { describe, it } from 'node:test' + +import { encodeBase64 } from 'ethers' + +import { findExerciseResult } from './prepared-transaction.ts' + +function encodeVarint(value: number): number[] { + const bytes: number[] = [] + let v = value + do { + let byte = v & 0x7f + v = Math.floor(v / 128) + if (v > 0) byte |= 0x80 + bytes.push(byte) + } while (v > 0) + return bytes +} + +/** Length-delimited protobuf field: tag (field, wire type 2) + length + payload. */ +function field(fieldNumber: number, payload: number[]): number[] { + if (fieldNumber > 15) { + // multi-byte tag: low 7 bits first, then continuation + const tagValue = (fieldNumber << 3) | 2 + return [...encodeVarint(tagValue), ...encodeVarint(payload.length), ...payload] + } + return [((fieldNumber << 3) | 2) & 0xff, ...encodeVarint(payload.length), ...payload] +} + +function stringField(fieldNumber: number, text: string): number[] { + return field(fieldNumber, [...new TextEncoder().encode(text)]) +} + +/** Daml Value holding a Numeric (field 6). */ +function numericValue(text: string): number[] { + return stringField(6, text) +} + +/** Daml RecordField: label (1) + Value (2). */ +function recordField(label: string, value: number[]): number[] { + return [...stringField(1, label), ...field(2, value)] +} + +/** Daml Record body: repeated RecordField (2). */ +function record(...fields: number[][]): number[] { + return fields.flatMap((f) => field(2, f)) +} + +/** Daml Value holding a Record (field 14). */ +function recordValue(body: number[]): number[] { + return field(14, body) +} + +/** transaction.v1.Exercise: contract_id (2), choice_id (9), chosen_value (10), exercise_result (13). */ +function exerciseNode(choice: string, resultValue: number[]): number[] { + return [ + ...stringField(2, '#sender-cid'), + ...stringField(9, choice), + ...field(10, recordValue(record())), + ...field(13, resultValue), + ] +} + +/** DamlTransaction.Node: node_id (1), transaction.v1.Node (1000) wrapping Exercise (3). */ +function transactionNode(choice: string, resultValue: number[]): number[] { + return [...stringField(1, 'root'), ...field(1000, field(3, exerciseNode(choice, resultValue)))] +} + +/** PreparedTransaction: DamlTransaction (1) wrapping repeated Node (3). */ +function preparedTransaction(...nodes: number[][]): Uint8Array { + return new Uint8Array( + field( + 1, + nodes.flatMap((n) => field(3, n)), + ), + ) +} + +const GET_FEE_RESULT = recordValue( + record( + recordField('feeTokenAmount', numericValue('1.5000000000')), + recordField('poolFeeTokenAmount', numericValue('0.2500000000')), + ), +) + +describe('findExerciseResult', () => { + it('decodes the GetFee exercise result among several exercise nodes', () => { + const blob = encodeBase64( + preparedTransaction( + transactionNode('Send', numericValue('999')), + transactionNode('GetFee', GET_FEE_RESULT), + ), + ) + assert.deepEqual(findExerciseResult(blob, 'GetFee'), { + fields: [ + { label: 'feeTokenAmount', value: '1.5000000000' }, + { label: 'poolFeeTokenAmount', value: '0.2500000000' }, + ], + }) + }) + + it('returns undefined when the choice is not exercised', () => { + const blob = encodeBase64(preparedTransaction(transactionNode('Send', numericValue('999')))) + assert.equal(findExerciseResult(blob, 'GetFee'), undefined) + }) + + it('filters by contract id when given', () => { + const blob = encodeBase64(preparedTransaction(transactionNode('Send', numericValue('999')))) + assert.equal(findExerciseResult(blob, 'Send', '#other-cid'), undefined) + assert.deepEqual(findExerciseResult(blob, 'Send', '#sender-cid'), '999') + }) + + it('decodes unlabeled record fields (labels are optional on the wire)', () => { + // RecordField without a label (field 1 omitted): Value { 6: numeric } + const unlabeledResult = field(14, [ + ...field(2, field(2, numericValue('1.5000000000'))), + ...field(2, field(2, numericValue('0.2500000000'))), + ]) + const blob = encodeBase64(preparedTransaction(transactionNode('GetFee', unlabeledResult))) + const result = findExerciseResult(blob, 'GetFee') as { + fields: Array<{ label?: string; value?: unknown }> + } + assert.equal(result.fields.length, 2) + assert.equal(result.fields[0]!.label, undefined) + assert.equal(result.fields[0]!.value, '1.5000000000') + assert.equal(result.fields[1]!.value, '0.2500000000') + }) + + it('returns undefined for an empty transaction', () => { + const blob = encodeBase64(preparedTransaction()) + assert.equal(findExerciseResult(blob, 'GetFee'), undefined) + }) + + it('returns undefined when the exercise node has no result', () => { + const noResult = [...stringField(2, '#sender-cid'), ...stringField(9, 'GetFee')] + const node = [...stringField(1, 'root'), ...field(1000, field(3, noResult))] + const tx = new Uint8Array(field(1, field(3, node))) + assert.equal(findExerciseResult(encodeBase64(tx), 'GetFee'), undefined) + }) + + it('rejects malformed blobs', () => { + const blob = encodeBase64(new Uint8Array([0x0f])) // field 1, wire type 7 — unsupported + assert.throws(() => findExerciseResult(blob, 'GetFee'), /unsupported protobuf wire type/) + }) +}) diff --git a/ccip-sdk/src/canton/clients/ledger-api/prepared-transaction.ts b/ccip-sdk/src/canton/clients/ledger-api/prepared-transaction.ts new file mode 100644 index 000000000..77699403c --- /dev/null +++ b/ccip-sdk/src/canton/clients/ledger-api/prepared-transaction.ts @@ -0,0 +1,286 @@ +/** + * Reader for Canton interactive-submission `PreparedTransaction` blobs. + * + * `POST /v2/interactive-submission/prepare` (JSON API) / `PrepareSubmission` + * (gRPC Ledger API) interprets commands *without executing or signing them* — + * the response's `preparedTransaction` is the base64-encoded, interpreted + * transaction the submitting party would sign, and its Exercise nodes already + * carry the computed choice results. That makes a prepare-only submission a way + * to read a choice's return value (e.g. `CCIPSender.GetFee`) without prompting + * for a signature or committing anything to the ledger. + * + * Only the shapes needed to navigate to choice results are decoded, following + * Canton's `com.daml.ledger.api.v2.interactive` (interactive_submission_service.proto) + * and `com.daml.ledger.api.v2.interactive.transaction.v1` + * (interactive_submission_data.proto) messages: + * + * ``` + * PreparedTransaction + * ├─ 1: DamlTransaction transaction + * │ └─ 3: repeated Node nodes + * │ └─ 1000: transaction.v1.Node + * │ └─ 3: Exercise + * │ ├─ 9: string choice_id + * │ └─ 13: Value exercise_result + * └─ 2: Metadata + * ``` + * + * Decoded Daml values use the JSON Ledger API verbose shapes understood by the + * shared `daml-parse.ts` helpers (records as `{ fields: [{ label, value }] }`, + * numerics as decimal strings). + * + * @packageDocumentation + */ + +import { decodeBase64 } from 'ethers' + +import { CCIPError, CCIPErrorCode } from '../../../errors/index.ts' + +/** A single protobuf wire-format field. */ +interface ProtoField { + number: number + wireType: number + /** Wire type 0. */ + varint?: bigint + /** Wire type 2 (length-delimited message, string or bytes). */ + bytes?: Uint8Array +} + +const WIRE_VARINT = 0 +const WIRE_FIXED64 = 1 +const WIRE_LEN = 2 +const WIRE_FIXED32 = 5 + +/** Read a base-128 varint at `pos`; returns the value and the next position. */ +function readVarint(data: Uint8Array, pos: number): { value: bigint; pos: number } { + let result = 0n + let shift = 0n + let current = pos + for (;;) { + if (current >= data.length) { + throw new CCIPError(CCIPErrorCode.CANTON_API_ERROR, 'truncated protobuf varint') + } + const byte = data[current]! + result |= BigInt(byte & 0x7f) << shift + current++ + if ((byte & 0x80) === 0) return { value: result, pos: current } + shift += 7n + if (shift >= 64n) { + throw new CCIPError(CCIPErrorCode.CANTON_API_ERROR, 'protobuf varint too long') + } + } +} + +/** Parse a protobuf message body into its top-level fields. */ +function parseProtoFields(data: Uint8Array): ProtoField[] { + const fields: ProtoField[] = [] + let pos = 0 + while (pos < data.length) { + const tag = readVarint(data, pos) + pos = tag.pos + const number = Number(tag.value >> 3n) + const wireType = Number(tag.value & 7n) + if (number === 0) { + throw new CCIPError(CCIPErrorCode.CANTON_API_ERROR, 'invalid protobuf field number 0') + } + const field: ProtoField = { number, wireType } + switch (wireType) { + case WIRE_VARINT: { + const value = readVarint(data, pos) + field.varint = value.value + pos = value.pos + break + } + case WIRE_LEN: { + const length = readVarint(data, pos) + pos = length.pos + if (pos + Number(length.value) > data.length) { + throw new CCIPError(CCIPErrorCode.CANTON_API_ERROR, 'truncated protobuf field') + } + field.bytes = data.slice(pos, pos + Number(length.value)) + pos += Number(length.value) + break + } + case WIRE_FIXED64: + if (pos + 8 > data.length) { + throw new CCIPError(CCIPErrorCode.CANTON_API_ERROR, 'truncated protobuf fixed64') + } + field.varint = data + .slice(pos, pos + 8) + .reduce((acc, b, i) => acc | (BigInt(b) << BigInt(8 * i)), 0n) + pos += 8 + break + case WIRE_FIXED32: + if (pos + 4 > data.length) { + throw new CCIPError(CCIPErrorCode.CANTON_API_ERROR, 'truncated protobuf fixed32') + } + field.varint = data + .slice(pos, pos + 4) + .reduce((acc, b, i) => acc | (BigInt(b) << BigInt(8 * i)), 0n) + pos += 4 + break + default: + throw new CCIPError( + CCIPErrorCode.CANTON_API_ERROR, + `unsupported protobuf wire type ${wireType}`, + ) + } + fields.push(field) + } + return fields +} + +function stringField(field: ProtoField | undefined): string | undefined { + if (field?.bytes == undefined) return undefined + return new TextDecoder().decode(field.bytes) +} + +function subMessage(field: ProtoField | undefined): ProtoField[] | undefined { + return field?.bytes != undefined ? parseProtoFields(field.bytes) : undefined +} + +/** + * Decode a Daml `Value` (the `com.daml.ledger.api.v2` proto) into the JSON + * Ledger API verbose shape: records as `{ fields: [{ label, value }] }`, + * variants as `{ constructor, value }`, numerics/parties/texts as strings. + */ +function decodeDamlProtoValue(valueFields: ProtoField[]): unknown { + for (const field of valueFields) { + switch (field.number) { + case 1: // unit + return null + case 2: // bool + return field.varint !== 0n + case 3: { + // sint64 — zigzag encoded + const zigzag = field.varint! + const value = (zigzag >> 1n) ^ -(zigzag & 1n) + return Number.isSafeInteger(Number(value)) ? Number(value) : value + } + case 4: // date — days since epoch + return Number(field.varint) + case 5: // timestamp — sfixed64 microseconds + return field.varint! + case 6: // numeric + case 7: // party + case 8: // text + case 9: // contractId + return stringField(field) + case 10: { + // Optional { Value value = 1 } + const inner = subMessage(field) + return inner && inner.length > 0 ? decodeDamlProtoValue(inner) : null + } + case 11: { + // List { repeated Value elements = 1 } + const list: unknown[] = [] + for (const element of parseProtoFields(field.bytes!)) { + if (element.number === 1 && element.bytes) { + list.push(decodeDamlProtoValue(parseProtoFields(element.bytes))) + } + } + return list + } + case 12: { + // TextMap { repeated Entry entries = 1 { key = 1, value = 2 } } + const map: Record = {} + for (const entry of parseProtoFields(field.bytes!)) { + if (entry.number !== 1 || !entry.bytes) continue + const entryFields = parseProtoFields(entry.bytes) + const key = stringField(entryFields.find((f) => f.number === 1)) + const value = subMessage(entryFields.find((f) => f.number === 2)) + if (key != undefined && value) map[key] = decodeDamlProtoValue(value) + } + return map + } + case 13: { + // GenMap { repeated Entry entries = 1 { key = 1, value = 2 } } + const entries: Array<{ key: unknown; value: unknown }> = [] + for (const entry of parseProtoFields(field.bytes!)) { + if (entry.number !== 1 || !entry.bytes) continue + const entryFields = parseProtoFields(entry.bytes) + const keyField = subMessage(entryFields.find((f) => f.number === 1)) + const valueField = subMessage(entryFields.find((f) => f.number === 2)) + entries.push({ + key: keyField ? decodeDamlProtoValue(keyField) : undefined, + value: valueField ? decodeDamlProtoValue(valueField) : undefined, + }) + } + return entries + } + case 14: { + // Record { Identifier record_id = 1, repeated RecordField fields = 2 } + const fields: Array<{ label?: string; value: unknown }> = [] + for (const recordField of parseProtoFields(field.bytes!)) { + if (recordField.number !== 2 || !recordField.bytes) continue + const fieldFields = parseProtoFields(recordField.bytes) + fields.push({ + label: stringField(fieldFields.find((f) => f.number === 1)), + value: decodeDamlProtoValue(subMessage(fieldFields.find((f) => f.number === 2)) ?? []), + }) + } + return { fields } + } + case 15: { + // Variant { Identifier variant_id = 1, string constructor = 2, Value value = 3 } + const variantFields = parseProtoFields(field.bytes!) + const constructor = stringField(variantFields.find((f) => f.number === 2)) + const value = subMessage(variantFields.find((f) => f.number === 3)) + return { + constructor, + value: value ? decodeDamlProtoValue(value) : null, + } + } + case 16: { + // Enum { Identifier enum_id = 1, string constructor = 2 } + const enumFields = parseProtoFields(field.bytes!) + return { constructor: stringField(enumFields.find((f) => f.number === 2)) } + } + } + } + return undefined +} + +/** + * Find the result of exercising `choiceId` inside a base64-encoded interactive + * submission `PreparedTransaction`, decoded via {@link decodeDamlProtoValue}. + * + * @param preparedTransactionB64 - `preparedTransaction` from a + * `PrepareSubmissionResponse`. + * @param choiceId - Choice name to look for (e.g. `GetFee`). + * @param contractId - When given, only Exercise nodes on this contract match. + * Nested exercises may reuse the same choice name on other contracts, and + * they appear earlier in the node list than the root exercise. + * @returns The decoded exercise result, or `undefined` when the transaction + * contains no matching Exercise node (or no result). + */ +export function findExerciseResult( + preparedTransactionB64: string, + choiceId: string, + contractId?: string, +): unknown { + const preparedTransaction = parseProtoFields(decodeBase64(preparedTransactionB64)) + + const transaction = subMessage( + preparedTransaction.find((f) => f.number === 1), // PreparedTransaction.transaction + ) + if (!transaction) return undefined + + for (const node of transaction.filter((f) => f.number === 3)) { + // DamlTransaction.Node { node_id = 1, transaction.v1.Node v1 = 1000 } + const nodeV1 = subMessage(subMessage(node)?.find((f) => f.number === 1000)) + // transaction.v1.Node { oneof node_type { Exercise exercise = 3 } } + const exercise = nodeV1 ? subMessage(nodeV1.find((f) => f.number === 3)) : undefined + if (!exercise) continue + if (stringField(exercise.find((f) => f.number === 9)) !== choiceId) continue + if ( + contractId != undefined && + stringField(exercise.find((f) => f.number === 2)) !== contractId + ) { + continue + } + const result = subMessage(exercise.find((f) => f.number === 13)) + return result ? decodeDamlProtoValue(result) : undefined + } + return undefined +} diff --git a/ccip-sdk/src/canton/get-fee.test.ts b/ccip-sdk/src/canton/get-fee.test.ts new file mode 100644 index 000000000..630006bff --- /dev/null +++ b/ccip-sdk/src/canton/get-fee.test.ts @@ -0,0 +1,242 @@ +/** + * Unit tests for {@link CantonChain.getFee}: GetFee choice-argument derivation + * (Send args minus `feeTokenInput`), prepare-only submission, and result + * parsing into fee-token smallest units. + */ +import assert from 'node:assert/strict' +import { describe, it } from 'node:test' + +import { encodeBase64 } from 'ethers' + +import type { Send } from './bindings/ccip-sender-v2-2.1.0/CCIP/CCIPSender/module.js' +import { CantonChain } from './index.ts' + +const OWNER = 'sender::1220ab' +const CCIP_SENDER_CID = '#sender-cid' + +function encodeVarint(value: number): number[] { + const bytes: number[] = [] + let v = value + do { + let byte = v & 0x7f + v = Math.floor(v / 128) + if (v > 0) byte |= 0x80 + bytes.push(byte) + } while (v > 0) + return bytes +} + +function field(fieldNumber: number, payload: number[]): number[] { + return [...encodeVarint((fieldNumber << 3) | 2), ...encodeVarint(payload.length), ...payload] +} + +function stringField(fieldNumber: number, text: string): number[] { + return field(fieldNumber, [...new TextEncoder().encode(text)]) +} + +/** A PreparedTransaction with a GetFee exercise returning the given numerics. */ +function preparedTransaction(numerics: Array<[string, string]>): Uint8Array { + return preparedTransactionFromNodes([ + transactionNode(CCIP_SENDER_CID, 'GetFee', getResultValue(numerics)), + ]) +} + +/** A PreparedTransaction whose GetFee result record omits field labels (positional). */ +function preparedTransactionUnlabeled(numerics: string[]): Uint8Array { + const resultValue = field( + 14, + numerics.flatMap((numeric) => + // Record entry (2) → RecordField { Value (2) { Numeric (6) } } — no label (1) + field(2, field(2, field(6, [...new TextEncoder().encode(numeric)]))), + ), + ) + return preparedTransactionFromNodes([transactionNode(CCIP_SENDER_CID, 'GetFee', resultValue)]) +} + +/** Daml Value { 14: Record { 2: RecordField { 1: label, 2: Value { 6: numeric } } } }. */ +function getResultValue(numerics: Array<[string, string]>): number[] { + return field( + 14, + numerics.flatMap(([label, numeric]) => + field(2, [ + ...stringField(1, label), + ...field(2, field(6, [...new TextEncoder().encode(numeric)])), + ]), + ), + ) +} + +/** DamlTransaction.Node { node_id = 1, v1 Node { 3: Exercise } } for one exercise. */ +function transactionNode(contractId: string, choice: string, resultValue: number[]): number[] { + const exercise = [ + ...stringField(2, contractId), + ...stringField(9, choice), + ...field(13, resultValue), + ] + return [...stringField(1, 'root'), ...field(1000, field(3, exercise))] +} + +function preparedTransactionFromNodes(nodes: number[][]): Uint8Array { + return new Uint8Array( + field( + 1, + nodes.flatMap((n) => field(3, n)), + ), + ) +} + +const SEND_ARGS = { + destinationChainSelector: '16015286601757825753', + message: { + receiver: 'abc', + payload: '', + tokenTransfer: null, + feeToken: { admin: 'a', id: 'b' }, + extraArgs: {}, + }, + routerCid: '#router-cid', + ccvSendInputs: [], + tokenTransferInput: null, + executorInput: null, + context: { values: {} }, + feeTokenInput: { senderInputCids: [] }, +} as unknown as Send + +function chainWith(preparedTransactionB64?: string): { + chain: CantonChain + prepareRequests: Array> +} { + const prepareRequests: Array> = [] + const chain = Object.assign(Object.create(CantonChain.prototype), { + network: { family: 'canton' }, + logger: { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }, + activeParty: OWNER, + ledgerApiClient: { + prepareSubmission: async (request: Record) => { + prepareRequests.push(request) + return { + preparedTransaction: preparedTransactionB64 ?? '', + preparedTransactionHash: 'deadbeef', + } + }, + }, + }) as CantonChain + ;( + chain as unknown as { buildSendChoiceArgs: CantonChain['buildSendChoiceArgs'] } + ).buildSendChoiceArgs = async () => ({ + sendArgs: SEND_ARGS, + disclosedContracts: [{ contractId: CCIP_SENDER_CID } as never], + ccipSenderCid: CCIP_SENDER_CID, + }) + return { chain, prepareRequests } +} + +const FEE_OPTS = { + router: 'ccipsender', + destChainSelector: 16015286601757825753n, + message: { receiver: '0xabc', data: '0x' }, +} as Parameters[0] + +describe('CantonChain.getFee', () => { + it('parses the fee from the prepared GetFee exercise result', async () => { + const { chain } = chainWith( + encodeBase64( + preparedTransaction([ + ['feeTokenAmount', '1.5000000000'], + ['poolFeeTokenAmount', '0.2500000000'], + ]), + ), + ) + const fee = await chain.getFee(FEE_OPTS) + assert.equal(fee, 15000000000n) + }) + + it('falls back to positional fields when record labels are omitted', async () => { + const { chain } = chainWith( + encodeBase64(preparedTransactionUnlabeled(['1.5000000000', '0.2500000000'])), + ) + const fee = await chain.getFee(FEE_OPTS) + assert.equal(fee, 15000000000n) + }) + + it('exercises GetFee with the Send arguments minus feeTokenInput', async () => { + const { chain, prepareRequests } = chainWith( + encodeBase64(preparedTransaction([['feeTokenAmount', '0.0000000001']])), + ) + await chain.getFee(FEE_OPTS) + assert.equal(prepareRequests.length, 1) + + const request = prepareRequests[0]! + assert.deepEqual(request.actAs, [OWNER]) + assert.deepEqual(request.readAs, []) + const command = ( + request.commands as Array<{ + ExerciseCommand?: { + choice: string + contractId: string + templateId: string + choiceArgument: unknown + } + }> + )[0]!.ExerciseCommand! + assert.equal(command.choice, 'GetFee') + assert.equal(command.contractId, CCIP_SENDER_CID) + assert.match(command.templateId, /CCIP\.CCIPSender:CCIPSender$/) + + const choiceArgument = command.choiceArgument as Record + assert.ok(!('feeTokenInput' in choiceArgument)) + const sendArgsCopy = SEND_ARGS as unknown as Record + for (const key of Object.keys(sendArgsCopy)) { + if (key === 'feeTokenInput') continue + assert.deepEqual(choiceArgument[key], sendArgsCopy[key], `mismatched field ${key}`) + } + }) + + it('rejects when the prepared transaction has no GetFee result', async () => { + const { chain } = chainWith() + await assert.rejects(() => chain.getFee(FEE_OPTS), /did not include a GetFee exercise result/) + }) + + it('ignores nested same-name exercises on other contracts', async () => { + // A nested CrossChainVerifier-style GetFee on another contract, listed + // before the root CCIPSender.GetFee exercise (nested nodes come first). + const verifierQuote = getResultValue([ + ['ccvInstanceId', 'committeeverifier-pttst'], + ['feeUSDCents', '0.'], + ]) + const { chain } = chainWith( + encodeBase64( + preparedTransactionFromNodes([ + transactionNode('#verifier-cid', 'GetFee', verifierQuote), + transactionNode( + CCIP_SENDER_CID, + 'GetFee', + getResultValue([['feeTokenAmount', '3.3999999999']]), + ), + ]), + ), + ) + const fee = await chain.getFee(FEE_OPTS) + assert.equal(fee, 33999999999n) + }) + + it('rejects non-numeric feeTokenAmount values', async () => { + const { chain } = chainWith( + encodeBase64(preparedTransaction([['feeTokenAmount', 'committeeverifier-pttst']])), + ) + await assert.rejects(() => chain.getFee(FEE_OPTS), /unexpected GetFee exercise result/) + }) + + it('rejects when the GetFee result has no numeric field', async () => { + // exercise_result: Value { 14: Record { 2: RecordField { 2: Value { 14: Record {} } } } } + const nonNumericResult = field(14, field(2, field(14, []))) + const { chain } = chainWith( + encodeBase64( + preparedTransactionFromNodes([ + transactionNode(CCIP_SENDER_CID, 'GetFee', nonNumericResult), + ]), + ), + ) + await assert.rejects(() => chain.getFee(FEE_OPTS), /unexpected GetFee exercise result/) + }) +}) diff --git a/ccip-sdk/src/canton/index.ts b/ccip-sdk/src/canton/index.ts index 4d41ba810..3726ac72e 100644 --- a/ccip-sdk/src/canton/index.ts +++ b/ccip-sdk/src/canton/index.ts @@ -78,6 +78,7 @@ import { type UpdateFormat, createLedgerApiClientFromProvider, } from './clients/ledger-api/client.ts' +import { findExerciseResult } from './clients/ledger-api/prepared-transaction.ts' import { decodeDamlRecord, extractFieldValue } from './daml-parse.ts' import { CANTON_FEE_TOKEN_CLI_SYMBOLS, @@ -868,34 +869,110 @@ export class CantonChain extends Chain { } /** - * Returns the CCIP fee for sending a message. + * Returns the CCIP fee for sending a message, in the fee token's smallest + * units (10 decimals). * - * Canton has no scalar upfront CCIP fee — the cost is computed inside the - * on-chain command at send time. Returns `0n` so `--only-get-fee` and the - * balance check both pass cleanly. + * Exercises the `CCIPSender.GetFee` choice — which aggregates the CCV, + * token-pool, network and executor fee quotes for `message` — through a + * **prepare-only** interactive submission: the participant interprets the + * command and returns the computed choice result without anything being + * signed, sequenced or committed (no wallet signature prompt, no traffic + * cost, no ledger effect). */ - getFee(_opts: Parameters[0]): Promise { - return Promise.resolve(0n) + async getFee(opts: Parameters[0]): Promise { + const sender = this.activeParty + const { sendArgs, disclosedContracts, ccipSenderCid } = await this.buildSendChoiceArgs({ + ...opts, + sender, + }) + + // GetFee takes the same arguments as Send minus feeTokenInput + const { feeTokenInput: _feeTokenInput, ...getFeeArgs } = sendArgs + + const exerciseCommand = { + ExerciseCommand: { + templateId: CCIPSenderIdentifier.toString(), + contractId: ccipSenderCid, + choice: 'GetFee', + choiceArgument: getFeeArgs, + }, + } + + this.logger.debug('GetFeeArgs:', getFeeArgs) + this.logger.debug('DisclosedContracts:', disclosedContracts) + + const prepareResponse = await this.ledgerApiClient.prepareSubmission({ + commandId: `ccip-getfee-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, + commands: [exerciseCommand], + actAs: [sender], + readAs: [], + disclosedContracts, + // must be provided, even if empty + synchronizerId: '', + hashingSchemeVersion: 'HASHING_SCHEME_VERSION_V3', + // must be provided, even if empty + packageIdSelectionPreference: [], + }) + + const result = findExerciseResult(prepareResponse.preparedTransaction, 'GetFee', ccipSenderCid) + if (result == undefined) { + throw new CCIPError( + CCIPErrorCode.CANTON_API_ERROR, + 'CantonChain.getFee: prepared transaction did not include a GetFee exercise result', + ) + } + this.logger.debug('CantonChain.getFee: exercise result:', result) + + // Record labels are optional in the prepared-transaction wire format; when + // omitted, GetFeeResult fields are positional — feeTokenAmount first, + // poolFeeTokenAmount second (same as the chainlink-canton bindings). + const resultFields = (result as { fields?: Array<{ label?: string; value: unknown }> }).fields + const quote = decodeDamlRecord(result) + const firstField = resultFields?.[0]?.value + const rawFee = + typeof quote.feeTokenAmount === 'string' + ? quote.feeTokenAmount + : typeof firstField === 'string' + ? firstField + : undefined + const normalizedFee = rawFee?.replace(/\.$/, '') + if (rawFee === undefined || !/^\d+(\.\d+)?$/.test(normalizedFee!)) { + throw new CCIPError( + CCIPErrorCode.CANTON_API_ERROR, + `CantonChain.getFee: unexpected GetFee exercise result: ${JSON.stringify(result)}`, + ) + } + const fee = parseCantonDecimalAmountUnits(normalizedFee!) + this.logger.debug(`CantonChain.getFee: feeTokenAmount=${rawFee} (${fee} smallest units)`) + return fee } - /** {@inheritDoc Chain.generateUnsignedSendMessage} */ - override async generateUnsignedSendMessage( + /** + * Build the `CCIPSender.Send` choice arguments plus the EDS-disclosed + * contracts needed to authorize them — everything both a real `Send` + * submission and a `GetFee` quote require. + * + * @param opts - Send options; `sender` must match the chain's active party. + * @returns The choice arguments, the disclosed contracts backing them, and + * the resolved CCIPSender contract ID. + */ + private async buildSendChoiceArgs( opts: Parameters[0], - ): Promise { + ): Promise<{ sendArgs: Send; disclosedContracts: DisclosedContract[]; ccipSenderCid: string }> { const { sender, destChainSelector, message } = opts // --- validate inputs --- if (!sender) { throw new CCIPError( CCIPErrorCode.WALLET_INVALID, - 'CantonChain.generateUnsignedSendMessage: sender (party ID) is required', + 'CantonChain.buildSendChoiceArgs: sender (party ID) is required', ) } const senderPartyId = parsePartyId(sender) if (senderPartyId !== this.activeParty) { throw new CCIPError( CCIPErrorCode.WALLET_INVALID, - `CantonChain.generateUnsignedSendMessage: sender (${senderPartyId}) cannot differ from active party (${this.activeParty})`, + `CantonChain.buildSendChoiceArgs: sender (${senderPartyId}) cannot differ from active party (${this.activeParty})`, ) } @@ -916,7 +993,7 @@ export class CantonChain extends Chain { if (tokenAmounts.length > 1) { throw new CCIPError( CCIPErrorCode.METHOD_UNSUPPORTED, - `CantonChain.generateUnsignedSendMessage: only one token transfer is supported, got ${tokenAmounts.length}`, + `CantonChain.buildSendChoiceArgs: only one token transfer is supported, got ${tokenAmounts.length}`, ) } const tokenOnly = tokenAmounts.length === 1 && !hasPayload @@ -939,7 +1016,7 @@ export class CantonChain extends Chain { : this.ccvs if (cantonArgs?.ccvRawAddresses === undefined && this.ccvs.length) { this.logger.debug( - 'CantonChain.generateUnsignedSendMessage: using ccvs from canton config for senderRequiredCCVs', + 'CantonChain.buildSendChoiceArgs: using ccvs from canton config for senderRequiredCCVs', this.ccvs, ) } @@ -1041,7 +1118,7 @@ export class CantonChain extends Chain { if (tokenAmount.amount <= 0n) { throw new CCIPError( CCIPErrorCode.METHOD_UNSUPPORTED, - 'CantonChain.generateUnsignedSendMessage: token transfer amount must be greater than zero', + 'CantonChain.buildSendChoiceArgs: token transfer amount must be greater than zero', ) } @@ -1067,7 +1144,7 @@ export class CantonChain extends Chain { if (tokenAdminRegistryGetTokenResponse.error) { throw new CCIPError( CCIPErrorCode.CANTON_API_ERROR, - `CantonChain.generateUnsignedSendMessage: failed to fetch token admin registry token for ${tokenInstrument.toString()}: ${tokenAdminRegistryGetTokenResponse.error.error}`, + `CantonChain.buildSendChoiceArgs: failed to fetch token admin registry token for ${tokenInstrument.toString()}: ${tokenAdminRegistryGetTokenResponse.error.error}`, ) } const tokenPoolAddress = RawInstanceAddress.fromString( @@ -1079,7 +1156,7 @@ export class CantonChain extends Chain { if (!parsedTokenPoolAddress.instanceAddress().equals(tokenPoolAddress.instanceAddress())) { throw new CCIPError( CCIPErrorCode.METHOD_UNSUPPORTED, - `CantonChain.generateUnsignedSendMessage: tokenPoolAddress ${cantonArgs.tokenPoolAddress} does not match registry token pool ${tokenPoolAddress.toString()}`, + `CantonChain.buildSendChoiceArgs: tokenPoolAddress ${cantonArgs.tokenPoolAddress} does not match registry token pool ${tokenPoolAddress.toString()}`, ) } } @@ -1100,7 +1177,7 @@ export class CantonChain extends Chain { if (tokenPoolSendDisclosuresResponse.error) { throw new CCIPError( CCIPErrorCode.CANTON_API_ERROR, - `CantonChain.generateUnsignedSendMessage: failed to fetch token pool send disclosures for ${tokenPoolAddress.toString()}: ${tokenPoolSendDisclosuresResponse.error.error}`, + `CantonChain.buildSendChoiceArgs: failed to fetch token pool send disclosures for ${tokenPoolAddress.toString()}: ${tokenPoolSendDisclosuresResponse.error.error}`, ) } @@ -1139,7 +1216,7 @@ export class CantonChain extends Chain { if (ccipSendDisclosuresResponse.error) { throw new CCIPError( CCIPErrorCode.CANTON_API_ERROR, - `CantonChain.generateUnsignedSendMessage: failed to fetch CCIP send disclosures: ${ccipSendDisclosuresResponse.error.error}`, + `CantonChain.buildSendChoiceArgs: failed to fetch CCIP send disclosures: ${ccipSendDisclosuresResponse.error.error}`, ) } @@ -1152,7 +1229,7 @@ export class CantonChain extends Chain { if (!ccipSendDisclosuresResponse.data.feeTokenTransferFactoryCid) { throw new CCIPError( CCIPErrorCode.CANTON_API_ERROR, - 'CantonChain.generateUnsignedSendMessage: EDS did not return a feeTokenTransferFactoryCid; ' + + 'CantonChain.buildSendChoiceArgs: EDS did not return a feeTokenTransferFactoryCid; ' + 'ensure you are using a valid and supported fee token', ) } @@ -1188,7 +1265,7 @@ export class CantonChain extends Chain { if (ccvSendDisclosuresResponse.error) { throw new CCIPError( CCIPErrorCode.CANTON_API_ERROR, - `CantonChain.generateUnsignedSendMessage: failed to fetch CCV disclosure for ${ccvInstanceAddress.toString()}: ${ccvSendDisclosuresResponse.error.error}`, + `CantonChain.buildSendChoiceArgs: failed to fetch CCV disclosure for ${ccvInstanceAddress.toString()}: ${ccvSendDisclosuresResponse.error.error}`, ) } return ccvSendDisclosuresResponse @@ -1225,7 +1302,7 @@ export class CantonChain extends Chain { if (executorDisclosuresResponse.error) { throw new CCIPError( CCIPErrorCode.CANTON_API_ERROR, - `CantonChain.generateUnsignedSendMessage: failed to fetch executor disclosure for ${executorAddress.toString()}: ${executorDisclosuresResponse.error.error}`, + `CantonChain.buildSendChoiceArgs: failed to fetch executor disclosure for ${executorAddress.toString()}: ${executorDisclosuresResponse.error.error}`, ) } disclosedContracts.push(...executorDisclosuresResponse.data.disclosedContracts) @@ -1235,6 +1312,19 @@ export class CantonChain extends Chain { } } + this.logger.debug('SendArgs:', sendArgs) + this.logger.debug('DisclosedContracts:', disclosedContracts) + + return { sendArgs, disclosedContracts, ccipSenderCid } + } + + /** {@inheritDoc Chain.generateUnsignedSendMessage} */ + override async generateUnsignedSendMessage( + opts: Parameters[0], + ): Promise { + const { sender } = opts + const { sendArgs, disclosedContracts, ccipSenderCid } = await this.buildSendChoiceArgs(opts) + const exerciseCommand = { ExerciseCommand: { templateId: CCIPSenderIdentifier.toString(), @@ -1244,9 +1334,6 @@ export class CantonChain extends Chain { }, } - this.logger.debug('SendArgs:', sendArgs) - this.logger.debug('DisclosedContracts:', disclosedContracts) - const jsCommands: JsCommands = { commands: [exerciseCommand], commandId: @@ -1257,7 +1344,7 @@ export class CantonChain extends Chain { } this.logger.debug( - `CantonChain.generateUnsignedSendMessage: built command with ${ccipSendDisclosuresResponse.data.disclosedContracts.length} disclosed contracts`, + `CantonChain.generateUnsignedSendMessage: built command with ${disclosedContracts.length} disclosed contracts`, ) return { From 860f88d46ed4a754e2e30eeac48f13b1a097c84f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Friedemann=20F=C3=BCrst?= <59653747+friedemannf@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:55:16 +0100 Subject: [PATCH 2/3] fix lint --- ccip-sdk/src/canton/index.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ccip-sdk/src/canton/index.ts b/ccip-sdk/src/canton/index.ts index 3726ac72e..664dcb032 100644 --- a/ccip-sdk/src/canton/index.ts +++ b/ccip-sdk/src/canton/index.ts @@ -1322,9 +1322,11 @@ export class CantonChain extends Chain { override async generateUnsignedSendMessage( opts: Parameters[0], ): Promise { - const { sender } = opts + const { sender, message } = opts const { sendArgs, disclosedContracts, ccipSenderCid } = await this.buildSendChoiceArgs(opts) + const cantonArgs = message.extraArgs as CantonExtraArgsV1 | undefined + const exerciseCommand = { ExerciseCommand: { templateId: CCIPSenderIdentifier.toString(), From c93d2d17c8c5b2b59c69fdd4a29916c6786a9c00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Friedemann=20F=C3=BCrst?= <59653747+friedemannf@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:59:02 +0100 Subject: [PATCH 3/3] implement CantonChain.getBalance --- ccip-sdk/src/canton/index.ts | 99 ++++++++++++++++++++++-------------- 1 file changed, 60 insertions(+), 39 deletions(-) diff --git a/ccip-sdk/src/canton/index.ts b/ccip-sdk/src/canton/index.ts index 664dcb032..b43c23538 100644 --- a/ccip-sdk/src/canton/index.ts +++ b/ccip-sdk/src/canton/index.ts @@ -50,6 +50,11 @@ import { ExecutionState, } from '../types.ts' import { getDataBytes, normalizeHex } from '../utils.ts' +import { + decodeContract, + listActiveContractsByInterfaceId, + listActiveContractsByTemplateId, +} from './acs.ts' import { type CantonAddress, type PartyId, @@ -65,6 +70,35 @@ import { formatCantonDecimalAmountUnits, parseCantonDecimalAmountUnits, } from './amount.ts' +import type { ITokenConfig } from './bindings/ccip-api-v2-2.0.0/CCIP/APIV2/TokenAdminRegistry/module.js' +import { + type ExecutorExtraArg, + type GenericExtraArgsV3, + PerPartyRouter, +} from './bindings/ccip-client-api-v2-2.0.0/CCIP/ClientV2/module.js' +import type { FinalityConfig } from './bindings/ccip-codec-v2-2.0.0/CCIP/CodecV2/FinalityConfig/module.js' +import { + CCIPMessageSent, + ExecutionStateChanged, +} from './bindings/ccip-events-v2-2.0.0/CCIP/EventsV2/Events/index.js' +import type { ICrossChainVerifier } from './bindings/ccip-extension-api-v2-2.0.0/CCIP/InterfacesV2/CrossChainVerifier/module.js' +import type { IExecutor } from './bindings/ccip-extension-api-v2-2.0.0/CCIP/InterfacesV2/Executor/module.js' +import type { ITokenPool } from './bindings/ccip-extension-api-v2-2.0.0/CCIP/InterfacesV2/TokenPool/module.js' +import { + type Execute, + CCIPReceiver, +} from './bindings/ccip-receiver-v2-2.1.0/CCIP/CCIPReceiver/module.js' +import { + type CreateRouter, + PerPartyRouterFactory, +} from './bindings/ccip-runtime-v2-2.1.1/CCIP/RuntimeV2/PerPartyRouter/module.js' +import { type Send, CCIPSender } from './bindings/ccip-sender-v2-2.1.0/CCIP/CCIPSender/module.js' +import { + Holding, + HoldingView, +} from './bindings/splice-api-token-holding-v1-1.0.0/Splice/Api/Token/HoldingV1/module.js' +import type { ChoiceContext } from './bindings/splice-api-token-metadata-v1-1.0.0/Splice/Api/Token/MetadataV1/module.js' +import type { TransferFactory } from './bindings/splice-api-token-transfer-instruction-v1-1.0.0/Splice/Api/Token/TransferInstructionV1/module.js' import { hashedRawInstanceAddress } from './ccv-addresses.ts' import { type Message, EdsClientProvider } from './clients/eds/client.ts' import { @@ -79,6 +113,7 @@ import { createLedgerApiClientFromProvider, } from './clients/ledger-api/client.ts' import { findExerciseResult } from './clients/ledger-api/prepared-transaction.ts' +import { TokenStandardClientProvider } from './clients/tokenStandard/client.ts' import { decodeDamlRecord, extractFieldValue } from './daml-parse.ts' import { CANTON_FEE_TOKEN_CLI_SYMBOLS, @@ -138,42 +173,6 @@ export { formatCantonLinkFeeToken, } from './defaults.ts' -import { - decodeContract, - listActiveContractsByInterfaceId, - listActiveContractsByTemplateId, -} from './acs.ts' -import type { ITokenConfig } from './bindings/ccip-api-v2-2.0.0/CCIP/APIV2/TokenAdminRegistry/module.js' -import { - type ExecutorExtraArg, - type GenericExtraArgsV3, - PerPartyRouter, -} from './bindings/ccip-client-api-v2-2.0.0/CCIP/ClientV2/module.js' -import type { FinalityConfig } from './bindings/ccip-codec-v2-2.0.0/CCIP/CodecV2/FinalityConfig/module.js' -import { - CCIPMessageSent, - ExecutionStateChanged, -} from './bindings/ccip-events-v2-2.0.0/CCIP/EventsV2/Events/index.js' -import type { ICrossChainVerifier } from './bindings/ccip-extension-api-v2-2.0.0/CCIP/InterfacesV2/CrossChainVerifier/module.js' -import type { IExecutor } from './bindings/ccip-extension-api-v2-2.0.0/CCIP/InterfacesV2/Executor/module.js' -import type { ITokenPool } from './bindings/ccip-extension-api-v2-2.0.0/CCIP/InterfacesV2/TokenPool/module.js' -import { - type Execute, - CCIPReceiver, -} from './bindings/ccip-receiver-v2-2.1.0/CCIP/CCIPReceiver/module.js' -import { - type CreateRouter, - PerPartyRouterFactory, -} from './bindings/ccip-runtime-v2-2.1.1/CCIP/RuntimeV2/PerPartyRouter/module.js' -import { type Send, CCIPSender } from './bindings/ccip-sender-v2-2.1.0/CCIP/CCIPSender/module.js' -import { - Holding, - HoldingView, -} from './bindings/splice-api-token-holding-v1-1.0.0/Splice/Api/Token/HoldingV1/module.js' -import type { ChoiceContext } from './bindings/splice-api-token-metadata-v1-1.0.0/Splice/Api/Token/MetadataV1/module.js' -import type { TransferFactory } from './bindings/splice-api-token-transfer-instruction-v1-1.0.0/Splice/Api/Token/TransferInstructionV1/module.js' -import { TokenStandardClientProvider } from './clients/tokenStandard/client.ts' - // Authentication providers (OAuth 2.0: static, clientCredentials, authorizationCode protocol helpers) export { type AccessToken, @@ -795,10 +794,24 @@ export class CantonChain extends Chain { /** * {@inheritDoc Chain.getBalance} - * @throws {@link CCIPNotImplementedError} always (not yet implemented for Canton) */ - getBalance(_opts: GetBalanceOpts): Promise { - throw new CCIPNotImplementedError('CantonChain.getBalance') + async getBalance(opts: GetBalanceOpts): Promise { + let token: CantonInstrumentId + if (opts.token) { + token = CantonInstrumentId.fromString(opts.token) + } else { + token = CantonInstrumentId.fromString(this.nativeToken.instrumentId) + } + + return ( + (await this.listTokenHoldings(token)) + // Filter by holder if specified (empty string = all holders) + .filter((holding) => opts.holder === '' || holding.view.owner === opts.holder) + // Filter out locked holdings + .filter((holding) => holding.view.lock === null) + .map((holding) => parseCantonDecimalAmountUnits(holding.view.amount)) + .reduce((acc, holdingAmount) => acc + holdingAmount, 0n) + ) } /** @@ -2513,6 +2526,10 @@ export class CantonChain extends Chain { } else { // Select holdings from lowest-to-highest amount in order to minimize dust const holdings = (await this.listTokenHoldings(tokenTransfer.instrumentId)) + // filter out holdings not owned by the active party, listTokenHoldings returns all holdings visible to the active party + .filter((holding) => holding.view.owner === this.activeParty) + // filter out locked holdings + .filter((holding) => holding.view.lock === null) .map((holding) => ({ contractId: holding.contractId, units: parseCantonDecimalAmountUnits(holding.view.amount), @@ -2561,6 +2578,10 @@ export class CantonChain extends Chain { // Pass all holdings, sorted from lowest-to-highest amount in order to minimize dust const transferCids = new Set(tokenTransferHoldingCids) feeTokenHoldingCids = (await this.listTokenHoldings(feeTokenInstrumentId)) + // filter out holdings not owned by the active party, listTokenHoldings returns all holdings visible to the active party + .filter((holding) => holding.view.owner === this.activeParty) + // filter out locked holdings + .filter((holding) => holding.view.lock === null) .map((holding) => ({ contractId: holding.contractId, units: parseCantonDecimalAmountUnits(holding.view.amount),