tronprotocol / tronweb

Javascript API Library for interacting with the TRON Network
MIT License
431 stars 272 forks source link

CORS error #494

Closed Emirhan-Cavusoglu-sftw closed 6 months ago

Emirhan-Cavusoglu-sftw commented 6 months ago

I am trying to call my contract's function but it givees me this error

Access to XMLHttpRequest at 'https://api.shasta.trongrid.io/wallet/getcontract?value=411ad64bbbe85a807efe697f505fea747cd015359c' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field tron-pro-api-key is not allowed by Access-Control-Allow-Headers in preflight response.

my repo: https://github.com/Emirhan-Cavusoglu-sftw/TVA

code

"use client"
import React, { useState, useEffect } from "react";
import { AnimatePresence, motion } from "framer-motion";
import testABI from "./abis/testABI.json";
import {testAddress} from "./Utils/addresses.js";
import { addRequestMeta } from "next/dist/server/request-meta";
const TronWeb = require('tronweb');

const tronWeb = new TronWeb({
  fullHost: 'https://api.shasta.trongrid.io',
  headers: { 'TRON-PRO-API-KEY': '7c7f62a2-256b-4779-a1c0-1e6a6f7f934b' ,

},
  privateKey: process.env.NEXT_PUBLIC_PRIVATE_KEY,

});

const images = [
  "https://images.unsplash.com/photo-1505533321630-975218a5f66f?q=80&w=1074&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1591779051696-1c3fa1469a79?q=80&w=1074&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1626808642875-0aa545482dfb?q=80&w=987&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1526779259212-939e64788e3c?q=80&w=1174&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1530076886461-ce58ea8abe24?q=80&w=1171&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1570051008600-b34baa49e751?q=80&w=1185&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
];

const variants = {
  initial: (direction) => {
    return {
      x: direction > 0 ? 1000 : -1000,
      opacity: 0,
    };
  },
  animate: {
    x: 0,
    opacity: 1,

    transition: {
      x: { type: "spring", stiffness: 300, damping: 30 },
      opacity: { duration: 0.2 },
    },
  },
  exit: (direction) => {
    return {
      x: direction > 0 ? -1000 : 1000,
      opacity: 0,

      transition: {
        x: { type: "spring", stiffness: 300, damping: 30 },
        opacity: { duration: 0.2 },
      },
    };
  },
};

export default function Home() {
  const [index, setIndex] = useState(0);
  const [direction, setDirection] = useState(0);
  const [result, setresult] = useState({})
  const [contract, setContract] = useState({})
  // const contract = tronWeb.contract(testABI, testAddress);

  // console.log(contract);
console.log(window.tronWeb.defaultAddress.base58);
tronWeb.setAddress(window.tronWeb.defaultAddress.base58);
  async function store() {
    try {
      const result = await contract.store(4).send({
        callValue: 0,
        shouldPollResponse: true,

      })
    } catch (error) {
      console.log(error);
    }

    setresult(result);
  }
  console.log(result);
  useEffect(() => {
    // const interval = setInterval(() => {
    //   nextStep();
    // }, 5000);

    // return () => clearInterval(interval);
  }, [index]);

  useEffect(() => {
    async function setContract(){
      const contract = await tronWeb.contract().at("TCR7Haj8axUtxaWQq8V8hFuEySHmRHnHK9");
      setContract(contract);
    }

   setContract();

  }, [])

  function nextStep() {
    setDirection(1);
    if (index === images.length - 1) {
      setIndex(0);
      return;
    }
    setIndex(index + 1);
  }

  function prevStep() {
    setDirection(-1);
    if (index === 0) {
      setIndex(images.length - 1);
      return;
    }
    setIndex(index - 1);
  }

  return (
    <div className="bg-gradient-to-r flex items-center justify-center from-purple-950 to-violet-600 min-h-screen flex-col">
      <div className="slideshow">
        <AnimatePresence initial={false} custom={direction}>
          <motion.img
            variants={variants}
            animate="animate"
            initial="initial"
            exit="exit"
            src={images[index]}
            alt="slides"
            className="slides"
            key={images[index]}
            custom={direction}
          />
        </AnimatePresence>
        <button className="prevButton" onClick={prevStep}>
          ◀
        </button>
        <button className="nextButton" onClick={nextStep}>
          ▶
        </button>
      </div>

      <motion.div
          className="text-white h-10"
          initial={{ opacity: 0, scale: 0.5 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.5 }}>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Placeat sit adipisci aliquam cum magnam vero tempore facilis voluptatibus eius, fuga repudiandae tenetur reprehenderit? Ducimus ullam vel, aut deleniti magnam suscipit.</p>
      </motion.div>

      <button onClick={()=>store()}>
        ONCLICK
      </button>

    </div>
  );
}

