Skip to content

Commit 0c7950c

Browse files
committed
feat(sdk-coin-stx): allow a caller-supplied staking contract
The contract builder only accepts the canonical pox-4 / pox-5 / send-many-memo contracts: contractName must be in VALID_STAKING_CONTRACT_NAMES and contractAddress must be one of the network's contract addresses. That blocks building for a non-canonical staking contract (e.g. a test/dummy pox-5, or a future pox version) without an SDK change. Add an opt-in allowlist of staking contracts ({ name, address } pairs) that the caller supplies. Empty by default, so the canonical set and every existing flow is unchanged. It is threaded through every path that builds or rebuilds a contract call: - ContractBuilder takes the allowlist (constructor) and accepts a name/address only when they match one allowlisted pair (canonical set otherwise); - TransactionBuilderFactory.from(hex, { allowedStakingContracts }) passes it to getContractBuilder; - Stx.signTransaction / explainTransaction (and the recovery rebuild) pass the coin's setAllowedStakingContracts(...) value, so a rehydrated transaction re-validates against the same rules as the build path. Validation is therefore unchanged: the canonical checks run on every path (including initBuilder), and only an explicitly allowlisted contract is accepted in addition. A contract name that is allowlisted is validated against the canonical pox-5 function set (the dummy is an ABI-identical copy). Ticket: SI-2106
1 parent dbc2194 commit 0c7950c

5 files changed

Lines changed: 230 additions & 16 deletions

File tree

‎modules/sdk-coin-stx/src/lib/contractBuilder.ts‎

Lines changed: 85 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import { Transaction } from './transaction';
1818
import { contractPrincipalCVFromString, isValidAddress, standardPrincipalCVFromString } from './utils';
1919
import { ClarityValueJson } from './iface';
2020
import { Utils } from '.';
21-
import { CONTRACT_NAME_SENDMANY, VALID_STAKING_CONTRACT_NAMES } from './constants';
21+
import { CONTRACT_NAME_SENDMANY, VALID_POX5_CONTRACT_FUNCTION_NAMES, VALID_STAKING_CONTRACT_NAMES } from './constants';
2222
import { AbstractContractBuilder } from './abstractContractBuilder';
2323

2424
export class ContractBuilder extends AbstractContractBuilder {
@@ -30,13 +30,64 @@ export class ContractBuilder extends AbstractContractBuilder {
3030
ClarityType.BoolFalse,
3131
]);
3232

