Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getMultipleAccounts #27

Merged
merged 10 commits into from
Mar 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions examples/positions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@ using json = nlohmann::json;
int main() {
const auto& config = mango_v3::DEVNET;
auto connection = solana::rpc::Connection(config.endpoint);
const auto& mangoAccount = connection.getAccountInfo<mango_v3::MangoAccount>(
"9aWg1jhgRzGRmYWLbTrorCFE7BQbaz2dE5nYKmqeLGCW");
spdlog::info(mangoAccount.owner.toBase58());
const auto& mangoAccountInfo =
connection.getAccountInfo<mango_v3::MangoAccountInfo>(
"9aWg1jhgRzGRmYWLbTrorCFE7BQbaz2dE5nYKmqeLGCW");
const auto& mangoAccount = mango_v3::MangoAccount(mangoAccountInfo);
spdlog::info(mangoAccountInfo.owner.toBase58());
spdlog::info(mangoAccount.accountInfo.owner.toBase58());
// TODO: #13
}
22 changes: 19 additions & 3 deletions include/mango_v3.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ struct MangoGroup {

enum Side : uint8_t { Buy, Sell };

struct PerpAccount {
struct PerpAccountInfo {
int64_t basePosition;
i80f48 quotePosition;
i80f48 longSettledFunding;
Expand All @@ -116,7 +116,8 @@ struct PerpAccount {
int64_t takerQuote;
uint64_t mngoAccrued;
};
struct MangoAccount {

struct MangoAccountInfo {
MetaData metaData;
solana::PublicKey mangoGroup;
solana::PublicKey owner;
Expand All @@ -125,7 +126,7 @@ struct MangoAccount {
i80f48 deposits[MAX_TOKENS];
i80f48 borrows[MAX_TOKENS];
solana::PublicKey spotOpenOrders[MAX_PAIRS];
PerpAccount perpAccounts[MAX_PAIRS];
PerpAccountInfo perpAccounts[MAX_PAIRS];
uint8_t orderMarket[MAX_PERP_OPEN_ORDERS];
Side orderSide[MAX_PERP_OPEN_ORDERS];
__int128_t orders[MAX_PERP_OPEN_ORDERS];
Expand All @@ -140,6 +141,21 @@ struct MangoAccount {
uint8_t padding[5];
};

struct MangoAccount {
MangoAccountInfo accountInfo;
explicit MangoAccount(const MangoAccountInfo &accountInfo_) noexcept {
accountInfo = accountInfo_;
}
// Fetch `accountInfo` from `endpoint` and decode it
explicit MangoAccount(const std::string &pubKey,
const std::string &endpoint = MAINNET.endpoint) {
auto connection = solana::rpc::Connection(endpoint);
const auto &accountInfo_ =
connection.getAccountInfo<MangoAccountInfo>(pubKey);
accountInfo = accountInfo_;
}
};

struct LiquidityMiningInfo {
i80f48 rate;
i80f48 maxDepthBps;
Expand Down
41 changes: 41 additions & 0 deletions include/solana.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,10 @@ class Connection {
json getAccountInfoRequest(const std::string &account,
const std::string &encoding = "base64",
const size_t offset = 0, const size_t length = 0);
json getMultipleAccountsRequest(const std::vector<std::string> &accounts,
const std::string &encoding = "base64",
const size_t offset = 0,
const size_t length = 0);
json getBlockhashRequest(const std::string &commitment = "finalized",
const std::string &method = "getRecentBlockhash");
json sendTransactionRequest(
Expand Down Expand Up @@ -297,6 +301,43 @@ class Connection {
memcpy(&result, decoded.data(), sizeof(T));
return result;
}
/// Returns account information for a list of pubKeys
/// Returns a map of {pubKey : AccountInfo} for accounts that exist.
/// Accounts that don't exist return a `null` result and are skipped
template <typename T>
inline std::map<std::string, T> getMultipleAccounts(
const std::vector<std::string> &accounts,
const std::string &encoding = "base64", const size_t offset = 0,
const size_t length = 0) {
const json req =
getMultipleAccountsRequest(accounts, encoding, offset, length);
cpr::Response r =
cpr::Post(cpr::Url{rpc_url_}, cpr::Body{req.dump()},
cpr::Header{{"Content-Type", "application/json"}});
if (r.status_code != 200)
throw std::runtime_error("unexpected status_code " +
std::to_string(r.status_code));

json res = json::parse(r.text);
const auto &account_info_vec = res["result"]["value"];
std::map<std::string, T> result;
int index = -1;
for (const auto &account_info : account_info_vec) {
++index;
if (account_info.is_null()) continue; // Account doesn't exist
const std::string encoded = account_info["data"][0];
const std::string decoded = b64decode(encoded);
if (decoded.size() != sizeof(T))
throw std::runtime_error("invalid response length " +
std::to_string(decoded.size()) + " expected " +
std::to_string(sizeof(T)));
T account;
memcpy(&account, decoded.data(), sizeof(T));
result[req["params"][0][index]] = account; // Retrieve the corresponding
// pubKey from the request
}
return result;
}

private:
const std::string &rpc_url_;
Expand Down
18 changes: 18 additions & 0 deletions lib/solana.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,24 @@ json Connection::getAccountInfoRequest(const std::string &account,

return jsonRequest("getAccountInfo", params);
}
json Connection::getMultipleAccountsRequest(
const std::vector<std::string> &accounts, const std::string &encoding,
const size_t offset, const size_t length) {
json pubKeys = json::array();
for (auto &account : accounts) {
pubKeys.emplace_back(account);
}
json params = {};
params.emplace_back(pubKeys);
json options = {{"encoding", encoding}};
if (offset && length) {
json dataSlice = {"dataSlice", {{"offset", offset}, {"length", length}}};
options.emplace(dataSlice);
}
params.emplace_back(options);

return jsonRequest("getMultipleAccounts", params);
}
json Connection::getBlockhashRequest(const std::string &commitment,
const std::string &method) {
const json params = {{{"commitment", commitment}}};
Expand Down
45 changes: 43 additions & 2 deletions tests/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ TEST_CASE("base58 decode & encode") {
"14ivtgssEBoBjuZJtSAPKYgpUK7DmnSwuPMqJoVTSgKJ"};

std::string resources_dir = FIXTURES_DIR;
for (const auto &bs58 : bs58s) {
for (const auto& bs58 : bs58s) {
const auto decoded = solana::b58decode(bs58);
const auto encoded = solana::b58encode(decoded);
const auto redecoded = solana::b58decode(encoded);
Expand Down Expand Up @@ -45,7 +45,7 @@ TEST_CASE("decode mango_v3 Fill") {
"Tgm1NbL9IaU3AQAAAADOMAYAAAAAAAAAAAAAAAAA46WbxCAAAAAAAAAAAAAAAHJYBgAAAAAA"
"AQAAAAAAAAA=");
const std::string decoded = solana::b64decode(encoded);
const mango_v3::FillEvent *event = (mango_v3::FillEvent *)decoded.data();
const mango_v3::FillEvent* event = (mango_v3::FillEvent*)decoded.data();
CHECK_EQ(event->eventType, mango_v3::EventType::Fill);
CHECK_EQ(event->takerSide, mango_v3::Side::Sell);
CHECK_EQ(event->makerOut, 0);
Expand Down Expand Up @@ -97,3 +97,44 @@ TEST_CASE("Test getLatestBlock") {
CHECK(!blockHash.publicKey.toBase58().empty());
CHECK_GT(blockHash.lastValidBlockHeight, 0);
}
TEST_CASE("MangoAccount is correctly created") {
const std::string& key = "9aWg1jhgRzGRmYWLbTrorCFE7BQbaz2dE5nYKmqeLGCW";
auto connection = solana::rpc::Connection(mango_v3::DEVNET.endpoint);
// Test prefetched account info
const auto& mangoAccountInfo =
connection.getAccountInfo<mango_v3::MangoAccountInfo>(key);
const auto& mangoAccount = mango_v3::MangoAccount(mangoAccountInfo);
CHECK(!mangoAccount.accountInfo.owner.toBase58().empty());
// Test fetching account info in construction
REQUIRE_NOTHROW(mango_v3::MangoAccount(key, mango_v3::DEVNET.endpoint));
const auto& account = mango_v3::MangoAccount(key, mango_v3::DEVNET.endpoint);
CHECK(!account.accountInfo.owner.toBase58().empty());
}
TEST_CASE("Test getMultipleAccounts") {
// Existing accounts
std::vector<std::string> accounts{
"9aWg1jhgRzGRmYWLbTrorCFE7BQbaz2dE5nYKmqeLGCW",
"DRUZRfLQtki4ZYvRXhi5yGmyqCf6iMfTzxtBpxo6rbHu",
};
auto connection = solana::rpc::Connection(mango_v3::DEVNET.endpoint);
auto accountInfoMap =
connection.getMultipleAccounts<mango_v3::MangoAccountInfo>(accounts);
REQUIRE_EQ(accountInfoMap.size(), accounts.size());
// Check results have the initial pubKeys
auto it = accountInfoMap.find(accounts[0]);
CHECK_NE(it, accountInfoMap.end());
it = accountInfoMap.find(accounts[1]);
CHECK_NE(it, accountInfoMap.end());
// Check AccountInfo is non-empty
for (const auto& [pubKey, accountInfo] : accountInfoMap) {
auto owner = accountInfo.owner;
CHECK(!(owner == solana::PublicKey::empty()));
}
// Introduce an account that doesn't exist
accounts.push_back("9aZg1jhgRzGRmYWLbTrorCFE7BQbaz2dE5nYKmqeLGCW");
accountInfoMap =
connection.getMultipleAccounts<mango_v3::MangoAccountInfo>(accounts);
REQUIRE_NE(accountInfoMap.size(), accounts.size());
it = accountInfoMap.find("9aZg1jhgRzGRmYWLbTrorCFE7BQbaz2dE5nYKmqeLGCW");
CHECK_EQ(it, accountInfoMap.end());
}