Think in Coin | DEV Docs
  • Develop Documents
  • Networks
    • Fantom Network
      • quick-start
        • Short Guide
      • technology
        • Lachesis aBFT
        • Overview
        • Proof of Stake
        • Transaction Fees
        • FAQ
      • staking
        • Quick start
        • Overview
        • Stake on Fantom
        • Run a Validator Node
        • Run a Read-only node
        • Run a Testnet Validator
        • Troubleshooting
      • api
        • Public API endpoints
        • Getting Started
        • Installation
        • GraphQL Schema Basics
        • Schema Structure
        • Implementation Details and Notes
        • Covalent indexing and querying API
      • tutorials
        • Set up Metamask
        • Set up Metamask (testnet)
        • Deploy a Smart Contract
        • Create a Fixed-cap Asset
    • xDAI Chain
      • Welcome to xDai
      • untitled
        • About xdai
          • Projects & DApps
          • Features
          • Use Cases
          • News & Information
          • Roadmaps
          • FAQs
        • For users
          • xDai Token
          • Getting Started with xDai
          • Bridges
          • Wallets
          • Applications
          • Block Explorers
          • Governance
        • For stakers
          • STAKE Token
          • Staking on xDai
          • EasyStaking on Ethereum
          • POSDAO Staking Roadmap
        • For developers
          • Developer Resources & Tools
          • On-Chain Random Numbers
          • Install xDai Client - Run a Non-Validator Node
          • Stable Chain Network Deployment
          • Grants for building on xDai
          • Immunefi Bug Bounty
        • For validators
    • Polygon Network
      • About - Polygon
      • Technology
    • Huobi HECO Chain
      • Huobi Open Platform
    • Binance Chain
      • Create Address
      • Fees
      • Governance
      • Threshold Signature Scheme
      • Atomic Swap
      • WalletConnect
      • Wallets Support
        • WalletConnect Support
        • Trust Wallet User Guide
        • Ledger Wallet Guide
        • Trezor Wallet Guide
        • How to manage BEP8 token with Web Wallet
      • BEP8 Token Protocol
      • Binance DEX Trading
      • Binance Chain Testnet
      • Exchange Integration
      • List Instructions
    • Binance Smart Chain
      • Concepts
        • Consensus
        • Comparison
        • Genesis File
        • BC > BSC Cross-Chain
          • Mechanism
          • Cross-Chain Transfer
          • BSC Relayer
          • Oracle Module
          • Oracle Relayer
          • Relayer incentives
        • Build-in System Contract
        • Governance
      • Ecosystem
      • Gnosis
      • Binance Bridge
        • Release
        • Roadmap
        • User Guides
        • Developer
          • Widget
          • Swagger API reference
        • Partnership
        • Support
          • Customer Support
        • guides
          • Binance Bridge v2
          • Binance Bridge v1
          • Supported Assets
          • Buy BNB as Gas
    • Ethereum (ERC)
      • Ether - Introduction
        • The Ethereum Foundation
        • Community
        • History of Ethereum
        • The Homestead Release
        • What is Ethereum?
        • A platform for decentralized apps
      • The Ethereum network
        • Connecting to the Network
        • Test Networks
      • Mining
      • Contracts and Transactions
        • Account Types, Gas, and Transactions
        • Contracts
        • Accessing Contracts and Transactions
        • Dapps
        • Mix
          • Project Editor
          • Scenarios Editor
          • State Viewer
          • Transaction Explorer
          • JavaScript console
          • Transaction debugger
          • Dapps deployment
          • Code Editor
        • Ethereum Tests
          • Blockchain Tests
          • State Tests
        • Web3 Base Layer Services
    • Harmony ONE
      • developers
        • Getting Started
        • Network & Faucets
        • Deploying on Harmony
        • SDK
        • API
        • Wallets
        • Tools
        • Showcases
        • Hackathon & Bounties
        • Learn
      • network
        • Governance
        • Holders
        • Validators
        • Delegators
      • general
        • Grants
        • Introduction
          • What is Harmony?‌
          • Roadmap
          • Strategy & Architecture
          • Study Materials
          • FAQ
        • Technology
        • Horizon Bridge
        • DApps
        • Ecosystem
        • Community
    • TRON Network (TRC)
      • Introduction
      • Tron Protocol
        • Account
        • Resource Model
        • Super Representatives
          • Mechanism
          • Step to become a Candidate
          • Committee and Proposal
        • Transaction
        • Multi-Signature
          • Example Process Flow
        • Concensus
        • untitled
          • Build transaction locally
      • TRX AND TRC TOKEN
        • TRX
          • TRX Transfer
          • Query TRX balance
        • TRC-10
          • Issue TRC-10 token
          • Participate TRC-10
          • TRC-10 Transfer
          • Query TRC-10 balance
          • TRC-10 Transfer in Smart Contracts
          • Other TRC-10 Interfaces
        • TRC-20
          • Protocol Interface
          • Issuing TRC-20 tokens tutorial
          • TRC-20 Contract Interaction
        • TRC-721
  • Community
    • Github
    • Telegram DEVs
Powered by GitBook
On this page

