Skip to content

Commit 5019af4

Browse files
bhavidhingraclaude
andcommitted
feat(sdk-core): add bulk TRX resource delegation SDK methods
Adds buildAccountDelegations, sendAccountDelegation, sendAccountDelegations to the Wallet class and IWallet interface, mirroring the consolidation API. Adds Express typed route schema and handler for POST /api/v2/:coin/wallet/:id/delegateResources with TSS/custodial/hot wallet branching and partial-success (202) response handling. CHALO-287 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 4b63462 commit 5019af4

8 files changed

Lines changed: 347 additions & 0 deletions

File tree

modules/express/src/clientRoutes.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1050,6 +1050,58 @@ export async function handleV2ResourceDelegations(
10501050
});
10511051
}
10521052

1053+
/**
1054+
* Handle bulk resource delegation (e.g. TRX ENERGY/BANDWIDTH delegation).
1055+
* Builds, signs, and sends one on-chain delegation transaction per entry in req.body.delegations.
1056+
* @param req
1057+
*/
1058+
export async function handleV2DelegateResources(
1059+
req: ExpressApiRouteRequest<'express.v2.wallet.delegateresources', 'post'>
1060+
) {
1061+
const bitgo = req.bitgo;
1062+
const coin = bitgo.coin(req.decoded.coin);
1063+
1064+
if (!Array.isArray(req.decoded.delegations) || req.decoded.delegations.length === 0) {
1065+
throw new Error('delegations must be a non-empty array');
1066+
}
1067+
1068+
if (!coin.supportsResourceDelegation()) {
1069+
throw new Error(`${coin.getFamily()} does not support resource delegation`);
1070+
}
1071+
1072+
const wallet = await coin.wallets().get({ id: req.decoded.id });
1073+
1074+
let result: any;
1075+
try {
1076+
if (coin.supportsTss()) {
1077+
result = await wallet.sendResourceDelegations(createTSSSendParams(req, wallet));
1078+
} else {
1079+
result = await wallet.sendResourceDelegations(createSendParams(req));
1080+
}
1081+
} catch (err) {
1082+
// Surface unexpected errors as 400 rather than 500
1083+
(err as any).status = 400;
1084+
throw err;
1085+
}
1086+
1087+
// Handle partial success / failure
1088+
if (result.failure.length > 0) {
1089+
let msg = '';
1090+
let status = 202;
1091+
1092+
if (result.success.length > 0) {
1093+
msg = `Transactions failed: ${result.failure.length} and succeeded: ${result.success.length}`;
1094+
} else {
1095+
status = 400;
1096+
msg = `All transactions failed`;
1097+
}
1098+
1099+
throw apiResponse(status, result, msg);
1100+
}
1101+
1102+
return result;
1103+
}
1104+
10531105
/**
10541106
* payload meant for prebuildAndSignTransaction() in sdk-core which
10551107
* validates the payload and makes the appropriate request to WP to
@@ -1829,6 +1881,10 @@ export function setupAPIRoutes(app: express.Application, config: Config): void {
18291881
prepareBitGo(config),
18301882
typedPromiseWrapper(handleV2ResourceDelegations),
18311883
]);
1884+
router.post('express.v2.wallet.delegateresources', [
1885+
prepareBitGo(config),
1886+
typedPromiseWrapper(handleV2DelegateResources),
1887+
]);
18321888

18331889
// Miscellaneous
18341890
router.post('express.canonicaladdress', [prepareBitGo(config), typedPromiseWrapper(handleCanonicalAddress)]);

modules/express/src/typedRoutes/api/index.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ import { PostWalletAccelerateTx } from './v2/walletAccelerateTx';
5555
import { PostIsWalletAddress } from './v2/isWalletAddress';
5656
import { GetAccountResources } from './v2/accountResources';
5757
import { GetResourceDelegations } from './v2/resourceDelegations';
58+
import { PostDelegateResources } from './v2/delegateResources';
5859

5960
// Too large types can cause the following error
6061
//
@@ -180,6 +181,12 @@ export const ExpressV2WalletConsolidateAccountApiSpec = apiSpec({
180181
},
181182
});
182183

184+
export const ExpressV2WalletDelegateResourcesApiSpec = apiSpec({
185+
'express.v2.wallet.delegateresources': {
186+
post: PostDelegateResources,
187+
},
188+
});
189+
183190
export const ExpressWalletFanoutUnspentsApiSpec = apiSpec({
184191
'express.v1.wallet.fanoutunspents': {
185192
put: PutFanoutUnspents,
@@ -385,6 +392,7 @@ export type ExpressApi = typeof ExpressPingApiSpec &
385392
typeof ExpressV2WalletAccelerateTxApiSpec &
386393
typeof ExpressV2WalletAccountResourcesApiSpec &
387394
typeof ExpressV2WalletResourceDelegationsApiSpec &
395+
typeof ExpressV2WalletDelegateResourcesApiSpec &
388396
typeof ExpressWalletManagementApiSpec;
389397

390398
export const ExpressApi: ExpressApi = {
@@ -428,6 +436,7 @@ export const ExpressApi: ExpressApi = {
428436
...ExpressV2WalletAccelerateTxApiSpec,
429437
...ExpressV2WalletAccountResourcesApiSpec,
430438
...ExpressV2WalletResourceDelegationsApiSpec,
439+
...ExpressV2WalletDelegateResourcesApiSpec,
431440
...ExpressWalletManagementApiSpec,
432441
};
433442

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import * as t from 'io-ts';
2+
import { httpRoute, httpRequest, optional } from '@api-ts/io-ts-http';
3+
import { BitgoExpressError } from '../../schemas/error';
4+
5+
/**
6+
* Path parameters for the delegate resources endpoint
7+
*/
8+
export const DelegateResourcesParams = {
9+
/** Coin identifier (e.g., 'trx', 'ttrx') */
10+
coin: t.string,
11+
/** Wallet ID */
12+
id: t.string,
13+
} as const;
14+
15+
/**
16+
* A single resource delegation entry
17+
*/
18+
export const DelegationEntryCodec = t.type({
19+
/** On-chain address that will receive the delegated resources */
20+
receiverAddress: t.string,
21+
/** Amount of TRX (in SUN) to stake for the delegation */
22+
amount: t.string,
23+
/** Resource type to delegate (e.g. 'ENERGY', 'BANDWIDTH') */
24+
resource: t.string,
25+
});
26+
27+
/**
28+
* Request body for delegating resources to multiple receiver addresses.
29+
* Each delegation entry triggers a separate on-chain staking transaction
30+
* from the wallet's root address to the receiver address.
31+
*
32+
* Signing behaviour by wallet type:
33+
* - Hot (non-TSS) → signed locally with walletPassphrase and submitted
34+
* - Custodial non-TSS → sent for BitGo approval via initiateTransaction
35+
* - TSS (any) → build response contains txRequestId; signed by TSS service
36+
*/
37+
export const DelegateResourcesRequestBody = {
38+
/** Delegation entries — one on-chain transaction is built per entry */
39+
delegations: t.array(DelegationEntryCodec),
40+
41+
/** Wallet passphrase to decrypt the user key (hot wallets) */
42+
walletPassphrase: optional(t.string),
43+
/** Extended private key (alternative to walletPassphrase) */
44+
xprv: optional(t.string),
45+
/** One-time password for 2FA */
46+
otp: optional(t.string),
47+
48+
/** API version for TSS transaction request response ('lite' or 'full') */
49+
apiVersion: optional(t.union([t.literal('lite'), t.literal('full')])),
50+
} as const;
51+
52+
export const DelegationFailureEntry = t.type({
53+
/** Human-readable error message */
54+
message: t.string,
55+
/** Receiver address that failed, if available */
56+
receiverAddress: t.union([t.string, t.undefined]),
57+
});
58+
59+
/**
60+
* Response for the delegate resources operation.
61+
* Returns arrays of successful and failed delegation transactions.
62+
*/
63+
export const DelegateResourcesResponse = t.type({
64+
/** Successfully sent delegation transactions */
65+
success: t.array(t.unknown),
66+
/** Errors from failed delegation transactions */
67+
failure: t.array(DelegationFailureEntry),
68+
});
69+
70+
/**
71+
* Response for partial success or failure cases (202/400).
72+
* Includes both the transaction results and error metadata.
73+
*/
74+
export const DelegateResourcesErrorResponse = t.intersection([DelegateResourcesResponse, BitgoExpressError]);
75+
76+
/**
77+
* Bulk Resource Delegation
78+
*
79+
* Delegates resources (ENERGY or BANDWIDTH) from a wallet's root address to one or more
80+
* receiver addresses. Each delegation entry produces a separate on-chain staking transaction.
81+
* This is the resource-delegation analogue of the consolidateAccount endpoint.
82+
*
83+
* Supported coins: TRON (trx, ttrx) and any future coins that support resource delegation.
84+
*
85+
* The API may return partial success (status 202) if some delegations succeed but others fail.
86+
*
87+
* @operationId express.v2.wallet.delegateresources
88+
* @tag express
89+
*/
90+
export const PostDelegateResources = httpRoute({
91+
path: '/api/v2/{coin}/wallet/{id}/delegateResources',
92+
method: 'POST',
93+
request: httpRequest({
94+
params: DelegateResourcesParams,
95+
body: DelegateResourcesRequestBody,
96+
}),
97+
response: {
98+
/** All delegations succeeded */
99+
200: DelegateResourcesResponse,
100+
/** Partial success — some delegations succeeded, others failed */
101+
202: DelegateResourcesErrorResponse,
102+
/** All delegations failed */
103+
400: DelegateResourcesErrorResponse,
104+
},
105+
});

