Skip to content
Merged
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-vet/src/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export const VET_BLOCK_ID_LENGTH = 64;

export const TRANSFER_TOKEN_METHOD_ID = '0xa9059cbb';
export const STAKING_METHOD_ID = '0xd8da3bbf';
export const STAKE_CLAUSE_METHOD_ID = '0x604f2177';
export const EXIT_DELEGATION_METHOD_ID = '0x69e79b7d';
export const BURN_NFT_METHOD_ID = '0x2e17de78';
export const TRANSFER_NFT_METHOD_ID = '0x23b872dd';
Expand Down
2 changes: 2 additions & 0 deletions modules/sdk-coin-vet/src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export { AddressInitializationTransaction } from './transaction/addressInitializ
export { FlushTokenTransaction } from './transaction/flushTokenTransaction';
export { TokenTransaction } from './transaction/tokenTransaction';
export { StakingTransaction } from './transaction/stakingTransaction';
export { StakeClauseTransaction } from './transaction/stakeClauseTransaction';
export { ExitDelegationTransaction } from './transaction/exitDelegation';
export { BurnNftTransaction } from './transaction/burnNftTransaction';
export { ClaimRewardsTransaction } from './transaction/claimRewards';
Expand All @@ -17,6 +18,7 @@ export { TransferBuilder } from './transactionBuilder/transferBuilder';
export { AddressInitializationBuilder } from './transactionBuilder/addressInitializationBuilder';
export { FlushTokenTransactionBuilder } from './transactionBuilder/flushTokenTransactionBuilder';
export { StakingBuilder } from './transactionBuilder/stakingBuilder';
export { StakeClauseTxnBuilder } from './transactionBuilder/stakeClauseTxnBuilder';
export { NFTTransactionBuilder } from './transactionBuilder/nftTransactionBuilder';
export { BurnNftBuilder } from './transactionBuilder/burnNftBuilder';
export { ExitDelegationBuilder } from './transactionBuilder/exitDelegationBuilder';
Expand Down
181 changes: 181 additions & 0 deletions modules/sdk-coin-vet/src/lib/transaction/stakeClauseTransaction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import { TransactionType, InvalidTransactionError } from '@bitgo/sdk-core';
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { Transaction as VetTransaction, Secp256k1 } from '@vechain/sdk-core';
import { Transaction } from './transaction';
import { VetTransactionData } from '../iface';
import EthereumAbi from 'ethereumjs-abi';
import utils from '../utils';
import BigNumber from 'bignumber.js';
import { addHexPrefix } from 'ethereumjs-util';

export class StakeClauseTransaction extends Transaction {
private _stakingContractAddress: string;
private _levelId: number;
private _amountToStake: string;

constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
this._type = TransactionType.StakingActivate;
}

get stakingContractAddress(): string {
return this._stakingContractAddress;
}

set stakingContractAddress(address: string) {
this._stakingContractAddress = address;
}

get levelId(): number {
return this._levelId;
}

set levelId(levelId: number) {
this._levelId = levelId;
}

get amountToStake(): string {
return this._amountToStake;
}

set amountToStake(amount: string) {
this._amountToStake = amount;
}

buildClauses(): void {
if (!this.stakingContractAddress) {
throw new Error('Staking contract address is not set');
}

utils.validateStakingContractAddress(this.stakingContractAddress, this._coinConfig);

if (this.levelId === undefined || this.levelId === null) {
throw new Error('Level ID is not set');
}

if (!this.amountToStake) {
throw new Error('Amount to stake is not set');
}

const data = this.getStakingData(this.levelId);
this._transactionData = data;

// Create the clause for staking
this._clauses = [
{
to: this.stakingContractAddress,
value: this.amountToStake,
data: this._transactionData,
},
];

// Set recipients based on the clauses
this._recipients = [
{
address: this.stakingContractAddress,
amount: this.amountToStake,
},
];
}
/**
* Encodes staking transaction data using ethereumjs-abi for stake method
*
* @param {number} levelId - The level ID for staking
* @returns {string} - The encoded transaction data
*/
getStakingData(levelId: number): string {
const methodName = 'stake';
const types = ['uint8'];
const params = [levelId];

const method = EthereumAbi.methodID(methodName, types);
const args = EthereumAbi.rawEncode(types, params);

return addHexPrefix(Buffer.concat([method, args]).toString('hex'));
}

