Skip to content

Adding unfreeze and withdraw for tron unstaking #6013

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
8 changes: 8 additions & 0 deletions modules/sdk-coin-trx/src/lib/enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ export enum ContractType {
* This is the contract for voting for witnesses
*/
VoteWitness,
/**
* This is the contract for unfreezing balances
*/
UnfreezeBalanceV2,
/**
* This is the contract for withdrawing expired unfrozen balances
*/
WithdrawExpireUnfreeze,
}

export enum PermissionType {
Expand Down
73 changes: 72 additions & 1 deletion modules/sdk-coin-trx/src/lib/iface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ export interface RawData {
| AccountPermissionUpdateContract[]
| TriggerSmartContract[]
| FreezeBalanceV2Contract[]
| VoteWitnessContract[];
| VoteWitnessContract[]
| UnfreezeBalanceV2Contract[]
| WithdrawExpireUnfreezeContract[];
}

export interface Value {
Expand Down Expand Up @@ -132,6 +134,15 @@ export interface FreezeBalanceValueFields {
owner_address: string;
}

/**
* Unfreeze transaction value fields
*/
export interface UnfreezeBalanceValueFields {
resource: string;
unfreeze_balance: number;
owner_address: string;
}

/**
* Freeze balance contract value interface
*/
Expand All @@ -148,6 +159,22 @@ export interface FreezeBalanceV2Contract {
type?: string;
}

/**
* Unfreeze balance contract value interface
*/
export interface UnfreezeBalanceValue {
type_url?: string;
value: UnfreezeBalanceValueFields;
}

/**
* Unfreeze balance v2 contract interface
*/
export interface UnfreezeBalanceV2Contract {
parameter: UnfreezeBalanceValue;
type?: string;
}

/**
* Freeze balance contract parameter interface
*/
Expand All @@ -161,6 +188,39 @@ export interface FreezeBalanceContractParameter {
};
}

/**
* Withdraw transaction value fields
*/
export interface WithdrawExpireUnfreezeValueFields {
owner_address: string;
}

/**
* Withdraw balance contract value interface
*/
export interface WithdrawExpireUnfreezeValue {
type_url?: string;
value: WithdrawExpireUnfreezeValueFields;
}

/**
* Withdraw expire unfreeze contract interface
*/
export interface WithdrawExpireUnfreezeContract {
parameter: WithdrawExpireUnfreezeValue;
type?: string;
}

export interface UnfreezeBalanceContractParameter {
parameter: {
value: {
resource: TronResource;
unfreeze_balance: number;
owner_address: string;
};
};
}

/**
* Freeze balance contract decoded interface
*/
Expand Down Expand Up @@ -227,3 +287,14 @@ export interface VoteWitnessContractParameter {
};
};
}

/**
* Withdraw expire unfreeze contract parameter interface
*/
export interface WithdrawExpireUnfreezeContractParameter {
parameter: {
value: {
owner_address: string;
};
};
}
4 changes: 4 additions & 0 deletions modules/sdk-coin-trx/src/lib/resourceTypes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export enum TronResource {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be used in freeze PR as well

BANDWIDTH = 'BANDWIDTH',
ENERGY = 'ENERGY',
}
26 changes: 26 additions & 0 deletions modules/sdk-coin-trx/src/lib/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import {
TransferContract,
TriggerSmartContract,
VoteWitnessContract,
UnfreezeBalanceV2Contract,
WithdrawExpireUnfreezeContract,
} from './iface';

