首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用sendTransaction调用合同的函数

如何使用sendTransaction调用合同的函数
EN

Ethereum用户
提问于 2016-09-20 08:14:03
回答 4查看 54.2K关注 0票数 32

这可能是一个非常基本的问题,我不知道为什么,但我无法找到正确的解决方案,我如何能够调用我的合同的方法使用sendTransaction。我有一个transfer(address, uint256)函数,我想使用sendTransactioncallTransaction调用它。我有我的合同汇编,我有它的abi和地址。现在,如何使用sendTransaction调用不同的合同节拍器?

我读到了调用契约状态更改方法的语法这个问题,我得到了关于函数具有单个参数的解释,但是如果它有多个不同类型的参数,比如这里transfer()函数接受2个参数,该怎么办?

EN

回答 4

Ethereum用户

回答已采纳

发布于 2017-03-10 04:29:08

为任何有需要的人张贴我自己问题的解决方案。要从geth调用契约函数:

代码语言:javascript
复制
const contractAbi = eth.contract(AbiOfContract);
const myContract = contractAbi.at(contractAddress);
// suppose you want to call a function named myFunction of myContract
const getData = myContract.myFunction.getData(function_parameters);
// finally pass this data parameter to send Transaction
web3.eth.sendTransaction({ to:Contractaddress, from:Accountaddress, data: getData });

注意:您可以在sendTransaction中添加其他字段,比如value等等,为了简单起见,我已经跳过了这些字段,以供新的用户使用。

对于所有使用私钥签名数据而面临挑战的用户。用于使用私钥签署事务并将其发送到合同的伪代码:

代码语言:javascript
复制
const Tx = require('ethereumjs-tx')
const web3 = new Web3()
web3.setProvider(new web3.providers.HttpProvider(web3RpcAddr))
const yourContract = new web3.eth.Contract(yourContract.abi, yourContract.address)

function sendCoin(toAddress, amount) {
  const nonce = await web3.eth.getTransactionCount(fromAddress, 'pending')
  const extraData = await yourContract.methods.transfer(toAddress, amount)
  const data = extraData.encodeABI()
  const txObj = {
    from: adminAddress,
    to: yourContractAddress,
    data,
    value: '0',
    gas: gasSent, // calculation of gas and gas Price is skipped here
    gasPrice: gasPriceSent,
    privKey: adminPvtKey,
    nonce
  }

  let signedTx = await signTx(txObj)
  signedTx = "0x" + signedTx.serialize().toString('hex')
  await submitSignedTx(signedTx)
}

async function signTx(payload) {
  let { from, to, data, value, gas, gasPrice, privKey, nonce } = payload
  let txParams = {
    to,
    data,
    value: web3.utils.toHex(value),
    gasPrice: web3.utils.toHex(gasPrice),
    gas: web3.utils.toHex(gas),
    nonce: web3.utils.toHex(nonce)
  }
  const tx = new Tx(txParams)
  privKey = await _validatePrivKey(privKey)
  privKey = new Buffer(privKey, 'hex')
  tx.sign(privKey)
  privKey = null
  return tx
}

async function submitSignedTx(serializedTx) {
  return new Promise((fullfill, reject) => {
    web3.eth.sendSignedTransaction(serializedTx)
      .on('transactionHash', txHash => {
        l.info('transaction sent. hash =>', txHash)
        return fullfill({success: true, txHash : txHash})
      })
      .on('error', e => {
        // console.log('unable to send tx', e)
        l.error(logmsg, e.message)
        return fullfill({success: false, message: e})
      })
  })
}
票数 43
EN

Ethereum用户

发布于 2019-05-13 14:36:34

改进@Prashant Prabhakar Singh回答:

代码语言:javascript
复制
var contractAbi = eth.contract(AbiOfContract);
var myContract = contractAbi.at(contractAddress);
// suppose you want to call a function named myFunction of myContract
var getData = myContract.myFunction.getData("1","boy");//just parameters you pass to myFunction
// And that is where all the magic happens
web3.eth.sendTransaction({
    to:ContractAddress,//contracts address
    from:web3.eth.accounts[0],
    data: getData,
    value: web3.toWei(EtherAmount, 'ether')//EtherAmount=>how much ether you want to move
},function (error, result){ 
            if(!error){
                console.log(result);//transaction successful
            } else{
                console.log(error);//transaction failed
            }
    });
票数 2
EN

Ethereum用户

发布于 2017-08-22 14:16:17

代码语言:javascript
复制
var abi=[//your abi array];
var contractAddress = "//your contract address";
var contract = web3.eth.contract(abi).at(contractAddress);

contract.functionName.sendTransaction(parameter_1,parameter_2,parameter_n,{
            from:web3.eth.accounts[0],
            gas:4000000},function (error, result){ //get callback from function which is your transaction key
                if(!error){
                    console.log(result);
                } else{
                    console.log(error);
                }
        });

然后,您可以尝试通过以下方法获取事务收据

代码语言:javascript
复制
var receipt=web3.eth.getTransactionReceipt(trHash);

-if您收到的收据为null,这意味着您的事务没有被挖掘,您可以在一段时间后继续尝试,直到得到收据值。-You可以签入收据,确认所有所提供的气体是否被使用,所有使用的气体都表示您的交易失败。

票数 1
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/8736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档