1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| type OpTrans struct { client *blockchain.Client }
func NewOpTrans(bcClient *blockchain.Client) *OpTrans { return &OpTrans{client: bcClient} }
func (op *OpTrans) Transfer(to string, value uint64) (string, error) { privateKey, err := crypto.HexToECDSA("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80") if err != nil { return "", err } pubKey, ok := privateKey.Public().(*ecdsa.PublicKey) if !ok { return "", errors.New("failed to get public key") } fromAddress := crypto.PubkeyToAddress(*pubKey) toAddress := common.HexToAddress(to)
nonce, err := op.client.Eth.PendingNonceAt(context.Background(), fromAddress) if err != nil { return "", err } val := big.NewInt(int64(value * 1000000000000000000)) gasLimit, err := op.client.Eth.EstimateGas(context.Background(), ethereum.CallMsg{ From: fromAddress, To: &toAddress, Value: val, Data: nil, }) if err != nil { return "", err } gasPrice, err := op.client.Eth.SuggestGasPrice(context.Background()) if err != nil { return "", err } chainId, err := op.client.Eth.NetworkID(context.Background()) if err != nil { return "", err } tx := types.NewTransaction(nonce, toAddress, val, gasLimit, gasPrice, nil) signTx, err := types.SignTx(tx, types.NewEIP155Signer(big.NewInt(chainId.Int64())), privateKey) if err != nil { return "", err } err = op.client.Eth.SendTransaction(context.Background(), signTx) if err != nil { return "", err } return signTx.Hash().Hex(), err }
func (op *OpTrans) GetHeaderTransactionCount() (uint, error) { headerBlockNum, err := op.client.Eth.HeaderByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } blockInfo, err := op.client.Eth.BlockByNumber(context.Background(), big.NewInt(int64(headerBlockNum.Number.Int64()))) if err != nil { log.Fatal(err) } return op.client.Eth.TransactionCount(context.Background(), blockInfo.Hash()) }
func (op *OpTrans) ListTX(blkHash string) ([]TXInfo, error) { block, err := op.client.Eth.BlockByHash(context.Background(), common.HexToHash(blkHash)) if err != nil { log.Fatal(err) return nil, err } var txInfos []TXInfo
for _, tx := range block.Transactions() { txHash := tx.Hash() receipt, err := op.client.Eth.TransactionReceipt(context.Background(), txHash) if err != nil { continue } chainId := tx.ChainId() from, err := types.Sender(types.NewEIP155Signer(chainId), tx) if err != nil { continue } txInfo := TXInfo{ TxHash: txHash.Hex(), TxValue: tx.Value().Uint64(), TxGas: tx.Gas(), TxGasPrice: tx.GasPrice().Uint64(), TxNonce: tx.Nonce(), TxData: tx.Data(), TxTo: tx.To().Hex(), TxReceipt: uint8(receipt.Status), TxFrom: from.Hex(), } txInfos = append(txInfos, txInfo) } return txInfos, nil }
|