dApp — это учетная запись Waves, на которую назначен скрипт dApp, созданный для использования смарт-контрактов в WAVES. Скрипт dApp — это скрипт Ride, который содержит вызываемые функции, которые могут быть вызваны извне транзакциями Waves
Скажите «Hello World» в сети WAVES
Каждый скрипт Ride должен начинаться с директив. Эти директивы сообщают компилятору, что:
{-# STDLIB_VERSION 6 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}
Вызываемая функция может быть вызвана извне транзакцией invoke script
Результат вызываемой функции — это набор действий скрипта, которые выполняются в блокчейне
@Callable(i)
func helloWorld(name: String) = {
[
StringEntry("answer", "Hello World! Hello, " + name)
]
}
Это намного проще, чем вы себе представляете. Скажите «Hello World» в сети WAVES Вставьте этот скрипт в свой проект
{-# STDLIB_VERSION 6 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}
@Callable(i)
func helloWorld(name: String) = {
[
StringEntry("answer", "Hello World! Hello, " + name)
]
}
Развертывание скрипта в сети Waves
Во время развертывания вам нужно будет создать свою учетную запись, если у вас ее еще нет
// Запустить тест с помощью Surfboard
const WAVES = 10 ** 8;
const FEE = 0.001 * WAVES;
const ADD_FEE = 0.004 * WAVES;
describe('HelloWorld dApp test suite', async function () {
this.timeout(100000);
// В предыдущем разделе мы выполняем все действия, необходимые для тестирования dApp, и генерируется определенное количество учетных записей с указанным балансом
before(async function () {
await setupAccounts({
dApp: 10 * WAVES,
});
//Развертывание осуществляется транзакцией установки скрипта на аккаунт
const dAppScript = compile(file('dApp.ride'));
const ssDAppTx = setScript({ script: dAppScript }, accounts.dApp);
await broadcast(ssDAppTx);
await waitForTx(ssDAppTx.id);
});
//Каждый раздел it() служит для проверки некоторой функциональности
it('Should say hello', async function () {
const name = "Alex";
const iInitTx = invokeScript({
fee: FEE + ADD_FEE,
dApp: address(accounts.dApp),
call: {
function: "helloWorld",
args: [
{ type: 'string', value: name },
]
},
}, accounts.dApp);
await broadcast(iInitTx);
await waitForTx(iInitTx.id);
//Вызов функции скрипта осуществляется транзакцией invokeScript
const result = await accountDataByKey("answer", address(accounts.dApp))
expect(result.value).to.be.equal("Hello World! Hello, " + name);
});
})
//В конце мы считываем данные учетной записи по ключу и проверяем правильность сохраненных данных
const result = await accountDataByKey("answer", address(accounts.dApp))
expect(result.value).to.be.equal("Hello World! Hello, " + name);
});
})
//Пример вызова функции из dApp
import com.wavesplatform.crypto.Crypto;
import com.wavesplatform.transactions.InvokeScriptTransaction;
import com.wavesplatform.transactions.SetScriptTransaction;
import com.wavesplatform.transactions.TransferTransaction;
import com.wavesplatform.transactions.account.PrivateKey;
import com.wavesplatform.transactions.common.Amount;
import com.wavesplatform.transactions.common.Base64String;
import com.wavesplatform.transactions.data.DataEntry;
import com.wavesplatform.transactions.invocation.Function;
import com.wavesplatform.transactions.invocation.StringArg;
import com.wavesplatform.wavesj.Node;
import com.wavesplatform.wavesj.Profile;
import com.wavesplatform.wavesj.exceptions.NodeException;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.web3j.utils.Files;
import java.io.File;
import java.io.IOException;
public class DappTest {
static PrivateKey dApp;
static Node node;
static Base64String dAppScript;
// additional info can be found - https://hub.docker.com/r/wavesplatform/waves-private-node
static PrivateKey faucet = PrivateKey.fromSeed("waves private node seed with waves tokens");
// In "Before section", we perform all the actions that we need to test the dApp
@BeforeClass
public static void before() throws NodeException, IOException {
node = new Node(Profile.LOCAL);
// Certain number of accounts with the specified balance is generated
dApp = PrivateKey.fromSeed(Crypto.getRandomSeedBytes());
TransferTransaction transfer = TransferTransaction.builder(
dApp.address(), Amount.of(1_00_000_000)
).getSignedWith(faucet);
node.broadcast(transfer);
node.waitForTransaction(transfer.id());
// Deployment is carried out by the transaction of installing the script on the account
String source = Files.readString(new File("src/test/resources/dApp.ride"));
dAppScript = node.compileScript(source).script();
SetScriptTransaction ssTx = SetScriptTransaction.builder(dAppScript).getSignedWith(dApp);
node.broadcast(ssTx);
node.waitForTransaction(ssTx.id());
}
@Test
public void should_say_hello() throws NodeException, IOException {
String name = "Alex";
// Call of the script function is carried out by the invokeScript transaction
InvokeScriptTransaction iInitTx = InvokeScriptTransaction.builder(
dApp.address(),
Function.as("helloWorld", StringArg.as(name))
).getSignedWith(dApp);
node.broadcast(iInitTx);
node.waitForTransaction(iInitTx.id());
// At the end, some checks are usually made.
// In this case, we read the account data by key and check the correctness of the saved data
DataEntry result = node.getData(dApp.address(), "answer");
Assert.assertEquals(result.valueAsObject(), "Hello World! Hello, " + name);
}
}
Вы успешно создали свой первый dApp. Он был опубликован в сети Waves.