/**
Expand Down Expand Up @@ -162,6 +164,30 @@ export class Transaction extends BaseTransaction {
value: totalVoteCount.toString(),
};
break;
case ContractType.UnfreezeBalanceV2:
this._type = TransactionType.StakingUnlock;
const unfreezeValues = (rawData.contract[0] as UnfreezeBalanceV2Contract).parameter.value;
output = {
address: unfreezeValues.owner_address,
value: unfreezeValues.unfreeze_balance.toString(),
};
input = {
address: unfreezeValues.owner_address,
value: unfreezeValues.unfreeze_balance.toString(),
};
break;
case ContractType.WithdrawExpireUnfreeze:
this._type = TransactionType.StakingWithdraw;
const withdrawValues = (rawData.contract[0] as WithdrawExpireUnfreezeContract).parameter.value;
output = {
address: withdrawValues.owner_address,
value: '0', // no value field
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just trying to understand, why this is 0 in StakingWithdraw type?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just set as a placeholder as we don't provide any explicit value for the amount to be withdrawn

};
input = {
address: withdrawValues.owner_address,
value: '0',
};
break;
default:
throw new ParseTransactionError('Unsupported contract type');
}
Expand Down
98 changes: 98 additions & 0 deletions modules/sdk-coin-trx/src/lib/unfreezeBalanceTxBuilder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { InvalidTransactionError, TransactionType } from '@bitgo/sdk-core';
import { TransactionBuilder } from './transactionBuilder';
import { Transaction } from './transaction';
import { TransactionReceipt } from './iface';
import { TronResource } from './resourceTypes';

interface RawUnfreezeBalanceContract {
parameter: {
value: {
resource?: string;
unfreeze_balance?: number;
owner_address?: string;
};
};
type: string;
}

export class UnfreezeBalanceTxBuilder extends TransactionBuilder {
/** @inheritdoc */
protected get transactionType(): TransactionType {
return TransactionType.StakingUnlock;
}

initBuilder(rawTransaction: TransactionReceipt | string): void {
this.transaction = this.fromImplementation(rawTransaction);
this.transaction.setTransactionType(this.transactionType);
}

validateTransaction(transaction: Transaction | TransactionReceipt): void {
if (transaction && typeof (transaction as Transaction).toJson === 'function') {
super.validateTransaction(transaction as Transaction);
const rawTx = (transaction as Transaction).toJson();
this.validateUnfreezeTransaction(rawTx);
} else {
this.validateUnfreezeTransaction(transaction as TransactionReceipt);
}
}

/**
* Validates if the transaction is a valid unfreeze transaction
* @param {TransactionReceipt} transaction - The transaction to validate
* @throws {InvalidTransactionError} when the transaction is invalid
*/
private validateUnfreezeTransaction(transaction: TransactionReceipt): void {
if (!transaction?.raw_data?.contract?.length) {
throw new InvalidTransactionError('Invalid transaction: missing or empty contract array');
}

const contract = transaction.raw_data.contract[0] as RawUnfreezeBalanceContract;

// Validate contract type
if (contract.type !== 'UnfreezeBalanceV2Contract') {
throw new InvalidTransactionError(
`Invalid unfreeze transaction: expected contract type UnfreezeBalanceV2Contract but got ${contract.type}`
);
}

// Validate parameter value
if (!contract?.parameter?.value) {
throw new InvalidTransactionError('Invalid unfreeze transaction: missing parameter value');
}

const value = contract.parameter.value;

// Validate resource
if (!Object.values(TronResource).includes(value.resource as TronResource)) {
throw new InvalidTransactionError(
`Invalid unfreeze transaction: resource must be ${Object.values(TronResource).join(' or ')}, got ${
value.resource
}`
);
}

// Validate unfreeze_balance
if (!value.unfreeze_balance || value.unfreeze_balance <= 0) {
throw new InvalidTransactionError('Invalid unfreeze transaction: unfreeze_balance must be positive');
}

// Validate owner_address
if (!value.owner_address || typeof value.owner_address !== 'string' || value.owner_address.length === 0) {
throw new InvalidTransactionError('Invalid unfreeze transaction: missing or invalid owner_address');
}
}

