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
92 changes: 92 additions & 0 deletions modules/express/src/clientRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1050,6 +1050,90 @@ export async function handleV2ResourceDelegations(
});
}

/**
* Shared handler for bulk resource management (delegation / undelegation).
* Builds, signs, and sends one on-chain transaction per entry.
*/
async function handleV2ResourceManagement(
type: 'delegateResource' | 'undelegateResource',
req:
| ExpressApiRouteRequest<'express.v2.wallet.delegateresources', 'post'>
| ExpressApiRouteRequest<'express.v2.wallet.undelegateresources', 'post'>
) {
const bitgo = req.bitgo;
const coin = bitgo.coin(req.decoded.coin);

if (type === 'delegateResource') {
const decoded = (req as ExpressApiRouteRequest<'express.v2.wallet.delegateresources', 'post'>).decoded;
if (!Array.isArray(decoded.delegations) || decoded.delegations.length === 0) {
throw new Error('delegations must be a non-empty array');
}
} else {
const decoded = (req as ExpressApiRouteRequest<'express.v2.wallet.undelegateresources', 'post'>).decoded;
if (!Array.isArray(decoded.undelegations) || decoded.undelegations.length === 0) {
throw new Error('undelegations must be a non-empty array');
}
}

if (!coin.supportsResourceDelegation()) {
throw new Error(`${coin.getFamily()} does not support resource delegation`);
}

const wallet = await coin.wallets().get({ id: req.decoded.id });

let result: any;
try {
const params = coin.supportsTss() ? createTSSSendParams(req, wallet) : createSendParams(req);
result =
type === 'delegateResource'
? await wallet.sendResourceDelegations(params)
: await wallet.sendResourceUndelegations(params);
} catch (err) {
// Surface unexpected errors as 400 rather than 500
(err as any).status = 400;
throw err;
}

// Handle partial success / failure
if (result.failure.length > 0) {
let msg = '';
let status = 202;

if (result.success.length > 0) {
msg = `Transactions failed: ${result.failure.length} and succeeded: ${result.success.length}`;
} else {
status = 400;
msg = `All transactions failed`;
}

throw apiResponse(status, result, msg);
}

return result;
}

/**
* Handle bulk resource delegation (e.g. TRX ENERGY/BANDWIDTH delegation).
* Builds, signs, and sends one on-chain delegation transaction per entry in req.body.delegations.
* @param req
*/
export async function handleV2DelegateResources(
req: ExpressApiRouteRequest<'express.v2.wallet.delegateresources', 'post'>
) {
return handleV2ResourceManagement('delegateResource', req);
}

/**
* Handle bulk resource undelegation (e.g. TRX ENERGY/BANDWIDTH undelegation).
* Builds, signs, and sends one on-chain undelegation transaction per entry in req.body.undelegations.
* @param req
*/
export async function handleV2UndelegateResources(
req: ExpressApiRouteRequest<'express.v2.wallet.undelegateresources', 'post'>
) {
return handleV2ResourceManagement('undelegateResource', req);
}

