Basic jetton and NFT contract examples from ton-blockchain/tolk-bench, extracted from commit cb9648b, appear here as accordions by source file.
Jetton
Source directory: contracts_Tolk/01_jetton.Some files in the source directory are not runnable on their own and depend on others. Keep all the listed files together.
import "@stdlib/gas-payments"import "errors"import "jetton-utils"import "messages"import "fees-management"import "storage"type AllowedMessageToWallet = | AskToTransfer | AskToBurn | InternalTransferSteptype BounceOpToHandle = InternalTransferStep | BurnNotificationForMinterfun onBouncedMessage(in: InMessageBounced) { in.bouncedBody.skipBouncedPrefix(); val msg = lazy BounceOpToHandle.fromSlice(in.bouncedBody); val restoreAmount = match (msg) { // fetching jettonAmount is safe because // it is at the beginning of the message body InternalTransferStep => msg.jettonAmount, BurnNotificationForMinter => msg.jettonAmount, }; var storage = lazy WalletStorage.load(); storage.jettonBalance += restoreAmount; storage.save();}fun onInternalMessage(in: InMessage) { val msg = lazy AllowedMessageToWallet.fromSlice(in.body); match (msg) { InternalTransferStep => { var storage = lazy WalletStorage.load(); if (in.senderAddress != storage.minterAddress) { assert (in.senderAddress == calcAddressOfJettonWallet( msg.transferInitiator!, storage.minterAddress, contract.getCode(), )) throw ERR_INVALID_WALLET; } storage.jettonBalance += msg.jettonAmount; storage.save(); var msgValue = in.valueCoins; var tonBalanceBeforeMsg = contract.getOriginalBalance() - msgValue; var storageFee = MIN_TONS_FOR_STORAGE - min( tonBalanceBeforeMsg, MIN_TONS_FOR_STORAGE, ); msgValue -= (storageFee + JETTON_WALLET_GAS_CONSUMPTION); if (msg.forwardTonAmount) { msgValue -= (msg.forwardTonAmount + in.originalForwardFee); val notifyOwnerMsg = createMessage({ // cause receiver can have uninitialized contract bounce: BounceMode.NoBounce, dest: storage.ownerAddress, value: msg.forwardTonAmount, body: TransferNotificationForRecipient { queryId: msg.queryId, jettonAmount: msg.jettonAmount, transferInitiator: msg.transferInitiator, forwardPayload: msg.forwardPayload } }); notifyOwnerMsg.send(SEND_MODE_PAY_FEES_SEPARATELY); } if (msg.sendExcessesTo != null & (msgValue > 0)) { val excessesMsg = createMessage({ bounce: BounceMode.NoBounce, dest: msg.sendExcessesTo!, value: msgValue, body: ReturnExcessesBack { queryId: msg.queryId } }); excessesMsg.send(SEND_MODE_IGNORE_ERRORS); } } AskToTransfer => { assert (msg.forwardPayload.remainingBitsCount()) throw ERR_INVALID_PAYLOAD; assert (msg.transferRecipient.getWorkchain() == BASECHAIN) throw ERR_WRONG_WORKCHAIN; var storage = lazy WalletStorage.load(); assert (in.senderAddress == storage.ownerAddress) throw ERR_NOT_FROM_OWNER; assert (storage.jettonBalance >= msg.jettonAmount) throw ERR_NOT_ENOUGH_BALANCE; storage.jettonBalance -= msg.jettonAmount; storage.save(); var forwardedMessagesCount = msg.forwardTonAmount ? 2 : 1; assert (in.valueCoins > msg.forwardTonAmount + // 3 messages: wal1->wal2, wal2->owner, wal2->response // but last one is optional (it is ok if it fails) forwardedMessagesCount * in.originalForwardFee + (2 * JETTON_WALLET_GAS_CONSUMPTION + MIN_TONS_FOR_STORAGE) ) throw ERR_NOT_ENOUGH_TON; val deployMsg = createMessage({ bounce: BounceMode.Only256BitsOfBody, dest: calcDeployedJettonWallet( msg.transferRecipient, storage.minterAddress, contract.getCode(), ), value: 0, body: InternalTransferStep { queryId: msg.queryId, jettonAmount: msg.jettonAmount, transferInitiator: storage.ownerAddress, sendExcessesTo: msg.sendExcessesTo, forwardTonAmount: msg.forwardTonAmount, forwardPayload: msg.forwardPayload, } }); deployMsg.send(SEND_MODE_CARRY_ALL_REMAINING_MESSAGE_VALUE); } AskToBurn => { var storage = lazy WalletStorage.load(); assert (in.senderAddress == storage.ownerAddress) throw ERR_NOT_FROM_OWNER; assert (storage.jettonBalance >= msg.jettonAmount) throw ERR_NOT_ENOUGH_BALANCE; storage.jettonBalance -= msg.jettonAmount; storage.save(); val notifyMinterMsg = createMessage({ bounce: BounceMode.Only256BitsOfBody, dest: storage.minterAddress, value: 0, body: BurnNotificationForMinter { queryId: msg.queryId, jettonAmount: msg.jettonAmount, burnInitiator: storage.ownerAddress, sendExcessesTo: msg.sendExcessesTo, } }); notifyMinterMsg.send( SEND_MODE_CARRY_ALL_REMAINING_MESSAGE_VALUE | SEND_MODE_BOUNCE_ON_ACTION_FAIL ); } else => { // ignore empty messages, "wrong opcode" for others assert (in.body.isEmpty()) throw 0xFFFF } }}struct JettonWalletDataReply { jettonBalance: coins ownerAddress: address minterAddress: address jettonWalletCode: cell}get fun get_wallet_data(): JettonWalletDataReply { val storage = lazy WalletStorage.load(); return { jettonBalance: storage.jettonBalance, ownerAddress: storage.ownerAddress, minterAddress: storage.minterAddress, jettonWalletCode: contract.getCode(), }}
NFT
Source directory: contracts_Tolk/02_nft.Some files in the source directory are not runnable on their own and depend on others. Keep all the listed files together.
// SnakeString describes a (potentially long) string inside a cell;// short strings are stored as-is, like "my-picture.png";// long strings are nested refs, like "xxxx".ref("yyyy".ref("zzzz"))type SnakeString = slicefun SnakeString.unpackFromSlice(mutate s: slice) { // SnakeString can be only the last — it's just the remainder; // For correctness, it's better to validate it has no more refs: // assert (s.remainingRefsCount() <= 1) throw 5; // Since it is matching the original FunC implementation, // checks are not kept val snakeRemainder = s; s = createEmptySlice(); // no more left to read return snakeRemainder}fun SnakeString.packToBuilder(self, mutate b: builder) { b.storeSlice(self)}struct RoyaltyParams { numerator: uint16 denominator: uint16 royaltyAddress: address}struct NftCollectionStorage { adminAddress: address nextItemIndex: uint64 content: Cell<CollectionContent> nftItemCode: cell royaltyParams: Cell<RoyaltyParams>}struct CollectionContent { collectionMetadata: cell commonContent: Cell<SnakeString>}struct NftItemStorage { itemIndex: uint64 collectionAddress: address ownerAddress: address content: Cell<SnakeString>}struct NftItemStorageNotInitialized { itemIndex: uint64 collectionAddress: address}fun NftCollectionStorage.load() { return NftCollectionStorage.fromCell(contract.getData())}fun NftCollectionStorage.save(self) { contract.setData(self.toCell())}// Actual storage of an NFT item is tricky: it's either initialized or not;// After NFT has been inited, it's represented as `NftItemStorage`;// Before initialization, it has only itemIndex and collectionAddress;// Hence, detect whether it's inited or not during parsing.struct NftItemStorageMaybeNotInitialized { contractData: slice}// how do we detect whether it's initialized or not?// the answer: when "inited", we store `content` (cell),// so, we have a ref, and for uninited, we don't have a reffun NftItemStorageMaybeNotInitialized.isInitialized(self) { val hasContent = self.contractData.remainingRefsCount(); return hasContent}fun NftItemStorageMaybeNotInitialized.parseNotInitialized(self) { return NftItemStorageNotInitialized.fromSlice(self.contractData)}fun NftItemStorageMaybeNotInitialized.parseInitialized(self) { return NftItemStorage.fromSlice(self.contractData)}fun startLoadingNftItemStorage(): NftItemStorageMaybeNotInitialized { return { contractData: contract.getData().beginParse() }}fun NftItemStorage.save(self) { contract.setData(self.toCell())}fun calcDeployedNftItem( itemIndex: uint64, collectionAddress: address, nftItemCode: cell,): AutoDeployAddress { val emptyNftItemStorage: NftItemStorageNotInitialized = { itemIndex, collectionAddress, }; return { stateInit: { code: nftItemCode, data: emptyNftItemStorage.toCell() } }}