please I am in hackathon btw but I couldnt even call the basic function

start940315 commented 6 months ago

Currently using Trongrid to request the Shasta/Nile testnet does not need to set an API Key. https://developers.tron.network/reference/select-network

Emirhan-Cavusoglu-sftw commented 6 months ago

thanks cors error fixed ı guess but it gives me this error now Private key does not match address in transaction

why is this happening do you have any idea because my private key is correct actually

"use client"
import React, { useState, useEffect } from "react";
import { AnimatePresence, motion } from "framer-motion";
import testABI from "./abis/testABI.json";
import {testAddress} from "./Utils/addresses.js";
import { addRequestMeta } from "next/dist/server/request-meta";
const TronWeb = require('tronweb');

const tronWeb = new TronWeb({
  fullHost: 'https://api.shasta.trongrid.io',
  headers: { 

},
  privateKey: process.env.NEXT_PUBLIC_PRIVATE_KEY,

});

const images = [
  "https://images.unsplash.com/photo-1505533321630-975218a5f66f?q=80&w=1074&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1591779051696-1c3fa1469a79?q=80&w=1074&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1626808642875-0aa545482dfb?q=80&w=987&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1526779259212-939e64788e3c?q=80&w=1174&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1530076886461-ce58ea8abe24?q=80&w=1171&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1570051008600-b34baa49e751?q=80&w=1185&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
];

const variants = {
  initial: (direction) => {
    return {
      x: direction > 0 ? 1000 : -1000,
      opacity: 0,
    };
  },
  animate: {
    x: 0,
    opacity: 1,

    transition: {
      x: { type: "spring", stiffness: 300, damping: 30 },
      opacity: { duration: 0.2 },
    },
  },
  exit: (direction) => {
    return {
      x: direction > 0 ? -1000 : 1000,
      opacity: 0,

      transition: {
        x: { type: "spring", stiffness: 300, damping: 30 },
        opacity: { duration: 0.2 },
      },
    };
  },
};

