2

I have a ERC20 token and I have created smart contract to buy and sell the token. I have also created frontend with next.js and ethers.js everything works perfectly. I have also created an API to buy my token. My API works when I use the signer with a predefined private address. But my requirement is that the signer changes based on the user. I want to know how to implement that.(My code below works for 1 user because I am using private key of my address directly) what I want : Use the same code for different users

My API for buy_token:

import {ethers} from 'ethers';
import { createTokenSwapInstance ,provider } from '../../../helpers/contractInstance/tokenSwapInstance';
//import { tokenSwapAddress} from '../../../config';

export default async function handler(req,res){
    if(req.method === 'POST'){
        //Check if data is present
        const tokenSwapAddress = '<token address>'
        const numberOfTokens = req.body.numberOfTokens;
        console.log("numberOfTokens", numberOfTokens)
      
        if(numberOfTokens === undefined ||numberOfTokens === ''|| numberOfTokens === 0){
            res.status(400).json({success: false, msg: 'Number of tokens is required.'});
            return;
        }
        
        const feePercent = 3;
        const tokenPrice = 0.0168;
        
        //Calculating total fee amount to pay
        const numberOfTokensinNum = Number(numberOfTokens)
        const numberOftokensinWei = ethers.utils.parseEther(String(numberOfTokens))
        console.log('numberOftokensinWei', numberOftokensinWei)
        const totalfee = (numberOfTokensinNum * feePercent)/100;
        const totalAmount = (numberOfTokensinNum + totalfee) * tokenPrice
        const totalAmountinWei = ethers.utils.parseEther(String(totalAmount))
        console.log('TotalAmount', totalAmountinWei)
        
        //Buy tokens
        try{
           const tx = await createTokenSwapInstance.functions.buyTokens(numberOftokensinWei,{
            value: totalAmountinWei,
            gasLimit: 5000000
           })
           await tx.wait();
           res.status(200).json({success: true, msg:'Transaction Successful.'})
        }
        catch(error){
            console.log(error);
            res.status(500).json({success: false, msg:'Transaction Failed. Please try again.'})
        }
    }else{
        res.status(400).json({success: false, msg: 'Bad request.'})
    }
}

My createTokenSwapInstance:

import { ethers } from 'ethers';
//import Web3Modal from 'web3modal';
import path from 'path';
import fs from 'fs';
import { sign } from 'crypto';

export const infuraId = `<END POINT>`


export const provider = new ethers.providers.StaticJsonRpcProvider(infuraId)
const signer = new ethers.Wallet('<PRIVATE KEY>', provider)

const swapContractAddress = '<TOKEN SWAP ADDRESS>'
const tokenContractAddress ='<TOKEN ADDRESS>'


const tokenSwapContractAbi = () => {
    try {
      const dir = path.resolve(
        './',
        './artifacts/contracts/token_swap.sol/AeroSwap.json'
      )
      const file = fs.readFileSync(dir, 'utf8')
      const json = JSON.parse(file)
      const abi = json.abi
      return abi
    } catch (e) {
      console.log(`e`, e)
    }
  }

  export const createTokenSwapInstance = new ethers.Contract(
    swapContractAddress,
    tokenSwapContractAbi(),
    signer
  )

1 Answer 1

2

You need multiple signers:

const signer1 = new ethers.Wallet('<PRIVATE KEY>', provider)
const signer2 = new ethers.Wallet('<PRIVATE KEY>', provider)
const signer3 = new ethers.Wallet('<PRIVATE KEY>', provider)

You can then call any function using connect method with the signer of your choice.

await createTokenSwapInstance.connect(signer1).buyTokens(...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.