Was this helpful?

  1. Networks
  2. TRON Network (TRC)
  3. Tron Protocol
  4. untitled

Build transaction locally

package org.tron.demo;

​

import com.google.protobuf.Any;

import com.google.protobuf.ByteString;

import com.google.protobuf.InvalidProtocolBufferException;

import org.tron.api.GrpcAPI.Return;

import org.tron.api.GrpcAPI.TransactionExtention;

import org.tron.common.crypto.ECKey;

import org.tron.common.crypto.Sha256Sm3Hash;

import org.tron.common.utils.ByteArray;

import org.tron.core.exception.CancelException;

import org.tron.protos.Contract;

import org.tron.protos.Protocol.Block;

import org.tron.protos.Protocol.Transaction;

import org.tron.walletserver.WalletApi;

​

import java.util.Arrays;

​

public class TransactionSignDemo {

/* Set reference block data*/

public static Transaction setReference(Transaction transaction, Block newestBlock) {

long blockHeight = newestBlock.getBlockHeader().getRawData().getNumber();

byte[] blockHash = getBlockHash(newestBlock).getBytes();

byte[] refBlockNum = ByteArray.fromLong(blockHeight);

Transaction.raw rawData = transaction.getRawData().toBuilder()

.setRefBlockHash(ByteString.copyFrom(ByteArray.subArray(blockHash, 8, 16)))

.setRefBlockBytes(ByteString.copyFrom(ByteArray.subArray(refBlockNum, 6, 8)))

.setRefBlockNum(blockHeight)

.build();

return transaction.toBuilder().setRawData(rawData).build();

}

​

public static Sha256Sm3Hash getBlockHash(Block block) {

return Sha256Sm3Hash.of(block.getBlockHeader().getRawData().toByteArray());

}

​

public static String getTransactionHash(Transaction transaction) {

String txid = ByteArray.toHexString(Sha256Sm3Hash.hash(transaction.getRawData().toByteArray()));

return txid;

}

​

public static Transaction createTransaction(byte[] from, byte[] to, long amount) {

Transaction.Builder transactionBuilder = Transaction.newBuilder();

Block newestBlock = WalletApi.getBlock(-1);

/*设置合约内部数据*/

Transaction.Contract.Builder contractBuilder = Transaction.Contract.newBuilder();

Contract.TransferContract.Builder transferContractBuilder =

Contract.TransferContract.newBuilder();

transferContractBuilder.setAmount(amount);

ByteString bsTo = ByteString.copyFrom(to);

ByteString bsOwner = ByteString.copyFrom(from);

transferContractBuilder.setToAddress(bsTo);

transferContractBuilder.setOwnerAddress(bsOwner);

try {

Any any = Any.pack(transferContractBuilder.build());

contractBuilder.setParameter(any);

} catch (Exception e) {

return null;

}

/* Set memo, transaction expiration time and other data*/

contractBuilder.setType(Transaction.Contract.ContractType.TransferContract);

transactionBuilder.getRawDataBuilder().addContract(contractBuilder)

.setTimestamp(System.currentTimeMillis())

.setExpiration(newestBlock.getBlockHeader().getRawData().getTimestamp() + 10 * 60 * 60 * 1000)

.setData(ByteString.copyFromUtf8("memo"))

.setScripts(ByteString.copyFromUtf8("scripts"));

Transaction transaction = transactionBuilder.build();

Transaction refTransaction = setReference(transaction, newestBlock);

return refTransaction;

}

​

private static byte[] signTransaction2Byte(byte[] transaction, byte[] privateKey)

throws InvalidProtocolBufferException {

ECKey ecKey = ECKey.fromPrivate(privateKey);

Transaction transaction1 = Transaction.parseFrom(transaction);

byte[] rawdata = transaction1.getRawData().toByteArray();

byte[] hash = Sha256Sm3Hash.hash(rawdata);

byte[] sign = ecKey.sign(hash).toByteArray();

return transaction1.toBuilder().addSignature(ByteString.copyFrom(sign)).build().toByteArray();

}

​

private static boolean broadcast(byte[] transactionBytes) throws InvalidProtocolBufferException {

return WalletApi.broadcastTransaction(transactionBytes);

}

​

public static void main(String[] args) throws InvalidProtocolBufferException, CancelException {

String privateStr = "da146374a75310b9666e834ee4ad0866d6f4035967bfc76217c5a495fff9f0d0";

byte[] privateBytes = ByteArray.fromHexString(privateStr);

ECKey ecKey = ECKey.fromPrivate(privateBytes);

byte[] from = ecKey.getAddress();

byte[] to = WalletApi.decodeFromBase58Check("TN9RRaXkCFtTXRso2GdTZxSxxwufzxLQPP");

long amount = 100_000_000L; // 100 TRX, api only receive trx in Sun, and 1 trx = 1000000 Sun

Transaction transaction = createTransaction(from, to, amount);

byte[] transactionBytes = transaction.toByteArray();

byte[] transaction4 = signTransaction2Byte(transactionBytes, privateBytes);

boolean result = broadcast(transaction4);

​

System.out.println(result);

}

}

PreviousuntitledNextTRX AND TRC TOKEN

Last updated 1 year ago

Was this helpful?