Repository navigation
Expand file tree
/
Copy pathcontract-control.js
More file actions
66 lines (59 loc) · 2.3 KB
/
Copy pathcontract-control.js
File metadata and controls
66 lines (59 loc) · 2.3 KB
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
import { ethers } from "ethers"
import { abi } from "./BasePay.json"
const contractAddress = "0x255A1891359A67A50a459e64445E6429f652a23f"
// pass in window.ethereum to this function
// returns back a contract instance
async function connectNode(eth) {
if (eth?.enable) {
await eth.enable(); // Ensure connectivity with the wallet
}
const provider = new ethers.providers.Web3Provider(eth);
await provider.send("eth_requestAccounts", []);
const signer = provider.getSigner();
const basePayContractInstance = new ethers.Contract(
contractAddress,
abi,
signer
);
return basePayContractInstance;
}
// pass in window.ethereum to eth
// note that _etherValue is in Ether NOT Wei
async function initiatePayment(eth, _paymentRecipient, _etherValue, callback) {
try {
const basePayContractInstance = await connectNode(eth);
const txResponse = await basePayContractInstance.initiatePayment(_paymentRecipient, {
value: ethers.utils.parseEther(_etherValue),
// gasLimit: 29000 // Setting a low gas limit to intentionally fail the transaction
});
console.log("Transaction Hash: ", txResponse.hash);
// Return the transaction hash immediately
const txHash = txResponse.hash;
// Wait for the transaction to be mined
txResponse.wait().then(receipt => {
if (receipt) {
if (receipt.status === 1) {
console.log("Transaction successful!");
} else {
console.log("Transaction failed or reverted.");
}
// Call the callback with the receipt if provided
if (callback) callback(receipt);
} else {
console.log("Receipt is null or undefined.");
if (callback) callback({status: 0}); // Call the callback with a failure status
}
}).catch(error => {
// Handle the error here
console.log("Transaction failed with an exception:", error.message);
if (callback) callback({status: 0}); // Call the callback with a failure status
});
return txHash;
} catch(error) {
console.log(error.message);
return null;
}
}
module.exports = {
initiatePayment
};