near-api-js icon indicating copy to clipboard operation
near-api-js copied to clipboard

Idea: make view-only calls simpler

Open ryancwalsh opened this issue 3 years ago • 0 comments

The good news is that the following code works (or rather, when combined with more code that I haven't shared here).

 export function getNftContract(account: Account) {
 const contract = new Contract(
 account, // the account object that is connecting
 certificateContractName,

 { viewMethods: ['nft_token'], // view methods do not change state but usually return a value changeMethods: ['nft_mint'], // change methods modify state } 

,
 );
 return contract;
 }

async function fetchCertificateDetails(tokenId: string) {
 const accountId: AccountId = ''; // TODO Why would account_id be required for a simple `near view` call? Clearly it's allowed to be empty.
 const keyStore = new InMemoryKeyStore(); // TODO: Why is this required? Clearly it's allowed to be empty.
 const config: ConnectConfig = {
 headers: {},
 networkId,
 keyStore, // optional if not signing transactions
 nodeUrl,
 walletUrl,
 helperUrl,
 // explorerUrl,
 };
 const near = await connect(config);
 const account = new Account(near.connection, accountId);
 const contract = getNftContract(account);
 console.log(

 { contract } 

);
 const response = await (contract as NFT).nft_token(

 { token_id: tokenId } 

);
 console.log(

 { response } 

);

But as you can see in my TODO comments and my confusion at https://discord.com/channels/490367152054992913/542945453533036544/937863529250320424, this feels really clunky.

accountId and keyStore don't actually get used. Therefore, ideally, the near-api-js shouldn't require them. I recommend updating near-api-js to not throw errors when they are omitted for view-only calls.

Additionally, look above at all of the lines of code involved to do a simple near view call.

Really, the only relevant pieces are networkId, `.nft_token(

{ token_id: tokenId }

), the contract ID / name, and I guess nodeUrl`. Right?

So shouldn't I be able to use a one-liner to fetch the JSON result of a near view call if I provide just those ingredients (arguments)?

It could be something like const result = nearView(networkId, nodeUrl, contractId, viewMethodName, viewMethodArgs);

Or maybe two lines would be better, like:

const network = nearNetwork(networkId, nodeUrl); const result = nearView(network, contractId, viewMethodName, viewMethodArgs);

Thanks!

-Ryan on NEAR Foundation's Education team

P.S. I'm totally new to blockchain and NEAR, so this suggestion might be bonkers. I'm eager to learn what you think!

ryancwalsh avatar Feb 01 '22 00:02 ryancwalsh