web3p / web3.php

A php interface for interacting with the Ethereum blockchain and ecosystem. Native ABI parsing and smart contract interactions.
MIT License
1.17k stars 550 forks source link

Calling a function that has owner privilege #240

Closed Razorholt closed 2 years ago

Razorholt commented 2 years ago

I have this function in the smart contract that I would like to call from PHP:

modifier onlyOwner() {
    require(isOwner(msg.sender), "!OWNER"); _;
}

function addToCommunityList(address[] calldata addresses) external onlyOwner{
    for (uint256 i; i < addresses.length; ++i) {
      isAddedToCommunity[addresses[i]] = true;
    }
}

How do I sign this?

$contract->at($contractAddress)->call("addToCommunityList", "0x7href...", function ($err, $added) use(&$done) {
     if($err) { 
         echo 'getTransactionCount error: ' . $err->getMessage() . "<br>"; 
     } else {
         $done = $added;
     }
});

Thank you!

samyan commented 2 years ago

Hello,

Try in this way. Adapt it to your code.

$data = $this->contractInstance->getData('addToCommunityList', $yourAddressList);

// Build transaction
$transaction = new Transaction([
    'nonce' => $nonce,
    'from' => $fromAddress,
    'to' => $contractAddress,
    'gasPrice' => $gasPrice,
    'gasLimit' => $gasLimit,
    'value' => '0x0',
    'data' => sprintf('0x%s', $data),
    'chainId' => $chainId,
]);

// Sign transaction
$signedTx = $transaction->sign($fromAddressKey);

$txId = '';

// Send transaction
$this->web3->getEth()->sendRawTransaction(sprintf('0x%s', $signedTx), function ($err, $tx) use (&$txId) {
    if ($err !== null) {
        throw new \Exception($err->getMessage());
    }

    $txId = $tx;
});

echo $txId;

Dependency: ethereum-tx

Razorholt commented 2 years ago

Works perfectly! Thank you so much @samyan !!