John Davidson

erc721 - Get past transactions on a contract using web3.php

0 comments
Message:


I am using web3.php script and need to get minted NFT IDs from a contract.


Solution I think about is to read past contract "transfer" events and get tokenId from its data.
but couldn't find any manual on how to do this with WEB3 PHP or if there is another way to this?


PS: Because of some restrictions on development, we have to use php


PS2: It can be done in seconds using Moralis but we are using a custom chain on our local so cannot use moralis web3 api



My Answer:
To get past transactions on a contract using web3.php, you can use the following steps:

1. Connect to your Ethereum node using web3.php:

php
use Web3\Web3;
use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;

$web3 = new Web3(new HttpProvider(new HttpRequestManager('http://localhost:8545')));


2. Get the contract ABI and address:

php
$contractABI = json_decode('[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"}]');
$contractAddress = '0x1234567890abcdef1234567890abcdef12345678';


3. Create a contract instance:

php
$contract = $web3->eth->contract($contractABI)->at($contractAddress);


4. Get past events for the "Transfer" event:

php
$events = $contract->getPastEvents('Transfer', [
'fromBlock' => 'earliest',
'toBlock' => 'latest',
]);


5. Iterate through the events and extract the token IDs:

php
foreach ($events as $event) {
$tokenId = $event['args']['tokenId'];
echo "Token ID: $tokenId\n";
}


This code will allow you to retrieve past "Transfer" events from the contract and extract the token IDs. You can modify it to suit your specific contract and requirements.

Rate this post

5 of 5 based on 3462 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us