|
| 1 | +import { createHash } from 'crypto'; |
| 2 | +import { TransactionType, BaseKey, ExtendTransactionError, BuildTransactionError, SigningError } from '@bitgo/sdk-core'; |
| 3 | +import { BaseCoin as CoinConfig } from '@bitgo/statics'; |
| 4 | +import { TransactionBuilder } from './transactionBuilder'; |
| 5 | +import { Transaction } from './transaction'; |
| 6 | +import { TransactionReceipt, WithdrawBalanceContract } from './iface'; |
| 7 | +import { protocol } from '../../resources/protobuf/tron'; |
| 8 | +import { |
| 9 | + decodeTransaction, |
| 10 | + getByteArrayFromHexAddress, |
| 11 | + getBase58AddressFromHex, |
| 12 | + TRANSACTION_MAX_EXPIRATION, |
| 13 | + TRANSACTION_DEFAULT_EXPIRATION, |
| 14 | +} from './utils'; |
| 15 | + |
| 16 | +import ContractType = protocol.Transaction.Contract.ContractType; |
| 17 | + |
| 18 | +export class WithdrawBalanceTxBuilder extends TransactionBuilder { |
| 19 | + protected _signingKeys: BaseKey[]; |
| 20 | + |
| 21 | + constructor(_coinConfig: Readonly<CoinConfig>) { |
| 22 | + super(_coinConfig); |
| 23 | + this._signingKeys = []; |
| 24 | + this.transaction = new Transaction(_coinConfig); |
| 25 | + } |
| 26 | + |
| 27 | + /** @inheritdoc */ |
| 28 | + protected get transactionType(): TransactionType { |
| 29 | + return TransactionType.StakingClaim; |
| 30 | + } |
| 31 | + |
| 32 | + /** @inheritdoc */ |
| 33 | + extendValidTo(extensionMs: number): void { |
| 34 | + if (this.transaction.signature && this.transaction.signature.length > 0) { |
| 35 | + throw new ExtendTransactionError('Cannot extend a signed transaction'); |
| 36 | + } |
| 37 | + |
| 38 | + if (extensionMs <= 0) { |
| 39 | + throw new Error('Value cannot be below zero'); |
| 40 | + } |
| 41 | + |
| 42 | + if (extensionMs > TRANSACTION_MAX_EXPIRATION) { |
| 43 | + throw new ExtendTransactionError('The expiration cannot be extended more than one year'); |
| 44 | + } |
| 45 | + |
| 46 | + if (this._expiration) { |
| 47 | + this._expiration = this._expiration + extensionMs; |
| 48 | + } else { |
| 49 | + throw new Error('There is not expiration to extend'); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + initBuilder(rawTransaction: TransactionReceipt | string): this { |
| 54 | + this.transaction = this.fromImplementation(rawTransaction); |
| 55 | + this.transaction.setTransactionType(this.transactionType); |
| 56 | + this.validateRawTransaction(rawTransaction); |
| 57 | + const tx = this.fromImplementation(rawTransaction); |
| 58 | + this.transaction = tx; |
| 59 | + this._signingKeys = []; |
| 60 | + const rawData = tx.toJson().raw_data; |
| 61 | + this._refBlockBytes = rawData.ref_block_bytes; |
| 62 | + this._refBlockHash = rawData.ref_block_hash; |
| 63 | + this._expiration = rawData.expiration; |
| 64 | + this._timestamp = rawData.timestamp; |
| 65 | + const contractCall = rawData.contract[0] as WithdrawBalanceContract; |
| 66 | + this.initWithdrawBalanceContractCall(contractCall); |
| 67 | + return this; |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * Initialize the withdraw balance contract call specific data |
| 72 | + * |
| 73 | + * @param {WithdrawBalanceContract} withdrawBalanceContractCall object with freeze txn data |
| 74 | + */ |
| 75 | + protected initWithdrawBalanceContractCall(withdrawBalanceContractCall: WithdrawBalanceContract): void { |
| 76 | + const { owner_address } = withdrawBalanceContractCall.parameter.value; |
| 77 | + if (owner_address) { |
| 78 | + this.source({ address: getBase58AddressFromHex(owner_address) }); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + protected async buildImplementation(): Promise<Transaction> { |
| 83 | + this.createWithdrawBalanceTransaction(); |
| 84 | + /** @inheritdoccreateTransaction */ |
| 85 | + // This method must be extended on child classes |
| 86 | + if (this._signingKeys.length > 0) { |
| 87 | + this.applySignatures(); |
| 88 | + } |
| 89 | + |
| 90 | + if (!this.transaction.id) { |
| 91 | + throw new BuildTransactionError('A valid transaction must have an id'); |
| 92 | + } |
| 93 | + return Promise.resolve(this.transaction); |
| 94 | + } |
| 95 | + |
| 96 | + /** |
| 97 | + * Helper method to create the withdraw balance transaction |
| 98 | + */ |
| 99 | + private createWithdrawBalanceTransaction(): void { |
| 100 | + const rawDataHex = this.getWithdrawBalanceRawDataHex(); |
| 101 | + const rawData = decodeTransaction(rawDataHex); |
| 102 | + const contract = rawData.contract[0] as WithdrawBalanceContract; |
| 103 | + const contractParameter = contract.parameter; |
| 104 | + contractParameter.value.owner_address = this._ownerAddress.toLocaleLowerCase(); |
| 105 | + contractParameter.type_url = 'type.googleapis.com/protocol.WithdrawBalanceContract'; |
| 106 | + contract.type = 'WithdrawBalanceContract'; |
| 107 | + const hexBuffer = Buffer.from(rawDataHex, 'hex'); |
| 108 | + const id = createHash('sha256').update(hexBuffer).digest('hex'); |
| 109 | + const txRecip: TransactionReceipt = { |
| 110 | + raw_data: rawData, |
| 111 | + raw_data_hex: rawDataHex, |
| 112 | + txID: id, |
| 113 | + signature: this.transaction.signature, |
| 114 | + }; |
| 115 | + this.transaction = new Transaction(this._coinConfig, txRecip); |
| 116 | + } |
| 117 | + |
| 118 | + /** |
| 119 | + * Helper method to get the withdraw expire unfreeze transaction raw data hex |
| 120 | + * |
| 121 | + * @returns {string} the freeze balance transaction raw data hex |
| 122 | + */ |
| 123 | + private getWithdrawBalanceRawDataHex(): string { |
| 124 | + const rawContract = { |
| 125 | + ownerAddress: getByteArrayFromHexAddress(this._ownerAddress), |
| 126 | + }; |
| 127 | + const withdrawBalanceContract = protocol.WithdrawBalanceContract.fromObject(rawContract); |
| 128 | + const withdrawBalanceContractBytes = protocol.WithdrawBalanceContract.encode(withdrawBalanceContract).finish(); |
| 129 | + const txContract = { |
| 130 | + type: ContractType.WithdrawBalanceContract, |
| 131 | + parameter: { |
| 132 | + value: withdrawBalanceContractBytes, |
| 133 | + type_url: 'type.googleapis.com/protocol.WithdrawBalanceContract', |
| 134 | + }, |
| 135 | + }; |
| 136 | + const raw = { |
| 137 | + refBlockBytes: Buffer.from(this._refBlockBytes, 'hex'), |
| 138 | + refBlockHash: Buffer.from(this._refBlockHash, 'hex'), |
| 139 | + expiration: this._expiration || Date.now() + TRANSACTION_DEFAULT_EXPIRATION, |
| 140 | + timestamp: this._timestamp || Date.now(), |
| 141 | + contract: [txContract], |
| 142 | + }; |
| 143 | + const rawTx = protocol.Transaction.raw.create(raw); |
| 144 | + return Buffer.from(protocol.Transaction.raw.encode(rawTx).finish()).toString('hex'); |
| 145 | + } |
| 146 | + |
| 147 | + /** @inheritdoc */ |
| 148 | + protected signImplementation(key: BaseKey): Transaction { |
| 149 | + if (this._signingKeys.some((signingKey) => signingKey.key === key.key)) { |
| 150 | + throw new SigningError('Duplicated key'); |
| 151 | + } |
| 152 | + this._signingKeys.push(key); |
| 153 | + |
| 154 | + // We keep this return for compatibility but is not meant to be use |
| 155 | + return this.transaction; |
| 156 | + } |
| 157 | + |
| 158 | + private applySignatures(): void { |
| 159 | + if (!this.transaction.inputs) { |
| 160 | + throw new SigningError('Transaction has no inputs'); |
| 161 | + } |
| 162 | + |
| 163 | + this._signingKeys.forEach((key) => this.applySignature(key)); |
| 164 | + } |
| 165 | + |
| 166 | + /** |
| 167 | + * Validates the transaction |
| 168 | + * |
| 169 | + * @param {Transaction} transaction - The transaction to validate |
| 170 | + * @throws {BuildTransactionError} when the transaction is invalid |
| 171 | + */ |
| 172 | + validateTransaction(transaction: Transaction): void { |
| 173 | + this.validateWithdrawBalanceTransactionFields(); |
| 174 | + } |
| 175 | + |
| 176 | + /** |
| 177 | + * Validates if the transaction is a valid withdraw balance transaction |
| 178 | + * |
| 179 | + * @param {TransactionReceipt} transaction - The transaction to validate |
| 180 | + * @throws {BuildTransactionError} when the transaction is invalid |
| 181 | + */ |
| 182 | + private validateWithdrawBalanceTransactionFields(): void { |
| 183 | + if (!this._ownerAddress) { |
| 184 | + throw new BuildTransactionError('Missing parameter: source'); |
| 185 | + } |
| 186 | + |
| 187 | + if (!this._refBlockBytes || !this._refBlockHash) { |
| 188 | + throw new BuildTransactionError('Missing block reference information'); |
| 189 | + } |
| 190 | + } |
| 191 | +} |
0 commit comments