diff --git a/examples/account-exists.php b/examples/account-exists.php new file mode 100644 index 0000000..a62dcc4 --- /dev/null +++ b/examples/account-exists.php @@ -0,0 +1,32 @@ +accountExists('GCP6IHMHWRCF5TQ4ZP6TVIRNDZD56W42F42VHYWMVDGDAND75YGAHHBQ'); + + if ($exists) { + print "Account exists!" . PHP_EOL; + } + else { + print "Account does not exist." . PHP_EOL; + } +} +// If there's an exception it could be a temporary error, like a connection issue +// to Horizon, so we cannot tell for sure if the account exists or not +catch (\Exception $e) { + print "Error: " . $e->getMessage() . PHP_EOL; +} diff --git a/src/Server.php b/src/Server.php index f150477..2540e73 100755 --- a/src/Server.php +++ b/src/Server.php @@ -3,6 +3,7 @@ namespace ZuluCrypto\StellarSdk; +use phpseclib\Math\BigInteger; use Prophecy\Exception\InvalidArgumentException; use ZuluCrypto\StellarSdk\Horizon\ApiClient; use ZuluCrypto\StellarSdk\Horizon\Exception\HorizonException; @@ -104,6 +105,29 @@ public function getAccount($accountId) return $account; } + /** + * Returns true if the account exists on this server and has been funded + * + * @param $accountId + * @return bool + * @throws HorizonException + * @throws \ErrorException + */ + public function accountExists($accountId) + { + // Handle basic errors such as malformed account IDs + try { + $account = $this->getAccount($accountId); + } catch (\InvalidArgumentException $e) { + return false; + } + + // Account ID may be valid but hasn't been funded yet + if (!$account) return false; + + return $account->getNativeBalanceStroops() != '0'; + } + /** * @param $accountId string|Keypair * @return TransactionBuilder