Integrating Contracts
To integrate NEAR to your frontend, you will leverage two tools:
Wallet Selector
: Enables the user to select their preferred NEAR wallet in your dApp.NEAR API JS
: A suit of tools to interact with the NEAR RPC.
Using those tools you will implement the following flow:
- Setup a wallet selector.
- Load the wallet selector on start-up.
- Ask the user to sign-in using a NEAR wallet.
- Call methods in the contract.
Adding NEAR API JS and Wallet Selector
In order to use near-api-js
and the wallet-selector
you will need to first add them to your project.
The wallet selector has multiple wallet packages to select from, see in their website.
npm install \
near-api-js \
@near-wallet-selector/core \
@near-wallet-selector/my-near-wallet \
@near-wallet-selector/ledger \
@near-wallet-selector/modal-ui
Create a Wallet Object
In our examples we implement a ./wallets/near.js
module, where we abstracted the wallet selector
into a Wallet
object to simplify using it.
To create a wallet, simply import the Wallet
object from the module and initialize it. This wallet
will later allows the user to call any contract in NEAR.
- 🌐 Javascript
- _app.js
- 1
Loading...
<Github fname="near.js"
url="https://github.com/near-examples/hello-near-examples/blob/main/frontend/src/wallets/near.js"
start="15" end="142" />
Under the hood (check the near
tab) you can see that we are actually setting up the wallet selector, and asking it if the user logged-in already. During the setup, we pass a hook to the wallet selector, which will be called each time a user logs in or out.
Setting customs RPC endpoints
If you want to use a user-defined RPC endpoint with the Wallet Selector, you need to setup a network options object with the custom URLs. For example:
- 🌐 Javascript
const CONTRACT_ADDRESS = process.env.CONTRACT_NAME;
const my_network = {
networkId: "my-custom-network",
nodeUrl: "https://rpc.custom-rpc.com",
helperUrl: "https://helper.custom-helper.com",
explorerUrl: "https://custom-explorer.com",
indexerUrl: "https://api.custom-indexer.com",
};
const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS, network: my_network });
You can find the entire Wallet Selector API reference here.
Function Call Key
When instantiating the wallet you can choose if you want to create a FunctionCall Key.
If you create the key, then your dApp will be able to automatically sign non-payable transactions for the user on the specified contract.
Calling View Methods
Once the wallet is up we can start calling view methods, i.e. the methods that perform read-only operations.
Because of their read-only nature, view methods are free to call, and do not require the user to be logged in.