toJson(): VetTransactionData {
const json: VetTransactionData = {
id: this.id,
chainTag: this.chainTag,
blockRef: this.blockRef,
expiration: this.expiration,
gasPriceCoef: this.gasPriceCoef,
gas: this.gas,
dependsOn: this.dependsOn,
nonce: this.nonce,
data: this.transactionData,
value: this.amountToStake,
sender: this.sender,
to: this.stakingContractAddress,
stakingContractAddress: this.stakingContractAddress,
amountToStake: this.amountToStake,
nftTokenId: this.levelId,
};

return json;
}

fromDeserializedSignedTransaction(signedTx: VetTransaction): void {
try {
if (!signedTx || !signedTx.body) {
throw new InvalidTransactionError('Invalid transaction: missing transaction body');
}

// Store the raw transaction
this.rawTransaction = signedTx;

// Set transaction body properties
const body = signedTx.body;
this.chainTag = typeof body.chainTag === 'number' ? body.chainTag : 0;
this.blockRef = body.blockRef || '0x0';
this.expiration = typeof body.expiration === 'number' ? body.expiration : 64;
this.clauses = body.clauses || [];
this.gasPriceCoef = typeof body.gasPriceCoef === 'number' ? body.gasPriceCoef : 128;
this.gas = typeof body.gas === 'number' ? body.gas : Number(body.gas) || 0;
this.dependsOn = body.dependsOn || null;
this.nonce = String(body.nonce);

// Set staking-specific properties
if (body.clauses.length > 0) {
const clause = body.clauses[0];
if (clause.to) {
this.stakingContractAddress = clause.to;
}
if (clause.value) {
this.amountToStake = String(clause.value);
}
if (clause.data) {
this.transactionData = clause.data;
const decoded = utils.decodeStakeClauseData(clause.data);
this.levelId = decoded.levelId;
}
}

// Set recipients from clauses
this.recipients = body.clauses.map((clause) => ({
address: (clause.to || '0x0').toString().toLowerCase(),
amount: new BigNumber(clause.value || 0).toString(),
}));
this.loadInputsAndOutputs();

// Set sender address
if (signedTx.signature && signedTx.origin) {
this.sender = signedTx.origin.toString().toLowerCase();
}

// Set signatures if present
if (signedTx.signature) {
// First signature is sender's signature
this.senderSignature = Buffer.from(signedTx.signature.slice(0, Secp256k1.SIGNATURE_LENGTH));

// If there's additional signature data, it's the fee payer's signature
if (signedTx.signature.length > Secp256k1.SIGNATURE_LENGTH) {
this.feePayerSignature = Buffer.from(signedTx.signature.slice(Secp256k1.SIGNATURE_LENGTH));
}
}
} catch (e) {
throw new InvalidTransactionError(`Failed to deserialize transaction: ${e.message}`);
}
}
}
1 change: 1 addition & 0 deletions modules/sdk-coin-vet/src/lib/transaction/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,7 @@ export class Transaction extends BaseTransaction {
this.type === TransactionType.SendToken ||
this.type === TransactionType.SendNFT ||
this.type === TransactionType.ContractCall ||
this.type === TransactionType.StakingActivate ||
this.type === TransactionType.StakingUnlock ||
this.type === TransactionType.StakingWithdraw ||
this.type === TransactionType.StakingClaim
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import assert from 'assert';
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { TransactionType } from '@bitgo/sdk-core';
import { TransactionClause } from '@vechain/sdk-core';

import { TransactionBuilder } from './transactionBuilder';
import { Transaction } from '../transaction/transaction';
import { StakeClauseTransaction } from '../transaction/stakeClauseTransaction';
import utils from '../utils';

export class StakeClauseTxnBuilder extends TransactionBuilder {
/**
* Creates a new StakingBuilder instance.
*
* @param {Readonly<CoinConfig>} _coinConfig - The coin configuration object
*/
constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
this._transaction = new StakeClauseTransaction(_coinConfig);
}

/**
* Initializes the builder with an existing StakingTransaction.
*
* @param {StakingTransaction} tx - The transaction to initialize the builder with
*/
initBuilder(tx: StakeClauseTransaction): void {
this._transaction = tx;
}

/**
* Gets the staking transaction instance.
*
* @returns {StakingTransaction} The staking transaction
*/
get stakingTransaction(): StakeClauseTransaction {
return this._transaction as StakeClauseTransaction;
}

/**
* Gets the transaction type for staking.
*
* @returns {TransactionType} The transaction type
*/
protected get transactionType(): TransactionType {
return TransactionType.StakingActivate;
}

/**
* Validates the transaction clauses for staking transaction.
* @param {TransactionClause[]} clauses - The transaction clauses to validate.
* @returns {boolean} - Returns true if the clauses are valid, false otherwise.
*/
protected isValidTransactionClauses(clauses: TransactionClause[]): boolean {
try {
if (!clauses || !Array.isArray(clauses) || clauses.length === 0) {
return false;
}

const clause = clauses[0];

if (!clause.to || !utils.isValidAddress(clause.to)) {
return false;
}

// For staking transactions, value must be greater than 0
if (!clause.value || clause.value === '0x0' || clause.value === '0') {
return false;
}

return true;
} catch (e) {
return false;
}
}

/**
* Sets the staking contract address for this staking tx.
* The address must be explicitly provided to ensure the correct contract is used.
*
* @param {string} address - The staking contract address (required)
* @returns {StakingBuilder} This transaction builder
* @throws {Error} If no address is provided
*/
stakingContractAddress(address: string): this {
if (!address) {
throw new Error('Staking contract address is required');
}
this.validateAddress({ address });
this.stakingTransaction.stakingContractAddress = address;
return this;
}

/**
* Sets the level ID for this staking tx.
*
* @param {number} levelId - The level ID for staking
* @returns {StakingBuilder} This transaction builder
*/
levelId(levelId: number): this {
this.stakingTransaction.levelId = levelId;
return this;
}

/**
* Sets the amount to stake for this staking tx (VET amount being sent).
*
* @param {string} amount - The amount to stake in wei
* @returns {StakingBuilder} This transaction builder
*/
amountToStake(amount: string): this {
this.stakingTransaction.amountToStake = amount;
return this;
}

/**
* Sets the transaction data for this staking tx.
*
* @param {string} data - The transaction data
* @returns {StakingBuilder} This transaction builder
*/
transactionData(data: string): this {
this.stakingTransaction.transactionData = data;
return this;
}

/** @inheritdoc */
validateTransaction(transaction?: StakeClauseTransaction): void {
if (!transaction) {
throw new Error('transaction not defined');
}
assert(transaction.stakingContractAddress, 'Staking contract address is required');
assert(transaction.amountToStake, 'Amount to stake is required');

// Validate amount is a valid number string
if (transaction.amountToStake) {
try {
const bn = new (require('bignumber.js'))(transaction.amountToStake);
if (!bn.isFinite() || bn.isNaN()) {
throw new Error('Invalid character');
}
} catch (e) {
throw new Error('Invalid character');
}
}

assert(transaction.levelId, 'Level ID is required');
this.validateAddress({ address: transaction.stakingContractAddress });
}

/** @inheritdoc */
protected async buildImplementation(): Promise<Transaction> {
this.transaction.type = this.transactionType;
await this.stakingTransaction.build();
return this.transaction;
}
}
Loading