Search
 
SCRIPT & CODE EXAMPLE
 

TYPESCRIPT

deploy contract contracts using ethers.js ethers

const ethers = require("ethers")
// const solc = require("solc")
const fs = require("fs-extra")
require("dotenv").config()

async function main() {
    // First, compile this!
    // And make sure to have your ganache network up!
    let provider = new ethers.providers.JsonRpcProvider(process.env.RPC_URL)
    let wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider)
    // const encryptedJson = fs.readFileSync("./.encryptedKey.json", "utf8");
    // let wallet = new ethers.Wallet.fromEncryptedJsonSync(
    //   encryptedJson,
    //   process.env.PRIVATE_KEY_PASSWORD
    // );
    // wallet = wallet.connect(provider);
    const abi = fs.readFileSync("./SimpleStorage_sol_SimpleStorage.abi", "utf8")
    const binary = fs.readFileSync(
        "./SimpleStorage_sol_SimpleStorage.bin",
        "utf8"
    )
    const contractFactory = new ethers.ContractFactory(abi, binary, wallet)
    console.log("Deploying, please wait...")
    const contract = await contractFactory.deploy()
    // const contract = await contractFactory.deploy({ gasPrice: 100000000000 })
    const deploymentReceipt = await contract.deployTransaction.wait(1)
    console.log(`Contract deployed to ${contract.address}`)

    let currentFavoriteNumber = await contract.retrieve()
    console.log(`Current Favorite Number: ${currentFavoriteNumber}`)
    console.log("Updating favorite number...")
    let transactionResponse = await contract.store(7)
    let transactionReceipt = await transactionResponse.wait()
    currentFavoriteNumber = await contract.retrieve()
    console.log(`New Favorite Number: ${currentFavoriteNumber}`)
}

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error(error)
        process.exit(1)
    })
Comment

Contract in ethers.js

Provider:
A Provider (in ethers) is a class which provides an abstraction for a connection to the Ethereum Network. 
It provides read-only access to the Blockchain and its status.

import { ethers } from "ethers";
const provider = new ethers.providers.Web3Provider(window.ethereum)

Signer:
A Signer is a class which (usually) in some way directly or indirectly has access to a private key,
which can sign messages and transactions to authorize the network to charge your account ether to perform operations.

const signer = provider.getSigner()

Contract:
A Contract is an abstraction which represents a connection to a specific contract on the Ethereum Network,
so that applications can use it like a normal JavaScript object.
Comment

calling contract in ether.js

import { ethers, BigNumber } from 'ethers'


  const [contract, setContract] = useState<any>(undefined)
  const [count, setCount] = useState(BigNumber.from(0))

  useEffect(() => {
    // @ts-ignore
    const provider = new ethers.providers.Web3Provider(window.ethereum)
    setContract(
      new ethers.Contract(
        String(process.env.NEXT_PUBLIC_CONTRACT_ADDRESS),
        contractAbi,
        provider
      )
    )
  }, [])

return (
     <main>
        <button
          className="px-4 bg-red-500"
          onClick={async () => {setCount(await contract.count())}}
        >
          Count
        </button>
        <p>{count.toString()}</p>
      </main>
)

Comment

How to interact with a smart contract with ethers.js?

const tokenContract = new ethers.Contract(contractAddress, tokenAbi, connection);
const transaction = await tokenContract.balanceOf(req.body.address)
const data = Promise.resolve(transaction)
data.then(value => {
    const result = ethers.utils.formatUnits(value, 18);
    console.log(result)

});
Comment

PREVIOUS NEXT
Code Example
Typescript :: typescript returntype remove promise 
Typescript :: typescript loop over enum 
Typescript :: react-excel-renderer nextjs error 
Typescript :: typescript type number range 
Typescript :: typescript array of objects 
Typescript :: what is test data 
Typescript :: mongodb update all items in array 
Typescript :: decoDe query string to object javascript 
Typescript :: contract method calling with ether.js 
Typescript :: create react app with redux and typescript 
Typescript :: listobjects vba 
Typescript :: angular rxjs 
Typescript :: concat type typescript 
Typescript :: input fc typescript 
Typescript :: how to remove the last item from a collection powerapps 
Typescript :: from how many ways we can define props with typescript react 
Typescript :: react tailwind css components npm 
Typescript :: coldfusion arrayLast 
Typescript :: tar: refusing to read archive contents from terminal (missing -f option?) tar: error is not recoverable: exiting now 
Typescript :: Error: "prettier/@typescript-eslint" has been merged into "prettier" in eslint-config-prettier 8.0.0 
Typescript :: update object in array in ngxrx store in angular 
Typescript :: Start Angular App In Localhost 
Typescript :: No type arguments expected for interface Callback 
Typescript :: Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops. 
Typescript :: typescript export interface array 
Typescript :: nest js get request response 
Typescript :: share data across tab through localstorage 
Typescript :: not working npx react-native init MyApp --template react-native-template-typescript 
Typescript :: requests get with sign in 
Typescript :: what is use hsts in .net core 
ADD CONTENT
Topic
Content
Source link
Name
8+1 =