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
2 changes: 2 additions & 0 deletions modules/sdk-coin-vet/src/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
export const VET_TRANSACTION_ID_LENGTH = 64;
export const VET_ADDRESS_LENGTH = 40;
export const VET_BLOCK_ID_LENGTH = 64;
export const ZERO_VALUE_AMOUNT = '0';

export const TRANSFER_TOKEN_METHOD_ID = '0xa9059cbb';
export const STAKING_METHOD_ID = '0xd8da3bbf';
export const STAKE_CLAUSE_METHOD_ID = '0x604f2177';
export const DELEGATE_CLAUSE_METHOD_ID = '0x3207555d';
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 @@ -9,6 +9,7 @@ export { FlushTokenTransaction } from './transaction/flushTokenTransaction';
export { TokenTransaction } from './transaction/tokenTransaction';
export { StakingTransaction } from './transaction/stakingTransaction';
export { StakeClauseTransaction } from './transaction/stakeClauseTransaction';
export { DelegateClauseTransaction } from './transaction/delegateClauseTransaction';
export { ExitDelegationTransaction } from './transaction/exitDelegation';
export { BurnNftTransaction } from './transaction/burnNftTransaction';
export { ClaimRewardsTransaction } from './transaction/claimRewards';
Expand All @@ -19,6 +20,7 @@ export { AddressInitializationBuilder } from './transactionBuilder/addressInitia
export { FlushTokenTransactionBuilder } from './transactionBuilder/flushTokenTransactionBuilder';
export { StakingBuilder } from './transactionBuilder/stakingBuilder';
export { StakeClauseTxnBuilder } from './transactionBuilder/stakeClauseTxnBuilder';
export { DelegateTxnBuilder } from './transactionBuilder/delegateTxnBuilder';
export { NFTTransactionBuilder } from './transactionBuilder/nftTransactionBuilder';
export { BurnNftBuilder } from './transactionBuilder/burnNftBuilder';
export { ExitDelegationBuilder } from './transactionBuilder/exitDelegationBuilder';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
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';
import { ZERO_VALUE_AMOUNT } from '../constants';

export class DelegateClauseTransaction extends Transaction {
private _stakingContractAddress: string;
private _tokenId: number;
private _delegateForever = true;

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

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

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

get tokenId(): number {
return this._tokenId;
}

set tokenId(tokenId: number) {
this._tokenId = tokenId;
}

get delegateForever(): boolean {
return this._delegateForever;
}

set delegateForever(delegateForever: boolean) {
this._delegateForever = delegateForever;
}

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

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

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

const data = this.getDelegateData(this.tokenId, this.delegateForever);
this._transactionData = data;

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

// Set recipients based on the clauses
this._recipients = [
{
address: this.stakingContractAddress,
amount: ZERO_VALUE_AMOUNT,
},
];
}
/**
* Encodes delegation transaction data using ethereumjs-abi for delegate method
*
* @param {number} tokenId - The Token ID for delegation
* @returns {string} - The encoded transaction data
*/
getDelegateData(levelId: number, delegateForever = true): string {
const methodName = 'delegate';
const types = ['uint256', 'bool'];
const params = [levelId, delegateForever];

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: ZERO_VALUE_AMOUNT,
sender: this.sender,
to: this.stakingContractAddress,
stakingContractAddress: this.stakingContractAddress,
amountToStake: ZERO_VALUE_AMOUNT,
nftTokenId: this.tokenId,
autorenew: this.delegateForever,
};

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 delegation-specific properties
if (body.clauses.length > 0) {
const clause = body.clauses[0];
if (clause.to) {
this.stakingContractAddress = clause.to;
}
if (clause.data) {
this.transactionData = clause.data;
const decoded = utils.decodeDelegateClauseData(clause.data);
this.tokenId = decoded.tokenId;
this.delegateForever = decoded.delegateForever;
}
}

// 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 @@ -390,6 +390,7 @@ export class Transaction extends BaseTransaction {
this.type === TransactionType.SendNFT ||
this.type === TransactionType.ContractCall ||
this.type === TransactionType.StakingActivate ||
this.type === TransactionType.StakingDelegate ||
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,128 @@
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 { DelegateClauseTransaction } from '../transaction/delegateClauseTransaction';
import utils from '../utils';

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

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

/**
* Gets the staking transaction instance.
*
* @returns {DelegateClauseTransaction} The delegate transaction
*/
get delegateTransaction(): DelegateClauseTransaction {
return this._transaction as DelegateClauseTransaction;
}

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

/**
* Validates the transaction clauses for delegate 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;
}

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

/**
* Sets the staking contract address for this delegate tx.
* The address must be explicitly provided to ensure the correct contract is used.
*
* @param {string} address - The staking contract address (required)
* @returns {DelegateTxnBuilder} 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.delegateTransaction.stakingContractAddress = address;
return this;
}

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

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

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

assert(transaction.tokenId, 'Token ID is required');
assert(transaction.delegateForever, 'delegate forever flag is required');
this.validateAddress({ address: transaction.stakingContractAddress });
}

/** @inheritdoc */
protected async buildImplementation(): Promise<Transaction> {
this.transaction.type = this.transactionType;
await this.delegateTransaction.build();
return this.transaction;
}
}
10 changes: 10 additions & 0 deletions modules/sdk-coin-vet/src/lib/transactionBuilderFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import { NFTTransactionBuilder } from './transactionBuilder/nftTransactionBuilde
import { NFTTransaction } from './transaction/nftTransaction';
import { StakeClauseTransaction } from './transaction/stakeClauseTransaction';
import { StakeClauseTxnBuilder } from './transactionBuilder/stakeClauseTxnBuilder';
import { DelegateTxnBuilder } from './transactionBuilder/delegateTxnBuilder';
import { DelegateClauseTransaction } from './transaction/delegateClauseTransaction';

export class TransactionBuilderFactory extends BaseTransactionBuilderFactory {
constructor(_coinConfig: Readonly<CoinConfig>) {
Expand Down Expand Up @@ -63,6 +65,10 @@ export class TransactionBuilderFactory extends BaseTransactionBuilderFactory {
const stakeClauseTx = new StakeClauseTransaction(this._coinConfig);
stakeClauseTx.fromDeserializedSignedTransaction(signedTx);
return this.getStakingActivateBuilder(stakeClauseTx);
case TransactionType.StakingDelegate:
const delegateClauseTx = new DelegateClauseTransaction(this._coinConfig);
delegateClauseTx.fromDeserializedSignedTransaction(signedTx);
return this.getStakingDelegateBuilder(delegateClauseTx);
case TransactionType.StakingUnlock:
const exitDelegationTx = new ExitDelegationTransaction(this._coinConfig);
exitDelegationTx.fromDeserializedSignedTransaction(signedTx);
Expand Down Expand Up @@ -104,6 +110,10 @@ export class TransactionBuilderFactory extends BaseTransactionBuilderFactory {
return this.initializeBuilder(tx, new StakingBuilder(this._coinConfig));
}

getStakingDelegateBuilder(tx?: DelegateClauseTransaction): DelegateTxnBuilder {
return this.initializeBuilder(tx, new DelegateTxnBuilder(this._coinConfig));
}

getStakingActivateBuilder(tx?: StakeClauseTransaction): StakeClauseTxnBuilder {
return this.initializeBuilder(tx, new StakeClauseTxnBuilder(this._coinConfig));
}
Expand Down
Loading