Soy nuevo en Solidity y no puedo entender por qué recibo el error anterior a pesar de que la función de compra de Producto () se declara pagadera. Probé este código en Remix IDE y obtuve este error.
Error de máquina virtual: revertir. revert La transacción ha sido revertida al estado inicial. Nota: La función llamada debe pagarse si envía valor y el valor que envía debe ser menor que su saldo actual. Depure la transacción para obtener más información.
Todo funciona bien, excepto la función de compraProducto(). Estoy tratando de obtener los datos de la estructura 'Usuario', 'Producto' y almacenar los datos en una nueva estructura que es 'Pedido'.
He llevado a cabo la validación usando require(). Mientras ejecuta el código en Remix:
1. Cree 2 usuarios
2.
3. comprarProducto usando un segundo usuario
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
//Address: '0x7772B9117586b5F745bDb563a935E91b00449157'
contract Buyproduct{
uint public orderCount = 0;
mapping(uint => Order) public orders;
uint public productCount = 0;
mapping(uint => Product) public products;
uint public userCount = 0;
mapping(address => User) public users;
struct Order {
uint oid;
address payable seller;
address payable buyer;
// string timestamp;
string status;
uint pid;
string location;
uint quantitiy;
}
struct Product {
uint pid;
string name;
uint price;
address payable seller;
string info;
uint quantity;
}
struct User {
uint uid;
string name;
uint role;
address payable user;
string location;
bool created;
}
event ProductCreated(
uint pid,
string name,
uint price,
address payable seller,
string info,
uint quantity
);
event UserCreated(
uint uid,
string name,
uint role,
address payable user,
string location,
bool created
);
event ProductPurchased(
uint oid,
address payable seller,
address payable buyer,
string status,
uint pid,
string location,
uint quantity
);
event ReviewAdded(
uint rid,
address reviewer,
uint pid,
string review
);
function createUser(string memory _name, uint _role, string memory _location) public payable{
//No repeated address
require(users[msg.sender].created == false, 'User already created');
//Increase userCount
userCount++;
//Add user
users[msg.sender] = User(userCount, _name, _role, msg.sender, _location, true);
//Trigger an event
emit UserCreated(userCount, _name, _role, msg.sender, _location, true);
}
function createProduct(string memory _name, uint _price, string memory _info, uint _quantity) public payable {
// Require a valid price
require(_price > 0, 'Invalid Price');
// Increment product count
productCount ++;
// Create the product
products[productCount] = Product(productCount, _name, _price, msg.sender, _info, _quantity);
// Trigger an event
emit ProductCreated(productCount, _name, _price, msg.sender, _info, _quantity);
}
function purchaseProduct(uint _id, /*string memory timestamp,*/ uint _quantity) public payable {
// Fetch the product
Product memory _product = products[_id];
// Fetch the owner
address payable _seller = _product.seller;
//Validate the buyer
require(users[msg.sender].created == true, 'Unregistered user');
// Make sure the product has a valid id
require(_product.pid > 0 && _product.pid <= productCount, 'Invalid Product ID');
// Require that there is enough Ether in the transaction
require(msg.value >= _product.price, 'Not enough ether in Wallet');
// Require that the buyer is not the seller
require(_seller != msg.sender,'Invalid Purchase');
//Incrmement orderCount
orderCount++;
// Transfer ownership to the buyer
orders[orderCount] = Order(orderCount, _seller, msg.sender,/* ts,*/ 'Ordered', _product.pid, users[msg.sender].location, _quantity);
//Reduce the quantity of the product
_product.quantity -= _quantity;
// Pay the contract by sending them Ether
address payable wallet = address(uint160(address(this)));
wallet.transfer(msg.value);
// Trigger an event
emit ProductPurchased(orderCount, _seller, msg.sender, /*timestamp,*/ 'Ordered', _product.pid, users[msg.sender].location, _quantity);
}
}'''
function createProduct(string memory _name, uint _price, string memory _info, uint _quantity) public payable {
La firma de esta función tiene _price en éteres. Así que intente cambiar las unidades predeterminadas al éter de Wei y envíe el precio apropiado del producto.
el mio esta funcionando
[vm]from:0x4b0...4d2dbto:Buyproduct.purchaseProduct(uint256,uint256) 0x1df...bda71value:2000000000000000000 weidata:0xa04...00001logs:1hash:0x4e0...0d2b0
Tampoco necesita llamarlos explícitamente.
address payable wallet = address(uint160(address(this)));
wallet.transfer(msg.value);
El saldo del contrato se actualizará automáticamente. Puede comprobarlo implementando esta función en su contrato.
function getBalance()
public
view
returns(uint) {
return address(this).balance;}
Espinascrema
punto gráfico
Espinascrema