33-
constructor(_coinConfig: Readonly<CoinConfig>) {
33+
/**
34+
* Caller-supplied staking contracts this builder accepts **in addition to** the canonical ones
35+
* (pox-4 / pox-5 / send-many-memo). Empty by default, so behaviour is unchanged unless a caller
36+
* opts in. Lets a deployment target a different staking contract (e.g. a test/dummy pox-5, or a
37+
* future pox version) without an SDK change — the caller passes the name/address it is configured
38+
* with. Threaded in via the constructor so every path that rebuilds a transaction
39+
* (`factory.from(hex, { allowedStakingContracts })`) re-validates against the same rules.
40+
*/
41+
private _allowedStakingContracts: ReadonlyArray<{ name: string; address: string }>;
42+
43+
constructor(
44+
_coinConfig: Readonly<CoinConfig>,
45+
allowedStakingContracts: ReadonlyArray<{ name: string; address: string }> = []
46+
) {
3447
super(_coinConfig);
48+
this._allowedStakingContracts = allowedStakingContracts;
49+
}
50+
51+
allowedStakingContracts(contracts: ReadonlyArray<{ name: string; address: string }>): this {
52+
const list = contracts ?? [];
53+
const names = new Set<string>();
54+
for (const contract of list) {
55+
if (names.has(contract.name)) {
56+
throw new InvalidParameterValueError(`Duplicate staking contract name: ${contract.name}`);
57+
}
58+
names.add(contract.name);
59+
}
60+
this._allowedStakingContracts = list;
61+
return this;
62+
}
63+
64+
/** True when the current (name, address) is a canonical pair or an explicitly allowlisted pair. */
65+
private isContractPairValid(): boolean {
66+
const isCanonicalName =
67+
VALID_STAKING_CONTRACT_NAMES.includes(this._contractName) || this._contractName === CONTRACT_NAME_SENDMANY;
68+
const isCanonicalAddress = Utils.isValidContractAddress(
69+
this._contractAddress,
70+
this._coinConfig.network as BitgoStacksNetwork
71+
);
72+
if (isCanonicalName && isCanonicalAddress) {
73+
return true;
74+
}
75+
return this._allowedStakingContracts.some(
76+
(contract) => contract.name === this._contractName && contract.address === this._contractAddress
77+
);
78+
}
79+
80+
/** True when the name belongs to an allowlisted staking contract. */
81+
private isAllowedStakingContractName(name: string): boolean {
82+
return this._allowedStakingContracts.some((contract) => contract.name === name);
3583
}
3684

3785
initBuilder(tx: Transaction): void {
3886
super.initBuilder(tx);
39-
// Retro compatibility, checks parameters.
87+
// Retro compatibility, checks parameters — run unchanged on every path. The allowlist is threaded
88+
// into this builder (constructor / `factory.from(hex, { allowedStakingContracts })`), so an
89+
// allowlisted contract re-validates against the same rules as on the build path, and a
90+
// non-allowlisted one is still rejected (no relaxation).
4091
this.contractAddress(this._contractAddress);
4192
this.contractName(this._contractName);
4293
this.functionName(this._functionName);
@@ -54,10 +105,16 @@ export class ContractBuilder extends AbstractContractBuilder {
54105
if (!isValidAddress(address)) {
55106
throw new InvalidParameterValueError('Invalid address');
56107
}
57-
if (!Utils.isValidContractAddress(address, this._coinConfig.network as BitgoStacksNetwork)) {
108+
const isCanonicalAddress = Utils.isValidContractAddress(address, this._coinConfig.network as BitgoStacksNetwork);
109+
const isAllowedAddress = this._allowedStakingContracts.some((contract) => contract.address === address);
110+
if (!isCanonicalAddress && !isAllowedAddress) {
58111
throw new InvalidParameterValueError('Invalid contract address');
59112
}
60113
this._contractAddress = address;
114+
// Order-independent: if the name is already set, the (name, address) pair must be valid.
115+
if (this._contractName && !this.isContractPairValid()) {
116+
throw new InvalidParameterValueError('Contract name and address are not an allowlisted pair');
117+
}
61118
return this;
62119
}
63120

@@ -71,13 +128,26 @@ export class ContractBuilder extends AbstractContractBuilder {
71128
if (name.length === 0) {
72129
throw new InvalidParameterValueError('Invalid name');
73130
}
74-
if (!VALID_STAKING_CONTRACT_NAMES.includes(name) && name !== CONTRACT_NAME_SENDMANY) {
131+
const isCanonicalName = VALID_STAKING_CONTRACT_NAMES.includes(name) || name === CONTRACT_NAME_SENDMANY;
132+
if (!isCanonicalName && !this.isAllowedStakingContractName(name)) {
75133
throw new InvalidParameterValueError('Only pox-4, pox-5, and send-many-memo contracts supported');
76134
}
77-
if (this._functionName && !Utils.isValidContractFunctionName(this._functionName, name)) {
78-
throw new InvalidParameterValueError(`${this._functionName} is not supported contract function name`);
79-
}
80135
this._contractName = name;
136+
// Order-independent: if the address is already set, the (name, address) pair must be valid.
137+
if (this._contractAddress && !this.isContractPairValid()) {
138+
throw new InvalidParameterValueError('Contract name and address are not an allowlisted pair');
139+
}
140+
// A caller-allowlisted contract (e.g. the dummy pox-5) is ABI-identical to the canonical pox-5,
141+
// so its functions are validated against the pox-5 set instead of being skipped. (A contract
142+
// with a genuinely different ABI would need to carry its own function list.)
143+
if (this._functionName) {
144+
const validFunction = this.isAllowedStakingContractName(name)
145+
? VALID_POX5_CONTRACT_FUNCTION_NAMES.includes(this._functionName)
146+
: Utils.isValidContractFunctionName(this._functionName, name);
147+
if (!validFunction) {
148+
throw new InvalidParameterValueError(`${this._functionName} is not supported contract function name`);
149+
}
150+
}
81151
return this;
82152
}
83153

@@ -91,7 +161,13 @@ export class ContractBuilder extends AbstractContractBuilder {
91161
if (name.length === 0) {
92162
throw new InvalidParameterValueError('Invalid name');
93163
}
94-
if (!Utils.isValidContractFunctionName(name, this._contractName)) {
164+
if (this.isAllowedStakingContractName(this._contractName)) {
165+
// Caller-allowlisted contract: validate against the canonical pox-5 function set (ABI-identical
166+
// copy) rather than skipping the check.
167+
if (!VALID_POX5_CONTRACT_FUNCTION_NAMES.includes(name)) {
168+
throw new InvalidParameterValueError(`${name} is not supported contract function name`);
169+
}
170+
} else if (!Utils.isValidContractFunctionName(name, this._contractName)) {
95171
throw new InvalidParameterValueError(`${name} is not supported contract function name`);
96172
}
97173
this._functionName = name;

‎modules/sdk-coin-stx/src/lib/transactionBuilderFactory.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,10 @@ export class TransactionBuilderFactory extends BaseTransactionBuilderFactory {
2222
}
2323

2424
/** @inheritdoc */
25-
from(raw: string): TransactionBuilder {
25+
from(
26+
raw: string,
27+
params?: { allowedStakingContracts?: ReadonlyArray<{ name: string; address: string }> }
28+
): TransactionBuilder {
2629
this.validateRawTransaction(raw);
2730
try {
2831
const tx = this.parseTransaction(raw);
@@ -42,7 +45,7 @@ export class TransactionBuilderFactory extends BaseTransactionBuilderFactory {
4245
if (Pox5Builder.isValidContractCall(this._coinConfig, tx.stxTransaction.payload)) {
4346
return this.getPox5Builder(tx);
4447
}
45-
return this.getContractBuilder(tx);
48+
return this.getContractBuilder(tx, params?.allowedStakingContracts);
4649
default:
4750
throw new InvalidTransactionError('Invalid transaction');
4851
}
@@ -69,8 +72,14 @@ export class TransactionBuilderFactory extends BaseTransactionBuilderFactory {
6972
return TransactionBuilderFactory.initializeBuilder(new TransferBuilder(this._coinConfig), tx);
7073
}
7174

72-
getContractBuilder(tx?: Transaction): ContractBuilder {
73-
return TransactionBuilderFactory.initializeBuilder(new ContractBuilder(this._coinConfig), tx);
75+
getContractBuilder(
76+
tx?: Transaction,
77+
allowedStakingContracts?: ReadonlyArray<{ name: string; address: string }>
78+
): ContractBuilder {
79+
return TransactionBuilderFactory.initializeBuilder(
80+
new ContractBuilder(this._coinConfig, allowedStakingContracts),
81+
tx
82+
);
7483
}
7584

7685
getSendmanyBuilder(tx?: Transaction): SendmanyBuilder {

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,9 @@ export class Stx extends BaseCoin {
283283
*/
284284
async signTransaction(params: StxSignTransactionOptions): Promise<SignedTransaction> {
285285
const factory = new StxLib.TransactionBuilderFactory(coins.get(this.getChain()));
286-
const txBuilder = factory.from(params.txPrebuild.txHex);
286+
const txBuilder = factory.from(params.txPrebuild.txHex, {
287+
allowedStakingContracts: params.allowedStakingContracts,
288+
});
287289
const prvKeys = params.prv instanceof Array ? params.prv : [params.prv];
288290
prvKeys.forEach((prv) => txBuilder.sign({ key: prv }));
289291
if (params.pubKeys) txBuilder.fromPubKey(params.pubKeys);
@@ -316,7 +318,7 @@ export class Stx extends BaseCoin {
316318
}
317319

318320
const factory = new StxLib.TransactionBuilderFactory(coins.get(this.getChain()));
319-
const txBuilder = factory.from(txHex);
321+
const txBuilder = factory.from(txHex, { allowedStakingContracts: params.allowedStakingContracts });
320322

321323
if (params.publicKeys !== undefined) {
322324
txBuilder.fromPubKey(params.publicKeys);

‎modules/sdk-coin-stx/src/types.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,20 @@ export interface ExplainTransactionOptions {
2929
};
3030
publicKeys?: string[];
3131
feeInfo: TransactionFee;
32+
/**
33+
* Non-canonical staking contracts to accept while re-parsing (e.g. a dummy pox-5), passed
34+
* explicitly so no shared/instance state is involved. Empty/omitted ⇒ canonical-only.
35+
*/
36+
allowedStakingContracts?: ReadonlyArray<{ name: string; address: string }>;
3237
}
3338

3439
export interface StxSignTransactionOptions extends SignTransactionOptions {
3540
txPrebuild: TransactionPrebuild;
3641
prv: string | string[];
3742
pubKeys?: string[];
3843
numberSignature?: number;
44+
/** @see ExplainTransactionOptions.allowedStakingContracts */
45+
allowedStakingContracts?: ReadonlyArray<{ name: string; address: string }>;
3946
}
4047

4148
export interface TransactionPrebuild extends BaseTransactionPrebuild {

‎modules/sdk-coin-stx/test/unit/transactionBuilder/contractBuilder.ts‎

Lines changed: 121 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import assert from 'assert';
22
import should from 'should';
33
import BigNum from 'bn.js';
44
import { STACKS_TESTNET, STACKS_MAINNET } from '@stacks/network';
5-
import { InvalidParameterValueError, TransactionType } from '@bitgo/sdk-core';
5+
import { InvalidParameterValueError, ParseTransactionError, TransactionType } from '@bitgo/sdk-core';
66
import { bufferCV, noneCV, someCV, standardPrincipalCV, tupleCV, uintCV, intCV } from '@stacks/transactions';
77
import { TestBitGo, TestBitGoAPI } from '@bitgo/sdk-test';
88
import { BitGoAPI } from '@bitgo/sdk-api';
@@ -168,6 +168,126 @@ describe('Stacks: Contract Builder', function () {
168168
txJson.payload.functionArgs.length.should.equal(5);
169169
});
170170

171+
it('an unsigned caller-allowlisted non-canonical pox-5 (dummy) contract call transaction', async () => {
172+
// The caller supplies the staking contract it is configured for — no SDK change needed.
173+
const builder = factoryProd.getContractBuilder();
174+
builder.allowedStakingContracts([
175+
{ name: 'pox-5-dummy-v1', address: 'SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY' },
176+
]);
177+
builder.fee({ fee: '180' });
178+
builder.nonce(0);
179+
builder.contractAddress('SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY');
180+
builder.contractName('pox-5-dummy-v1');
181+
builder.functionName('register-for-bond');
182+
builder.functionArgs([
183+
{ type: 'uint128', val: '210' },
184+
{ type: 'principal', val: 'SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY.signer-manager-stackslabs-dummy-v1' },
185+
{ type: 'uint128', val: '1005000' },
186+
{ type: 'optional' },
187+
{ type: 'optional' },
188+
]);
189+
builder.fromPubKey(testData.TX_SENDER.pub);
190+
builder.numberSignatures(1);
191+
192+
const tx = await builder.build();
193+
const txJson = tx.toJson();
194+
should.deepEqual(txJson.payload.contractName, 'pox-5-dummy-v1');
195+
should.deepEqual(txJson.payload.contractAddress, 'SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY');
196+
should.deepEqual(txJson.payload.functionName, 'register-for-bond');
197+
});
198+
199+
it('rehydrates an allowlisted non-canonical contract call (sign / explain / fee-rebuild path)', async () => {
200+
// `signTransaction` / `explainTransaction` / the fee re-build all go through `factory.from(hex)`,
201+
// which re-creates the builder — re-parsing must not reject the allowlisted contract.
202+
const allowlist = [{ name: 'pox-5-dummy-v1', address: 'SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY' }];
203+
const builder = factoryProd.getContractBuilder();
204+
builder.allowedStakingContracts(allowlist);
205+
builder.fee({ fee: '180' });
206+
builder.nonce(0);
207+
builder.contractAddress('SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY');
208+
builder.contractName('pox-5-dummy-v1');
209+
builder.functionName('register-for-bond');
210+
builder.functionArgs([
211+
{ type: 'uint128', val: '210' },
212+
{ type: 'principal', val: 'SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY.signer-manager-stackslabs-dummy-v1' },
213+
{ type: 'uint128', val: '1005000' },
214+
{ type: 'optional' },
215+
{ type: 'optional' },
216+
]);
217+
builder.fromPubKey(testData.TX_SENDER.pub);
218+
builder.numberSignatures(1);
219+
const tx = await builder.build();
220+
221+
const reparsed = factoryProd.from(tx.toBroadcastFormat(), { allowedStakingContracts: allowlist });
222+
reparsed.fromPubKey(testData.TX_SENDER.pub);
223+
reparsed.numberSignatures(1);
224+
const payload = (await reparsed.build()).toJson().payload;
225+
should.deepEqual(payload.contractAddress, 'SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY');
226+
should.deepEqual(payload.contractName, 'pox-5-dummy-v1');
227+
228+
// Without the allowlist the rebuild is rejected — canonical validation is preserved (no relaxation).
229+
(() => factoryProd.from(tx.toBroadcastFormat())).should.throw(ParseTransactionError);
230+
});
231+
232+
it('rejects an allowlisted name followed by a canonical address (order-independent pair check)', function () {
233+
const builder = factoryProd.getContractBuilder();
234+
builder.allowedStakingContracts([
235+
{ name: 'pox-5-dummy-v1', address: 'SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY' },
236+
]);
237+
builder.contractName('pox-5-dummy-v1'); // allowlisted name first
238+
(() => builder.contractAddress('SP000000000000000000002Q6VF78')).should.throw(/not an allowlisted pair/);
239+
});
240+
241+
it('rejects an allowlisted address followed by a canonical name (order-independent pair check)', function () {
242+
const builder = factoryProd.getContractBuilder();
243+
builder.allowedStakingContracts([
244+
{ name: 'pox-5-dummy-v1', address: 'SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY' },
245+
]);
246+
builder.contractAddress('SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY'); // allowlisted address first
247+
(() => builder.contractName('pox-5')).should.throw(/not an allowlisted pair/);
248+
});
249+
250+
it('rejects duplicate allowlisted contract names', function () {
251+
const builder = factoryProd.getContractBuilder();
252+
(() =>
253+
builder.allowedStakingContracts([
254+
{ name: 'pox-5-dummy-v1', address: 'SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY' },
255+
{ name: 'pox-5-dummy-v1', address: 'SP000000000000000000002Q6VF78' },
256+
])).should.throw(/Duplicate staking contract name/);
257+
});
258+
259+
it('rejects an allowlisted name paired with a different address', function () {
260+
const builder = factoryProd.getContractBuilder();
261+
builder.allowedStakingContracts([
262+
{ name: 'pox-5-dummy-v1', address: 'SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY' },
263+
]);
264+
builder.contractAddress('SP000000000000000000002Q6VF78'); // canonical address, wrong pair
265+
(() => builder.contractName('pox-5-dummy-v1')).should.throw(/not an allowlisted pair/);
266+
});
267+
268+
it('rejects a function that is not in the pox-5 set for an allowlisted contract', function () {
269+
const builder = factoryProd.getContractBuilder();
270+
builder.allowedStakingContracts([
271+
{ name: 'pox-5-dummy-v1', address: 'SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY' },
272+
]);
273+
builder.contractAddress('SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY');
274+
builder.contractName('pox-5-dummy-v1');
275+
// `stack-stx` is a pox-4 function, not part of the pox-5 ABI the dummy mirrors.
276+
(() => builder.functionName('stack-stx')).should.throw(/is not supported contract function name/);
277+
});
278+
279+
it('rejects a contract name that is not allowlisted', function () {
280+
const builder = factory.getContractBuilder();
281+
(() => builder.contractName('some-other-contract')).should.throw(/Only pox-4, pox-5, and send-many-memo/);
282+
});
283+
284+
it('rejects a contract address that is not allowlisted', function () {
285+
const builder = factory.getContractBuilder();
286+
(() => builder.contractAddress('SP3JVSE4ZB5GMDJP5XBPX7ZB1BG3QDFW7RCEQJDMY')).should.throw(
287+
/Invalid contract address/
288+
);
289+
});
290+
171291
it('a signed contract call with args', async () => {
172292
const builder = initTxBuilder();
173293
builder.functionArgs([

0 commit comments

Comments
 (0)