export default function Home() {
  const [index, setIndex] = useState(0);
  const [direction, setDirection] = useState(0);
  const [result, setresult] = useState({})
  // const [contract, setContract] = useState({})
  const contract = tronWeb.contract(testABI, testAddress);

  // console.log(contract);
console.log(window.tronWeb.defaultAddress.base58);
tronWeb.setAddress(window.tronWeb.defaultAddress.base58);
  async function store() {
    try {
      const result = await contract.store(4).send({
        callValue: 0,
        shouldPollResponse: true,

      })
    } catch (error) {
      console.log(error);
    }

    setresult(result);
  }
  console.log(result);
  useEffect(() => {
    // const interval = setInterval(() => {
    //   nextStep();
    // }, 5000);

    // return () => clearInterval(interval);
  }, [index]);

  // useEffect(() => {
  //   async function setContract(){
  //     const contract = await tronWeb.contract().at("TCR7Haj8axUtxaWQq8V8hFuEySHmRHnHK9");
  //     setContract(contract);
  //   }

  //  setContract();

  // }, [])

  function nextStep() {
    setDirection(1);
    if (index === images.length - 1) {
      setIndex(0);
      return;
    }
    setIndex(index + 1);
  }

  function prevStep() {
    setDirection(-1);
    if (index === 0) {
      setIndex(images.length - 1);
      return;
    }
    setIndex(index - 1);
  }

  return (
    <div className="bg-gradient-to-r flex items-center justify-center from-purple-950 to-violet-600 min-h-screen flex-col">
      <div className="slideshow">
        <AnimatePresence initial={false} custom={direction}>
          <motion.img
            variants={variants}
            animate="animate"
            initial="initial"
            exit="exit"
            src={images[index]}
            alt="slides"
            className="slides"
            key={images[index]}
            custom={direction}
          />
        </AnimatePresence>
        <button className="prevButton" onClick={prevStep}>
          ◀
        </button>
        <button className="nextButton" onClick={nextStep}>
          ▶
        </button>
      </div>

      <motion.div
          className="text-white h-10"
          initial={{ opacity: 0, scale: 0.5 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.5 }}>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Placeat sit adipisci aliquam cum magnam vero tempore facilis voluptatibus eius, fuga repudiandae tenetur reprehenderit? Ducimus ullam vel, aut deleniti magnam suscipit.</p>
      </motion.div>

      <button onClick={()=>store()}>
        ONCLICK
      </button>

    </div>
  );
}
start940315 commented 6 months ago

You have called

tronWeb.setAddress(window.tronWeb.defaultAddress.base58);

which means you set the address to the tronlink address. It happens when your tronlink privateKey does not match process.env.NEXT_PUBLIC_PRIVATE_KEY.

Emirhan-Cavusoglu-sftw commented 6 months ago

I did that because if I don't it gives me invalid issuer address but I will try thank you again

Emirhan-Cavusoglu-sftw commented 6 months ago

