openchain-sdk-yxl-ts
Version:
OpenChain SDK for browser
105 lines (96 loc) • 2.69 kB
JavaScript
import errors from '../exception/index.js';
/**
* OP 操作相关的方法集合
* 这些方法将被混入到 Operation 类中
*/
class OpOperations {
/**
* BU转移操作
* @param {Object} args - 转移参数
* @param {string} [args.sourceAddress] - 源地址
* @param {string} args.destAddress - 目标地址
* @param {string|number} args.opAmount - 转移金额
* @param {string} [args.metadata] - 元数据
* @returns {Object} 操作结果
*/
opSendOperation(args) {
try {
// 参数类型检查
if (Array.isArray(args) || typeof args !== 'object' || args === null) {
return this._responseError(errors.INVALID_ARGUMENTS);
}
// 参数验证模式
const schema = {
sourceAddress: {
required: false,
address: true,
},
destAddress: {
required: true,
address: true,
},
opAmount: {
required: true,
numeric: true,
},
metadata: {
required: false,
string: true,
},
};
// 验证参数
const validation = this._validate(args, schema);
if (!validation.tag) {
return this._responseError(errors[validation.msg]);
}
// 检查源地址和目标地址是否相同
if (args.sourceAddress && args.destAddress === args.sourceAddress) {
return this._responseError(errors.SOURCEADDRESS_EQUAL_DESTADDRESS_ERROR);
}
// 构建操作数据
return this._responseData({
operation: {
type: 'payCoin',
data: this._sanitizeOperationData(args),
},
});
} catch (err) {
console.error('Error in opSendOperation:', err);
throw err;
}
}
/**
* 清理操作数据,移除未定义的字段
* @private
* @param {Object} data - 原始数据
* @returns {Object} 清理后的数据
*/
_sanitizeOperationData(data) {
return Object.entries(data).reduce((acc, [key, value]) => {
if (value !== undefined && value !== null) {
acc[key] = value;
}
return acc;
}, {});
}
/**
* 验证 BU 金额
* @private
* @param {string|number} amount - BU 金额
* @returns {boolean} 是否有效
*/
_isValidOpAmount(amount) {
try {
const numAmount = Number(amount);
return !isNaN(numAmount) && numAmount > 0;
} catch {
return false;
}
}
}
// 导出操作方法
export default {
opSendOperation: OpOperations.prototype.opSendOperation,
_sanitizeOperationData: OpOperations.prototype._sanitizeOperationData,
_isValidOpAmount: OpOperations.prototype._isValidOpAmount,
};