/**
* payload meant for prebuildAndSignTransaction() in sdk-core which
* validates the payload and makes the appropriate request to WP to
Expand Down Expand Up @@ -1830,6 +1914,14 @@ export function setupAPIRoutes(app: express.Application, config: Config): void {
prepareBitGo(config),
typedPromiseWrapper(handleV2ResourceDelegations),
]);
router.post('express.v2.wallet.delegateresources', [
prepareBitGo(config),
typedPromiseWrapper(handleV2DelegateResources),
]);
router.post('express.v2.wallet.undelegateresources', [
prepareBitGo(config),
typedPromiseWrapper(handleV2UndelegateResources),
]);

// Miscellaneous
router.post('express.canonicaladdress', [prepareBitGo(config), typedPromiseWrapper(handleCanonicalAddress)]);
Expand Down
18 changes: 18 additions & 0 deletions modules/express/src/typedRoutes/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ import { PostWalletAccelerateTx } from './v2/walletAccelerateTx';
import { PostIsWalletAddress } from './v2/isWalletAddress';
import { GetAccountResources } from './v2/accountResources';
import { GetResourceDelegations } from './v2/resourceDelegations';
import { PostDelegateResources } from './v2/delegateResources';
import { PostUndelegateResources } from './v2/undelegateResources';

// Too large types can cause the following error
//
Expand Down Expand Up @@ -184,6 +186,18 @@ export const ExpressV2WalletConsolidateAccountApiSpec = apiSpec({
},
});

export const ExpressV2WalletDelegateResourcesApiSpec = apiSpec({
'express.v2.wallet.delegateresources': {
post: PostDelegateResources,
},
});

export const ExpressV2WalletUndelegateResourcesApiSpec = apiSpec({
'express.v2.wallet.undelegateresources': {
post: PostUndelegateResources,
},
});

export const ExpressWalletFanoutUnspentsApiSpec = apiSpec({
'express.v1.wallet.fanoutunspents': {
put: PutFanoutUnspents,
Expand Down Expand Up @@ -389,6 +403,8 @@ export type ExpressApi = typeof ExpressPingApiSpec &
typeof ExpressV2WalletAccelerateTxApiSpec &
typeof ExpressV2WalletAccountResourcesApiSpec &
typeof ExpressV2WalletResourceDelegationsApiSpec &
typeof ExpressV2WalletDelegateResourcesApiSpec &
typeof ExpressV2WalletUndelegateResourcesApiSpec &
typeof ExpressWalletManagementApiSpec;

export const ExpressApi: ExpressApi = {
Expand Down Expand Up @@ -432,6 +448,8 @@ export const ExpressApi: ExpressApi = {
...ExpressV2WalletAccelerateTxApiSpec,
...ExpressV2WalletAccountResourcesApiSpec,
...ExpressV2WalletResourceDelegationsApiSpec,
...ExpressV2WalletDelegateResourcesApiSpec,
...ExpressV2WalletUndelegateResourcesApiSpec,
...ExpressWalletManagementApiSpec,
};

Expand Down
105 changes: 105 additions & 0 deletions modules/express/src/typedRoutes/api/v2/delegateResources.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import * as t from 'io-ts';
import { httpRoute, httpRequest, optional } from '@api-ts/io-ts-http';
import { BitgoExpressError } from '../../schemas/error';

/**
* Path parameters for the delegate resources endpoint
*/
export const DelegateResourcesParams = {
/** Coin identifier (e.g., 'trx', 'ttrx') */
coin: t.string,
/** Wallet ID */
id: t.string,
} as const;

/**
* A single resource delegation entry
*/
export const DelegationEntryCodec = t.type({
/** On-chain address that will receive the delegated resources */
receiverAddress: t.string,
/** Amount of TRX (in SUN) to stake for the delegation */
amount: t.string,
/** Resource type to delegate (e.g. 'ENERGY', 'BANDWIDTH') */
resource: t.string,
});

/**
* Request body for delegating resources to multiple receiver addresses.
* Each delegation entry triggers a separate on-chain staking transaction
* from the wallet's root address to the receiver address.
*
* Signing behaviour by wallet type:
* - Hot (non-TSS) → signed locally with walletPassphrase and submitted
* - Custodial non-TSS → sent for BitGo approval via initiateTransaction
* - TSS (any) → build response contains txRequestId; signed by TSS service
*/
export const DelegateResourcesRequestBody = {
/** Delegation entries — one on-chain transaction is built per entry */
delegations: t.array(DelegationEntryCodec),

/** Wallet passphrase to decrypt the user key (hot wallets) */
walletPassphrase: optional(t.string),
/** Extended private key (alternative to walletPassphrase) */
xprv: optional(t.string),
/** One-time password for 2FA */
otp: optional(t.string),

/** API version for TSS transaction request response ('lite' or 'full') */
apiVersion: optional(t.union([t.literal('lite'), t.literal('full')])),
} as const;

export const DelegationFailureEntry = t.type({
/** Human-readable error message */
message: t.string,
/** Receiver address that failed, if available */
receiverAddress: t.union([t.string, t.undefined]),
});

/**
* Response for the delegate resources operation.
* Returns arrays of successful and failed delegation transactions.
*/
export const DelegateResourcesResponse = t.type({
/** Successfully sent delegation transactions */
success: t.array(t.unknown),
/** Errors from failed delegation transactions */
failure: t.array(DelegationFailureEntry),
});

/**
* Response for partial success or failure cases (202/400).
* Includes both the transaction results and error metadata.
*/
export const DelegateResourcesErrorResponse = t.intersection([DelegateResourcesResponse, BitgoExpressError]);

