velas / velas-account-integration-example

0 stars 1 forks source link

getting error state does not match invalid state in processAuthResult function #1

Open webexpert979 opened 1 year ago

webexpert979 commented 1 year ago

Hi I am getting error state does not match invalid state in processAuthResult function image `import { React, useState, useEffect } from "react"; import { motion } from "framer-motion"; import Web3 from 'web3'; import { CONTACT_ABI } from '../abi'; import { MEMBER_ABI } from '../abi1'; import { COLLECTION_ABI } from '../abi2'; import {vaclient} from "./vaclient";

import questionMark from "../assets/images/questionMark.png"; import va from "../assets/images/va.svg" import mm from "../assets/images/MetaMask.png"

export default function MyNfts() { const dummayArray = Array(8).fill(0); const [account, setAccount] = useState(''); const [nfts, setNfts] = useState([]); const [userInfo, setUserInfo] = useState(null); const [sessionData, setSessionData] = useState(null);

const fadeLeft = { hidden: { opacity: 0, x: 300 }, show: { opacity: 1, x: 0, }, };

function processAuthResult (e, authResult) { window.history.replaceState({}, document.title, window.location.pathname); if (authResult && authResult.access_token_payload) { setSessionData(authResult);

  vaclient.userinfo(authResult.access_token, (e, result) => {
    if (e) {
      setSessionData(null);
      if (e.error === 'failed_authorization') {
        console.log(`Session terminated: ${e.description || e}`);
      } else {
        console.log(`Userinfo error: ${e.description || e}`);
      }
    } else {
      setUserInfo(result.userinfo);
      connect();
      document.getElementById('connect_lib').innerText = 'CONNECTED WALLET: '+sessionData.access_token_payload.sub;
    }
  });
} else if (e) {
  console.log(e);
}

}

useEffect(()=>{ vaclient.handleRedirectCallback(processAuthResult).catch((e)=>console.log(e)); }, [])

async function connect1() { document.getElementById('modalpopup').style.display= 'block'; } async function connect(){ document.getElementById('modalpopup').style.display= 'none'; const web3 = new Web3(Web3.givenProvider || "http://localhost:8545") const accounts = await web3.eth.requestAccounts(); const account = accounts[0]; setAccount(account); document.getElementById('connect_lib').innerText = 'CONNECTED WALLET: '+account; const contract = new web3.eth.Contract(COLLECTION_ABI, "0x480358ac2D4cD2f63BE59A5C4747bd07cd9a93C6"); const collections = await contract.methods.fetchCollectionItems().call(); console.log(collections); let collection = []; for(let i=0;i<collections.length;i++) { if(collections[i].deprecated==false) { let data = await fetch('https://evmexplorer.velas.com/address/0x103b074044fed0d0fcebeb028a65b8c29f1a17e6/tokens/'+collections[i].contractAddress+'/token-transfers?type=JSON') .then(res=>res.json()); for(let j=0;j<data.items.length;j++) { let parser = new DOMParser(); const doc = parser.parseFromString(data.items[j], 'text/html'); const tag = doc.querySelectorAll('[data-test="token_link"]'); const tokenId = tag[0].innerText; const tokenlink = tag[0].getAttribute('href'); const getpic = await fetch('https://evmexplorer.velas.com'+tokenlink+'/token-transfers').then(res=>res.text()); let parser1 = new DOMParser(); const doc1 = parser1.parseFromString(getpic, 'text/html');

        const img = doc1.querySelectorAll('[class="erc721-media"] img');
        const imgsrc = img[0].getAttribute('src');

        const name = doc.querySelectorAll('[class="d-none d-md-none d-lg-inline d-xl-inline"]');
        const nametag = collections[i].name;
        const contractAddress = collections[i].contractAddress;
        let nfts = {
            contractAddress,
            nametag,
            tokenId,
            imgsrc
        }
        collection.push(nfts);
    }
}
setNfts(collection);

}

} async function transferto(nft) { const web3 = new Web3(Web3.givenProvider || "http://localhost:8545") const accounts = await web3.eth.requestAccounts(); const account = accounts[0]; console.log(account); const contract = new web3.eth.Contract(MEMBER_ABI, "0xd4faA4a9cA8879E48aED6635e6f77eEaeE568Bad"); const contract1 = new web3.eth.Contract(CONTACT_ABI, nft.contractAddress); const member = await contract.methods.walletOfOwner(account).call(); if(member.length>0) { alert('Accept transfer request on metamask'); contract1.methods.transferFrom(account,"0xd4faA4a9cA8879E48aED6635e6f77eEaeE568Bad", nft.tokenId).send({from: account,gas:'3000000'}) .on('confirmation', function(confirmationNumber, receipt){ alert('Accept swapped nft metamask transfer request'); contract.methods.transfer().send({from: account, value:'30000000000000000000', gas:'3000000'}) .on('confirmation', function(confirmationNumber, receipt){ alert('You have successfully got swapped NFT'); }); });

}
else {
    alert('Accept transfer request on metamask');
    contract1.methods.transferFrom(account,"0xd4faA4a9cA8879E48aED6635e6f77eEaeE568Bad",
    nft.tokenId).send({from: account,gas:'3000000'})
    .on('confirmation', function(confirmationNumber, receipt){
        alert('Accept swapped nft metamask transfer request');
        contract.methods.transfer().send({from: account, value:'60000000000000000000',
        gas:'3000000'})
        .on('confirmation', function(confirmationNumber, receipt){
            alert('You have successfully got swapped NFT');
        });
    });

}

}; async function transferto2(nft) { const web3 = new Web3(vaclient.provider) const accounts = await web3.eth.requestAccounts(); const account = accounts[0]; console.log(account); const contract = new web3.eth.Contract(MEMBER_ABI, "0xd4faA4a9cA8879E48aED6635e6f77eEaeE568Bad"); const contract1 = new web3.eth.Contract(CONTACT_ABI, nft.contractAddress); const member = await contract.methods.walletOfOwner(account).call(); if(member.length>0) { alert('Accept transfer request on velas account'); contract1.methods.transferFrom(account,"0xd4faA4a9cA8879E48aED6635e6f77eEaeE568Bad", nft.tokenId).send({from: account,gas:'3000000'}) .on('confirmation', function(confirmationNumber, receipt){ alert('Accept swapped nft velas account transfer request'); contract.methods.transfer().send({from: account, value:'30000000000000000000', gas:'3000000'}) .on('confirmation', function(confirmationNumber, receipt){ alert('You have successfully got swapped NFT'); }); });

}
else {
    alert('Accept transfer request on metamask');
    contract1.methods.transferFrom(account,"0xd4faA4a9cA8879E48aED6635e6f77eEaeE568Bad",
    nft.tokenId).send({from: account,gas:'3000000'})
    .on('confirmation', function(confirmationNumber, receipt){
        alert('Accept swapped nft metamask transfer request');
        contract.methods.transfer().send({from: account, value:'60000000000000000000',
        gas:'3000000'})
        .on('confirmation', function(confirmationNumber, receipt){
            alert('You have successfully got swapped NFT');
        });
    });

}

}; async function transferto1(nft) { const web3 = new Web3(Web3.givenProvider || "http://localhost:8545") const accounts = await web3.eth.requestAccounts(); const account = accounts[0]; console.log(account); const contract = new web3.eth.Contract(MEMBER_ABI, "0x98829f0B9Eb3860DEB1444DE2d5d26bcB46fBF6A"); const contract2 = new web3.eth.Contract(MEMBER_ABI, "0xd4faA4a9cA8879E48aED6635e6f77eEaeE568Bad"); const contract1 = new web3.eth.Contract(CONTACT_ABI, nft.contractAddress); const member = await contract.methods.walletOfOwner(account).call(); if(member.length>0) { alert('Accept transfer request on metamask'); contract1.methods.transferFrom(account,"0xd4faA4a9cA8879E48aED6635e6f77eEaeE568Bad", nft.tokenId).send({from: account,gas:'3000000'}) .on('confirmation', function(confirmationNumber, receipt){ alert('Accept one time use token transfer request'); contract.methods.transferFrom(account,"0xd4faA4a9cA8879E48aED6635e6f77eEaeE568Bad", member[0]).send({from: account,gas:'3000000'}) .on('confirmation', function(confirmationNumber, receipt){ alert('Accept swapped nft metamask transfer request'); contract2.methods.transfer().send({from: account,gas:'3000000',value:'0'}) .on('confirmation', function(confirmationNumber, receipt){ alert('You have successfully got swapped NFT'); }); }); });

}
else {

    alert('You do not have one time use token');
}

}; async function transferto3(nft) { const web3 = new Web3(vaclient.provider) const accounts = await web3.eth.requestAccounts(); const account = accounts[0]; console.log(account); const contract = new web3.eth.Contract(MEMBER_ABI, "0x98829f0B9Eb3860DEB1444DE2d5d26bcB46fBF6A"); const contract2 = new web3.eth.Contract(MEMBER_ABI, "0xd4faA4a9cA8879E48aED6635e6f77eEaeE568Bad"); const contract1 = new web3.eth.Contract(CONTACT_ABI, nft.contractAddress); const member = await contract.methods.walletOfOwner(account).call(); if(member.length>0) { alert('Accept transfer request on velas account'); contract1.methods.transferFrom(account,"0xd4faA4a9cA8879E48aED6635e6f77eEaeE568Bad", nft.tokenId).send({from: account,gas:'3000000'}) .on('confirmation', function(confirmationNumber, receipt){ alert('Accept one time use token transfer request'); contract.methods.transferFrom(account,"0xd4faA4a9cA8879E48aED6635e6f77eEaeE568Bad", member[0]).send({from: account,gas:'3000000'}) .on('confirmation', function(confirmationNumber, receipt){ alert('Accept swapped nft velas account transfer request'); contract2.methods.transfer().send({from: account,gas:'3000000',value:'0'}) .on('confirmation', function(confirmationNumber, receipt){ alert('You have successfully got swapped NFT'); }); }); });

}
else {

    alert('You do not have one time use token');
}

}; return ( <section className="w-full bg-primary bg-full bg-center bg-no-repeat object-cover px-6 font-primary py-[8rem] smMax:py-[4rem] text-center" id="kennels"

<button onClick={()=>{
    if(!sessionData && !userInfo){
      vaclient.authorize({
        csrfToken: async function () {
          const response = await fetch("http://localhost:3002/csrf/", {
            method: "GET",
            headers: {
              'Content-Type': 'application/json'
            }
          });
          const {token} = await response.json();
          return token
        },
        scope: 'VelasAccountProgram:Transfer VelasAccountProgram:Execute'
      }, processAuthResult);
    }
}} className="w-1/4 bg-white px-6 py-6 border-black border-2 opacity-100">

                  <img src={va} />

              </button>
             <br />
<button onClick={()=>connect()} className="w-1/4 bg-white px-6 py-6 border-black border-2 opacity-100">

                  <img src={mm} />

              </button>

</div>
<button onClick={()=>connect1()} id='connect_lib' className="text-2xl mb-4 font-bold text-white bg-pink-500 rounded py-2 px-12 m-auto">

                  CONNECT

              </button>
  <h2 className="font-goBold text-4xl text-white text-center pb-[5.5rem] pt-12 uppercase">
    My NFT's
  </h2>
  <div className="max-w-[93rem] m-auto grid grid-cols-4 xlMax:grid-cols-3 mdMax:grid-cols-2 smMax:grid-cols-1 gap-10">

        { nfts.map((nft, i) => (

          <div key={i} className="border shadow rounded-xl overflow-hidden">
          <div className="p-4">
              <p style={{ height: '64px' }} className="text-2xl font-semibold text-white">{nft.nametag}</p>
              <div className="p-4 bg-black">
              <p className="text-2xl mb-4 font-bold text-white">TokenID {nft.tokenId}</p>
              <img src={nft.imgsrc} />
              <br />
              {sessionData && userInfo ?
              <>
              <button onClick={()=>transferto2(nft)} className="text-2xl mb-4 font-bold text-white bg-pink-500 rounded py-2 px-12">

                  SWAP WITH VLX

              </button>
              <button onClick={()=>transferto3(nft)} className="text-2xl mb-4 font-bold text-white bg-pink-500 rounded py-2 px-12">

                  SWAP WITH ONE TIME USE TOKEN

              </button>
              </>
              :
              <>
              <button onClick={()=>transferto(nft)} className="text-2xl mb-4 font-bold text-white bg-pink-500 rounded py-2 px-12">

                  SWAP WITH VLX

              </button>
              <button onClick={()=>transferto1(nft)} className="text-2xl mb-4 font-bold text-white bg-pink-500 rounded py-2 px-12">

                  SWAP WITH ONE TIME USE TOKEN

              </button>
              </>
              }
            </div>
          </div>
          </div>

        ))
      }
  </div>
</section>

); } `

yelagins commented 1 year ago

Hi!

After vaclient.authorize "state" is created in the localstorage:

image

Check that your application does not clear them. This data should remain after the redirect with successful authorization.

Also you can compare how it woks on https://account-demo.testnet.velas.com

webexpert979 commented 1 year ago

After successful redirect it is there only until the page is still loading when the page loads completely it has cleared automatically I don't know why and in the demo it creates a session variable in the localstorage but here it doesn't create it.

yelagins commented 1 year ago

Please check if the vaclient.handleRedirectCallback method is being called multiple times during page loading?

webexpert979 commented 1 year ago

Yes i think that could be the issue because i see console.logs two times but i don't know how to fix it though useEffect is used only once in code image

webexpert979 commented 1 year ago

i removed React.StrictMode and now it is showing console.log one time so useeffect is running one time but still the localstorage state is cleared on page load

webexpert979 commented 1 year ago

Hi, can anyone please help I am still stuck with the issue ?

yelagins commented 1 year ago

you already have another error. Show pls what response you get after "handleRedirectCallback"

webexpert979 commented 1 year ago

ok I solved it somehow and it is logging in successfully but now I have another problem it is not able to fetch the provider for web3 transactions. it gives the error Method not found image I am getting the following VAClient object after login image `