I don't know how can I write a smart contract in Solana that after executing the logic, returns an array of integers, strings, ... to the client, and how can I fetch it using Web3?
How can I return an array of integers from Solana rust program function to front end?
832 views Asked by Yaser Mohammadu At
2
There are 2 answers
1
On
So, programs do not return data (other than success or failure).
However; most programs write data to a program owned account's data
field and this could be read from client apps (Rust, Python, TS/JS, etc.).
If using the Solana web3 library, you can call getAccountInfo
on the Connection
object. This will return the byte array of the account. You will then need to deserialize
that data. You have to know how the program serializes
the data to reverse it successfully.
Check the Solana Cookbook for overview using borsh
https://solanacookbook.com/guides/serialization.html#how-to-deserialize-account-data-on-the-client
There's a syscall available to on-chain programs called
set_return_data
, which puts data into a buffer that can be read by the higher-level programs usingget_return_data
. This all mediated through opaque byte buffers, so you'll need to know how to decode the response.If you want to fetch the data from the client side, you can simulate the transaction and read the data back from the
return_data
field in the response: https://edge.docs.solana.com/developing/clients/jsonrpc-api#results-50The RPC support in simulated transactions is very new in version 1.11, but the return data is available in earlier versions.
Source code for
set_return_data
at https://github.com/solana-labs/solana/blob/658752cda710cb358d7ccbbc2cee06bf8009c2d4/sdk/program/src/program.rs#L102Source code for
get_return_data
at https://github.com/solana-labs/solana/blob/658752cda710cb358d7ccbbc2cee06bf8009c2d4/sdk/program/src/program.rs#L117