Direct Contract Interaction
Prerequisites
Ensure that Node.js and npm are installed on your machine.
Step 1: Install Ethers.js
Use npm
to install ethers.js
:
npm install ethers
Step 2: Connect to the Network that You'd Like to Add Liquidity to
Connect to Ethereum, for example. You can do this using a default provider from ethers, which automatically connects to the Ethereum mainnet:
const ethers = require('ethers');
const provider = ethers.getDefaultProvider();
Step 3: Import the Contract ABI and Address
The contract ABI and address will enable ethers.js
to interact with the contract. Import these values:
const contractABI = [
{
"inputs": [
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "deposit",
"outputs": [],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "withdraw",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
];
const contractAddress = '' // fill with the relay contract address
Step 4: Create a Contract Instance
Now, using the provider, the contract ABI, and the contract address, you can create a contract instance:
const contract = new ethers.Contract(contractAddress, contractABI, provider);
Step 5: Create a Signer
In order to modify the blockchain state, transactions need to be signed. Create a signer from a private key:
const privateKey = 'your-private-key';
const wallet = new ethers.Wallet(privateKey);
const signer = wallet.connect(provider);
Make sure to replace 'your-private-key'
with your actual private key.
Step 6: Connect Contract to Signer
Connect the contract instance to the signer:
const contractWithSigner = contract.connect(signer);
Step 7: Interact with the Contract
Now that you have a contract instance connected to a signer, you can interact with the contract's functions.
Deposit:
async function deposit(amount) {
const transaction = await contractWithSigner.deposit(amount, { value: value });
const receipt = await transaction.wait();
console.log(receipt);
}
Withdraw:
async function withdraw(amount) {
const transaction = await contractWithSigner.withdraw(amount);
const receipt = await transaction.wait();
console.log(receipt);
}
❗️❗️ Please review the following information before implementation❗️❗️
Remember to approve
contract
beforedeposit
if you're about to deposit ERC20 token.Remember to replace
amount
with the amount you want to deposit or withdraw.Remember to set
value
with the same amount asamount
if you're about to deposit native token.
Last updated
Was this helpful?