Reputation: 227
Is there a way I can initially connect to a contract without a signer? I want like to create a user flow where the user can explore with view calls, then choose to connect their wallet at a later time.
Most examples I can find of Contract Connection code includes a wallet connected Account. docs github docs
Upvotes: 3
Views: 281
Reputation: 66
For those of you, who stumbled upon this question in 2024, there's been recently released update for near-api-js
that extends the Contract
class to enable view function calls with a plain Connection
object
It ensures backward compatibility, so it won't break anything in your existing codebase https://github.com/near/near-api-js/pull/1325
The code example above can be re-written as:
const provider = new JsonRpcProvider("https://rpc.testnet.near.org");
const connection = new Connection("testnet", provider);
const contract = new Contract(connection, "guest-book.testnet", { viewMethods: ["getMessages"] });
await contract.getMessages({});
Upvotes: 0
Reputation: 326
Yes! You can query the state of an account by using the providers
in near-api-js
.
Example:
const { providers } = require("near-api-js");
const provider = new providers.JsonRpcProvider("https://rpc.testnet.near.org");
getState();
async function getState() {
const rawResult = await provider.query({
request_type: "call_function",
account_id: "guest-book.testnet",
method_name: "getMessages",
args_base64: "e30=",
finality: "optimistic",
});
const res = JSON.parse(Buffer.from(rawResult.result).toString());
console.log(res);
}
https://docs.near.org/docs/api/naj-cookbook#read-state-without-an-account
Upvotes: 3