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?
2 Answers
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 using get_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-50
The 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#L102
Source code for get_return_data
at https://github.com/solana-labs/solana/blob/658752cda710cb358d7ccbbc2cee06bf8009c2d4/sdk/program/src/program.rs#L117

- 7,019
- 10
- 17
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

- 7,758
- 4
- 35
- 45
-
See more recent option, defined in Jon C answer, to this question. – Frank C. Apr 29 '22 at 08:49