Examples¶
The ETOPay SDK is built in rust
. It is primarily an implementation of the various interfaces for managing users, wallets, on-boarding of users through KYC (Know Your Customer) processes, payment methods and listing usage information. The flows discussed in this document show examples using the rust language. For examples related to the specific language, refer to the corresponding pages.
The ETOPay SDK can be used only if the following pre-requisites have been fulfilled and the information resulting from these conditions is available:
- Oauth2.0 Identity and Access Management Provider is configured correctly,
- The backend base URL of the ETOPay system is known,
- The path to a certain file storage is available, where the application has read/write rights to create, modify and delete files related to the SDK like log files, local key-value DBs, and wallet files.
Once this information is available, the SDK can be instantiated and the basic functions can be used.
The examples shows the usage of the SDK in rust for creating a user. The user credentials are taken from the environment but could also be easily a user input.
The environment configuration to Development
attaches the SDK to the development backend of ETOPay automatically. It also configures the authentication provider correctly with the one used by the development team internally. This configuration is used by ETOPay developers and is only restricted to the users controlled by the identity provider configured for ETOPay internal testing.
0. Shared Setup Code¶
use etopay_sdk::{
core::{Config, Sdk},
types::newtypes::{AccessToken, EncryptionPin},
};
use std::path::Path;
use testing::{CleanUp, USER_SATOSHI};
pub async fn init_sdk() -> (Sdk, CleanUp) {
dotenvy::dotenv().ok();
// for the examples we want logs to go to the console for easier troubleshooting
env_logger::builder().filter_level(log::LevelFilter::Info).init();
let user = &USER_SATOSHI;
let cleanup = CleanUp::default();
let backend_url = std::env::var("EXAMPLES_BACKEND_URL")
.expect("EXAMPLES_BACKEND_URL environment variable need to be set to run the examples");
// construct the config to use for the SDK
let config = Config {
backend_url: backend_url.parse().expect("EXAMPLES_BACKEND_URL must be a valid URL"),
path_prefix: Path::new(&cleanup.path_prefix).into(),
auth_provider: "standalone".to_string(),
log_level: log::LevelFilter::Debug,
};
let mut sdk = Sdk::new(config).expect("should not fail to initialize sdk"); // set the backend url if the environment variable is set
// generate access token
let access_token = testing::get_access_token(&user.username, &user.password)
.await
.access_token;
let access_token = AccessToken::try_from(access_token).unwrap();
sdk.refresh_access_token(Some(access_token)).await.unwrap();
(sdk, cleanup)
}
package com.etospheres.etopay.examples;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.nio.file.Path;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import com.etospheres.etopay.ETOPaySdk;
public class utils {
public static String USERNAME_SATOSHI = "satoshi";
public static String PIN = "123456";
public static String NEW_PIN = "432156";
public static String USERNAME_ARCHIVEME = "archiveme";
public static String USERNAME_HANS48 = "hans48";
public static ETOPaySdk initSdk(String username) {
ETOPaySdk sdk = new ETOPaySdk();
// config sdk
try {
// on CI we want to store the logs as artifacts, so we force the location
Path directory;
if (getEnvVariable("CI") != null) {
Path path = FileSystems.getDefault().getPath("logs");
Files.createDirectories(path);
directory = Files.createTempDirectory(path, "etopay_examples");
} else {
directory = Files.createTempDirectory("etopay_examples");
}
System.out.println("Setting storage path to temporary directory: " + directory.toString());
String url = getEnvVariable("EXAMPLES_BACKEND_URL");
sdk.setConfig("""
{
"backend_url": "%s",
"storage_path": "%s",
"log_level": "info",
"auth_provider": "standalone"
}
""".formatted(url, directory.toString()));
System.out.println("SDK environment set to development and validated.");
// get the access token
String access_token = generateAccessToken(username);
sdk.refreshAccessToken(access_token);
System.out.println("retrieved access token");
} catch (Exception e) {
throw new RuntimeException("Failed to initialize SDK", e);
}
return sdk;
}
// Enum with possible error cases which might happen during the generation of
// the access token call.
enum TokenError {
MISSING_ENVIRONMENT_VARIABLE,
INVALID_URL,
PARSING_ERROR,
ACCESS_TOKEN_NOT_FOUND
}
// Generate an access token by making a call to the KC API
public static String generateAccessToken(String username) throws IOException {
// get from env vars
String kcURL = getEnvVariable("KC_URL");
String kcRealm = getEnvVariable("KC_REALM");
String clientId = getEnvVariable("KC_CLIENT_ID");
String clientSecret = getEnvVariable("KC_CLIENT_SECRET");
String password = getEnvVariable("PASSWORD");
if (kcURL == null || kcRealm == null || clientId == null || clientSecret == null || password == null) {
throw new RuntimeException(TokenError.MISSING_ENVIRONMENT_VARIABLE.name());
}
String urlString = kcURL + "/realms/" + kcRealm + "/protocol/openid-connect/token";
@SuppressWarnings("deprecation")
URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Construct body parameters
Map<String, String> bodyParameters = new HashMap<>();
bodyParameters.put("grant_type", "password");
bodyParameters.put("scope", "profile email openid");
bodyParameters.put("client_id", clientId);
bodyParameters.put("client_secret", clientSecret);
bodyParameters.put("username", username);
bodyParameters.put("password", password);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : bodyParameters.entrySet()) {
if (postData.length() != 0)
postData.append('&');
postData.append(param.getKey());
postData.append('=');
postData.append(param.getValue());
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
con.setDoOutput(true);
con.getOutputStream().write(postDataBytes);
// Read response
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// Parse JSON response using Jackson ObjectMapper
InputStream inputStream = con.getInputStream();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonResponse = mapper.readTree(inputStream);
// Check if access_token exists in JSON response
if (jsonResponse.has("access_token")) {
// System.out.println(jsonResponse.get("access_token").asText());
return jsonResponse.get("access_token").asText();
} else {
throw new RuntimeException(TokenError.ACCESS_TOKEN_NOT_FOUND.name());
}
} else {
throw new RuntimeException("Failed to get access token: " + responseCode);
}
}
public static String getEnvVariable(String varName) {
// Check if running in CI environment
if (System.getenv("CI") != null) {
// Use CI environment variables directly
return System.getenv(varName);
} else {
// Load environment variables from .env file for local development
Dotenv dotenv = Dotenv.configure().load();
return dotenv.get(varName);
}
}
}
import ETOPaySdk
import Foundation
// Struct to hold environment variables for examples
public struct Environment {
public let username: String
public let password: String
public let wallet_password: String
public let pin: String
public let mnemonic: String
public init() {
guard
let username = ProcessInfo.processInfo.environment["USERNAME"],
let password = ProcessInfo.processInfo.environment["PASSWORD"],
let mnemonic = ProcessInfo.processInfo.environment["MNEMONIC"]
else {
fatalError("Missing environment variables")
}
self.username = username
self.password = password
self.wallet_password = "correcthorsebatterystaple"
self.pin = "123456"
self.mnemonic = mnemonic
}
}
// Helper function to access env variables
public func getEnvironment() -> Environment {
return Environment()
}
// Create sdk instance and set env
public func initSdk(username: String, password: String) async throws -> ETOPaySdk {
// remove user and wallet generated files
cleanup(atPaths: ["sdk-user.db", "wallets"])
let url = ProcessInfo.processInfo.environment["EXAMPLES_BACKEND_URL"]!
// initialize the etopay sdk
let sdk = ETOPaySdk()
// set the sdk config and validate it
try await sdk.setConfig(
"""
{
"backend_url": "\(url)",
"storage_path": ".",
"log_level": "info",
"auth_provider": "standalone"
}
""")
// get the access token
let access_token = try await generateAccessToken(username: username, password: password)
try await sdk.refreshAccessToken(access_token)
print("retrieved access token")
return sdk
}
// Enum with possible error cases which might happen during the generation of the access token call.
enum TokenError: Error {
case missingEnvironmentVariable(String)
case invalidURL
case parsingError(String)
case accessTokenNotFound
}
// Struct to get the access token from the response
struct TokenResponse: Codable {
let accessToken: String
}
// Generate an access token by making a call to the KC API. This is mirroring the `hello.http` endpoint
func generateAccessToken(username: String, password: String) async throws -> String {
// access environment variables
guard
let kcURL = ProcessInfo.processInfo.environment["KC_URL"],
let kcRealm = ProcessInfo.processInfo.environment["KC_REALM"],
let clientId = ProcessInfo.processInfo.environment["KC_CLIENT_ID"],
let clientSecret = ProcessInfo.processInfo.environment["KC_CLIENT_SECRET"]
else {
throw TokenError.missingEnvironmentVariable("One or more environment variables are missing")
}
let urlString = "\(kcURL)/realms/\(kcRealm)/protocol/openid-connect/token"
guard let url = URL(string: urlString) else {
throw TokenError.invalidURL
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
// Construct body parameters
let bodyParameters = [
"grant_type": "password",
"scope": "profile email openid",
"client_id": clientId,
"client_secret": clientSecret,
"username": username,
"password": password,
]
request.httpBody =
bodyParameters
.map { "\($0.key)=\($0.value)" }
.joined(separator: "&")
.data(using: .utf8)
let (data, _) = try await URLSession.shared.data(for: request)
let jsonString = String(data: data, encoding: .utf8)
guard let jsonData = jsonString?.data(using: .utf8) else {
throw TokenError.parsingError("failed to parse json data from string")
}
do {
// Parse the JSON data
if let json = try JSONSerialization.jsonObject(with: jsonData, options: [])
as? [String: Any],
let accessToken = json["access_token"] as? String
{
return accessToken
} else {
throw TokenError.accessTokenNotFound
}
} catch _ {
throw TokenError.parsingError("failed to serialize json data")
}
}
// cleanup
func cleanup(atPaths paths: [String]) {
let fileManager = FileManager.default
for path in paths {
do {
// Check if the file or directory exists
if fileManager.fileExists(atPath: path) {
// Remove the file or directory
try fileManager.removeItem(atPath: path)
} else {
print("File or directory does not exist: \(path). Moving on ..")
}
} catch {
print("Error removing file or directory at \(path): \(error)")
}
}
}
import * as wasm from "../pkg";
import * as dotenv from 'dotenv';
import axios from 'axios';
import { LocalStorage } from "node-localstorage";
export const PIN = "123456";
export async function initSdk(username: string) {
dotenv.config();
// setup localStorage to use a file-based mock version
globalThis.window = { localStorage: new LocalStorage('./local-storage') } as any;
// make sure the localStorage is clear to run each example in isolation
try {
window.localStorage.clear();
} catch (e) {
console.log("Could not clear local storage: ", e);
}
console.log("Starting SDK initialization...");
const sdk = new wasm.ETOPaySdk();
// set the backend url if the environment variable is set
let url: string = (process.env.EXAMPLES_BACKEND_URL as string);
if (url == undefined) {
throw new Error("EXAMPLES_BACKEND_URL environment variable must be present")
}
await sdk.setConfig(`
{
"backend_url": "${url}",
"log_level": "info",
"auth_provider": "standalone"
}
`);
// Generate access token
let access_token = await generateAccessToken(username);
await sdk.refreshAccessToken(access_token);
return sdk;
}
// Custom error class for handling token errors
class TokenError extends Error {
constructor(message: string) {
super(message);
this.name = "TokenError";
}
static missingEnvironmentVariable(message: string) {
return new TokenError(`Missing environment variable: ${message}`);
}
static invalidURL() {
return new TokenError('Invalid URL');
}
static parsingError(message: string) {
return new TokenError(`Parsing error: ${message}`);
}
static accessTokenNotFound() {
return new TokenError('Access token not found');
}
}
// Generate an access token by making a call to the KC API. This is mirroring the `hello.http` endpoint
async function generateAccessToken(username: string): Promise<string> {
// Access environment variables
const kcURL = process.env.KC_URL;
const kcRealm = process.env.KC_REALM;
const clientId = process.env.KC_CLIENT_ID;
const clientSecret = process.env.KC_CLIENT_SECRET;
const password = process.env.PASSWORD
if (!kcURL || !kcRealm || !clientId || !clientSecret || !password) {
throw TokenError.missingEnvironmentVariable('One or more environment variables are missing');
}
const urlString = `${kcURL}/realms/${kcRealm}/protocol/openid-connect/token`;
let env_data = {
grant_type: 'password',
scope: 'profile email openid',
client_id: clientId,
client_secret: clientSecret,
username: username,
password: password
};
try {
const response = await axios.post(urlString, env_data, {
headers: { 'content-type': 'application/x-www-form-urlencoded' },
});
const data = response.data;
if (data && data.access_token) {
return data.access_token;
} else {
throw TokenError.accessTokenNotFound();
}
} catch (error: any) {
if (error.response) {
// Server responded with a status other than 2xx
throw TokenError.parsingError(`Server responded with status ${error.response.status}: ${error.response.statusText}`);
} else if (error.request) {
// No response was received
throw TokenError.invalidURL();
} else {
// Something happened in setting up the request
throw TokenError.parsingError(error.message);
}
}
}
1. Create New User¶
mod utils;
use testing::USER_SATOSHI;
use utils::init_sdk;
#[allow(clippy::unwrap_used, clippy::expect_used)]
#[tokio::main]
async fn main() {
// Initialize SDK
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
}
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
public class CreateNewUser01 {
public static void main(String[] args) {
// Initialize SDK
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
try {
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
} catch (Exception e) {
throw new RuntimeException("Create new user example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
import ETOPaySdk
import Foundation
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
// Create new user
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
} catch let error as RustString {
fatalError("Create new user example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
2. Onboard User Postident¶
mod utils;
use testing::USER_SATOSHI;
use utils::init_sdk;
// ---------------------------------------------
// Note: This examples does not work unless you do manual postident verification at https://postident-itu.deutschepost.de/testapp
// ---------------------------------------------
#[allow(clippy::unwrap_used, clippy::expect_used)]
#[tokio::main]
async fn main() {
// Initialize SDK and create a new user
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Exit if user is already verified
let is_verified = sdk.is_kyc_status_verified(&user.username).await.unwrap();
if is_verified {
println!("User is already verified, please run the delete_user example first.");
return;
}
// Start KYC verification for postident
let new_case_id = sdk.start_kyc_verification_for_postident().await.unwrap();
println!("New postident user with case: {:#?}", new_case_id);
// Do manual postident verification at
// https://postident-itu.deutschepost.de/testapp
let mut enter = String::new();
println!("Do postident KYC and hit enter to continue...");
std::io::stdin()
.read_line(&mut enter)
.expect("error: unable to read user input");
// Finish KYC verification for postident
sdk.update_kyc_status_for_postident(&new_case_id.case_id).await.unwrap();
// Check that the user is verified
let is_verified = sdk.is_kyc_status_verified(&user.username).await.unwrap();
println!("IsVerified: {:#?}", is_verified);
}
/**
* Do manual postident verification at https://postident-itu.deutschepost.de/testapp
*/
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
public class OnboardUserPostident02 {
public static void main(String[] args) {
// Initialize SDK
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
try {
// create and init new user
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
// check if user is kyc verified
boolean is_verified = sdk.isKycVerified(utils.USERNAME_SATOSHI);
if (is_verified == true) {
System.out.println("User is already verified, please run the delete_user example first.");
return;
}
// Start KYC verification for postident
String new_case = sdk.startKycVerificationForPostident();
System.out.println("New postident user with case: " + new_case);
// Do manual postident verification at
// https://postident-itu.deutschepost.de/testapp
// Finish KYC verification for postident
sdk.updateKycStatusForPostident("new case id");
// Check that the user is verified
boolean is_verified_after = sdk.isKycVerified(utils.USERNAME_SATOSHI);
System.out.println("IsVerified: " + is_verified_after);
} catch (
Exception e) {
throw new RuntimeException("Onboard user postident example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
// ! Need to do manual verification on postident: https://postident-itu.deutschepost.de/testapp
import ETOPaySdk
import Foundation
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
// Create new user
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
// Exit if user is already verified
let is_verified = try await sdk.isKycVerified(env.username)
print("is verified: \(is_verified)")
if is_verified {
print("User is already verified. No need to delete. Exiting")
return
}
// Start KYC verification for postident
let new_user = try await sdk.initKycVerificationForPostident()
print("New postident user: \(new_user.case_id.toString()), \(new_user.case_url.toString())")
// Do manual postident verification at https://postident-itu.deutschepost.de/testapp
// Finish KYC verification for postident
try await sdk.updateKycDetailsForPostident(new_user.case_id)
// Check that the user is verified.
// Should be true if the manual verification in postident is done.
// Here it will return false.
let verified = try await sdk.isKycVerified(env.username)
print("Is Verified: \(verified)")
} catch let error as RustString {
fatalError("Onboard user with postident example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
// Need to do manual verification on postident: https://postident-itu.deutschepost.de/testapp
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk } from './utils';
async function main() {
let username = "satoshi";
const sdk = await initSdk(username);
await sdk.createNewUser(username);
await sdk.initializeUser(username);
// Start KYC verification for Postident
let response = await sdk.startKycVerificationForPostident();
console.log("Postident case id:", response.case_id);
console.log("Postident case url:", response.case_url);
// --> Do Postident KYC process with URL
// Get KYC details for Postident
let caseDetails = await sdk.getKycDetailsForPostident();
console.log("Case details:", caseDetails);
// Update KYC status for Postident
await sdk.updateKycStatusForPostident(response.case_id);
console.log("Case status updated.");
// Check if KYC is verified
let isVerified = await sdk.isKycVerified(username);
console.log("IsVerified:", isVerified);
}
main();
4. Migrate Wallet From Mnemonic¶
mod utils;
use etopay_sdk::types::newtypes::PlainPassword;
use testing::USER_SATOSHI;
use utils::init_sdk;
#[allow(clippy::unwrap_used, clippy::expect_used)]
#[tokio::main]
async fn main() {
// Initialize SDK
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
sdk.set_wallet_password(
&user.pin,
&PlainPassword::try_from_string("correcthorsebatterystaple").unwrap(),
)
.await
.unwrap();
// Create new wallet
sdk.create_wallet_from_existing_mnemonic(&user.pin, &user.mnemonic)
.await
.unwrap();
// Fetch networks from backend
let networks = sdk.get_networks().await.unwrap();
let iota_network_key = &networks.first().unwrap().key;
sdk.set_network(iota_network_key.to_string()).await.unwrap();
// use wallet
let _address = sdk.generate_new_address(&user.pin).await.unwrap();
}
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
import com.etospheres.etopay.model.Network;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.List;
import com.etospheres.etopay.ETOPaySdk;
public class MigrateWalletFromMnemonic04 {
public static void main(String[] args) {
// initialize the sdk
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
String password = "correcthorsebatterystaple";
String mnemonic = utils.getEnvVariable("MNEMONIC");
try {
// create and init user
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
// create new wallet
sdk.setWalletPassword(utils.PIN, password);
sdk.createWalletFromMnemonic(utils.PIN, mnemonic);
System.out.println("Created new wallet from mnemonic.");
// fetch networks from backend
String networks = sdk.getNetworks();
List<Network> networksList;
try {
ObjectMapper objectMapper = new ObjectMapper();
networksList = objectMapper.readValue(networks, new TypeReference<List<Network>>() {
});
} catch (JsonProcessingException e) {
throw new RuntimeException("Error processing JSON response", e);
}
Network iotaNetwork = networksList.get(0);
// set the network configuration for the wallet
sdk.setNetwork(iotaNetwork.key);
} catch (Exception e) {
throw new RuntimeException("Migrate wallet from mnemonic example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
import Foundation
import ETOPaySdk
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
// Create new user
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
// Migrate wallet
try await sdk.setWalletPassword(env.pin, env.wallet_password)
let _ = try await sdk.createWalletFromMnemonic(env.pin, env.mnemonic)
print("migrated wallet from mnemonic")
} catch let error as RustString {
fatalError("Migrate wallet from mnemonic example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk, PIN } from './utils';
async function main() {
let username = "satoshi";
const sdk = await initSdk(username);
let password = "correcthorsebatterystaple";
let mnemonic: string = (process.env.MNEMONIC as string);
await sdk.createNewUser(username);
await sdk.initializeUser(username);
await sdk.setWalletPassword(PIN, password);
// Create new wallet from the mnemonic
await sdk.createWalletFromMnemonic(PIN, mnemonic);
// fetch networks from backend
let networks = await sdk.getNetworks();
// set the network configuration for the wallet
sdk.setNetwork(networks[0].key);
// use wallet
let _address = await sdk.generateNewAddress(PIN);
}
main();
5. Migrate Wallet From Backup¶
use etopay_sdk::types::newtypes::PlainPassword;
mod utils;
use testing::USER_SATOSHI;
use utils::init_sdk;
#[allow(clippy::unwrap_used, clippy::expect_used)]
#[tokio::main]
async fn main() {
// Initialize SDK
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Create new wallet
sdk.set_wallet_password(
&user.pin,
&PlainPassword::try_from_string("correcthorsebatterystaple").unwrap(),
)
.await
.unwrap();
sdk.create_wallet_from_new_mnemonic(&user.pin).await.unwrap();
// Create wallet backup and delete it
let backup_password = PlainPassword::try_from_string("backup_password").unwrap();
let backup = sdk.create_wallet_backup(&user.pin, &backup_password).await.unwrap();
sdk.delete_wallet(&user.pin).await.unwrap();
// Migrate wallet from backup
sdk.create_wallet_from_backup(&user.pin, &backup, &backup_password)
.await
.unwrap();
// Fetch networks from backend
let networks = sdk.get_networks().await.unwrap();
let iota_network_key = &networks.first().unwrap().key;
sdk.set_network(iota_network_key.to_string()).await.unwrap();
// use wallet
let _address = sdk.generate_new_address(&user.pin).await.unwrap();
}
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
public class MigrateWalletFromBackup05 {
public static void main(String[] args) {
// initialize the sdk
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
String password = "correcthorsebatterystaple";
try {
// create and init user
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
// create new wallet
sdk.setWalletPassword(utils.PIN, password);
sdk.createNewWallet(utils.PIN);
System.out.println("Created and initialized new wallet.");
// create backup
byte[] backup_bytes = sdk.createWalletBackup(utils.PIN, "backup_password");
// delete existing wallet
sdk.deleteWallet(utils.PIN);
System.out.println("deleted existing wallet");
// migrate wallet from backup
sdk.createWalletFromBackup(utils.PIN, backup_bytes, "backup_password");
System.out.println("wallet restored from backup");
} catch (Exception e) {
throw new RuntimeException("Migrate wallet from backup example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
import Foundation
import ETOPaySdk
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
// Create new user
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
// Create new wallet
try await sdk.setWalletPassword(env.pin, env.wallet_password)
let _ = try await sdk.createNewWallet(env.pin)
print("created new wallet")
// Create backup
let backup_password = "backup_password"
let backup = try await sdk.createWalletBackup(env.pin, backup_password)
// Delete existing wallet
try await sdk.deleteWallet(env.pin)
print("deleted existing wallet")
// Migrate wallet from backup
try await sdk.restoreWalletFromBackup(env.pin, backup, backup_password)
print("wallet restored from backup")
} catch let error as RustString {
fatalError("Migrate wallet from backup example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk, PIN } from './utils';
async function main() {
let username = "satoshi";
const sdk = await initSdk(username);
let password = "correcthorsebatterystaple";
let mnemonic: string = (process.env.MNEMONIC as string);
await sdk.createNewUser(username);
await sdk.initializeUser(username);
await sdk.setWalletPassword(PIN, password);
// Create new wallet from the mnemonic
await sdk.createNewWallet(PIN);
// Create wallet backup and delete it
let backup_password = "backup_password";
let backup = await sdk.createWalletBackup(PIN, backup_password);
await sdk.deleteWallet(PIN)
// Migrate wallet from backup
await sdk.createWalletFromBackup(PIN, backup, backup_password);
// fetch networks from backend
let networks = await sdk.getNetworks();
// set the network configuration for the wallet
sdk.setNetwork(networks[0].key);
// use wallet
let _address = await sdk.generateNewAddress(PIN);
}
main();
6. Generate New Receiver Address¶
use etopay_sdk::types::newtypes::PlainPassword;
use testing::USER_SATOSHI;
mod utils;
use utils::init_sdk;
#[allow(clippy::unwrap_used)]
#[tokio::main]
async fn main() {
// Initialize SDK
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Create / init new wallet from mnemonic
sdk.set_wallet_password(
&user.pin,
&PlainPassword::try_from_string("correcthorsebatterystaple").unwrap(),
)
.await
.unwrap();
sdk.create_wallet_from_existing_mnemonic(&user.pin, &user.mnemonic)
.await
.unwrap();
// Fetch networks from backend
let networks = sdk.get_networks().await.unwrap();
let iota_network_key = &networks.first().unwrap().key;
sdk.set_network(iota_network_key.to_string()).await.unwrap();
// Generate address
let address = sdk.generate_new_address(&user.pin).await.unwrap();
println!("Address: {}", address);
}
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
import com.etospheres.etopay.model.Network;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.List;
import com.etospheres.etopay.ETOPaySdk;
public class GenerateNewAddress06 {
public static void main(String[] args) {
// initialize the sdk
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
String password = "correcthorsebatterystaple";
String mnemonic = utils.getEnvVariable("MNEMONIC");
try {
// create and init user
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
// create new wallet
sdk.setWalletPassword(utils.PIN, password);
sdk.createWalletFromMnemonic(utils.PIN, mnemonic);
System.out.println("Created and initialized new wallet from mnemonic.");
// fetch networks from backend
String networks = sdk.getNetworks();
List<Network> networksList;
try {
ObjectMapper objectMapper = new ObjectMapper();
networksList = objectMapper.readValue(networks, new TypeReference<List<Network>>() {
});
} catch (JsonProcessingException e) {
throw new RuntimeException("Error processing JSON response", e);
}
Network iotaNetwork = networksList.get(0);
// set the network configuration for the wallet
sdk.setNetwork(iotaNetwork.key);
// generate receiver address
String address = sdk.generateNewAddress(utils.PIN);
System.out.println("address: " + address);
} catch (Exception e) {
throw new RuntimeException("Generate new address example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
import ETOPaySdk
import Foundation
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
// Create new user
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
// Migrate wallet
try await sdk.setWalletPassword(env.pin, env.wallet_password)
let _ = try await sdk.createWalletFromMnemonic(env.pin, env.mnemonic)
print("migrated wallet from mnemonic")
// Fetch networks from backend
let networks = try await sdk.getNetworks()
try await sdk.setNetwork(networks[0].key())
print("retrieved available networks and set the network for the wallet")
// Generate address
let address = try await sdk.generateNewAddress(env.pin)
print("generated new receiver address: \(address.toString())")
} catch let error as RustString {
fatalError("Generate new iota address example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk, PIN } from './utils';
async function main() {
let username = "satoshi";
const sdk = await initSdk(username);
let password = "correcthorsebatterystaple";
let mnemonic: string = (process.env.MNEMONIC as string);
await sdk.createNewUser(username);
await sdk.initializeUser(username);
await sdk.setWalletPassword(PIN, password);
// fetch networks from backend
let networks = await sdk.getNetworks();
// set the network configuration for the wallet
sdk.setNetwork(networks[0].key);
await sdk.createNewWallet(PIN);
console.log("Wallet initialized!");
let address = await sdk.generateNewAddress(PIN);
console.log("Address:", address);
}
main();
7. Get Balance¶
use etopay_sdk::types::newtypes::PlainPassword;
use testing::USER_SATOSHI;
mod utils;
use utils::init_sdk;
#[allow(clippy::unwrap_used)]
#[tokio::main]
async fn main() {
// Initialize SDK
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Create / init new wallet from mnemonic
sdk.set_wallet_password(
&user.pin,
&PlainPassword::try_from_string("correcthorsebatterystaple").unwrap(),
)
.await
.unwrap();
sdk.create_wallet_from_existing_mnemonic(&user.pin, &user.mnemonic)
.await
.unwrap();
// Fetch networks from backend
let networks = sdk.get_networks().await.unwrap();
let iota_network_key = &networks.first().unwrap().key;
sdk.set_network(iota_network_key.to_string()).await.unwrap();
// Generate address
let address = sdk.generate_new_address(&user.pin).await.unwrap();
println!("Address: {}", address);
// Get balance
let balance = sdk.get_balance(&user.pin).await.unwrap();
println!("Balance: {:?}", balance);
}
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
import com.etospheres.etopay.model.Network;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.List;
import com.etospheres.etopay.ETOPaySdk;
public class GetBalance07 {
public static void main(String[] args) {
// initialize the sdk
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
String password = "correcthorsebatterystaple";
String mnemonic = utils.getEnvVariable("MNEMONIC");
try {
// create and init user
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
// create new wallet
sdk.setWalletPassword(utils.PIN, password);
sdk.createWalletFromMnemonic(utils.PIN, mnemonic);
System.out.println("Created and initialized new wallet from mnemonic.");
// fetch networks from backend
String networks = sdk.getNetworks();
List<Network> networksList;
try {
ObjectMapper objectMapper = new ObjectMapper();
networksList = objectMapper.readValue(networks, new TypeReference<List<Network>>() {
});
} catch (JsonProcessingException e) {
throw new RuntimeException("Error processing JSON response", e);
}
Network iotaNetwork = networksList.get(0);
// set the network configuration for the wallet
sdk.setNetwork(iotaNetwork.key);
// generate receiver address
String address = sdk.generateNewAddress(utils.PIN);
System.out.println("address: " + address);
// get balance
double balance = sdk.getWalletBalance(utils.PIN);
System.out.println("balance: " + balance);
} catch (Exception e) {
throw new RuntimeException("Get balance example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
import ETOPaySdk
import Foundation
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
// Create new user
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
// Migrate wallet
try await sdk.setWalletPassword(env.pin, env.wallet_password)
let _ = try await sdk.createWalletFromMnemonic(env.pin, env.mnemonic)
print("migrated wallet from mnemonic")
// Fetch networks from backend
let networks = try await sdk.getNetworks()
try await sdk.setNetwork(networks[0].key())
print("retrieved available networks and set the network for the wallet")
// Generate address
let address = try await sdk.generateNewAddress(env.pin)
print("generated new receiver address: \(address.toString())")
// Get wallet balance
let balance = try await sdk.getWalletBalance(env.pin)
print("balance: \(balance)")
} catch let error as RustString {
fatalError("Get wallat balance failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk, PIN } from './utils';
async function main() {
console.log("start");
let username = "satoshi";
const sdk = await initSdk(username);
let password = "correcthorsebatterystaple";
let mnemonic: string = (process.env.MNEMONIC as string);
await sdk.createNewUser(username);
await sdk.initializeUser(username);
await sdk.setWalletPassword(PIN, password);
await sdk.createWalletFromMnemonic(PIN, mnemonic);
// fetch networks from backend
let networks = await sdk.getNetworks();
// set the network configuration for the wallet
sdk.setNetwork(networks[0].key);
let address = await sdk.generateNewAddress(PIN);
console.log("Address:", address);
let balance = await sdk.getWalletBalance(PIN);
console.log("Balance:", balance);
}
main();
8. Create Purchase Request¶
use etopay_sdk::types::{currencies::CryptoAmount, newtypes::PlainPassword};
use rust_decimal_macros::dec;
use testing::USER_SATOSHI;
mod utils;
use utils::init_sdk;
#[allow(clippy::unwrap_used)]
#[tokio::main]
async fn main() {
// Initialize SDK
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Create / init new wallet from mnemonic
sdk.set_wallet_password(
&user.pin,
&PlainPassword::try_from_string("correcthorsebatterystaple").unwrap(),
)
.await
.unwrap();
sdk.create_wallet_from_existing_mnemonic(&user.pin, &user.mnemonic)
.await
.unwrap();
// Fetch networks from backend
let networks = sdk.get_networks().await.unwrap();
let iota_network_key = &networks.first().unwrap().key;
sdk.set_network(iota_network_key.to_string()).await.unwrap();
// Generate address
let address = sdk.generate_new_address(&user.pin).await.unwrap();
println!("Address: {}", address);
// Get balance
let balance = sdk.get_balance(&user.pin).await.unwrap();
println!("Balance: {:?}", balance);
// Create purchase request
let product_hash = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";
let app_data = "{\"imageUrl\":\"https://httpbin.org/\",\"imageId\":\"a846ad10-fc69-4b22-b442-5dd740ace361\"}";
let purchase_type = "CLIK";
let amount = CryptoAmount::try_from(dec!(2.0)).unwrap();
let purchase_id = sdk
.create_purchase_request("alice", amount, product_hash, app_data, purchase_type)
.await
.unwrap();
println!("Purchase_id {} ", purchase_id); // print the purchase id to facilitate debugging
}
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
import com.etospheres.etopay.model.Network;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.List;
import com.etospheres.etopay.ETOPaySdk;
public class CreatePurchaseRequest08 {
public static void main(String[] args) {
// initialize the sdk
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
String password = "correcthorsebatterystaple";
String mnemonic = utils.getEnvVariable("MNEMONIC");
try {
// create and init user
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
// create new wallet
sdk.setWalletPassword(utils.PIN, password);
sdk.createWalletFromMnemonic(utils.PIN, mnemonic);
System.out.println("Created and initialized new wallet from mnemonic.");
// fetch networks from backend
String networks = sdk.getNetworks();
List<Network> networksList;
try {
ObjectMapper objectMapper = new ObjectMapper();
networksList = objectMapper.readValue(networks, new TypeReference<List<Network>>() {
});
} catch (JsonProcessingException e) {
throw new RuntimeException("Error processing JSON response", e);
}
Network iotaNetwork = networksList.get(0);
// set the network configuration for the wallet
sdk.setNetwork(iotaNetwork.key);
// generate receiver address
String address = sdk.generateNewAddress(utils.PIN);
System.out.println("address: " + address);
// get balance
double balance = sdk.getWalletBalance(utils.PIN);
System.out.println("balance: " + balance);
// create purchase request
// Create purchase request
String product_hash = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";
String app_data = "{\"imageUrl\":\"https://httpbin.org/\",\"imageId\":\"a846ad10-fc69-4b22-b442-5dd740ace361\"}";
String purchase_type = "CLIK";
String purchase_id = sdk.purchaseRequestCreate("alice", 2, product_hash, app_data, purchase_type);
System.out.println("purchase request id: " + purchase_id);
} catch (Exception e) {
throw new RuntimeException("Create purchase request example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
import ETOPaySdk
import Foundation
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
// Create new user
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
// Migrate wallet
try await sdk.setWalletPassword(env.pin, env.wallet_password)
let _ = try await sdk.createWalletFromMnemonic(env.pin, env.mnemonic)
print("migrated wallet from mnemonic")
// Fetch networks from backend
let networks = try await sdk.getNetworks()
try await sdk.setNetwork(networks[0].key())
print("retrieved available networks and set the network for the wallet")
// Generate address
let address = try await sdk.generateNewAddress(env.pin)
print("generated new receiver address: \(address.toString())")
// Get wallet balance
let balance = try await sdk.getWalletBalance(env.pin)
print("balance: \(balance)")
// Create purchase request
let product_hash = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
let app_data =
"{\"imageUrl\":\"https://httpbin.org/\",\"imageId\":\"a846ad10-fc69-4b22-b442-5dd740ace361\"}"
let purchase_type = "CLIK"
let purchase_id = try await sdk.createPurchaseRequest(
"alice", 2, product_hash, app_data, purchase_type)
print("Purchase Request created: \(purchase_id.toString())")
} catch let error as RustString {
fatalError("Create purchase request example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
import { debug } from "util";
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk, PIN } from './utils';
async function main() {
let username = "satoshi";
let receiver = "alice";
const sdk = await initSdk(username);
let mnemonic: string = (process.env.MNEMONIC as string);
let password = "correcthorsebatterystaple";
await sdk.createNewUser(username);
await sdk.initializeUser(username);
await sdk.setWalletPassword(PIN, password);
await sdk.createWalletFromMnemonic(PIN, mnemonic);
// fetch networks from backend
let networks = await sdk.getNetworks();
// set the network configuration for the wallet
sdk.setNetwork(networks[0].key);
let address = await sdk.generateNewAddress(PIN);
debug(`Generated new IOTA receiver address: ${address}`);
let balance = await sdk.getWalletBalance(PIN);
console.log("balance : ", balance);
let product_hash = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";
let app_data = JSON.stringify({
"imageUrl": "https://httpbin.org/",
"imageId": "a846ad10-fc69-4b22-b442-5dd740ace361"
});
let purchase_type = "CLIK";
let purchase_id = await sdk.createPurchaseRequest(receiver, 2.0, product_hash, app_data, purchase_type);
console.log("Purchase ID:", purchase_id);
}
main();
9. Onboard a User on Viviswap¶
use etopay_sdk::types::viviswap::{ViviswapVerificationStatus, ViviswapVerificationStep};
use fake::{
Fake,
faker::name::{en::LastName, raw::FirstName},
locales::EN,
};
use std::io::Write;
use testing::USER_SATOSHI;
mod utils;
use utils::init_sdk;
// ---------------------------------------------
// Note: This example will not run until the end because the user already exists in Viviswap db and it will not create a new one.
// ---------------------------------------------
#[allow(clippy::unwrap_used, clippy::expect_used)]
#[tokio::main]
async fn main() {
// Initialize SDK and create a new user
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Exit if user is already verified
let is_verified = sdk.is_kyc_status_verified(&user.username).await.unwrap();
if is_verified {
println!("User is already verified, please run the delete_user example first.");
return;
}
// Start KYC verification for viviswap
// The user already exists in viviswap db. Therefore, the test will fail here.
let new_user = sdk
.start_kyc_verification_for_viviswap(&format!("{}@gmail.com", user.username), true)
.await
.unwrap();
println!("New Viviswap user: {:#?}", new_user);
// Get KYC status for viviswap
let status = sdk.get_kyc_details_for_viviswap().await.unwrap();
println!("Status: {:#?}", status);
// Update KYC status for viviswap
let is_individual = Some(true);
let is_pep = Some(false);
let is_us_citizen = Some(false);
let is_regulatory_disclosure = Some(true);
let country_of_residence = Some("DE".into());
let nationality = Some("DE".to_string());
let full_name = Some(format!(
"{} {}",
FirstName(EN).fake::<String>(),
LastName().fake::<String>()
));
let date_of_birth = Some("2001-11-05".to_string());
let details = sdk
.update_kyc_partially_status_for_viviswap(
is_individual,
is_pep,
is_us_citizen,
is_regulatory_disclosure,
country_of_residence,
nationality,
full_name,
date_of_birth,
)
.await
.unwrap();
println!("Details: {:#?}", details);
sdk.submit_kyc_partially_status_for_viviswap().await.unwrap();
// Create a waiting loop that prints a dot every 5 seconds for 30 secounds
println!("Waiting for KYC verification to complete");
for _ in 0..12 {
tokio::time::sleep(tokio::time::Duration::from_secs(6)).await;
print!(".");
std::io::stdout().flush().unwrap();
let kyc_details = sdk.get_kyc_details_for_viviswap().await.unwrap();
if kyc_details.verified_step == ViviswapVerificationStep::Personal {
break;
}
}
println!();
// Check that the user is verified
let is_verified = sdk.is_kyc_status_verified(&user.username).await.unwrap();
println!("IsVerified: {:#?}", is_verified);
let kyc_details = sdk.get_kyc_details_for_viviswap().await.unwrap();
println!("KycDetails: {:#?}", kyc_details);
assert!(kyc_details.verification_status == ViviswapVerificationStatus::Unverified);
assert!(kyc_details.verified_step == ViviswapVerificationStep::Personal);
assert!(kyc_details.submission_step == ViviswapVerificationStep::Identity);
}
/**
* This example will not run until the end because the user already exists in Viviswap db and it will not create a new one.
*/
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
public class OnboardUserViviswap09 {
public static void main(String[] args) {
// Initialize SDK
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
try {
// create and init new user
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
// check if user is kyc verified
boolean is_verified = sdk.isKycVerified(utils.USERNAME_SATOSHI);
if (is_verified == true) {
System.out.println("User is already verified, please run the delete_user example first.");
return;
}
// Start KYC verification for viviswap
// The user already exists in viviswap db. Therefore, the test will fail here.
String new_user = sdk
.startViviswapKyc("javaexamples@gmail.com", true);
System.out.println("New Viviswap user: " + new_user);
// Get KYC status for viviswap
String details = sdk.getViviswapKyc();
System.out.println("Viviswap KYC details: " + details);
} catch (
Exception e) {
throw new RuntimeException("Onboard user viviswap example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
// Onboard with viviswap example
// The user already exists in viviswap db. Therefore, the test will fail here.
import ETOPaySdk
import Foundation
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
// Create new user
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
// Exit if user is already verified
let is_verified = try await sdk.isKycVerified(env.username)
print("is verified: \(is_verified)")
if is_verified {
print("User is already verified. No need to delete. Exiting")
return
}
// Start KYC verification for viviswap
let new_user = try await sdk.startKycVerificationForViviswap(
"swift_example@gmail.com", true)
print("New viviswap user: \(new_user)")
// Get KYC status for viviswap
let status = try await sdk.getKycDetailsForViviswap()
print("Status: \(status)")
// Update KYC status for viviswap
var isIndividual: Bool? = true
var isPep: Bool? = false
var isUsCitizen: Bool? = false
var isRegulatoryDisclosure: Bool? = true
var countryOfResidence: String? = "DE"
var nationality: String? = "DE"
var fullName: String? = "fake fake"
var dateOfBirth: String? = "2001-11-05"
let details =
try await sdk
.updateKycPartiallyStatusForViviswap(
isIndividual,
isPep,
isUsCitizen,
isRegulatoryDisclosure,
countryOfResidence,
nationality,
fullName,
dateOfBirth
)
print("Details: \(details)")
try await sdk.submitKycPartiallyStatusForViviswap()
// Create a waiting loop that prints a dot every 5 seconds for 30 seconds
print("Waiting for KYC verification to complete")
for _ in 0..<12 {
sleep(6)
print(".")
fflush(stdout)
let kycDetails = try await sdk.getKycDetailsForViviswap()
if kycDetails.verified_step == .Personal {
break
}
}
// Check that the user is verified
let isVerified = try await sdk.isKycVerified(env.username)
print("IsVerified: \(isVerified)")
} catch let error as RustString {
fatalError("Onboard user with viviswap example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk } from './utils';
async function main() {
let username = "satoshi";
const sdk = await initSdk(username);
await sdk.createNewUser(username);
await sdk.initializeUser(username);
let is_verified = await sdk.isKycVerified(username)
if (is_verified) {
console.log("user is verified");
return;
}
// Start KYC verification for viviswap
// The user already exists in viviswap db. Therefore, the test will fail here.
let newUser = await sdk.startKycVerificationForViviswap("wasmtest@gmail.com", true);
console.log(`New viviswap user: ${newUser}`);
}
main();
10. Verify Pin¶
mod utils;
use etopay_sdk::types::newtypes::PlainPassword;
use testing::USER_SATOSHI;
use utils::init_sdk;
#[allow(clippy::unwrap_used, clippy::expect_used)]
#[tokio::main]
async fn main() {
// Initialize SDK
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Create new wallet
sdk.set_wallet_password(
&user.pin,
&PlainPassword::try_from_string("correcthorsebatterystaple").unwrap(),
)
.await
.unwrap();
sdk.create_wallet_from_new_mnemonic(&user.pin).await.unwrap();
// Verify pin
sdk.verify_pin(&user.pin).await.unwrap();
}
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
public class VerifyPin10 {
public static void main(String[] args) {
// initialize the sdk
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
String password = "correcthorsebatterystaple";
try {
// create and init user
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
// create new wallet
sdk.setWalletPassword(utils.PIN, password);
sdk.createNewWallet(utils.PIN);
System.out.println("Created and initialized new wallet.");
// verify pin
sdk.pinVerify(utils.PIN);
System.out.println("Pin verified");
} catch (Exception e) {
throw new RuntimeException("Verify pin example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
import Foundation
import ETOPaySdk
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
// Create new user
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
// Create new wallet
try await sdk.setWalletPassword(env.pin, env.wallet_password)
let _ = try await sdk.createNewWallet(env.pin)
// Verify pin
try await sdk.verifyPin(env.pin)
print("pin verified")
} catch let error as RustString {
fatalError("Verify pin example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk, PIN } from './utils';
async function main() {
let username = "satoshi";
const sdk = await initSdk(username);
let mnemonic: string = (process.env.MNEMONIC as string);
let password = "correcthorsebatterystaple";
await sdk.createNewUser(username);
await sdk.initializeUser(username);
await sdk.setWalletPassword(PIN, password);
await sdk.createWalletFromMnemonic(PIN, mnemonic);
await sdk.verifyPin(PIN);
console.log("Pin verified successfully");
}
main();
11. Reset Pin¶
use etopay_sdk::types::newtypes::{EncryptionPin, PlainPassword};
mod utils;
use testing::USER_SATOSHI;
use utils::init_sdk;
// ---------------------------------------------
// Note: This examples does not work. It gets stuck. Does not pass or fail.
// ---------------------------------------------
#[allow(clippy::unwrap_used, clippy::expect_used)]
#[tokio::main]
async fn main() {
// Initialize SDK
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Create new wallet
sdk.set_wallet_password(
&user.pin,
&PlainPassword::try_from_string("correcthorsebatterystaple").unwrap(),
)
.await
.unwrap();
sdk.create_wallet_from_new_mnemonic(&user.pin).await.unwrap();
// Reset pin
let new_pin = EncryptionPin::try_from_string("123456").unwrap();
sdk.change_pin(&user.pin, &new_pin).await.unwrap();
// Verify pin
sdk.verify_pin(&new_pin).await.unwrap();
}
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
public class ResetPin11 {
public static void main(String[] args) {
// initialize the sdk
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
String password = "correcthorsebatterystaple";
try {
// create and init user
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
// create and init new wallet
sdk.setWalletPassword(utils.PIN, password);
sdk.createNewWallet(utils.PIN);
System.out.println("Created and init new wallet.");
// reset pin
sdk.pinReset(utils.PIN, utils.NEW_PIN);
// verify new pin
sdk.pinVerify(utils.NEW_PIN);
System.out.println("New pin verified");
} catch (Exception e) {
throw new RuntimeException("Reset pin example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
import ETOPaySdk
import Foundation
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
let new_pin = "432156"
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
// Create new user
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
// Create new wallet
try await sdk.setWalletPassword(env.pin, env.wallet_password)
let _ = try await sdk.createNewWallet(env.pin)
print("created new wallet")
// Reset pin
try await sdk.resetPin(env.pin, new_pin)
print("pin reseted")
// Verify new pin
try await sdk.verifyPin(new_pin)
print("new pin verified")
} catch let error as RustString {
fatalError("Reset pin example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk, PIN } from './utils';
async function main() {
let username = "satoshi";
let new_pin = "543216";
const sdk = await initSdk(username);
let mnemonic: string = (process.env.MNEMONIC as string);
let password = "correcthorsebatterystaple";
await sdk.createNewUser(username);
await sdk.initializeUser(username);
await sdk.setWalletPassword(PIN, password);
await sdk.createWalletFromMnemonic(PIN, mnemonic);
await sdk.resetPin(PIN, new_pin);
console.log("Reset PIN successful");
await sdk.verifyPin(new_pin);
console.log("new PIN verified");
}
main();
12. Change Password¶
use etopay_sdk::types::newtypes::PlainPassword;
mod utils;
use testing::USER_SATOSHI;
use utils::init_sdk;
#[allow(clippy::unwrap_used, clippy::expect_used)]
#[tokio::main]
async fn main() {
// Initialize SDK
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Create new wallet
sdk.set_wallet_password(
&user.pin,
&PlainPassword::try_from_string("correcthorsebatterystaple").unwrap(),
)
.await
.unwrap();
sdk.create_wallet_from_new_mnemonic(&user.pin).await.unwrap();
// Change password
let new_password = PlainPassword::try_from_string("new_correcthorsebatterystaple").unwrap();
sdk.set_wallet_password(&user.pin, &new_password).await.unwrap();
// Fetch networks from backend
let networks = sdk.get_networks().await.unwrap();
let iota_network_key = &networks.first().unwrap().key;
sdk.set_network(iota_network_key.to_string()).await.unwrap();
// use wallet
let _address = sdk.generate_new_address(&user.pin).await.unwrap();
}
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
public class ChangePassword12 {
public static void main(String[] args) {
// initialize the sdk
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
String password = "correcthorsebatterystaple";
try {
// create and init user
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
// create new wallet
sdk.setWalletPassword(utils.PIN, password);
sdk.createNewWallet(utils.PIN);
System.out.println("Created and initialized new wallet.");
// change password
sdk.setWalletPassword(utils.PIN, "new_correcthorsebatterystaple");
System.out.println("Password changed");
} catch (Exception e) {
throw new RuntimeException("Change password example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
import ETOPaySdk
import Foundation
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
let new_password = "correcthorsebatterystaple"
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
// Create new user
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
// Create new wallet
try await sdk.setWalletPassword(env.pin, env.wallet_password)
let _ = try await sdk.createNewWallet(env.pin)
print("created new wallet")
// Change password
try await sdk.setWalletPassword(env.pin, new_password)
print("password changed")
} catch let error as RustString {
fatalError("Change password example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk, PIN } from './utils';
async function main() {
let username = "satoshi";
const sdk = await initSdk(username);
let mnemonic: string = (process.env.MNEMONIC as string);
let password = "correcthorsebatterystaple";
await sdk.createNewUser(username);
await sdk.initializeUser(username);
await sdk.setWalletPassword(PIN, password);
await sdk.createWalletFromMnemonic(PIN, mnemonic);
let new_password = "new_correcthorsebatterystaple"
await sdk.setWalletPassword(PIN, new_password);
console.log("change password successful");
// fetch networks from backend
let networks = await sdk.getNetworks();
// set the network configuration for the wallet
sdk.setNetwork(networks[0].key);
let _address = await sdk.generateNewAddress(PIN);
}
main();
13. Send Amount¶
mod utils;
use etopay_sdk::types::newtypes::PlainPassword;
use rust_decimal_macros::dec;
use testing::USER_SATOSHI;
use utils::init_sdk;
#[allow(clippy::unwrap_used, clippy::expect_used)]
#[tokio::main]
async fn main() {
// Initialize SDK
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
let (mut sdk, _cleanup) = init_sdk().await;
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Create / init new wallet from mnemonic
sdk.set_wallet_password(
&user.pin,
&PlainPassword::try_from_string("correcthorsebatterystaple").unwrap(),
)
.await
.unwrap();
sdk.create_wallet_from_existing_mnemonic(&user.pin, &user.mnemonic)
.await
.unwrap();
// Fetch networks from backend
let networks = sdk.get_networks().await.unwrap();
let iota_network_key = &networks.first().unwrap().key;
sdk.set_network(iota_network_key.to_string()).await.unwrap();
// Generate new address
let recipient_address = sdk.generate_new_address(&user.pin).await.unwrap();
let balance = sdk.get_balance(&user.pin).await.unwrap();
println!("address: {recipient_address}, balance: {balance:?}");
// Send amount
let amount = dec!(2.0).try_into().unwrap();
let data = Some("test".to_string().into_bytes());
// estimate gas
let estimate = sdk
.estimate_gas(&user.pin, &recipient_address, amount, data.clone())
.await
.unwrap();
println!("Estimated gas: {estimate:?}");
let tx_id = sdk
.send_amount(&user.pin, &recipient_address, amount, data)
.await
.unwrap();
println!("Success with transaction id: {tx_id}");
let details = sdk.get_wallet_tx(&user.pin, &tx_id).await.unwrap();
println!("Details:\n{:#?}", details);
}
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
import com.etospheres.etopay.model.Network;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.List;
import com.etospheres.etopay.ETOPaySdk;
public class SendAmount13 {
public static void main(String[] args) {
// initialize the sdk
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
String password = "correcthorsebatterystaple";
String mnemonic = utils.getEnvVariable("MNEMONIC");
try {
// create and init user
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
// create new wallet
sdk.setWalletPassword(utils.PIN, password);
sdk.createWalletFromMnemonic(utils.PIN, mnemonic);
System.out.println("Created and initialized new wallet from mnemonic.");
// fetch networks from backend
String networks = sdk.getNetworks();
List<Network> networksList;
try {
ObjectMapper objectMapper = new ObjectMapper();
networksList = objectMapper.readValue(networks, new TypeReference<List<Network>>() {
});
} catch (JsonProcessingException e) {
throw new RuntimeException("Error processing JSON response", e);
}
Network iotaNetwork = networksList.get(0);
// set the network configuration for the wallet
sdk.setNetwork(iotaNetwork.key);
// generate receiver address
String address = sdk.generateNewAddress(utils.PIN);
System.out.println("address: " + address);
// get balance
double balance = sdk.getWalletBalance(utils.PIN);
System.out.println("balance: " + balance);
// send amount
String tx_id = sdk.sendAmount(utils.PIN, address.toString(), 1, "java bindings test".getBytes());
System.out.println("send amount of 1 with transaction " + tx_id);
// get new balance
double new_balance = sdk.getWalletBalance(utils.PIN);
System.out.println("new balance: " + new_balance);
// print the details
String details = sdk.getWalletTransaction(utils.PIN, tx_id);
System.out.println("details: " + details);
} catch (Exception e) {
throw new RuntimeException("Send amount example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
import ETOPaySdk
import Foundation
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
// Create new user
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
// Migrate wallet
try await sdk.setWalletPassword(env.pin, env.wallet_password)
let _ = try await sdk.createWalletFromMnemonic(env.pin, env.mnemonic)
print("migrated wallet from mnemonic")
// Fetch networks from backend
let networks = try await sdk.getNetworks()
try await sdk.setNetwork(networks[0].key())
print("retrieved available networks and set the network for the wallet")
// Generate address
let address = try await sdk.generateNewAddress(env.pin)
print("generated new receiver address: \(address.toString())")
// Get wallet balance
let balance = try await sdk.getWalletBalance(env.pin)
print("balance: \(balance)")
// Send amount
let message = "swift bindings test"
// convert to a RustVec by copying over all values
let rustVec = RustVec<UInt8>.init()
for byte in message.utf8 {
rustVec.push(value: byte)
}
let bytes: [UInt8] = Array(message.utf8)
let tx_id = try await sdk.sendAmount(env.pin, address.toString(), 1, rustVec)
print("sent amount of 1 on transaction \(tx_id.toString())")
// Get new balance
let new_balance = try await sdk.getWalletBalance(env.pin)
print("new balance: \(new_balance)")
// Get the details (wrap env.pin in RustString to make sure parameters have the same type (they share same generic type))
let details = try await sdk.getWalletTransaction(RustString(env.pin), tx_id)
print("tx details status: \(details.status().toString())")
print("tx details amount: \(details.amount())")
print("tx details receiver: \(details.receiver().toString())")
print("tx details block_id: \(details.block_id().toString())")
} catch let error as RustString {
fatalError("Send amount example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk, PIN } from './utils';
async function main() {
let username = "satoshi";
const sdk = await initSdk(username);
let mnemonic: string = (process.env.MNEMONIC as string);
let password = "correcthorsebatterystaple";
await sdk.createNewUser(username);
await sdk.initializeUser(username);
await sdk.setWalletPassword(PIN, password);
await sdk.createWalletFromMnemonic(PIN, mnemonic);
// fetch networks from backend
let networks = await sdk.getNetworks();
// set the network configuration for the wallet
sdk.setNetwork(networks[0].key);
let recipient_address = await sdk.generateNewAddress(PIN);
console.log("address", recipient_address);
let balance_before = await sdk.getWalletBalance(PIN);
console.log("balance before sending amount", balance_before);
const data = new TextEncoder().encode("wasm example");
let tx_id = await sdk.sendAmount(PIN, recipient_address, 1.0, data);
console.log("sent amount with transaction", tx_id);
let balance_after = await sdk.getWalletBalance(PIN);
console.log("balance after sending amount", balance_after);
let details = await sdk.getWalletTransaction(PIN, tx_id);
console.log("transaction details: ", details);
}
main();
14. Get Exchange Rate¶
mod utils;
use testing::USER_SATOSHI;
use utils::init_sdk;
#[allow(clippy::unwrap_used, clippy::expect_used)]
#[tokio::main]
async fn main() {
// Initialize SDK
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Fetch networks from backend
let networks = sdk.get_networks().await.unwrap();
let iota_network_key = &networks.first().unwrap().key;
sdk.set_network(iota_network_key.to_string()).await.unwrap();
// Get exchange rate
let exchange_rate = sdk.get_exchange_rate().await.unwrap();
println!("Exchange rate: {}", exchange_rate);
}
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
import com.etospheres.etopay.model.Network;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.List;
import com.etospheres.etopay.ETOPaySdk;
public class GetExchangeRate14 {
public static void main(String[] args) {
// initialize the sdk
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
try {
// create and init user
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
// fetch networks from backend
String networks = sdk.getNetworks();
List<Network> networksList;
try {
ObjectMapper objectMapper = new ObjectMapper();
networksList = objectMapper.readValue(networks, new TypeReference<List<Network>>() {
});
} catch (JsonProcessingException e) {
throw new RuntimeException("Error processing JSON response", e);
}
Network iotaNetwork = networksList.get(0);
// set the network configuration for the wallet
sdk.setNetwork(iotaNetwork.key);
// get exchange rate
double exchange_rate = sdk.getExchangeRate();
System.out.println("Exchange rate: " + exchange_rate);
} catch (Exception e) {
throw new RuntimeException("Get exchange rate example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
import ETOPaySdk
import Foundation
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
// Fetch networks from backend
let networks = try await sdk.getNetworks()
try await sdk.setNetwork(networks[0].key())
print("retrieved available networks and set the network for the wallet")
let exchange_rate = try await sdk.getExchangeRate()
print("exchange rate: \(exchange_rate)")
} catch let error as RustString {
fatalError("Get exchange rate example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk } from './utils';
async function main() {
let username = "satoshi";
const sdk = await initSdk(username);
await sdk.createNewUser(username);
await sdk.initializeUser(username);
// fetch networks from backend
let networks = await sdk.getNetworks();
// set the network configuration for the wallet
sdk.setNetwork(networks[0].key);
let course = await sdk.getExchangeRate();
console.log(course);
}
main();
16. Get Purchase List¶
mod utils;
use etopay_sdk::types::newtypes::PlainPassword;
use testing::USER_SATOSHI;
use utils::init_sdk;
#[allow(clippy::unwrap_used, clippy::expect_used)]
#[tokio::main]
async fn main() {
// Initialize SDK
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Create new wallet
sdk.set_wallet_password(
&user.pin,
&PlainPassword::try_from_string("correcthorsebatterystaple").unwrap(),
)
.await
.unwrap();
sdk.create_wallet_from_new_mnemonic(&user.pin).await.unwrap();
// Get tx list
let tx_list = sdk.get_tx_list(0, 10).await.unwrap();
tx_list
.txs
.iter()
.for_each(|tx| println!("tx reference id: {:?}", tx.reference_id));
}
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
public class GetTxList16 {
public static void main(String[] args) {
// initialize the sdk
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
String password = "correcthorsebatterystaple";
try {
// create and init user
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
// create new wallet
sdk.setWalletPassword(utils.PIN, password);
sdk.createNewWallet(utils.PIN);
System.out.println("Created and initialized new wallet.");
// get tx list
String tx_list = sdk.txList(0, 10);
System.out.println("tx list: " + tx_list);
} catch (Exception e) {
throw new RuntimeException("Get tx list example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
import Foundation
import ETOPaySdk
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
// Create new user
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
// Create new wallet
try await sdk.setWalletPassword(env.pin, env.wallet_password)
let _ = try await sdk.createNewWallet(env.pin)
print("created new wallet")
// Get tx list
let tx_list = try await sdk.getTransactionList(0, 10)
// need to properly print the list
print("Tx list: \(tx_list)")
} catch let error as RustString {
fatalError("Get transaction list example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk, PIN } from './utils';
async function main() {
let username = "satoshi";
// Define the PIN
const sdk = await initSdk(username); // Initialize the SDK
let mnemonic: string = (process.env.MNEMONIC as string);
let password = "correcthorsebatterystaple";
await sdk.createNewUser(username); //Creating a new user
await sdk.initializeUser(username); // Initialize the user
await sdk.setWalletPassword(PIN, password);
await sdk.createWalletFromMnemonic(PIN, mnemonic); // Initialize the wallet
console.log("Wallet initialized!");
let transactions = await sdk.getTransactionList(0, 10); // Get the transaction list
console.log("Transactions: " + JSON.stringify(transactions));
}
main();
18. Delete User¶
use etopay_sdk::types::newtypes::{AccessToken, PlainPassword};
mod utils;
use testing::USER_ARCHIVEME;
use utils::init_sdk;
// ---------------------------------------------
// Note: Do not run this example with user `satoshi` because it will then be unverified and it will affect other examples / tests.
// ---------------------------------------------
#[allow(clippy::unwrap_used, clippy::expect_used)]
#[tokio::main]
async fn main() {
// Initialize SDK
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_ARCHIVEME).clone().into();
// the `init_sdk()` function generates an access token for `satoshi`.
// in this example we use `archiveme` user. Therefore, we generate a new access token for the `archiveme` user.
let access_token = testing::get_access_token(&user.username, user.password.as_str())
.await
.access_token;
let access_token = AccessToken::try_from(access_token).unwrap();
sdk.refresh_access_token(Some(access_token)).await.unwrap();
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Create new wallet
sdk.set_wallet_password(
&user.pin,
&PlainPassword::try_from_string("correcthorsebatterystaple").unwrap(),
)
.await
.unwrap();
sdk.create_wallet_from_new_mnemonic(&user.pin).await.unwrap();
// Delete user
sdk.delete_user(Some(&user.pin)).await.unwrap();
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
}
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
public class DeleteUser18 {
public static void main(String[] args) {
// initialize the sdk
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_ARCHIVEME);
String password = "correcthorsebatterystaple";
try {
// create and init user
sdk.createNewUser(utils.USERNAME_ARCHIVEME);
sdk.initializeUser(utils.USERNAME_ARCHIVEME);
System.out.println("Created and initialized new user.");
// create and init new wallet
sdk.setWalletPassword(utils.PIN, password);
sdk.createNewWallet(utils.PIN);
System.out.println("Created and initialized new wallet.");
// Delete user and wallet
sdk.deleteUser(utils.PIN);
// check verification after deletion. Should be false
boolean verified = sdk.isKycVerified(utils.USERNAME_ARCHIVEME);
System.out.println("is verified: " + verified);
} catch (Exception e) {
throw new RuntimeException("Delete user example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
import Foundation
import ETOPaySdk
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
let username_archive = ProcessInfo.processInfo.environment["ARCHIEVEME"]!;
// Initialize SDK
let sdk = try await initSdk(username: username_archive, password: env.wallet_password)
// Create new user
try await sdk.createNewUser(username_archive)
print("created new user: \(username_archive)")
try await sdk.initUser(username_archive)
print("initialized new user: \(username_archive)")
// Create new wallet
try await sdk.setWalletPassword(env.pin, env.wallet_password)
let _ = try await sdk.createNewWallet(env.pin)
print("created new wallet")
print("deleting user and wallet")
try await sdk.deleteUser(env.pin)
// check verification after deletion. Should be false
let verified = try await sdk.isKycVerified(username_archive)
print("is verified: \(verified)")
} catch let error as RustString {
fatalError("Delete user example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk, PIN } from './utils';
async function main() {
let username = "archiveme";
const sdk = await initSdk(username);
let password = "correcthorsebatterystaple";
let mnemonic: string = (process.env.MNEMONIC as string);
await sdk.createNewUser(username);
await sdk.initializeUser(username);
await sdk.setWalletPassword(PIN, password);
await sdk.createWalletFromMnemonic(PIN, mnemonic);
await sdk.deleteUser(PIN);
console.log("user deleted_successfully");
}
export { main }
19. Get Wallet Transaction List¶
mod utils;
use etopay_sdk::types::newtypes::PlainPassword;
use testing::USER_SATOSHI;
use utils::init_sdk;
#[allow(clippy::unwrap_used, clippy::expect_used)]
#[tokio::main]
async fn main() {
// Initialize SDK
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Create new wallet
sdk.set_wallet_password(
&user.pin,
&PlainPassword::try_from_string("correcthorsebatterystaple").unwrap(),
)
.await
.unwrap();
sdk.create_wallet_from_new_mnemonic(&user.pin).await.unwrap();
// Fetch networks from backend
let networks = sdk.get_networks().await.unwrap();
let iota_network_key = &networks.first().unwrap().key;
sdk.set_network(iota_network_key.to_string()).await.unwrap();
// Get wallet tx list
let wallet_tx_list = sdk.get_wallet_tx_list(&user.pin, 0, 10).await.unwrap();
wallet_tx_list
.transactions
.iter()
.for_each(|tx| println!("Wallet transaction id: {:?}", tx.transaction_id));
}
package com.etospheres.etopay.examples;
import com.etospheres.etopay.ETOPaySdk;
import com.etospheres.etopay.model.Network;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.List;
import com.etospheres.etopay.ETOPaySdk;
public class GetWalletTxList19 {
public static void main(String[] args) {
// initialize the sdk
ETOPaySdk sdk = utils.initSdk(utils.USERNAME_SATOSHI);
String password = "correcthorsebatterystaple";
try {
// create and init user
sdk.createNewUser(utils.USERNAME_SATOSHI);
sdk.initializeUser(utils.USERNAME_SATOSHI);
System.out.println("Created and initialized new user.");
// create new wallet
sdk.setWalletPassword(utils.PIN, password);
sdk.createNewWallet(utils.PIN);
System.out.println("Created and initialized new wallet.");
// fetch networks from backend
String networks = sdk.getNetworks();
List<Network> networksList;
try {
ObjectMapper objectMapper = new ObjectMapper();
networksList = objectMapper.readValue(networks, new TypeReference<List<Network>>() {
});
} catch (JsonProcessingException e) {
throw new RuntimeException("Error processing JSON response", e);
}
Network iotaNetwork = networksList.get(0);
// set the network configuration for the wallet
sdk.setNetwork(iotaNetwork.key);
// get wallet_tx_list
String wallet_tx_list = sdk.getWalletTransactionList(utils.PIN, 0, 10);
System.out.println("wallet tx list: " + wallet_tx_list);
} catch (Exception e) {
throw new RuntimeException("Get wallet tx list example failed", e);
}
}
}
// The Swift Programming Language
// https://docs.swift.org/swift-book
import ETOPaySdk
import Foundation
import utils
// We use a DispatchGroup to make the program wait until async functions finish before exiting.
// Not needed in long-running applications.
let group = DispatchGroup()
group.enter()
Task {
do {
// Get environment variables from the Utils module
let env = getEnvironment()
// Initialize SDK
let sdk = try await initSdk(username: env.username, password: env.password)
// Create new user
try await sdk.createNewUser(env.username)
print("created new user: \(env.username)")
try await sdk.initUser(env.username)
print("initialized new user: \(env.username)")
// Create new wallet
try await sdk.setWalletPassword(env.pin, env.wallet_password)
let _ = try await sdk.createNewWallet(env.pin)
print("created new wallet")
// Fetch networks from backend
let networks = try await sdk.getNetworks()
try await sdk.setNetwork(networks[0].key())
print("retrieved available networks and set the network for the wallet")
// Get wallet tx list
let tx_list = try await sdk.getWalletTransactionList(env.pin, 0, 10)
// need to properly print the list
print("Tx list: \(tx_list)")
} catch let error as RustString {
fatalError("Get wallet transaction list example failed: \(error.toString())")
} catch {
fatalError("Unexpected error occurred: \(error)")
}
group.leave()
}
group.wait()
import * as wasm from "../pkg/etopay_sdk_wasm";
import { initSdk, PIN } from './utils';
async function main() {
let username = "satoshi";
const sdk = await initSdk(username); // Initialize the SDK
let mnemonic: string = (process.env.MNEMONIC as string);
let password = "correcthorsebatterystaple";
await sdk.createNewUser(username); //Creating a new user
await sdk.initializeUser(username); // Initialize the user
await sdk.setWalletPassword(PIN, password);
await sdk.createWalletFromMnemonic(PIN, mnemonic); // Initialize the wallet
console.log("Wallet initialized!");
// fetch networks from backend
let networks = await sdk.getNetworks();
// set the network configuration for the wallet
sdk.setNetwork(networks[0].key);
let transactions = await sdk.getWalletTransactionList(PIN, 0, 10); // Get the transaction list
console.log("Wallet transactions list: " + JSON.stringify(transactions));
}
main();
22. Initialize Wallet from Shares¶
use etopay_sdk::{ErrorKind, WalletError, types::newtypes::PlainPassword};
use testing::USER_SATOSHI;
use utils::init_sdk;
mod utils;
#[allow(clippy::unwrap_used, clippy::expect_used)]
#[tokio::main]
async fn main() {
dotenvy::dotenv().ok();
// Initialize SDK
let (mut sdk, _cleanup) = init_sdk().await;
let user: utils::TestUser = (*USER_SATOSHI).clone().into();
// Create new user
sdk.create_new_user(&user.username).await.unwrap();
sdk.init_user(&user.username).await.unwrap();
// Fetch networks from backend
let networks = sdk.get_networks().await.unwrap();
let iota_network_key = &networks.first().unwrap().key;
sdk.set_network(iota_network_key.to_string()).await.unwrap();
// use wallet without creating a new one first
let output = sdk.generate_new_address(&user.pin).await;
match output {
Ok(_address) => {
println!("Wallet initialized successfully");
}
Err(etopay_sdk::Error::Wallet(WalletError::WalletNotInitialized(ErrorKind::MissingPassword))) => {
// Wallet requires a password, try again with the password provided
sdk.set_wallet_password(
&user.pin,
&PlainPassword::try_from_string("correcthorsebatterystaple").unwrap(),
)
.await
.unwrap();
let result = sdk.generate_new_address(&user.pin).await;
if result.is_ok() {
println!("Wallet initialized successfully with password set");
} else {
panic!("Unexpected result after providing password: {:?}", result);
}
}
Err(etopay_sdk::Error::Wallet(WalletError::WalletNotInitialized(ErrorKind::SetRecoveryShare))) => {
// Ask user for recovery share
let share = "<User Input>".parse().unwrap();
sdk.set_recovery_share(share).await.unwrap();
let result = sdk.generate_new_address(&user.pin).await;
if result.is_ok() {
println!("Wallet initialized successfully with recovery share");
} else {
panic!("Unexpected result after setting recovery share: {:?}", result);
}
}
Err(etopay_sdk::Error::Wallet(WalletError::WalletNotInitialized(ErrorKind::UseMnemonic))) => {
sdk.set_wallet_password(
&user.pin,
&PlainPassword::try_from_string("correcthorsebatterystaple").unwrap(),
)
.await
.unwrap();
sdk.create_wallet_from_existing_mnemonic(&user.pin, &user.mnemonic)
.await
.unwrap();
let result = sdk.generate_new_address(&user.pin).await;
if result.is_ok() {
println!("Wallet initialized successfully from mnemonic");
} else {
panic!("Unexpected result after creating wallet from mnemonic: {:?}", result);
}
}
other => panic!("unexpected result: {other:?}"),
}
// Ensure the wallet is functioning
let address = sdk.generate_new_address(&user.pin).await.unwrap();
let balance = sdk.get_balance(&user.pin).await.unwrap();
println!("New address : {address} , Wallet balance: , {balance:?}");
}