modules/sdk-coin-trx/src/trx.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,11 @@ export class Trx extends BaseCoin {
225225
return true;
226226
}
227227

228+
/** @inheritDoc */
229+
supportsResourceDelegation(): boolean {
230+
return true;
231+
}
232+
228233
/**
229234
* Checks if this is a valid base58
230235
* @param address

modules/sdk-core/src/bitgo/baseCoin/baseCoin.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,10 @@ export abstract class BaseCoin implements IBaseCoin {
173173
return false;
174174
}
175175

176+
supportsResourceDelegation(): boolean {
177+
return false;
178+
}
179+
176180
/**
177181
* Gets config for how token enablements work for this coin
178182
* @returns

modules/sdk-core/src/bitgo/baseCoin/iBaseCoin.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,7 @@ export interface IBaseCoin {
575575
sweepWithSendMany(): boolean;
576576
transactionDataAllowed(): boolean;
577577
allowsAccountConsolidations(): boolean;
578+
supportsResourceDelegation(): boolean;
578579
getTokenEnablementConfig(): TokenEnablementConfig;
579580
supportsTss(): boolean;
580581
supportsMultisig(): boolean;

modules/sdk-core/src/bitgo/wallet/iWallet.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,19 @@ export interface BuildConsolidationTransactionOptions extends PrebuildTransactio
6363
consolidateAddresses?: string[];
6464
}
6565

66+
export interface ResourceDelegationEntry {
67+
receiverAddress: string;
68+
amount: string;
69+
/** Resource type to delegate (e.g. 'ENERGY', 'BANDWIDTH'). */
70+
resource: string;
71+
}
72+
73+
export interface BuildResourceDelegationTransactionOptions
74+
extends PrebuildTransactionOptions,
75+
WalletSignTransactionOptions {
76+
delegations: ResourceDelegationEntry[];
77+
}
78+
6679
export interface BuildTokenEnablementOptions extends PrebuildTransactionOptions {
6780
enableTokens: TokenEnablement[];
6881
}
@@ -251,6 +264,7 @@ export interface PrebuildTransactionResult extends TransactionPrebuild {
251264
pendingApprovalId?: string;
252265
reqId?: IRequestTracer;
253266
payload?: string;
267+
stakingParams?: unknown;
254268
}
255269

256270
export interface CustomSigningFunction {
@@ -1096,6 +1110,12 @@ export interface IWallet {
10961110
buildAccountConsolidations(params?: BuildConsolidationTransactionOptions): Promise<PrebuildTransactionResult[]>;
10971111
sendAccountConsolidation(params?: PrebuildAndSignTransactionOptions): Promise<any>;
10981112
sendAccountConsolidations(params?: BuildConsolidationTransactionOptions): Promise<any>;
1113+
buildResourceDelegations(params: BuildResourceDelegationTransactionOptions): Promise<PrebuildTransactionResult[]>;
1114+
sendResourceDelegation(params: PrebuildAndSignTransactionOptions): Promise<any>;
1115+
sendResourceDelegations(params: BuildResourceDelegationTransactionOptions): Promise<{
1116+
success: any[];
1117+
failure: { message: string; receiverAddress?: string }[];
1118+
}>;
10991119
buildTokenEnablements(params?: BuildTokenEnablementOptions): Promise<PrebuildTransactionResult[]>;
11001120
sendTokenEnablement(params?: PrebuildAndSignTransactionOptions): Promise<any>;
11011121
sendTokenEnablements(params?: BuildTokenEnablementOptions): Promise<any>;

0 commit comments

Comments
 (0)