/**
* Bulk Resource Delegation
*
* Delegates resources (ENERGY or BANDWIDTH) from a wallet's root address to one or more
* receiver addresses. Each delegation entry produces a separate on-chain staking transaction.
* This is the resource-delegation analogue of the consolidateAccount endpoint.
*
* Supported coins: TRON (trx, ttrx) and any future coins that support resource delegation.
*
* The API may return partial success (status 202) if some delegations succeed but others fail.
*
* @operationId express.v2.wallet.delegateresources
* @tag express
*/
export const PostDelegateResources = httpRoute({
path: '/api/v2/{coin}/wallet/{id}/delegateResources',
method: 'POST',
request: httpRequest({
params: DelegateResourcesParams,
body: DelegateResourcesRequestBody,
}),
response: {
/** All delegations succeeded */
200: DelegateResourcesResponse,
/** Partial success — some delegations succeeded, others failed */
202: DelegateResourcesErrorResponse,
/** All delegations failed */
400: DelegateResourcesErrorResponse,
},
});
75 changes: 75 additions & 0 deletions modules/express/src/typedRoutes/api/v2/undelegateResources.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import * as t from 'io-ts';
import { httpRoute, httpRequest, optional } from '@api-ts/io-ts-http';
import { BitgoExpressError } from '../../schemas/error';
import { DelegateResourcesParams, DelegationEntryCodec, DelegationFailureEntry } from './delegateResources';

/**
* Request body for undelegating resources from multiple receiver addresses.
* Each undelegation entry triggers a separate on-chain transaction that reclaims
* previously delegated resources back to the wallet's root address.
*
* Signing behaviour by wallet type:
* - Hot (non-TSS) → signed locally with walletPassphrase and submitted
* - Custodial non-TSS → sent for BitGo approval via initiateTransaction
* - TSS (any) → build response contains txRequestId; signed by TSS service
*/
export const UndelegateResourcesRequestBody = {
/** Undelegation entries — one on-chain transaction is built per entry */
undelegations: t.array(DelegationEntryCodec),

/** Wallet passphrase to decrypt the user key (hot wallets) */
walletPassphrase: optional(t.string),
/** Extended private key (alternative to walletPassphrase) */
xprv: optional(t.string),
/** One-time password for 2FA */
otp: optional(t.string),

/** API version for TSS transaction request response ('lite' or 'full') */
apiVersion: optional(t.union([t.literal('lite'), t.literal('full')])),
} as const;

/**
* Response for the undelegate resources operation.
* Returns arrays of successful and failed undelegation transactions.
*/
export const UndelegateResourcesResponse = t.type({
/** Successfully sent undelegation transactions */
success: t.array(t.unknown),
/** Errors from failed undelegation transactions */
failure: t.array(DelegationFailureEntry),
});

/**
* Response for partial success or failure cases (202/400).
*/
export const UndelegateResourcesErrorResponse = t.intersection([UndelegateResourcesResponse, BitgoExpressError]);

/**
* Bulk Resource Undelegation
*
* Reclaims delegated resources (ENERGY or BANDWIDTH) back to a wallet's root address
* from one or more receiver addresses. Each entry produces a separate on-chain transaction.
*
* Supported coins: TRON (trx, ttrx) and any future coins that support resource delegation.
*
* The API may return partial success (status 202) if some undelegations succeed but others fail.
*
* @operationId express.v2.wallet.undelegateresources
* @tag express
*/
export const PostUndelegateResources = httpRoute({
path: '/api/v2/{coin}/wallet/{id}/undelegateResources',
method: 'POST',
request: httpRequest({
params: DelegateResourcesParams,
body: UndelegateResourcesRequestBody,
}),
response: {
/** All undelegations succeeded */
200: UndelegateResourcesResponse,
/** Partial success — some undelegations succeeded, others failed */
202: UndelegateResourcesErrorResponse,
/** All undelegations failed */
400: UndelegateResourcesErrorResponse,
},
});
5 changes: 5 additions & 0 deletions modules/sdk-coin-trx/src/trx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,11 @@ export class Trx extends BaseCoin {
return true;
}

/** @inheritDoc */
supportsResourceDelegation(): boolean {
return true;
}

/**
* Checks if this is a valid base58
* @param address
Expand Down
4 changes: 4 additions & 0 deletions modules/sdk-core/src/bitgo/baseCoin/baseCoin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,10 @@ export abstract class BaseCoin implements IBaseCoin {
return false;
}

supportsResourceDelegation(): boolean {
return false;
}

/**
* Gets config for how token enablements work for this coin
* @returns
Expand Down
1 change: 1 addition & 0 deletions modules/sdk-core/src/bitgo/baseCoin/iBaseCoin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,7 @@ export interface IBaseCoin {
sweepWithSendMany(): boolean;
transactionDataAllowed(): boolean;
allowsAccountConsolidations(): boolean;
supportsResourceDelegation(): boolean;
getTokenEnablementConfig(): TokenEnablementConfig;
supportsTss(): boolean;
supportsMultisig(): boolean;
Expand Down
Loading
Loading