You might want to send tokens from a contract for many reasons.
- The contract uses something like the Storage Standard and needs to return deposits to users when they unregister.
- Users pay into the contract and the contract later pays these fees to the maintainers, redistributes them to users, or disburses them to some cause the users vote on.
- And more!
Blockchains give us programmable money, and the ability for a smart contract to send tokens lies at the heart of that ability.
NEAR makes this easy. Transferring NEAR tokens is the simplest transaction you can send from a smart contract. Here's all you need:
AccountId behavior described throughout this document is a feature of
near-sdk-rs v4. The functionality is still possible using v3, but if you want to use the cleaner v4 syntax, use this in your
In the context of a full contract and function call, this could look like:
U128with a capital
paymethod defined here accepts JSON as input, and JSON numbers cannot be larger than 2^53, which is about 9 followed by a mere 15 zeroes. Since the
transfermethod takes a number in yoctoNEAR, it's likely to need numbers much larger than 2^53.
When a function takes
U128as input, it means that callers need to specify the number a a string. near-sdk-rs will then cast it to
U128type, which wraps Rust's native
u128. The underlying
u128can be retrieved with
.0– used in
AccountId: this will automatically check that the provided string is a well-formed NEAR account ID, and panic with a useful error if not.
Promise: This allows NEAR Explorer, near-cli, near-api-js, and other tooling to correctly determine if a whole chain of transactions is successful. If your function does not return
Promise, tools like near-cli will return immediately after your function call. And then even if the
transferfails, your function call will be considered successful. You can see a before & after example of this behavior here.
Using near-cli, someone could invoke this function with a call like: