UNPKG

@secux/app-trx

Version:
18 lines (15 loc) 6.81 kB
"use strict"; /*! Copyright 2022 SecuX Technology Inc Copyright Chen Wei-En Copyright Wu Tsung-Yu Licensed under the Apache License, Version 2.0 (the License); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */Object.defineProperty(exports,"__esModule",{value:!0}),exports.SecuxTRX=void 0;const e=require("@ethersproject/keccak256"),r=require("hash.js"),t=require("base-x"),a=require("@tronscan/client/src/utils/transactionBuilder"),{TriggerSmartContract:n,TransferContract:o,TransferAssetContract:i}=require("@tronscan/client/src/protocol/core/Contract_pb"),{Transaction:s}=require("@tronscan/client/src/protocol/core/Tron_pb"),c=require("secp256k1/elliptic"),u=require("ow"),l=require("@secux/utility/lib/communication"),f=require("@secux/protocol-transaction"),d=require("@secux/protocol-transaction/lib/interface"),g=require("./interface"),m=require("./utils"),p=require("@secux/utility"),T=null===p.Logger||void 0===p.Logger?void 0:p.Logger.child({id:"trx"}),h=t("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),w=(new RegExp(`^${65..toString(16)}`),(0,p.ow_strictPath)(195,44));class x{static addressConvert(t){let a=function(e){(0,u.default)(e,u.default.any(p.owTool.hexString,u.default.buffer));let r="string"==typeof e?Buffer.from(e,"hex"):e;if(!c.publicKeyVerify(r))throw Error(`ArgumentError: invalid secp256k1 publickey, got "${r.toString("hex")}"`);return r=c.publicKeyConvert(r,!1),r}(t);a=a.slice(1);return function(e,t){const a=t?Buffer.concat([Buffer.from([t]),e]):e,n=function(e){const t=(0,r.sha256)().update(e).digest(),a=(0,r.sha256)().update(t).digest();return Buffer.from(a)}(a).slice(0,4),o=Buffer.concat([a,n]);return h.encode(o)}(Buffer.from((0,e.keccak256)(a).slice(2),"hex").slice(-20),65)}static toHexAddress(e){return(0,u.default)(e,u.default.string),y(e)}static prepareAddress(e){return this.preparePublickey(e)}static resolveAddress(e){const r=x.resolvePublickey(e);return x.addressConvert(r)}static preparePublickey(e){return(0,u.default)(e,w),f.SecuxTransactionTool.getPublickey(e,d.EllipticCurve.SECP256K1)}static resolvePublickey(e){const r=f.SecuxTransactionTool.resolvePublickey(e,d.EllipticCurve.SECP256K1,!1);return Buffer.from(r,"base64").toString("hex")}static prepareXPublickey(e){return(0,u.default)(e,w),f.SecuxTransactionTool.getXPublickey(e)}static resolveXPublickey(e,r){return(0,u.default)(r,w),f.SecuxTransactionTool.resolveXPublickey(e,r)}static prepareSign(e,r){var t;let c,d;if((0,u.default)(e,w),(0,u.default)(r,u.default.any(g.ow_transferData,g.ow_trc10_Data,g.ow_trc20_Data)),d=(0,m.isTransfer)(r)){null==T||T.debug("transfer contract");const e=new o;e.setToAddress(new Uint8Array(S(d.to))),e.setOwnerAddress(new Uint8Array(S(d.from))),e.setAmount(d.amount),c=a.buildTransferContract(e,s.Contract.ContractType.TRANSFERCONTRACT,"TransferContract")}else if(d=(0,m.isTrc10Data)(r)){null==T||T.debug("trc10 contract");const e=new i;e.setToAddress(new Uint8Array(S(d.to))),e.setOwnerAddress(new Uint8Array(S(d.from))),e.setAmount(d.amount),e.setAssetName(new Uint8Array(Buffer.from(d.token.toString(10)))),c=a.buildTransferContract(e,s.Contract.ContractType.TRANSFERASSETCONTRACT,"TransferAssetContract")}else if(d=(0,m.isTrc20Data)(r)){null==T||T.debug("trc20 contract");const e=new n;if(e.setOwnerAddress(new Uint8Array(S(d.from))),e.setContractAddress(new Uint8Array(S(d.contract))),d.tokenId&&e.setTokenId(d.tokenId),d.tokenValue&&e.setCallTokenValue(d.tokenValue),d.callValue&&e.setCallValue(d.callValue),d.data)e.setData(Buffer.from(d.data,"hex"));else{if(!d.to)throw Error("ArgumentError: missing receiving address.");if(!d.amount)throw Error("ArgumentError: missing sending amount.");e.setData(function(e,r){const t=Buffer.from(y(e).slice(2).padStart(64,"0"),"hex"),a=(0,p.BigIntToBuffer)(r,32,!1);return Buffer.from([169,5,156,187,...t,...a])}(d.to,d.amount))}c=a.buildTransferContract(e,s.Contract.ContractType.TRIGGERSMARTCONTRACT,"TriggerSmartContract")}null==T||T.debug("builder created");const h=c.getRawData();h.setRefBlockHash(Buffer.from(r.blockID.slice(16,32),"hex"));const x=Buffer.alloc(2);x.writeUInt16BE(65535&r.blockNumber),h.setRefBlockBytes(x),void 0!==r.feeLimit&&h.setFeeLimit(r.feeLimit),h.setTimestamp(r.timestamp);const b=null!==(t=r.expiration)&&void 0!==t?t:r.timestamp+86399999;if(b<=r.timestamp)throw Error("ArgumentError: timestamp greater than expiration time.");h.setExpiration(b);const A=Buffer.from(h.serializeBinary());return(0,l.wrapResult)({commandData:f.SecuxTransactionTool.signRawTransaction(e,A),rawTx:(0,l.toCommunicationData)(Buffer.from(A))})}static resolveSignature(e){const r=f.SecuxTransactionTool.resolveSignature(e),t=p.Signature.fromSignature(Buffer.from(r,"base64"));return t.flipS(!0),Buffer.concat([t.r,t.s,t.v]).toString("hex")}static resolveTransaction(e,r){(0,u.default)(e,l.ow_communicationData),(0,u.default)(r,l.ow_communicationData);const t=Buffer.from(x.resolveSignature(e),"hex");null==T||T.debug(`signature: ${t.toString("hex")}`);const a=new s,n=s.raw.deserializeBinary((0,l.getBuffer)(r));a.setRawData(n);for(let e=0;e<n.getContractList().length;e++)a.addSignature(t);return Buffer.from(a.serializeBinary()).toString("hex")}static async getAddress(e){const r=x.prepareAddress(e),t=await this.Exchange((0,l.getBuffer)(r));return x.resolveAddress(t)}static async getPublickey(e){const r=x.preparePublickey(e),t=await this.Exchange((0,l.getBuffer)(r));return x.resolvePublickey(t)}static async getXPublickey(e){const r=x.prepareXPublickey(e),t=await this.Exchange((0,l.getBuffer)(r));return x.resolveXPublickey(t,e)}static async sign(e,r){(0,u.default)(e,w),r.from||(r.from=await x.getAddress.call(this,e));const{commandData:t,rawTx:a}=x.prepareSign(e,r),n=await this.Exchange((0,l.getBuffer)(t));return{raw_tx:x.resolveTransaction(n,a),signature:x.resolveSignature(n)}}}function y(e){if(e.startsWith("T"))return S(e).toString("hex");if(e.match(new RegExp(`^${65..toString(16)}[0-9a-fA-F]+$`)))return e;throw Error(`Invalid Tron Address: ${e}`)}function b(e){return Buffer.from((0,r.sha256)().update(e).digest())}function S(e){var r=h.decode(e);if(r.length<=4)throw null==T||T.warn(`base58 decode error, address: ${e}`),Error("base58 decode error");var t=r.slice(0,r.length-4),a=b(t),n=b(a);if(n[0]===r[t.length]&&n[1]===r[t.length+1]&&n[2]===r[t.length+2]&&n[3]===r[t.length+3])return t;throw Error("base58 check error")}exports.SecuxTRX=x,(0,p.loadPlugin)(x,"SecuxTRX");