16 Sep 2024
Stories by BitTorrent Inc. on Medium
BTFS Protocol V3.1.0 Beta Is Now Live!
This update improves the security of the protocol, and the specifics are as follows:
1. Added password verification to Dashboard: This provides users with a higher level of protection, enhancing the security of data access.
2. Eliminated deprecated and seldom-used functionalities: This streamlines user experience and boosts system performance.
We stay dedicated to continuously refining the BTFS protocol with the aim of fostering the growth of decentralized networks. If you have any questions or suggestions, feel free to contact us at any time.
Resources for BTFS V3.1.0 Beta:
● Release notes for BTFS V3.1.0 Beta:https://github.com/bittorrent/go-btfs/tree/release_3.1.0
● BTFS Dashboard repo: https://github.com/bittorrent/btfs-dashboard
● BTFS official website: https://www.btfs.io
● BTFS SCAN: https://scan.btfs.io
● BTFS documentation: https://docs.btfs.io/docs
Find us on
Have any questions or want to engage with fellow BTFS users? Connect with us and be part of the community:
● Discord: https://discord.gg/tJ4fz6C6rw
● Medium: https://medium.com/@BitTorrent
● X (formerly Twitter): https://twitter.com/BitTorrent
About BTFS
The BitTorrent File System (BTFS) is both a protocol and a web application that provides a content-addressable peer-to-peer mechanism for storing and sharing digital content in a decentralized file system, as well as a base platform for decentralized applications (Dapp). The BTFS team has been working on the latest network operations and BTT market sentiment, etc., to make a series of dynamic adjustments such as upload prices and airdrop reward schemes.
16 Sep 2024 3:38am GMT
11 Sep 2024
Stories by BitTorrent Inc. on Medium
Revolutionizing Digital Asset Trading: The Ultimate NFT Marketplace on BTTC
Welcome to the future of digital asset trading! Today, we are diving into the intricacies of a decentralized NFT marketplace built on the BitTorrent Chain (BTTC). This marketplace is designed to facilitate the trading of Non-Fungible Tokens (NFTs), integrating auction mechanisms, transaction fees, and robust security features. Whether you're a creator, collector, or trader, this contract provides a secure and transparent environment for all your NFT transactions.
The MarketPlace Contract: Your Gateway to Decentralized NFT Trading
The MarketPlace contract is a comprehensive solution for managing NFT transactions. It supports the creation and management of sell orders, bidding on NFTs, and the execution of trades. Let's break down the key components and functionalities of this contract.
State Variables and Structs
The contract defines several state variables and data structures to manage orders, bids, and administrative settings:
using SafeERC20 for IERC20;
uint256 private _orderIds;
uint256 private _bidIds;
address public _adminAddress = "<VAULT ADDRESS For Commission>";
// To store commission percentage for each mint
uint8 private _adminCommissionPercentage = 25;
// Mapping from token to the current ask for the token
mapping(uint256 => IUtils.Order) private _orders;
// Mapping from token to the current ask for the token
mapping(uint256 => IUtils.Bid) private _bids;
mapping(address => bool) public approvedCurrency;
mapping(address => bool) public approvedNfts;
uint256 private constant EXPO = 1e18;
uint256 private constant BASE = 1000 * EXPO;
Key Functions
Administrative Functions
These functions allow the admin to manage various aspects of the marketplace:
- Set Admin Address: Updates the admin wallet where all commissions will go.
function setAdminAddress(address _newAdminWallet) external override returns (bool) {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller is not a admin");
require(_newAdminWallet != address(0), "Admin Wallet cannot be empty address");
emit UpdateAdminWallet(_adminAddress, _newAdminWallet);
_adminAddress = _newAdminWallet;
return true;
}
- Set Commission Percentage: Updates the commission percentage of the admin.
function setCommissionPercentage(uint8 _commissionPercentage) external override returns (bool) {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller is not a admin");
_adminCommissionPercentage = _commissionPercentage;
emit CommissionUpdated(_adminCommissionPercentage);
return true;
}
- Update Currency: Updates the currency accepted for bidding.
function updateCurrency(address _tokenAddress, bool _status) external override returns (bool) {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller is not a admin");
approvedCurrency[_tokenAddress] = _status;
return true;
}
- Update NFT Contract: Adds a new NFT to the marketplace.
function updateNFTContract(address _tokenAddress, bool _status) external override returns (bool) {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller is not a admin");
approvedNfts[_tokenAddress] = _status;
return true;
}
Order Management Functions
These functions handle the creation, management, and execution of orders:
- Set Order: Creates a new sell order for an NFT.
function setOrder(address _nftContract, uint256 _tokenId, address _currency, uint256 _askAmount, uint256 _expiryTime)
whenNotPaused
external
override
{
_orderIds += 1;
require(approvedNfts[_nftContract], "NFT is not approved by admin");
require(approvedCurrency[_currency], "Currency is not approved by admin");
require(_askAmount > 0, "Ask Amount Cannot be Zero");
require(_expiryTime > block.timestamp, "Expiry Time cannot be in Past");
ERC721 nftContract = ERC721(_nftContract);
require(nftContract.ownerOf(_tokenId) == msg.sender, "You are not owner of Token Id");
bool isAllTokenApproved = nftContract.isApprovedForAll(_msgSender(), address(this));
address approvedSpenderOfToken = nftContract.getApproved(_tokenId);
require((isAllTokenApproved || approvedSpenderOfToken == address(this)), "Market Contract is not allowed to manage this Token ID");
uint256 currentOrderId = _orderIds;
IUtils.Order storage order = _orders[currentOrderId];
order.orderId = currentOrderId;
order.sender = _msgSender();
order.askAmount = _askAmount;
order.currency = _currency;
order.nftContract = _nftContract;
order.tokenId = _tokenId;
order.expiryTime = _expiryTime;
order.orderStatus = IUtils.OrderStatus.OPEN;
order.createdAt = block.timestamp;
order.updatedAt = block.timestamp;
emit OrderCreated(currentOrderId, order);
}
- Get Order: Retrieves the details of a specific order by its ID.
function getOrder(uint256 _orderId) external override view returns (IUtils.Order memory) {
return _orders[_orderId];
}
Cancel Order: Allows the order creator or an admin to cancel an open order.
function cancelOrder(uint256 _orderId) whenNotPaused external override returns (bool) {
IUtils.Order storage order = _orders[_orderId];
require(order.sender != address(0), "Invalid Order Id");
require(order.orderStatus == IUtils.OrderStatus.OPEN, "Order status is not Open");
bool hasAdminRole = hasRole(DEFAULT_ADMIN_ROLE, _msgSender());
require(order.sender == _msgSender() || hasAdminRole, "You Don't have right to cancel order");
order.orderStatus = IUtils.OrderStatus.CANCELED;
emit OrderRemoved(_orderId, order);
return true;
}
- Complete Order: Executes a purchase of an NFT based on an open order.
function completeOrder(uint256 _orderId) whenNotPaused external override returns (bool) {
IUtils.Order storage order = _orders[_orderId];
require(order.sender != address(0), "Invalid Order Id");
require(order.orderStatus == IUtils.OrderStatus.OPEN, "Order status is not Open");
IERC20 token = IERC20(order.currency);
ERC721 nft = ERC721(order.nftContract);
require(block.timestamp <= order.expiryTime, "Order is expired");
require(token.balanceOf(_msgSender()) >= order.askAmount, "Not enough funds available to buy");
require(token.allowance(_msgSender(), address(this)) >= order.askAmount, "Please Approve Tokens Before You Buy");
uint256 _amountToDistribute = order.askAmount;
uint256 adminCommission = (_amountToDistribute * (_adminCommissionPercentage * EXPO)) / (BASE);
uint256 _amount = _amountToDistribute - adminCommission;
token.safeTransferFrom(_msgSender(), _adminAddress, adminCommission);
token.safeTransferFrom(_msgSender(), order.sender, _amount);
nft.transferFrom(order.sender, _msgSender(), order.tokenId);
order.orderStatus = IUtils.OrderStatus.COMPLETED;
order.recipient = _msgSender();
emit OrderCompleted(order.orderId, order);
return true;
}
Bid Management Functions
These functions handle the creation, management, and execution of bids:
- Add Bid: Allows users to place bids on NFTs.
function addBid(address _nftContract, uint256 _tokenId, address _currency, uint256 _bidAmount, uint256 _expiryTime)
whenNotPaused
external
override
{
_bidIds += 1;
require(approvedNfts[_nftContract], "NFT is not approved by admin");
require(approvedCurrency[_currency], "Currency is not approved by admin");
require(_bidAmount > 0, "Bid Amount Cannot be Zero");
require(_expiryTime > block.timestamp, "Expiry Time cannot be in Past");
ERC721 nft = ERC721(_nftContract);
require(nft.ownerOf(_tokenId) != msg.sender, "You Can't Bid on your Own Token");
IERC20 token = IERC20(_currency);
require(token.balanceOf(_msgSender()) >= _bidAmount, "Not enough funds available to add bid");
require(token.allowance(_msgSender(), address(this)) >= _bidAmount, "Please Approve Tokens Before You Bid");
uint256 currentBidId = _bidIds;
IUtils.Bid storage bid = _bids[currentBidId];
bid.bidId = currentBidId;
bid.sender = _msgSender();
bid.bidAmount = _bidAmount;
bid.currency = _currency;
bid.nftContract = _nftContract;
bid.tokenId = _tokenId;
bid.expiryTime = _expiryTime;
bid.bidStatus = IUtils.OrderStatus.OPEN;
bid.createdAt = block.timestamp;
bid.updatedAt = block.timestamp;
emit BidAdded(currentBidId, bid);
}
- Cancel Bid: Allows the bidder, the NFT owner, or an admin to cancel an open bid.
function cancelBid(uint256 _bidId) whenNotPaused external override returns (bool) {
IUtils.Bid storage bid = _bids[_bidId];
require(bid.sender != address(0), "Invalid Bid Id");
require(bid.bidStatus == IUtils.OrderStatus.OPEN, "Bid status is not Open");
bool hasAdminRole = hasRole(DEFAULT_ADMIN_ROLE, _msgSender());
ERC721 nft = ERC721(bid.nftContract);
require(bid.sender == _msgSender() || nft.ownerOf(bid.tokenId) == _msgSender() || hasAdminRole, "You Don't have right to cancel bid");
bid.bidStatus = IUtils.OrderStatus.CANCELED;
emit BidRemoved(_bidId, bid);
return true;
}
- Accept Bid: Allows the NFT owner to accept a bid, transferring the NFT to the bidder and the bid amount (minus commission) to the NFT owner.
function acceptBid(uint256 _bidId) whenNotPaused external override returns (bool) {
IUtils.Bid storage bid = _bids[_bidId];
require(bid.sender != address(0), "Invalid Bid Id");
require(bid.bidStatus == IUtils.OrderStatus.OPEN, "Bid status is not Open");
require(block.timestamp <= bid.expiryTime, "Bid is expired");
IERC20 token = IERC20(bid.currency);
ERC721 nft = ERC721(bid.nftContract);
require(nft.ownerOf(bid.tokenId) == msg.sender, "You are not owner of Token Id");
require(token.balanceOf(bid.sender) >= bid.bidAmount, "Bidder doesn't have Enough Funds");
require(token.allowance(bid.sender, address(this)) >= bid.bidAmount, "Bidder has not Approved Tokens");
bool isAllTokenApproved = nft.isApprovedForAll(_msgSender(), address(this));
address approvedSpenderOfToken = nft.getApproved(bid.tokenId);
require((isAllTokenApproved || approvedSpenderOfToken == address(this)), "Market Contract is not allowed to manage this Token ID");
uint256 _amountToDistribute = bid.bidAmount;
uint256 adminCommission = (_amountToDistribute * (_adminCommissionPercentage * EXPO)) / (BASE);
uint256 _amount = _amountToDistribute - adminCommission;
nft.transferFrom(_msgSender(), bid.sender, bid.tokenId);
token.safeTransferFrom(bid.sender, _adminAddress, adminCommission);
token.safeTransferFrom(bid.sender, _msgSender(), _amount);
bid.bidStatus = IUtils.OrderStatus.COMPLETED;
bid.recipient = _msgSender();
emit BidAccepted(bid.bidId, bid);
return true;
}
Conclusion
The MarketPlace contract is a comprehensive solution for managing NFT transactions. By leveraging the power of smart contracts, it ensures transparency, security, and efficiency in the trading process. Whether you're minting new NFTs, bidding on unique digital assets, or managing a marketplace, this contract provides the tools you need to succeed in the dynamic world of blockchain-based digital assets.
Github URL:
https://github.com/adeelch9/bttc-examples/tree/master/projects/nft-marketplace
Bonus Section: Diving Deeper into BTTC Smart Contracts
We've only scratched the surface of what's possible with smart contracts on the BitTorrent Chain. For those eager to take their blockchain development skills to the next level, we've got a treasure trove of resources waiting for you in our GitHub repository!
🚀 Explore the Full Project
Head over to our BTTC Examples GitHub Repository to discover a wealth of additional content and features:
- Complete Contract Code: While we've covered the main functions, the repository contains the full smart contract code, including any methods we didn't have space to discuss here.
- Deployment Scripts: Ever wondered how to deploy your smart contracts to the BTTC network? We've got you covered with ready-to-use deployment scripts that make the process a breeze.
- Comprehensive Tests: Writing tests for smart contracts is crucial for ensuring their reliability and security. Our repository includes a suite of tests that demonstrate best practices in smart contract testing.
- Multiple Projects: Beyond the contract we've discussed today, you'll find a variety of other smart contract examples, from simple to advanced, showcasing different aspects of blockchain development on BTTC.
- Documentation: Detailed README files and inline comments provide additional context and explanations, making it easier to understand and modify the code for your own projects.
🛠️ Getting Started
To make the most of these resources:
- Clone the repository: git clone https://github.com/adeelch9/bttc-examples.git
- Navigate to the project directory of your choice
- Follow the setup instructions in the project's README
- Experiment with the contracts, run tests, and try deploying to a testnet
🌟 Why This Matters
By exploring the full repository, you'll gain:
- A deeper understanding of smart contract development
- Hands-on experience with deployment and testing
- Exposure to best practices in blockchain development
- Inspiration for your own BTTC projects
Whether you're a beginner looking to learn or an experienced developer seeking to refine your skills, our BTTC Examples repository is your gateway to mastering smart contract development on the BitTorrent Chain.
Happy trading, and may your NFTs find their perfect homes!
11 Sep 2024 5:21am GMT
10 Sep 2024
Stories by BitTorrent Inc. on Medium
BitTorrent Weekly Report | 09.02–09.08
Founded with a leading peer-to-peer sharing technology standard in 2004, BitTorrent, Inc. is a consumer software company based in San Francisco. Its protocol is the largest decentralized P2P network in the world, driving 22% of upstream and 3% of downstream traffic globally.
Its flagship desktop and mobile products, BitTorrent and µTorrent, enable users to send large files over the internet, connecting legitimate third-party content providers with users. With over 100 million active users, BitTorrent products have been installed on over 1 billion devices in over 138 countries worldwide.
Since November 2018, TRON (TRX), Binance (BNB), and Bitcoin (BTC) holders have the opportunity to purchase one-year subscriptions of BitTorrent or µTorrent products, including Ads Free and Pro for Windows. Pro includes anti-virus and anti-malware screening, file converting and playability in HD. Users can visit bittorrent.com or utorrent.com to learn more.
10 Sep 2024 7:04am GMT
04 Sep 2024
Stories by BitTorrent Inc. on Medium
Unlocking the Future: Exploring the TokenTimeLock Contract on BTTC
Welcome, blockchain innovators and crypto enthusiasts! Today, we're diving into a powerful smart contract that brings time-based token management to the BitTorrent Chain (BTTC) - the TokenTimeLock contract. This contract acts as a digital vault, holding ERC20 tokens for a predetermined period before releasing them to a beneficiary. Let's unlock the secrets of this contract and explore its potential!
The TokenTimeLock Contract: Your Crypto Time Capsule
Imagine a smart contract that can hold your tokens and release them at a specific time in the future. That's exactly what the TokenTimeLock contract does. It's perfect for vesting schedules, delayed rewards, or any scenario where you want to ensure tokens are held securely for a set period.
Let's break down the key components of this contract:
State Variables: The Building Blocks
IERC20 private _token;
address private _beneficiary;
uint256 private _releaseTime;
These three variables form the core of our contract:
- _token: The ERC20 token being held.
- _beneficiary: The address that will receive the tokens when they're released.
- _releaseTime: The timestamp when the tokens can be released.
The Constructor: Setting the Stage
constructor(IERC20 token_, address beneficiary_, uint256 releaseTime_) {
require(releaseTime_ > block.timestamp, "TokenTimeLock: release time is before current time");
_token = token_;
_beneficiary = beneficiary_;
_releaseTime = releaseTime_;
}
This constructor is where the magic begins. It takes three parameters:
- token_: The address of the ERC20 token contract.
- beneficiary_: The address that will receive the tokens.
- releaseTime_: The timestamp when the tokens can be released.
Note the require statement
- it ensures that the release time is in the future. No time travel allowed in this contract!
Getter Functions: Peeking Inside the Vault
function token() public view virtual returns (IERC20) {
return _token;
}
function beneficiary() public view virtual returns (address) {
return _beneficiary;
}
function releaseTime() public view virtual returns (uint256) {
return _releaseTime;
}
These functions allow anyone to check the details of the time lock:
- Which token is locked?
- Who will receive the tokens?
- When will the tokens be released?
Transparency is key in blockchain, and these functions provide just that!
The Release Function: Unlocking the Vault
function release() public virtual {
require(block.timestamp >= _releaseTime, "TokenTimeLock: current time is before release time");
uint256 amount = _token.balanceOf(address(this));
require(amount > 0, "TokenTimeLock: no tokens to release");
_token.safeTransfer(_beneficiary, amount);
}
This is where the excitement happens! The release function:
1. Checks if it's time to release the tokens.
2. Ensures there are tokens to release.
3. Transfers all the tokens to the beneficiary.
It's simple, secure, and effective!
Beyond the Basics: Unlocking Potential
The TokenTimeLock contract opens up a world of possibilities:
- Vesting Schedules: Use multiple TimeLock contracts with different release times to create a vesting schedule for team tokens.
- Delayed Rewards: Set up future rewards for achievements or milestones.
- Timed Releases: Coordinate token releases with specific events or announcements.
Conclusion: The Future is Locked and Loaded
The TokenTimeLock contract is more than just a smart contract - it's a testament to the power of programmable money. By allowing us to control the timing of token releases, it opens up new possibilities for token economics, incentive structures, and financial planning in the blockchain space.
As you explore the potential of TokenTimeLock on BTTC, remember: you're not just locking tokens, you're unlocking the future of decentralized finance!
So, what will you lock up in your blockchain time capsule? The possibilities are as exciting as they are vast!
Github URL:
https://github.com/adeelch9/bttc-examples/tree/master/projects/token-time-lock
Bonus Section: Diving Deeper into BTTC Smart Contracts
We've only scratched the surface of what's possible with smart contracts on the BitTorrent Chain. For those eager to take their blockchain development skills to the next level, we've got a treasure trove of resources waiting for you in our GitHub repository!
🚀 Explore the Full Project
Head over to our BTTC Examples GitHub Repository to discover a wealth of additional content and features:
- Complete Contract Code: While we've covered the main functions, the repository contains the full smart contract code, including any methods we didn't have space to discuss here.
- Deployment Scripts: Ever wondered how to deploy your smart contracts to the BTTC network? We've got you covered with ready-to-use deployment scripts that make the process a breeze.
- Comprehensive Tests: Writing tests for smart contracts is crucial for ensuring their reliability and security. Our repository includes a suite of tests that demonstrate best practices in smart contract testing.
- Multiple Projects: Beyond the contract we've discussed today, you'll find a variety of other smart contract examples, from simple to advanced, showcasing different aspects of blockchain development on BTTC.
- Documentation: Detailed README files and inline comments provide additional context and explanations, making it easier to understand and modify the code for your own projects.
🛠️ Getting Started
To make the most of these resources:
- Clone the repository: git clone https://github.com/adeelch9/bttc-examples.git
- Navigate to the project directory of your choice
- Follow the setup instructions in the project's README
- Experiment with the contracts, run tests, and try deploying to a testnet
🌟 Why This Matters
By exploring the full repository, you'll gain:
- A deeper understanding of smart contract development
- Hands-on experience with deployment and testing
- Exposure to best practices in blockchain development
- Inspiration for your own BTTC projects
Whether you're a beginner looking to learn or an experienced developer seeking to refine your skills, our BTTC Examples repository is your gateway to mastering smart contract development on the BitTorrent Chain.
Happy coding, and may your tokens be released right on time!
04 Sep 2024 3:48am GMT
03 Sep 2024
Stories by BitTorrent Inc. on Medium
BitTorrent Weekly Report | 08.26–09.01
Founded with a leading peer-to-peer sharing technology standard in 2004, BitTorrent, Inc. is a consumer software company based in San Francisco. Its protocol is the largest decentralized P2P network in the world, driving 22% of upstream and 3% of downstream traffic globally.
Its flagship desktop and mobile products, BitTorrent and µTorrent, enable users to send large files over the internet, connecting legitimate third-party content providers with users. With over 100 million active users, BitTorrent products have been installed on over 1 billion devices in over 138 countries worldwide.
Since November 2018, TRON (TRX), Binance (BNB), and Bitcoin (BTC) holders have the opportunity to purchase one-year subscriptions of BitTorrent or µTorrent products, including Ads Free and Pro for Windows. Pro includes anti-virus and anti-malware screening, file converting and playability in HD. Users can visit bittorrent.com or utorrent.com to learn more.
03 Sep 2024 7:21am GMT
28 Aug 2024
Stories by BitTorrent Inc. on Medium
MultiSigWallet: Revolutionizing Secure Transactions on BTTC
Welcome, blockchain enthusiasts and security-conscious developers! Today, we're diving into an exciting smart contract that brings multi-signature functionality to the BitTorrent Chain (BTTC) - the MultiSigWallet contract. This powerful piece of code enhances transaction security by requiring multiple approvals before execution. Let's unpack this digital fortress and see how it works!
The MultiSigWallet Contract: Your Collaborative Vault on the Blockchain
Imagine a digital vault that requires multiple keys to open, ensuring that no single person can access the funds alone. That's exactly what our MultiSigWallet contract achieves. It's a robust system for managing shared funds with enhanced security and consensus.
State Variables and Structs: The Building Blocks
Let's break down the key components of our contract:
address[] public owners;
uint public numConfirm;
struct Transaction {
address to;
uint value;
bool executed;
}
mapping(uint => mapping(address => bool)) isConfirmed;
mapping(address => bool) isOwner;
Transaction[] public transactions;
These variables and structs form the backbone of our contract: - owners: An array of addresses that have ownership rights. - numConfirm: The number of confirmations required to execute a transaction. - Transaction: A struct defining the structure of each transaction. - isConfirmed: A nested mapping to track confirmations for each transaction. - isOwner: A mapping to quickly check if an address is an owner. - transactions: An array storing all submitted transactions.
Events: Keeping Everyone Informed
Events are crucial for transparency and off-chain tracking:
event TransactionSubmitted(
uint transactionId,
address sender,
address receiver,
uint amount
);
event TransactionConfirmed(uint transactionId);
event TransactionExecuted(uint transactionId);
These events help in tracking the lifecycle of transactions:
- TransactionSubmitted: Fired when a new transaction is proposed.
- TransactionConfirmed: Emitted when an owner confirms a transaction.
- TransactionExecuted: Logs when a transaction is successfully executed.
Constructor: Setting Up the Vault
The constructor initializes the wallet with the specified owners and confirmation threshold:
constructor(address[] memory _owners, uint _numConfirmationRequired) {
require(_owners.length > 1, "owners required must grater than 1");
require(
_numConfirmationRequired > 0 &&
_numConfirmationRequired <= _owners.length,
"Num of confirmation is not sync with num of owner"
);
numConfirm = _numConfirmationRequired;
for (uint i = 0; i < _owners.length; i++) {
require(_owners[i] != address(0), "Invalid Owner");
owners.push(_owners[i]);
isOwner[_owners[i]] = true;
}
}
This constructor ensures that: - There are at least two owners. - The number of required confirmations is valid. - All provided owner addresses are valid.
Key Functions: The Heart of Multi-Signature Operations
Submitting a Transaction
function submitTransaction(address _to) public payable {
require(_to != address(0), "Invalid address");
require(msg.value > 0, "Transfer amount must be grater than 0 ");
uint transactionId = transactions.length;
transactions.push(
Transaction({to: _to, value: msg.value, executed: false})
);
emit TransactionSubmitted(transactionId, msg.sender, _to, msg.value);
}
This function allows anyone to propose a new transaction, creating a new Transaction struct and emitting a TransactionSubmitted event.
Confirming a Transaction
function confirmTransaction(uint _transactionId) public onlyOwner {
require(_transactionId < transactions.length, "Invalid transaction");
require(
!isConfirmed[_transactionId][msg.sender],
"Transaction is already confirm by owner"
);
isConfirmed[_transactionId][msg.sender] = true;
emit TransactionConfirmed(_transactionId);
if (isTransactionConfirmed(_transactionId)) {
executeTransaction(_transactionId);
}
}
Only owners can confirm transactions. This function checks if the transaction is valid and not already confirmed by the caller. If the required number of confirmations is reached, it automatically triggers execution.
Checking Transaction Confirmation Status
function isTransactionConfirmed(
uint _transactionId
) public view returns (bool) {
require(_transactionId < transactions.length, "Invalid transaction");
uint confirmation;
for (uint i = 0; i < numConfirm; i++) {
if (isConfirmed[_transactionId][owners[i]]) {
confirmation++;
}
}
return confirmation >= numConfirm;
}
This view function checks if a transaction has received the required number of confirmations.
Executing a Transaction
function executeTransaction(uint _transactionId) public payable {
require(_transactionId < transactions.length, "Invalid transaction");
require(
!transactions[_transactionId].executed,
"Transaction is already executed"
);
(bool success, ) = transactions[_transactionId].to.call{
value: transactions[_transactionId].value
}("");
require(success, "Transaction Execution Failed ");
transactions[_transactionId].executed = true;
emit TransactionExecuted(_transactionId);
}
This function executes a confirmed transaction, transferring the funds to the specified recipient and marking the transaction as executed.
Beyond the Basics: The Power of Multi-Signature Wallets
This MultiSigWallet contract opens up a world of possibilities:
- Enhanced Security: Requires multiple approvals, reducing the risk of unauthorized transactions.
- Shared Control: Perfect for business accounts or shared funds management.
- Transparency: All actions are recorded on the blockchain, ensuring accountability.
- Flexibility: Customizable number of owners and required confirmations.
Conclusion: Securing the Future of Digital Assets
The MultiSigWallet smart contract is more than just code - it's a paradigm shift in how we think about digital asset security and management. By requiring multiple signatures for transactions, we're creating a more robust, trustworthy system for handling funds on the blockchain.
As you explore the potential of this contract on BTTC, remember: you're not just using a wallet, you're pioneering a new era of collaborative and secure digital finance.
So, who will you trust with your digital keys? The blockchain is waiting, and multi-signature security is ready to protect your assets!
Github URL:
https://github.com/adeelch9/bttc-examples/tree/master/projects/multisig
Bonus Section: Diving Deeper into BTTC Smart Contracts
We've only scratched the surface of what's possible with smart contracts on the BitTorrent Chain. For those eager to take their blockchain development skills to the next level, we've got a treasure trove of resources waiting for you in our GitHub repository!
🚀 Explore the Full Project
Head over to our BTTC Examples GitHub Repository to discover a wealth of additional content and features:
- Complete Contract Code: While we've covered the main functions, the repository contains the full smart contract code, including any methods we didn't have space to discuss here.
- Deployment Scripts: Ever wondered how to deploy your smart contracts to the BTTC network? We've got you covered with ready-to-use deployment scripts that make the process a breeze.
- Comprehensive Tests: Writing tests for smart contracts is crucial for ensuring their reliability and security. Our repository includes a suite of tests that demonstrate best practices in smart contract testing.
- Multiple Projects: Beyond the contract we've discussed today, you'll find a variety of other smart contract examples, from simple to advanced, showcasing different aspects of blockchain development on BTTC.
- Documentation: Detailed README files and inline comments provide additional context and explanations, making it easier to understand and modify the code for your own projects.
🛠️ Getting Started
To make the most of these resources:
- Clone the repository: git clone https://github.com/adeelch9/bttc-examples.git
- Navigate to the project directory of your choice
- Follow the setup instructions in the project's README
- Experiment with the contracts, run tests, and try deploying to a testnet
🌟 Why This Matters
By exploring the full repository, you'll gain:
- A deeper understanding of smart contract development
- Hands-on experience with deployment and testing
- Exposure to best practices in blockchain development
- Inspiration for your own BTTC projects
Whether you're a beginner looking to learn or an experienced developer seeking to refine your skills, our BTTC Examples repository is your gateway to mastering smart contract development on the BitTorrent Chain.
Happy coding, and may your transactions always be secure and consensual!
28 Aug 2024 6:48am GMT
27 Aug 2024
Stories by BitTorrent Inc. on Medium
BitTorrent Weekly Report | 08.19–08.25
Founded with a leading peer-to-peer sharing technology standard in 2004, BitTorrent, Inc. is a consumer software company based in San Francisco. Its protocol is the largest decentralized P2P network in the world, driving 22% of upstream and 3% of downstream traffic globally.
Its flagship desktop and mobile products, BitTorrent and µTorrent, enable users to send large files over the internet, connecting legitimate third-party content providers with users. With over 100 million active users, BitTorrent products have been installed on over 1 billion devices in over 138 countries worldwide.
Since November 2018, TRON (TRX), Binance (BNB), and Bitcoin (BTC) holders have the opportunity to purchase one-year subscriptions of BitTorrent or µTorrent products, including Ads Free and Pro for Windows. Pro includes anti-virus and anti-malware screening, file converting and playability in HD. Users can visit bittorrent.com or utorrent.com to learn more.
27 Aug 2024 7:19am GMT
21 Aug 2024
Stories by BitTorrent Inc. on Medium
Democracy on the Blockchain: Building a Voting Smart Contract on BTTC
Welcome, blockchain enthusiasts! Today, we're taking a significant step towards decentralizing democracy by creating a voting smart contract on the BitTorrent Chain (BTTC). This contract will allow us to register candidates, cast votes, and determine the winner in a transparent and tamper-proof manner. Let's dive into the details of our Voting Contract!
The Voting Contract: Blueprint for Digital Democracy
Our Voting Contract is designed to handle the entire voting process, from candidate registration to vote tallying. Here's a sneak peek at the core components of our contract:
Structs and State Variables
First, let's define the structures and state variables that will hold our voting data:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract Voting {
// saves voter info i.e., id and candidate id whom the voter voted
struct Voter {
string uid;
uint candidateIDVote;
}
// has candidate information like name, party, etc.
struct Candidate {
string name;
string party;
bool doesExist;
}
uint numCandidates; // declares a state variable - number of candidates
uint numVoters; // number of voters who voted
uint256 voteDeadline; // state variable for saving deadline
// These mappings will hold all the candidates and voters respectively
mapping(uint => Candidate) candidates;
mapping(uint => Voter) voters;
Events
Next, we define events that will be emitted at key moments during the voting process:
// event for candidate registration logging
event candidateRegistered(uint candidateID);
// event for vote logging
event voteRegistered(uint voterID, uint candidateID);
Functions
Now, let's dive into the functions that make our contract functional:
Setting and Getting the Vote Deadline
// @param _voteDeadline Timestamp value of the deadline
function setVoteDeadline(uint256 _voteDeadline) public {
voteDeadline = _voteDeadline;
}
function getVoteDeadline() public view returns (uint256) {
return voteDeadline;
}
Adding Candidates
// @param name string name of candidate
// @param party string name of party
function addCandidate(string calldata name, string calldata party) public {
numCandidates++;
candidates[numCandidates] = Candidate(name, party, true);
emit candidateRegistered(numCandidates);
}
Casting Votes
// @param uid string uid of user
// @param candidateID uint id of candidate
function vote(string calldata uid, uint candidateID) public {
require(block.timestamp <= voteDeadline, "Voting period has ended.");
require(candidates[candidateID].doesExist, "Candidate does not exist.");
numVoters++;
voters[numVoters] = Voter(uid, candidateID);
emit voteRegistered(numVoters, candidateID);
}
Getting the Winner
function getWinner() public view returns (string memory winnerName) {
uint[] memory voteCounts = new uint[](numCandidates + 1);
for (uint i = 1; i <= numVoters; i++) {
voteCounts[voters[i].candidateIDVote]++;
}
uint winningVoteCount = 0;
uint winningCandidateID = 0;
for (uint i = 1; i <= numCandidates; i++) {
if (voteCounts[i] > winningVoteCount) {
winningVoteCount = voteCounts[i];
winningCandidateID = i;
}
}
return candidates[winningCandidateID].name;
}
Getting Total Votes for a Candidate
// @param candidateID uint id of candidate
function totalVotes(uint candidateID) public view returns (uint) {
uint voteCount = 0;
for (uint i = 1; i <= numVoters; i++) {
if (voters[i].candidateIDVote == candidateID) {
voteCount++;
}
}
return voteCount;
}
}
The Power of Decentralized Voting
This Voting Contract demonstrates how blockchain can revolutionize traditional voting systems. By ensuring transparency, immutability, and security, we can build trust in the electoral process.
Beyond the Basics: Enhancing Your Voting Contract
Now that you have a basic voting contract, consider adding more features:
- Implement voter registration to prevent duplicate voting.
- Add candidate verification mechanisms.
- Create a user-friendly frontend for voters to interact with the contract.
Conclusion: Shaping the Future of Democracy
You've just taken a significant step towards decentralizing democracy. This Voting Contract is more than just code; it's a vision of a future where every vote counts, and every election is transparent and fair.
So, what will you build next? The blockchain world is full of possibilities, and the future of democracy is in your hands!
Github URL:
https://github.com/adeelch9/bttc-examples/tree/master/projects/voting
Bonus Section: Diving Deeper into BTTC Smart Contracts
We've only scratched the surface of what's possible with smart contracts on the BitTorrent Chain. For those eager to take their blockchain development skills to the next level, we've got a treasure trove of resources waiting for you in our GitHub repository!
🚀 Explore the Full Project
Head over to our BTTC Examples GitHub Repository to discover a wealth of additional content and features:
- Complete Contract Code: While we've covered the main functions, the repository contains the full smart contract code, including any methods we didn't have space to discuss here.
- Deployment Scripts: Ever wondered how to deploy your smart contracts to the BTTC network? We've got you covered with ready-to-use deployment scripts that make the process a breeze.
- Comprehensive Tests: Writing tests for smart contracts is crucial for ensuring their reliability and security. Our repository includes a suite of tests that demonstrate best practices in smart contract testing.
- Multiple Projects: Beyond the contract we've discussed today, you'll find a variety of other smart contract examples, from simple to advanced, showcasing different aspects of blockchain development on BTTC.
- Documentation: Detailed README files and inline comments provide additional context and explanations, making it easier to understand and modify the code for your own projects.
🛠️ Getting Started
To make the most of these resources:
- Clone the repository: git clone https://github.com/adeelch9/bttc-examples.git
- Navigate to the project directory of your choice
- Follow the setup instructions in the project's README
- Experiment with the contracts, run tests, and try deploying to a testnet
🌟 Why This Matters
By exploring the full repository, you'll gain:
- A deeper understanding of smart contract development
- Hands-on experience with deployment and testing
- Exposure to best practices in blockchain development
- Inspiration for your own BTTC projects
Whether you're a beginner looking to learn or an experienced developer seeking to refine your skills, our BTTC Examples repository is your gateway to mastering smart contract development on the BitTorrent Chain.
Happy coding, future blockchain democrat!
21 Aug 2024 4:15am GMT
20 Aug 2024
Stories by BitTorrent Inc. on Medium
BitTorrent Weekly Report | 08.12–08.18
Founded with a leading peer-to-peer sharing technology standard in 2004, BitTorrent, Inc. is a consumer software company based in San Francisco. Its protocol is the largest decentralized P2P network in the world, driving 22% of upstream and 3% of downstream traffic globally.
Its flagship desktop and mobile products, BitTorrent and µTorrent, enable users to send large files over the internet, connecting legitimate third-party content providers with users. With over 100 million active users, BitTorrent products have been installed on over 1 billion devices in over 138 countries worldwide.
Since November 2018, TRON (TRX), Binance (BNB), and Bitcoin (BTC) holders have the opportunity to purchase one-year subscriptions of BitTorrent or µTorrent products, including Ads Free and Pro for Windows. Pro includes anti-virus and anti-malware screening, file converting and playability in HD. Users can visit bittorrent.com or utorrent.com to learn more.
20 Aug 2024 8:25am GMT
14 Aug 2024
Stories by BitTorrent Inc. on Medium
Minting Your Future: Crafting an ERC20 Token on BTTC
Welcome, blockchain innovators! Today, we're leveling up from our "Hello World" adventure to create something truly exciting - your very own cryptocurrency token on the BitTorrent Chain (BTTC). Buckle up as we dive into the world of ERC20 tokens with our SimpleERC20 contract!
The Power of Standards: Enter ERC20
Before we jump into the code, let's talk about why ERC20 is a big deal. It's like the universal language of tokens in the Ethereum ecosystem, and by extension, BTTC. By following this standard, your token becomes instantly compatible with a vast array of wallets, exchanges, and DApps. It's your ticket to the big leagues of crypto!
Our SimpleERC20 Contract: Small Code, Big Potential
Let's unveil our compact yet powerful SimpleERC20 contract:
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract SimpleERC20 is ERC20 {
constructor(
string memory name,
string memory symbol,
uint256 initialSupply
) ERC20(name, symbol) {
_mint(msg.sender, initialSupply);
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
}
This little gem is your gateway to creating a fully-functional ERC20 token. Let's break it down and uncover the magic within!
Decoding the Digital Alchemy
The Magical Import
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
This line is where the real power comes from. We're importing OpenZeppelin's battle-tested ERC20 implementation. It's like standing on the shoulders of giants - we get all the standard ERC20 functionality without reinventing the wheel.
Our Token's Birth Certificate
contract SimpleERC20 is ERC20 {
// Contract body
}
Here, we're declaring our contract and inheriting from OpenZeppelin's ERC20. It's like saying, "I want all the cool features of ERC20, and I might add some of my own flair!"
The Constructor: Breathing Life into Your Token
constructor(
string memory name,
string memory symbol,
uint256 initialSupply
) ERC20(name, symbol) {
_mint(msg.sender, initialSupply);
}
This is where the magic happens! Our constructor takes three parameters:
- name: Your token's full name (e.g., "BitTorrent Chain Token")
- symbol: A short ticker symbol (e.g., "BTT")
- initialSupply: The number of tokens to mint initially
We pass name and symbol to the ERC20 constructor, then use _mint to create our initial supply of tokens, assigning them to whoever deploys the contract.
Decimal Places: The Fine Print
function decimals() public view virtual override returns (uint8) {
return 18;
}
This function sets the number of decimal places for your token. We're using 18, which is the standard for most ERC20 tokens. It means 1 token is represented as 1000000000000000000 (1 with 18 zeros) in its smallest unit.
The Power at Your Fingertips
By inheriting from OpenZeppelin's ERC20, your token automatically comes with all the standard functions:
- transfer: Send tokens from your address to another.
- approve and transferFrom: Allow third-party transfers (crucial for DeFi interactions).
- balanceOf: Check the token balance of any address.
- totalSupply: Get the total number of tokens in existence.
Beyond the Basics: Where to Next?
Now that you have your own token, the possibilities are endless:
- Add minting/burning functions to control the supply.
- Implement token vesting or time locks.
- Create a governance system based on token holdings.
- Launch a liquidity pool on a decentralized exchange.
The Birth of Your Token Empire
While our SimpleERC20 contract may seem straightforward, it's a powerful foundation for building in the world of decentralized finance. You've just created a token that could be the next big thing in the crypto space!
Remember, every great token starts with a simple contract. Today it's a basic ERC20, tomorrow it could be the backbone of a revolutionary DeFi protocol!
So, what will your token represent in the vast landscape of blockchain? The possibilities are as limitless as your imagination!
Github URL:
https://github.com/adeelch9/bttc-examples/tree/master/projects/erc20
Bonus Section: Diving Deeper into BTTC Smart Contracts
We've only scratched the surface of what's possible with smart contracts on the BitTorrent Chain. For those eager to take their blockchain development skills to the next level, we've got a treasure trove of resources waiting for you in our GitHub repository!
🚀 Explore the Full Project
Head over to our BTTC Examples GitHub Repository to discover a wealth of additional content and features:
- Complete Contract Code: While we've covered the main functions, the repository contains the full smart contract code, including any methods we didn't have space to discuss here.
- Deployment Scripts: Ever wondered how to deploy your smart contracts to the BTTC network? We've got you covered with ready-to-use deployment scripts that make the process a breeze.
- Comprehensive Tests: Writing tests for smart contracts is crucial for ensuring their reliability and security. Our repository includes a suite of tests that demonstrate best practices in smart contract testing.
- Multiple Projects: Beyond the contract we've discussed today, you'll find a variety of other smart contract examples, from simple to advanced, showcasing different aspects of blockchain development on BTTC.
- Documentation: Detailed README files and inline comments provide additional context and explanations, making it easier to understand and modify the code for your own projects.
🛠️ Getting Started
To make the most of these resources:
- Clone the repository: git clone https://github.com/adeelch9/bttc-examples.git
- Navigate to the project directory of your choice
- Follow the setup instructions in the project's README
- Experiment with the contracts, run tests, and try deploying to a testnet
🌟 Why This Matters
By exploring the full repository, you'll gain:
- A deeper understanding of smart contract development
- Hands-on experience with deployment and testing
- Exposure to best practices in blockchain development
- Inspiration for your own BTTC projects
Whether you're a beginner looking to learn or an experienced developer seeking to refine your skills, our BTTC Examples repository is your gateway to mastering smart contract development on the BitTorrent Chain.
Happy token crafting, future crypto mogul!
14 Aug 2024 3:20am GMT