Skip to main content

Handling Token Donations

Now we'll implement the core donation functionality. This involves creating payable methods that can receive NEAR tokens, managing storage costs, and automatically forwarding funds to the beneficiary.

Understanding Storage Costs

NEAR charges for data storage in smart contracts. Each new donor entry requires storage, so we need to account for this cost in our donation logic.

tip

Storage costs are one-time fees paid when first storing data. Subsequent updates to existing data don't require additional storage fees.

The Donation Method

The donate method is the heart of our contract. It must be marked as payable to accept NEAR tokens, handle storage costs, track donations, and forward funds.

Key Concepts Explained

Payable Functions: The #[payable] decorator (Rust) or payableFunction: true (TypeScript) allows methods to receive NEAR tokens.

Storage Management: We charge new donors a storage fee but not returning donors, since their data already exists.

Promise Transfers: We use Promise::new().transfer() in Rust or promiseBatchCreate + promiseBatchActionTransfer in TypeScript to send tokens to the beneficiary.

Deposit Handling: env::attached_deposit() (Rust) or near.attachedDeposit() (TypeScript) gets the amount of NEAR sent with the transaction.

Testing the Donation Logic

Let's examine how the donation handling is tested to understand the expected behavior.

Advanced Testing with Workspaces

For integration testing, both implementations use NEAR Workspaces to simulate real blockchain interactions:

Running Tests

Test your donation logic to ensure everything works correctly:

# Unit tests
cargo test

# Integration tests with workspaces
cargo test --test workspaces

Key Takeaways

  • Payable methods can receive NEAR tokens with transactions
  • Storage costs must be handled for new data entries
  • Promise transfers allow contracts to send tokens to other accounts
  • Testing verifies both donation recording and fund forwarding work correctly

Continue to Query Donation Data to learn about implementing view methods for retrieving donation information.