yep know it gives me Invalid issuer address provided why I cannot call basic function :( btw call() works I mean I can fetch from contract but I cannot call function that changes state :( I am using tronwallet adapter for wallet maybe there is a problem but I think not

"use client"
import React, { useState, useEffect } from "react";
import { AnimatePresence, motion } from "framer-motion";
import testABI from "./abis/testABI.json";
import {testAddress} from "./Utils/addresses.js";
import { addRequestMeta } from "next/dist/server/request-meta";
const TronWeb = require('tronweb');

const tronWeb = new TronWeb({
  fullHost: 'https://api.shasta.trongrid.io',
  headers: { 

},

  privatekey: process.env.NEXT_PUBLIC_PRIVATE_KEY,
});

const images = [
  "https://images.unsplash.com/photo-1505533321630-975218a5f66f?q=80&w=1074&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1591779051696-1c3fa1469a79?q=80&w=1074&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1626808642875-0aa545482dfb?q=80&w=987&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1526779259212-939e64788e3c?q=80&w=1174&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1530076886461-ce58ea8abe24?q=80&w=1171&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  "https://images.unsplash.com/photo-1570051008600-b34baa49e751?q=80&w=1185&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
];

const variants = {
  initial: (direction) => {
    return {
      x: direction > 0 ? 1000 : -1000,
      opacity: 0,
    };
  },
  animate: {
    x: 0,
    opacity: 1,

    transition: {
      x: { type: "spring", stiffness: 300, damping: 30 },
      opacity: { duration: 0.2 },
    },
  },
  exit: (direction) => {
    return {
      x: direction > 0 ? -1000 : 1000,
      opacity: 0,

      transition: {
        x: { type: "spring", stiffness: 300, damping: 30 },
        opacity: { duration: 0.2 },
      },
    };
  },
};

export default function Home() {
  const [index, setIndex] = useState(0);
  const [direction, setDirection] = useState(0);
  const [result, setresult] = useState({})
  // const [contract, setContract] = useState()
  const contract = tronWeb.contract(testABI, testAddress);

  // console.log(contract);
// console.log(window.tronWeb.defaultAddress.base58);
// tronWeb.setAddress(window.tronWeb.defaultAddress.base58);
  async function store(i) {
    try {
      const result = await contract.store(i).send({
        callValue: 0,
        shouldPollResponse: true,

      })
    } catch (error) {
      console.log(error);
    }

    setresult(result);
  }
  console.log(result);
  useEffect(() => {
    // const interval = setInterval(() => {
    //   nextStep();
    // }, 5000);

    // return () => clearInterval(interval);
  }, [index]);

  useEffect(() => {
  //   async function setContract(){
  //     const contract = await tronWeb.contract().at("TCR7Haj8axUtxaWQq8V8hFuEySHmRHnHK9");
  //     setContract(contract);
  //     console.log(contract);
  //   }

  //  setContract();
     async function getContract(){
      let result = await contract.retrieve().call();
      console.log(result);
     }
    getContract();
  }, [])

  function nextStep() {
    setDirection(1);
    if (index === images.length - 1) {
      setIndex(0);
      return;
    }
    setIndex(index + 1);
  }

  function prevStep() {
    setDirection(-1);
    if (index === 0) {
      setIndex(images.length - 1);
      return;
    }
    setIndex(index - 1);
  }

  return (
    <div className="bg-gradient-to-r flex items-center justify-center from-purple-950 to-violet-600 min-h-screen flex-col">
      <div className="slideshow">
        <AnimatePresence initial={false} custom={direction}>
          <motion.img
            variants={variants}
            animate="animate"
            initial="initial"
            exit="exit"
            src={images[index]}
            alt="slides"
            className="slides"
            key={images[index]}
            custom={direction}
          />
        </AnimatePresence>
        <button className="prevButton" onClick={prevStep}>
          ◀
        </button>
        <button className="nextButton" onClick={nextStep}>
          ▶
        </button>
      </div>

      <motion.div
          className="text-white h-10"
          initial={{ opacity: 0, scale: 0.5 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.5 }}>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Placeat sit adipisci aliquam cum magnam vero tempore facilis voluptatibus eius, fuga repudiandae tenetur reprehenderit? Ducimus ullam vel, aut deleniti magnam suscipit.</p>
      </motion.div>

      <button onClick={()=>store(3)}>
        ONCLICK
      </button>

    </div>
  );
}
start940315 commented 6 months ago

I pulled your repo and tried on my computer, your code works.

Emirhan-Cavusoglu-sftw commented 6 months ago

I didn't push this last error version can you pull it

start940315 commented 6 months ago

There is a typo in your code privateKey, not privatekey. You can try our beta version which support typescript, so you won't get this error:

npm install tronweb@beta
Emirhan-Cavusoglu-sftw commented 6 months ago

can you look at the latest push I have changed typo and comment the setAddress function line but it gives me Invalid issuer address provided but if I setAddress it fetchs data but cant write it when I click onclick button it still gives private key doesnt match error

start940315 commented 6 months ago

Did you start your dev server with the correct privateKey env variable?

Emirhan-Cavusoglu-sftw commented 6 months ago

yes isnt that tronlink private key

start940315 commented 6 months ago

As I tested using a valid privateKey, all things work. So I guess you have not provide a valid privateKey. Please recheck it.

Emirhan-Cavusoglu-sftw commented 6 months ago

As you said if I dont use setAddress function I dont get this error but I get İnvalid issuer provided error how can I fix it

start940315 commented 6 months ago

Can you print your tronWeb.defaultAddress.base58 out? If it is empty, it's definitely that your privateKey is invalid. Please recheck your privateKey. Is it 64 digits long? You can use tronWeb.address.fromPrivateKey to get the address of the privateKey

Emirhan-Cavusoglu-sftw commented 6 months ago

yup it gives the address TUwGQNag8QCWWWaPbbRuLs1Zsne1Ro7icv

Emirhan-Cavusoglu-sftw commented 6 months ago

heyy it I fixed it looked at your demo but there is an issue here when I click the button the tronlink pop-up shows up and I can sign it but transaction gives "Out of energy" Error my code is this

"use client";
import React, { useState, useEffect } from "react";
import { AnimatePresence, motion } from "framer-motion";
import testABI from "./abis/testABI.json";
import { testAddress } from "./Utils/addresses.js";
import { addRequestMeta } from "next/dist/server/request-meta";
import { useWallet } from "@tronweb3/tronwallet-adapter-react-hooks";
const TronWeb = require("tronweb");

const tronWeb = new TronWeb({
  fullHost: "https://nile.trongrid.io/",
  headers: {},

});

export const sign = async transaction => {
  try {
    const tronweb = window.tronWeb;
    const signedTransaction = await tronweb.trx.sign(transaction.transaction);
    return signedTransaction;
  } catch (error) {
    console.log(error, 'signerr');
    throw new Error(error);
  }
};

export const sendRawTransaction = async signedTransaction => {
  try {
    const tronweb = window.tronWeb;
    const result = await tronweb.trx.sendRawTransaction(signedTransaction);
    return result;
  } catch (error) {
    throw new Error(error);
  }
};

export default function Home() {
  const { connect, disconnect, select, connected ,address,} = useWallet();
  const [index, setIndex] = useState(0);
  const [direction, setDirection] = useState(0);
  const [result, setresult] = useState({});
  // const [contract, setContract] = useState()
  const contract = tronWeb.contract(testABI, testAddress);

  console.log(window.tronWeb);
  tronWeb.setAddress(window.tronWeb.defaultAddress.base58);

  console.log(tronWeb.defaultAddress.base58)

  async function store(i) {
    try {
      // const result = await contract.store(i).send({
      //   callValue: 0,
      //   shouldPollResponse: true,
      // });

      const result = await tronWeb.transactionBuilder.triggerSmartContract(
        "TB7T4yaLzYD1mhDp3FgbuzLFmhZdCy1QDH",
        "store(uint256)",
        { _isConstant: true },
        [{ type: "uint256", value: 5 }],
      );
      console.log(result);
      const signedTransaction = await sign(result);
      const transaction = await sendRawTransaction(signedTransaction);
      console.log(transaction);
    } catch (error) {
      console.log(error);
    }

    setresult(result);
  }

  useEffect(() => {
    // const interval = setInterval(() => {
    //   nextStep();
    // }, 5000);
    // return () => clearInterval(interval);
  }, [index]);

  useEffect(() => {
    //   async function setContract(){
    //     const contract = await tronWeb.contract().at("TCR7Haj8axUtxaWQq8V8hFuEySHmRHnHK9");
    //     setContract(contract);
    //     console.log(contract);
    //   }

    //  setContract();
    async function getContract() {
      let result = await contract.retrieve().call();
      console.log(result);
    }
    getContract();
  }, []);

  function nextStep() {
    setDirection(1);
    if (index === images.length - 1) {
      setIndex(0);
      return;
    }
    setIndex(index + 1);
  }

  function prevStep() {
    setDirection(-1);
    if (index === 0) {
      setIndex(images.length - 1);
      return;
    }
    setIndex(index - 1);
  }

  return (
    <div className="bg-gradient-to-r from-purple-950 to-violet-600 flex items-center justify-center min-h-screen flex-col">
      <div className="slideshow">

        <button className="prevButton" onClick={prevStep}>
          ◀
        </button>
        <button className="nextButton" onClick={nextStep}>
          ▶
        </button>
      </div>

      <motion.div
        className="text-white h-10"
        initial={{ opacity: 0, scale: 0.5 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ duration: 0.5 }}
      >
        <p>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Placeat sit
          adipisci aliquam cum magnam vero tempore facilis voluptatibus eius,
          fuga repudiandae tenetur reprehenderit? Ducimus ullam vel, aut
          deleniti magnam suscipit.
        </p>
      </motion.div>

      <button onClick={() => store(3)}>ONCLICK</button>
    </div>
  );
}
start940315 commented 6 months ago

You should set { _isConstant: false }.