/**
* Check if the transaction is a valid unfreeze transaction
* @param {TransactionReceipt} transaction - Transaction to check
* @returns True if the transaction is a valid unfreeze transaction
*/
canSign(transaction: TransactionReceipt): boolean {
try {
this.validateUnfreezeTransaction(transaction);
return true;
} catch (e) {
return false;
}
}
}
107 changes: 106 additions & 1 deletion modules/sdk-coin-trx/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import {
VoteWitnessContractParameter,
FreezeContractDecoded,
VoteContractDecoded,
UnfreezeBalanceContractParameter,
WithdrawExpireUnfreezeContractParameter,
} from './iface';
import { ContractType, PermissionType, TronResource } from './enum';
import { AbiCoder, hexConcat } from 'ethers/lib/utils';
Expand Down Expand Up @@ -177,7 +179,9 @@ export function decodeTransaction(hexString: string): RawData {
| AccountPermissionUpdateContract[]
| TriggerSmartContract[]
| FreezeBalanceContractParameter[]
| VoteWitnessContractParameter[];
| VoteWitnessContractParameter[]
| UnfreezeBalanceContractParameter[]
| WithdrawExpireUnfreezeContractParameter[];

let contractType: ContractType;

Expand All @@ -203,6 +207,14 @@ export function decodeTransaction(hexString: string): RawData {
contractType = ContractType.VoteWitness;
contract = decodeVoteWitnessContract(rawTransaction.contracts[0].parameter.value);
break;
case 'type.googleapis.com/protocol.WithdrawExpireUnfreezeContract':
contract = decodeWithdrawExpireUnfreezeContract(rawTransaction.contracts[0].parameter.value);
contractType = ContractType.WithdrawExpireUnfreeze;
break;
case 'type.googleapis.com/protocol.UnfreezeBalanceV2Contract':
contract = decodeUnfreezeBalanceV2Contract(rawTransaction.contracts[0].parameter.value);
contractType = ContractType.UnfreezeBalanceV2;
break;
default:
throw new UtilsError('Unsupported contract type');
}
Expand Down Expand Up @@ -488,6 +500,99 @@ export function decodeVoteWitnessContract(base64: string): VoteWitnessContractPa
},
},
];
}

/**
* Deserialize the segment of the txHex corresponding with unfreeze balance contract
*
* @param {string} base64 - The base64 encoded contract data
* @returns {UnfreezeBalanceContractParameter[]} - Array containing the decoded unfreeze contract
*/
export function decodeUnfreezeBalanceV2Contract(base64: string): UnfreezeBalanceContractParameter[] {
interface UnfreezeContractDecoded {
ownerAddress?: string;
resource?: number;
unfrozenBalance?: string | number;
}

let unfreezeContract: UnfreezeContractDecoded;
try {
unfreezeContract = protocol.UnfreezeBalanceContract.decode(Buffer.from(base64, 'base64')).toJSON();
} catch (e) {
throw new UtilsError('There was an error decoding the unfreeze contract in the transaction.');
}

if (!unfreezeContract.ownerAddress) {
throw new UtilsError('Owner address does not exist in this unfreeze contract.');
}

if (unfreezeContract.resource === undefined) {
throw new UtilsError('Resource type does not exist in this unfreeze contract.');
}

if (unfreezeContract.unfrozenBalance === undefined) {
throw new UtilsError('Unfreeze balance does not exist in this unfreeze contract.');
}


// deserialize attributes
const owner_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(unfreezeContract.ownerAddress, 'base64').toString('hex'))
);

// Convert ResourceCode enum value to string resource name
const resourceValue = unfreezeContract.resource;
const resourceEnum = resourceValue === protocol.ResourceCode.BANDWIDTH ? TronResource.BANDWIDTH : TronResource.ENERGY;

return [
{
parameter: {
value: {
resource: resourceEnum,
unfreeze_balance: Number(unfreezeContract.unfrozenBalance),
owner_address,
},
},
},
];
}

/**
* Deserialize the segment of the txHex corresponding with withdraw expire unfreeze contract
*
* @param {string} base64 - The base64 encoded contract data
* @returns {WithdrawExpireUnfreezeContractParameter[]} - Array containing the decoded withdraw contract
*/
export function decodeWithdrawExpireUnfreezeContract(base64: string): WithdrawExpireUnfreezeContractParameter[] {
interface WithdrawContractDecoded {
ownerAddress?: string;
}

let withdrawContract: WithdrawContractDecoded;
try {
withdrawContract = protocol.WithdrawBalanceContract.decode(Buffer.from(base64, 'base64')).toJSON();
} catch (e) {
throw new UtilsError('There was an error decoding the withdraw contract in the transaction.');
}

if (!withdrawContract.ownerAddress) {
throw new UtilsError('Owner address does not exist in this withdraw contract.');
}

// deserialize attributes
const owner_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(withdrawContract.ownerAddress, 'base64').toString('hex'))
);

return [
{
parameter: {
value: {
owner_address,
},
},
},
];
}

/**
Expand Down
Loading
Loading