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
1 change: 1 addition & 0 deletions modules/sdk-coin-starknet/src/lib/iface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ export interface TxData {
amount?: string;
fee?: string;
nonce: string;
recipients?: Array<{ recipient: string; amount: string; tokenContract: string }>;
type: BitGoTransactionType;
}

Expand Down
44 changes: 27 additions & 17 deletions modules/sdk-coin-starknet/src/lib/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,16 +112,15 @@ export class Transaction extends BaseTransaction {
nonce: data.nonce,
type: TransactionType.Send,
};

const firstCall = data.calls[0];
if (!firstCall) {
return result;
}

const transfer = parseTransferCall(firstCall);
if (transfer) {
result.recipient = transfer.recipient;
result.amount = transfer.amount;
const transfers = data.calls
.map(parseTransferCall)
.filter((transfer): transfer is NonNullable<typeof transfer> => transfer !== undefined);
if (transfers.length > 0) {
result.recipients = transfers;
result.recipient = transfers[0].recipient;
result.amount = transfers.reduce((total, transfer) => (BigInt(total) + BigInt(transfer.amount)).toString(), '0');
return result;
}

Expand All @@ -144,20 +143,31 @@ export class Transaction extends BaseTransaction {
explainTransaction(): StarknetTransactionExplanation {
const result = this.toJson();
const displayOrder = ['id', 'outputAmount', 'changeAmount', 'outputs', 'changeOutputs', 'fee'];
const outputs: TransactionRecipient[] = [];

if (result.recipient && result.amount) {
outputs.push({
address: result.recipient,
amount: result.amount,
});
}
const transfers =
result.recipients ??
(result.recipient && result.amount
? [
{
recipient: result.recipient,
amount: result.amount,
tokenContract: '',
},
]
: []);
const outputs: TransactionRecipient[] = transfers.map((transfer) => ({
address: transfer.recipient,
amount: transfer.amount,
}));
const outputAmount = transfers.reduce(
(total, transfer) => (BigInt(total) + BigInt(transfer.amount)).toString(),
'0'
);

return {
displayOrder,
id: this.id,
outputs,
outputAmount: result.amount || '0',
outputAmount,
fee: { fee: '0' },
type: result.type,
changeOutputs: [],
Expand Down
76 changes: 61 additions & 15 deletions modules/sdk-coin-starknet/src/lib/transferBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,21 @@ import { BuildTransactionError } from '@bitgo/sdk-core';
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { TransactionBuilder } from './transactionBuilder';
import { Transaction } from './transaction';
import { StarknetCall, StarknetTransactionType } from './iface';
import { StarknetTransactionType } from './iface';
import { STRK_TOKEN_CONTRACT, MASK_128 } from './constants';
import utils from './utils';

export interface StarknetTransferRecipient {
address: string;
amount: string;
tokenContractAddress?: string;
}

export class TransferBuilder extends TransactionBuilder {
protected _receiverAddress?: string;
protected _amount?: string;
protected _tokenContractAddress: string = STRK_TOKEN_CONTRACT;
protected _recipients: StarknetTransferRecipient[] = [];

constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
Expand All @@ -23,6 +30,7 @@ export class TransferBuilder extends TransactionBuilder {
if (!address || !utils.isValidAddress(address)) {
throw new BuildTransactionError('Invalid or missing receiver address, got: ' + address);
}
this._recipients = [];
this._receiverAddress = address;
return this;
}
Expand All @@ -32,10 +40,22 @@ export class TransferBuilder extends TransactionBuilder {
if (val < 0n) {
throw new BuildTransactionError(`Invalid amount: ${value}`);
}
this._recipients = [];
this._amount = value;
return this;
}

public recipients(recipients: StarknetTransferRecipient[]): this {
this.validateRecipients(recipients);
this._recipients = recipients.map((recipient) => ({
...recipient,
tokenContractAddress: recipient.tokenContractAddress ?? STRK_TOKEN_CONTRACT,
}));
this._receiverAddress = undefined;
this._amount = undefined;
return this;
}

public tokenContractAddress(address: string): this {
if (!address || !utils.isValidAddress(address)) {
throw new BuildTransactionError('Invalid token contract address, got: ' + address);
Expand All @@ -47,27 +67,36 @@ export class TransferBuilder extends TransactionBuilder {
/** @inheritdoc */
initBuilder(tx: Transaction): void {
super.initBuilder(tx);
if (this._calls.length > 0) {
const transfer = utils.parseTransferCall(this._calls[0]);
if (transfer) {
this._receiverAddress = transfer.recipient;
this._amount = transfer.amount;
this._tokenContractAddress = transfer.tokenContract;
}
const parsedRecipients = this._calls.map((call) => utils.parseTransferCall(call));
if (parsedRecipients.every((recipient): recipient is NonNullable<typeof recipient> => recipient !== undefined)) {
this._recipients = parsedRecipients.map((recipient) => ({
address: recipient.recipient,
amount: recipient.amount,
tokenContractAddress: recipient.tokenContract,
}));
}
}

/** @inheritdoc */
protected async buildImplementation(): Promise<Transaction> {
this.validateTransfer();
if (this._recipients.length === 0) {
this.validateTransfer();
this._recipients = [
{
address: this._receiverAddress as string,
amount: this._amount as string,
tokenContractAddress: this._tokenContractAddress,
},
];
} else {
this.validateRecipients(this._recipients);
}

const transferCall: StarknetCall = {
contractAddress: this._tokenContractAddress,
this._calls = this._recipients.map((recipient) => ({
contractAddress: recipient.tokenContractAddress ?? STRK_TOKEN_CONTRACT,
entrypoint: 'transfer',
calldata: this.compileTransferCalldata(this._receiverAddress as string, this._amount as string),
};

this._calls = [transferCall];
calldata: this.compileTransferCalldata(recipient.address, recipient.amount),
}));

return super.buildImplementation();
}
Expand All @@ -77,6 +106,23 @@ export class TransferBuilder extends TransactionBuilder {
return [recipient, '0x' + (amountBig & MASK_128).toString(16), '0x' + (amountBig >> 128n).toString(16)];
}

private validateRecipients(recipients: StarknetTransferRecipient[]): void {
if (!recipients || recipients.length === 0) {
throw new BuildTransactionError('At least one recipient is required');
}
for (const recipient of recipients) {
if (!recipient.address || !utils.isValidAddress(recipient.address)) {
throw new BuildTransactionError(`Invalid receiver address: ${recipient.address}`);
}
if (!recipient.amount || BigInt(recipient.amount) < 0n) {
throw new BuildTransactionError(`Invalid amount: ${recipient.amount}`);
}
if (recipient.tokenContractAddress && !utils.isValidAddress(recipient.tokenContractAddress)) {
throw new BuildTransactionError(`Invalid token contract address: ${recipient.tokenContractAddress}`);
}
}
}

private validateTransfer(): void {
if (!this._sender) {
throw new BuildTransactionError('Sender is required');
Expand Down
23 changes: 9 additions & 14 deletions modules/sdk-coin-starknet/src/starknet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,23 +82,18 @@ export class Starknet extends BaseCoin {
const explainedTx = await this.explainTransaction({ transactionHex: txHex });

if (Array.isArray(txParams.recipients) && txParams.recipients.length > 0) {
if (txParams.recipients.length > 1) {
throw new Error(
`${this.getChain()} doesn't support sending to more than 1 destination address within a single transaction. Try again, using only a single recipient.`
);
}

if (explainedTx.outputs.length !== 1) {
if (explainedTx.outputs.length !== txParams.recipients.length) {
throw new Error('Tx outputs does not match with expected txParams recipients');
}

const output = explainedTx.outputs[0];
const recipient = txParams.recipients[0];
const normalizedOutput = utils.normalizeAddress(output.address);
const normalizedRecipient = utils.normalizeAddress(recipient.address);
if (normalizedOutput !== normalizedRecipient || output.amount !== recipient.amount) {
throw new Error('Tx outputs does not match with expected txParams recipients');
}
txParams.recipients.forEach((recipient, index) => {
const output = explainedTx.outputs[index];
const normalizedOutput = utils.normalizeAddress(output.address);
const normalizedRecipient = utils.normalizeAddress(recipient.address);
if (normalizedOutput !== normalizedRecipient || output.amount !== recipient.amount) {
throw new Error(`Tx output at index ${index} does not match with expected txParams recipient`);
}
});
}
return true;
}
Expand Down
29 changes: 29 additions & 0 deletions modules/sdk-coin-starknet/test/unit/starknet.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { TestBitGo, TestBitGoAPI } from '@bitgo/sdk-test';
import { BitGoAPI } from '@bitgo/sdk-api';
import { Starknet } from '../../src/index';
import { coins } from '@bitgo/statics';
import { TransactionBuilderFactory } from '../../src/lib/transactionBuilderFactory';
import { Transaction } from '../../src/lib/transaction';

import * as testData from '../resources/starknet';
import should from 'should';
import { getAddressFromPublicKey } from '../../src/lib/utils';
Expand Down Expand Up @@ -148,4 +152,29 @@ describe('Starknet', function () {
result.should.equal(true);
});
});
it('should verify multiple recipients in a Starknet transaction', async function () {
const factory = new TransactionBuilderFactory(coins.get('starknet'));
const builder = factory.getTransferBuilder();
builder
.sender(testData.Accounts.account1.address)
.nonce('0x0')
.chainId('0x534e5f4d41494e')
.recipients([
{ address: testData.Accounts.account2.address, amount: '1000000000000000000' },
{ address: testData.Accounts.account3.address, amount: '2000000000000000000' },
]);
const tx = (await builder.build()) as Transaction;

const result = await basecoin.verifyTransaction({
txParams: {
recipients: [
{ address: testData.Accounts.account2.address, amount: '1000000000000000000' },
{ address: testData.Accounts.account3.address, amount: '2000000000000000000' },
],
},
txPrebuild: { txHex: tx.toInternalHex() },
wallet: {} as any,
});
result.should.equal(true);
});
});
23 changes: 23 additions & 0 deletions modules/sdk-coin-starknet/test/unit/transferBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,29 @@ describe('Starknet TransferBuilder', () => {
tx.signableHex.should.equal(tx.starknetTransactionData.transactionHash!.replace(/^0x/i, '').padStart(64, '0'));
tx.id.should.equal(tx.starknetTransactionData.transactionHash);
});
it('should build multiple STRK transfer calls and preserve them through round-trip', async () => {
const factory = new TransactionBuilderFactory(coinConfig);
const builder = factory.getTransferBuilder();

builder
.sender(Accounts.account1.address)
.nonce('0x0')
.chainId(SandboxTransferData.chainId)
.recipients([
{ address: Accounts.account2.address, amount: '1000000000000000000' },
{ address: Accounts.account3.address, amount: '2000000000000000000' },
]);

const tx = (await builder.build()) as Transaction;
tx.starknetTransactionData.calls.length.should.equal(2);
tx.starknetTransactionData.compiledCalldata?.[0].should.equal('0x2');

const roundTripBuilder = await factory.from(tx.toInternalHex());
const roundTrip = (await roundTripBuilder.build()) as Transaction;
roundTrip.starknetTransactionData.calls.length.should.equal(2);
roundTrip.signableHex.should.equal(tx.signableHex);
roundTrip.explainTransaction().outputs.length.should.equal(2);
});

it('should produce different hashes for different recipients', async () => {
const factory = new TransactionBuilderFactory(coinConfig);
Expand Down
1 change: 1 addition & 0 deletions modules/statics/src/coinFeatures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -700,6 +700,7 @@ export const STARKNET_FEATURES = [
CoinFeature.TSS_COLD,
CoinFeature.MPCV2,
CoinFeature.SHA256_WITH_ECDSA_TSS,
CoinFeature.BULK_TRANSACTION,
CoinFeature.REBUILD_ON_CUSTODY_SIGNING,
];

Expand Down
Loading