Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
nem-php: broadcast transaction
<?php
use NEM\API;
use NEM\Models\MosaicAttachments;
use NEM\Models\MosaicAttachment;
use NEM\Models\Mosaic;
use NEM\Models\Transaction\Transfer;
use NEM\Infrastructure\Transaction as TransactionService;
// prepare the transaction
$recipientAddr = "NB72EM6TTSX72O47T3GQFL345AB5WYKIDODKPPYW";
$txData = [
"amount" => 1000000,
"recipient" => $recipientAddr,
"mosaics" => (new MosaicAttachments([
new MosaicAttachment([
"mosaicId" => (new Mosaic(["namespaceId" => "nem", "name" => "xem"]))->toDTO(),
"quantity" => 1000000,
])
]))->toDTO(),
"message" => (new Message(["plain" => ""]))->toDTO(),
];
// transaction prepared
$transaction = new Transfer($txData);
// prepare the connection (for broadcast)
$api = new API([
"use_ssl" => false,
"protocol" => "http",
"host" => "hugealice.nem.ninja",
"port" => 7890,
"endpoint" => "/",
]);
// now prepare the keypair used for signing
$keypair = new KeyPair("dd19f3f3178c0867771eed180310a484e1b76527f7a271e3c8b5264e4a5aa414");
// use transaction SDK service to sign + broadcast transaction
$service = new TransactionService($api);
// sign transaction
$signature = $service->signTransaction($transaction, $keypair);
$broadcast = [
"data" => Buffer::fromUInt8($transaction->serialize())->getHex(),
"signature" => $signature->getHex(),
];
// broadcast transaction
$endpoint = $service->getAnnouncePath($transaction, $keypair);
$apiUrl = $service->getPath($endpoint, []);
$response = $api->postJSON($apiUrl, $broadcast);
// interpret result
$result = json_decode($response, true);
var_export($result, true);
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment