PHP code example of gmajor / php-substrate-api

1. Go to this page and download the library: Download gmajor/php-substrate-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gmajor / php-substrate-api example snippets



# When installed via composer


use Rpc\SubstrateRpc;
// http client
$httpClient = new SubstrateRpc("https://kusama-rpc.polkadot.io/");
// websocket client 
$websocketClient = new SubstrateRpc("wss://kusama-rpc.polkadot.io/");
$websocketClient->close(); // close websocket connection


use Rpc\SubstrateRpc;
$client = new SubstrateRpc("wss://kusama-rpc.polkadot.io/");

// call any json rpc you can use $client->rpc->{$pallet_name}->{$method}, like
// call rpc system_health 
$res = $client->rpc->system->health(); 
var_dump($res); #{"peers": 31, "isSyncing": false, "shouldHavePeers": true}
// or call rpc chain_getFinalizedHead
$client->rpc->chain->getFinalizedHead(); 

$client->close(); // do not forget close websocket connection !


use Rpc\Hasher\Hasher;

$hasher = new Hasher();
// Blake2_128
$hasher->ByHasherName("Blake2_128", "20be52a5a80cad065651ec35fcb1a212bc669aabb52d68d8780a41e29ec9c83e");
// Blake2_256
$hasher->ByHasherName("Blake2_256", "20be52a5a80cad065651ec35fcb1a212bc669aabb52d68d8780a41e29ec9c83e")
// Twox128
$hasher->TwoxHash("Key", 128)
// Twox128
$hasher->TwoxHash("Sudo", 256)
// XXHash64
$hasher->XXHash64(0, "test");
// Twox64Concat
$hasher->ByHasherName("Twox64Concat", "0xad2ecd66275a1ded")
//  Blake2_128Concat
$hasher->ByHasherName("Blake2_128Concat", "20be")


use Rpc\StorageKey;

use Codec\Base;
use Codec\ScaleBytes;
use Codec\Types\ScaleInstance;
use Rpc\StorageKey;

$codec = new ScaleInstance(Base::create());
$metadataV14RawValue = "...." //  from json rpc state_getMetadata
$metadata = $codec->process("metadata", new ScaleBytes($metadataV14RawValue))["metadata"];
// Timestamp.now storage key
$hasher = new Hasher();
print_r(StorageKey::encode($hasher,"Timestamp", "now", $metadata, []));
// Staking.Bonded storage key with param accountId
print_r(StorageKey::encode($hasher,"System", "Account", $metadata, ["0x1c79a5ada2ff0d55aaa65dfeaf0cba667babf312f9bf100444279b34cd769e49"]))


// On the api, these are exposed via <client>.rpc.<module>.<method>, like this 
$client->rpc->system->health(); // for rpc system_health
$client->rpc->author->rotateKeys(); // for rpc author_rotateKeys
$client->rpc->state->getMetadata("hash"); // for rpc state_getMetadata


use Rpc\KeyPair\KeyPair;
use Rpc\SubstrateRpc;
$AliceSeed = "0xe5be9a5092b81bca64be81d212e7f2f9eba183bb7a90954f7b76361f6edb5c0a";
$BobId = ["Id" => "8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48"];
$wsClient = new SubstrateRpc($endpoint);
$hasher = new Hasher();
$wsClient->setSigner(KeyPair::initKeyPair("sr25519", $AliceSeed, $hasher),$hasher);
$tx = $wsClient->tx;
$result = $tx->Balances->transfer($BobId, 12345);
var_dump($result); // transaction hash

// if you want waiting transaction exec, you can set tx with option
$tx->withOpt(["subscribe" => true]);
$result = $tx->Balances->transfer($BobId, 12345);
var_dump($result); // Will not return until execution is complete
$wsClient->close()


use Rpc\KeyPair\KeyPair;
$keyPair = KeyPair::initKeyPair("sr25519|ed25519", {$secretKey}, new Hasher());
// signed msg
$signature = $keyPair->sign("msg");
// verify this message
$keyPair->verify($signature, "123");


use Rpc\Contract\Abi\Convert;
use Codec\Base;
use Codec\Types\ScaleInstance;
$content = json_decode(file_get_contents(__DIR__ . '/ink/ink_v0.json'), true);
$metadata = Convert::toLatest($content); // convert metadata to latest version
// reg metadata types
$scale = new ScaleInstance(Base::create());
$metadata->register_type($scale->getGenerator(), "some_prefix");


use Rpc\KeyPair\KeyPair;
use Rpc\SubstrateRpc;
use Rpc\Contract;

$wsClient = new SubstrateRpc($endpoint);
// set deployer keyring
$hasher = new Hasher();
$wsClient->setSigner(KeyPair::initKeyPair("sr25519",$seed, $hasher),$hasher);
$contract = new Contract($wsClient->tx);
// $inputData = constructor_selector + encode(args...)
$result = $contract->new($contract_code, $inputData); // with default option

# If you need to additionally set the gas limit and storageDepositLimit, you can set it like this
$result = $contract->new($contract_code, $inputData,[], ["gasLimit"=>100000,"storageDepositLimit"=>50000]); // with default option


use Rpc\KeyPair\KeyPair;
use Rpc\SubstrateRpc;
use Rpc\Contract;
use Rpc\Contract\ContractExecResult;

$wsClient = new SubstrateRpc($endpoint);
// set signer
$hasher = new Hasher();
$wsClient->setSigner(KeyPair::initKeyPair("sr25519", $seed, $hash),$hash);
// get abi
$v4 = ContractMetadataV4::to_obj(json_decode(file_get_contents(__DIR__ . '/ink/ink_v4.json'), true));
// register contract type
$v4->register_type($wsClient->tx->codec->getGenerator(), "testAbiMetadataV4Parse");

// read contract
$contract = new Contract($wsClient->tx, $contractAddress, $v4);
// call get method
$execResult = $contract->state->get();
// parse exec Result
$result =ContractExecResult::getDecodeResult($execResult, $wsClient->tx->codec)
print_r($result);


use Rpc\KeyPair\KeyPair;
use Rpc\SubstrateRpc;
use Rpc\Contract;
$wsClient = new SubstrateRpc($endpoint);
// set signer
$hasher = new Hasher();
$wsClient->setSigner(KeyPair::initKeyPair("sr25519", $this->AliceSeed, $hasher),$hasher);

// register contract type
$v4 = ContractMetadataV4::to_obj(json_decode(file_get_contents(__DIR__ . '/ink/ink_v4.json'), true));
$v4->register_type($wsClient->tx->codec->getGenerator(), "testAbiMetadataV4Parse");

// send contract transaction
$contract = new Contract($wsClient->tx, $contractAddress, $v4);
$result = $contract->call->flip([]); // with default option

// If you need to additionally set the gas limit and storageDepositLimit, you can set it like this
$result = $contract->call->flip(["storageDepositLimit"=>$limit,["gasLimit"=>["refTime"=>$refTime,"proofSize"=>$proofSize]] ]); 
print_r($result);// extrinsic_hash


use Rpc\Hasher\Hasher;
use Rpc\Contract\Address;
use Codec\Base;
use Codec\Types\ScaleInstance;
$hasher = new Hasher();
$codec = new ScaleInstance(Base::create());
$bytes = $codec->createTypeByTypeString("bytes");
Address::GenerateAddress($hasher, $deployer, $codeHash, $bytes->encode($inputData), $bytes->encode($salt)));