簡體   English   中英

如何使用 web3.js 1.0 認證和發送合約方法

[英]How to authenticate and send contract method using web3.js 1.0

我對如何使用 web3 1.0 庫執行合同方法感到困惑。

此代碼有效(只要我先手動解鎖帳戶):

var contract = new web3.eth.Contract(contractJson, contractAddress);
contract.methods
  .transfer("0x0e0479bC23a96F6d701D003c5F004Bb0f28e773C", 1000)
  .send({
    from: "0x2EBd0A4729129b45b23aAd4656b98026cf67650A"
  })
  .on('confirmation', (confirmationNumber, receipt) => {
    io.emit('confirmation', confirmationNumber);
  });

我收到此錯誤(如果我不先手動解鎖):

返回錯誤:需要身份驗證:密碼或解鎖

上面的代碼是 node.js 中的一個 API 端點,所以我希望它以編程方式解鎖或驗證。

web3.js 1.0 中沒有解鎖賬戶的方法。

我也不認為這是必要的(至少我對此感到困惑)。 因為我在管理賬戶,所以我知道私鑰是什么。

我在想交易需要用私鑰簽名?? 這個對嗎? 這實際上與“解鎖帳戶”相同嗎?

我試過這樣做:

var contract = new web3.eth.Contract(contractJson, contractAddress);

var tx = {
  from: "...{fromAddress -- address that has the private key below}",
  to: "...",
  value: ...
};

var signed = web3.eth.accounts.signTransaction(tx, 
  "...{privateKey}");

console.log(signed);

var promise = web3.eth.sendSignedTransaction(signed);

我收到此錯誤:

返回錯誤:方法net_version不存在/不可用

驗證和提交交易的最簡單方法是什么?

理想情況下,我想在我的代碼示例中使用第一種方法,因為它是最干凈的。

此代碼允許我使用我創建的帳戶(使用 web3.eth.accounts.create())中的私鑰簽署交易服務器端(node.js),並將簽署的交易發送到網絡,而無需解鎖帳戶。

我正在使用 Geth 1.7.1

  var contract = new web3.eth.Contract(contractJson, contractAddress);
  var transfer = contract.methods.transfer("0x...", 490);
  var encodedABI = transfer.encodeABI();

  var tx = {
    from: "0x...",
    to: contractAddress,
    gas: 2000000,
    data: encodedABI
  }; 

  web3.eth.accounts.signTransaction(tx, privateKey).then(signed => {
    var tran = web3.eth.sendSignedTransaction(signed.rawTransaction);

    tran.on('confirmation', (confirmationNumber, receipt) => {
      console.log('confirmation: ' + confirmationNumber);
    });

    tran.on('transactionHash', hash => {
      console.log('hash');
      console.log(hash);
    });

    tran.on('receipt', receipt => {
      console.log('reciept');
      console.log(receipt);
    });

    tran.on('error', console.error);
  });

一種無需顯式簽署交易即可調用合約方法的方法是(web3js 1.0.0):

const privateKey = 'e0f3440344e4814d0dea8a65c1b9c488bab4295571c72fb879f5c29c8c861937';
const account = web3.eth.accounts.privateKeyToAccount('0x' + privateKey);
web3.eth.accounts.wallet.add(account);
web3.eth.defaultAccount = account.address;

// ...
contract = new web3.eth.Contract(JSON_INTERFACE, address);
contract.methods.myMethod(myParam1, myParam2)
        .send({
            from: this.web3.eth.defaultAccount,
            gas: myConfig.gas,
            gasPrice: myConfig.gasPrice
        })

這是一個完整的示例,說明如何在沒有本地錢包帳戶的情況下簽署交易。 如果您使用 infura 進行交易,則特別有用。 這是為

'use strict';
const Web3 = require('web3');

const wsAddress = 'wss://rinkeby.infura.io/ws';
const contractJson = '(taken from solc or remix online compiler)';
const privateKey = '0xOOOX';
const contractAddress = '0xOOOX';
const walletAddress = '0xOOOX';

const webSocketProvider = new Web3.providers.WebsocketProvider(wsAddress);
const web3 = new Web3(new Web3.providers.WebsocketProvider(webSocketProvider));
const contract = new web3.eth.Contract(
  JSON.parse(contractJson),
  contractAddress
);
// change this to whatever contract method you are trying to call, E.G. SimpleStore("Hello World")
const query = contract.methods.SimpleStore('Hello World');
const encodedABI = query.encodeABI();
const tx = {
  from: walletAddress,
  to: contractAddress,
  gas: 2000000,
  data: encodedABI,
};

const account = web3.eth.accounts.privateKeyToAccount(privateKey);
console.log(account);
web3.eth.getBalance(walletAddress).then(console.log);

web3.eth.accounts.signTransaction(tx, privateKey).then(signed => {
  const tran = web3.eth
    .sendSignedTransaction(signed.rawTransaction)
    .on('confirmation', (confirmationNumber, receipt) => {
      console.log('=> confirmation: ' + confirmationNumber);
    })
    .on('transactionHash', hash => {
      console.log('=> hash');
      console.log(hash);
    })
    .on('receipt', receipt => {
      console.log('=> reciept');
      console.log(receipt);
    })
    .on('error', console.error);
});

使用

“web3”:“1.0.0-beta.30”

這是我使用"@truffle/hdwallet-provider": "^2.0.3", "web3": "^1.6.1",


function getWeb3Provider() {
  return new HDWalletProvider({
    privateKeys: [NFT_MINTER_ACCOUNT_PRIVATE_KEY],
    providerOrUrl: BSC_RPC_ENDPOINT,
  });
}

const web3 = new Web3(BSC_RPC_ENDPOINT);
const contract = new web3.eth.Contract(
      jsonContractABI as unknown as AbiItem[],
      NFT_CONTRACT_ADDRESS
    );
contract.setProvider(getWeb3Provider());

然后在send方法中

contract.methods.safeMint(receiverAddress, itemUri).send({
      from: NFT_MINTER_ACCOUNT,
    });

call方法中

contract.methods.balanceOf(address).call();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM