如何使用ethers.js和metamask与角度服务签署sendTransaction

时间:2020-05-09 22:52:00

标签: angular solidity metamask

我正在使用角度9,并且在尝试运行以下代码时遇到以下错误。如何签署交易?

错误:发送交易需要签名者(operation =“ sendTransaction”,版本= 4.0.47)

      onSubmit(form: NgForm) {
    console.log(form);
    this.submitted = true;
    // TODO: This is where we connect to the solidity contract to create client.
    this.clientService.createClient(form.controls['accountAddress'].value, form.controls['name'].value).subscribe(
      (model: Client) =>
      {
        this.model = model;
        console.log('MODEL='+model);
      }, error => {
        console.log("error"+error);
      });
  }



export class ClientServiceService {

  //mweb3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545')); // keeping this for future reference.
  // Attempting to use the example from MI4-exercise7 to use metamask
  provider = new ethers.providers.EtherscanProvider('ropsten')
  contractAddress = "0xe6482f6554074c666593b5f38fe5357828a1fbd7";
  contractABI = [...];

  contract = new ethers.Contract(this.contractAddress, this.contractABI, this.provider);

  //constructor(private http: HttpClient) { }
  constructor() { }

  // getInvoiceTracker(): ethers.Contract {
  //   return this.contract.new();
  // }

  createClient(clientID: string, clientName: string): Observable<any> {
    return from(this.contract.addClient(clientID, clientName));
  }
}

1 个答案:

答案 0 :(得分:0)

要发送交易,您需要使用带有签名者的提供商。

const wallet = new ethers.Wallet(privateKey, provider)

,然后将您的合同实例连接到签名者。

contract.connect(wallet)

如果您要连接MetaMask,则从web3窗口提供者创建以太提供者:

  provider = new ethers.providers.Web3Provider(window.ethereum)