Class: TepuiEthereumClient

The entry-point object to interact with Tepui contracts in ethereum. A TepuiEthereumClient can be used in both front-end and back-end javascript. In the front-end it is typically initialized as follows:

// window.ethereum is available in crypto browsers and
// regular browsers with extension like [Metamask](https://metamask.io/)
const web3 = new Web3(window.ethereum);
await web3.currentProvider.enable();
const tepuiClient = await TepuiEthereumClient.init(web3);

In a javascript backend like node.js you can use a wallet provider like @truffle/hdwallet-provider. You also need to connect to a local ethereum node (e.g. Geth or Parity). If installing and maintaining a local ethereum node is too involved, you can use a provider like Infura.

const mnemonic = process.env["MNEMONIC"];
const projectId = process.env["INFURA_PROJECT_ID"];
const HDWalletProvider = require("@truffle/hdwallet-provider");
const provider = new HDWalletProvider(
  mnemonic,
  `https://${network}.infura.io/v3/${projectId}`
);
const web3 = new Web3(provider)
const tepuiClient = await TepuiEthereumClient.init(web3);

Hierarchy

  • TepuiEthereumClient

Index

Accessors

Methods

Accessors

defaultAccount

• get defaultAccount(): string | undefined

The default account used to submit transactions

Returns: string | undefined

Methods

accountChanged

â–¸ accountChanged(address: string): void

Sets the default account to a new value. This can be invoked when a user changes address in the browser crypto wallet

Parameters:

Name

Type

Description

address

string

the address to be set as the default

Returns: void

approveToken

▸ approveToken(contract: IEthPlan, amount: string, callback?: TransactionCallback): Promise‹void›

Requests approval from the subscriber to transfer a given amount of ERC20 tokens to the contract. This is commonly invoked when a user wants to subscribe or add funds to a contract configured with an ERC20 token.

remarks If the contract is configured with ether, then this operation does nothing

throws if the user denies the approval

Parameters:

Name

Type

Description

contract

the ethereum address of the plan contract to be withdrawn

amount

string

the amount to be approved

callback?

invoked with the transaction hash when it becomes available, normally much earlier than the function completion

Returns: Promise‹void›

cancelSubscription

▸ cancelSubscription(address: string, subscriber: string, callback?: TransactionCallback): Promise‹IEthBalanceEvent[]›

Cancels the subscriber in the given plan

Parameters:

Name

Type

Description

address

string

the address of the contract to be updated

subscriber

string

the address of the subscriber to be cancelled

callback?

invoked with the transaction hash when it becomes available, normally much earlier than the function completion

Returns: Promise‹IEthBalanceEvent[]›

a collection of BalanceEventType with details about the transaction

consumePlan

▸ consumePlan(address: string, feature: string, quantity: string, subscriber: string, bucket: string, callback?: TransactionCallback): Promise‹IEthBalanceEvent[]›

Consumes a feature for a certain quantity. When this method is invoked, the smart contract records the consumption event and records any token transfers to the related merchants according to pricing configuration in the contract. The tokens remain in the contract and become available for withdrawal by the merchant(s).

Parameters:

Name

Type

Default

Description

address

string

-

the ethereum address of the plan contract to be withdrawn

feature

string

-

the code of the feature to be consumed

quantity

string

-

the quantity to be consumed

subscriber

string

-

the address of the subscriber consuming the feature

bucket

string

""

an identifier for a transaction bucket. Transactions in the same bucket will have their quantities aggregated for purposes for tiered pricing. For example, if a feature has a price of $0 for the first 100 units in a given calendar month you can use a bucket formatted as YYYY-MM (e.g. "2020-07"). All transactions with this bucket are aggregated. If a subscriber has one consumption with quantity = 60 and a second with quantity = 50 and both have a bucket = "2020-07", then the second transaction will only have 10 units priced. If you want the tiers to apply only within the transaction you can leave the bucket empty. A common pattern is to set the bucket to the result of getSubscriptionPeriodForDate, which allows tiers to be aligned with the subscriber's subscription cycle.

callback?

-

invoked with the transaction hash when it becomes available, normally much earlier than the function completion

Returns: Promise‹IEthBalanceEvent[]›

a collection of BalanceEventType with details about the transaction

contractFromPlan

â–¸ contractFromPlan(plan: IPlan, token: IEthToken, addressMap: object, address?: undefined | string): IEthPlan

Parameters:

Name

Type

Description

plan

the IPlan from the Tepui registry

token

the configuration for the token associated with the plan

addressMap

object

an object that maps registry ids to ethereum addressses. The ids for operators and connectedPlans need to be included in this map or they will be omitted from the returned IEthPlan

address?

undefined | string

an address that will be set in the returned IEthPlan

Returns: IEthPlan

an ethereum plan that can be used to deploy a smart contract

createPlan

▸ createPlan(contract: IEthPlan, callback?: TransactionCallback): Promise‹string›

Deploys a new plan smart contract in the Ethereum blockchain

Parameters:

Name

Type

Description

contract

the plan to be created

callback?

invoked with the transaction hash when it becomes available, normally much earlier than the function completion

Returns: Promise‹string›

the address of the new contract after mining completes

getAddressMap

▸ getAddressMap(transactionMap: object): Promise‹object›

Parameters:

Name

Type

Description

transactionMap

object

an object map where the keys are identifiers and the values contain a list of transactions

Returns: Promise‹object›

a map where the keys are the identifiers from transactionMap and the values are a resolved contract address from the provided transactions. Only the address of the first transaction that is valid in the current blockchain network is returned.

getBalance

▸ getBalance(tokenAddress: string, accountAddress: string): Promise‹string›

Parameters:

Name

Type

Description

tokenAddress

string

the ethereum address of the token

accountAddress

string

the ethereum address of the account

Returns: Promise‹string›

the balance of a given ethereum account for a given ERC20 token

getBlockTimestamps

▸ getBlockTimestamps(events: EventData[]): Promise‹object›

Parameters:

Name

Type

Description

events

EventData[]

a list of contract events extracted from a blockchain

Returns: Promise‹object›

a mapping of the timestamps for any blocks referenced in the events provided. This is useful to quickly determine the actual time when a given event was mined.

getConsumedTimeSpans

▸ getConsumedTimeSpans(subscription: IEthSubscription): Promise‹ITimeSpan[] | undefined›

Parameters:

Name

Type

Description

subscription

the subscription to be queried

Returns: Promise‹ITimeSpan[] | undefined›

the consumption events associated with recurring charges

Remarks*

The timespans can be added to the subscription start date to determine the subscription expiration date. The expiration date indicates when the current subscription is set to end, assuming that the subscriber does not fund it. For example, if a subscriber signs up to an annual plan on June 25, 2020 then the expiration date will be June 25, 2021. The Tepui processor alerts subscribers as their expiration date approaches if the do not have sufficient funds to extend the subscription. When the subscription is renewed, its expiration date is extended another period (in this example, to June 25, 2022). If the subscriber does not renew, the expiration date does not change.

getNetworkId

▸ getNetworkId(): Promise‹number›

The ethereum network id

Returns: Promise‹number›

getPastEvents

▸ getPastEvents(address: string, event: EventType | "allEvents", account?: undefined | string, fromBlock: number): Promise‹EventData[]›

Parameters:

Name

Type

Default

Description

address

string

-

the address of the contract to be queried

event

EventType | "allEvents"

-

the type of events to be returned

account?

undefined | string

-

the address of the subscriber whose events

fromBlock

number

0

-

Returns: Promise‹EventData[]›

a list of events from a plan contract. This can be used to poll for new subscriptions or consumptions and perform provisioning of services.

getSubscriptionPeriodForDate

▸ getSubscriptionPeriodForDate(subscription: IEthSubscription, date: Date): Promise‹IPeriod | undefined›

Parameters:

Name

Type

Description

subscription

the subscription to be queries

date

Date

the event date used to determine the appropriate period

Returns: Promise‹IPeriod | undefined›

the subscription period containing a given date This function is useful to determine a tier bucket for an event occurring on a certain date

getSubscriptions

▸ getSubscriptions(address: string): Promise‹IEthSubscription[]›

Parameters:

Name

Type

Description

address

string

the address of the contract to be queried

Returns: Promise‹IEthSubscription[]›

all the subscriptions for a given plan contract

price

▸ price(address: string, subscriber: string, feature: string, quantity: string, bucket: string): Promise‹string›

Parameters:

Name

Type

Default

Description

address

string

-

the address of the plan contract

subscriber

string

-

the address of the subscriber to be priced

feature

string

-

the code of the feature to be priced

quantity

string

-

the quantity to be priced

bucket

string

""

an identifier for a transaction bucket. Transactions in the same bucket will have their quantities aggregated for purposes for tiered pricing. For example, if a feature has a price of $0 for the first 100 units in a given calendar month you can use a bucket formatted as YYYY-MM (e.g. "2020-07"). All transactions with this bucket are aggregated. If a subscriber has one consumption with quantity = 60 and a second with quantity = 50 and both have a bucket = "2020-07", then the second transaction will only have 10 units priced. If you want the tiers to apply only within the transaction you can leave the bucket empty. A common pattern is to set the bucket to the result of getSubscriptionPeriodForDate, which allows tiers to be aligned with the subscriber's subscription cycle.

Returns: Promise‹string›

the total amount that would be consumed for a given feature and quantity. This is similar to priceFeature, but it is used for an existing subscriber. The pricing calculation considers other consumption that the customer had for the bucket.

priceFeature

▸ priceFeature(address: string, feature: string, quantity: string, start: string): Promise‹IEthAmountTier[]›

Parameters:

Name

Type

Default

Description

address

string

-

the address of the plan contract

feature

string

-

the code of the feature to be priced

quantity

string

-

the quantity to be priced

start

string

"0"

-

Returns: Promise‹IEthAmountTier[]›

the total amount that would be consumed for a given feature and quantity, with a given tier start quantity. This operation is useful to offer a quote to a user before a consumption actually occurs. The amount returned is an integer with implied decimals based on the token used by the contract. You can invoke toDisplayAmount to obtain an amount with decimals that can be shown to a user.

recoverAddressFromSignature

▸ recoverAddressFromSignature(payload: string, signature: string): Promise‹string›

Recovers signer's ethereum address from a signature

Parameters:

Name

Type

Description

payload

string

the original data that was signed

signature

string

the signature to be used to recover the signing address

Returns: Promise‹string›

the ethereum address of the signer

retrieveContract

▸ retrieveContract(address: string): Promise‹IEthPlan›

The state of a plan contract in the blockchain

Parameters:

Name

Type

Description

address

string

the address of the plan to be returned

Returns: Promise‹IEthPlan›

retrieveContractAddress

▸ retrieveContractAddress(hash: string): Promise‹string | undefined›

Parameters:

Name

Type

Description

hash

string

the hash of the transaction used to either create the contract, or to interact with it

Returns: Promise‹string | undefined›

the address of a contract

retrieveContractToken

▸ retrieveContractToken(address: string): Promise‹IToken›

Parameters:

Name

Type

Description

address

string

the address of the plan to be queried

Returns: Promise‹IToken›

the token for a give plan contract

retrievePlanSubscriberCount

▸ retrievePlanSubscriberCount(address: string): Promise‹number›

Parameters:

Name

Type

Description

address

string

the address of the plan contract

Returns: Promise‹number›

the total number of subscribers for the plan

retrieveSubscriber

▸ retrieveSubscriber(address: string, index: number): Promise‹string›

Parameters:

Name

Type

Description

address

string

the plan contract to be queried

index

number

the index of the subscriber to be returned

Returns: Promise‹string›

the ethereum address of a subscriber at a given index

retrieveSubscription

▸ retrieveSubscription(address: string, subscriber: string): Promise‹IEthSubscription | undefined›

Parameters:

Name

Type

Description

address

string

the ethereum address for the contract

subscriber

string

the subscriber address

Returns: Promise‹IEthSubscription | undefined›

the subscription details for a given subscriber in a given plan, or undefined if it does not exist

retrieveToken

▸ retrieveToken(address: string): Promise‹IToken›

Retrieves an ethereum ERC20 token properties from the blockchain

Parameters:

Name

Type

Description

address

string

the contract address for the ERC20 token

Returns: Promise‹IToken›

signPayload

▸ signPayload(dataToSign: string): Promise‹string›

Signs the given payload with a digital signature for the default address. On a browser, the user will be prompted to confirm the signature by the wallet provider.

Parameters:

Name

Type

Description

dataToSign

string

the data to be signed

Returns: Promise‹string›

the signature for the provided data

subscribe

▸ subscribe(subscription: IEthSubscription, contract: IEthPlan, amount: string, callback?: TransactionCallback): Promise‹IEthBalanceEvent[]›

Creates or updates a subscription for the given plan in the blockchain. If this is a new subscription and the plan a cycle, the first period is consumed immediately. If the subscription already exists, its properties are updated but no consumption occurs.

throws if the amount is insufficient to pay for the initial consumption

Parameters:

Name

Type

Description

subscription

the details of the subscription

contract

the ethereum address of the plan contract to be subscribed

amount

string

the token amount entered by the subscriber

callback?

invoked with the transaction hash when it becomes available, normally much earlier than the function completion

Returns: Promise‹IEthBalanceEvent[]›

a collection of BalanceEventType with details about any consumption

sumAmounts

â–¸ sumAmounts(events: IEthBalanceEvent[], contract: string, subscriber: string, eventTypes: BalanceEventType | BalanceEventType[]): any

Parameters:

Name

Type

Description

events

balance events to be queried

contract

string

filters for a specific contract address

subscriber

string

filters for a specific subscriber address

eventTypes

filters for event types

Returns: any

the total amount from the events provided

toDisplayAmount

â–¸ toDisplayAmount(amount: string | number, __namedParameters: object): string

Converts an amount without decimals (typically coming from blockchain) to an appropriate amount with decimals that can be displayed to an end user.

Remarks

All amounts are strings since blockchain amounts can be very large numbers and regular javascript numbers would result in overflow errors

Parameters:

â–ª amount: string | number

the amount without decimals to be converted. e.g. "10250000"

â–ª __namedParameters: object

Name

Type

decimals

number

Returns: string

an amount without decimals that can be shown to a user e.g. "10.25"

toTokenAmount

â–¸ toTokenAmount(amount: string | number, __namedParameters: object): string

Converts an amount with decimals to an appropriate amount without decimals that can be used in blockchain operations.

Remarks

All amounts are strings since blockchain amounts can be very large numbers and regular javascript numbers would result in overflow errors

Parameters:

â–ª amount: string | number

the amount with decimals to be converted. e.g. "10.25"

â–ª __namedParameters: object

Name

Type

decimals

number

Returns: string

an amount without decimals that can be submitted to the blockchaing e.g. "10250000"

updatePlan

▸ updatePlan(plan: IEthPlan, callback?: TransactionCallback): Promise‹void›

Updates the properties of the smart contract in the Ethereum blockchain

Parameters:

Name

Type

Description

plan

the plan to be created

callback?

invoked with the transaction hash when it becomes available, normally much earlier than the function completion

Returns: Promise‹void›

withdrawPlan

▸ withdrawPlan(address: string, callback?: TransactionCallback): Promise‹IEthBalanceEvent[]›

Withdraws any consumed tokens from the contract and sends them to the merchant address. Merchants invoke this method to collect their revenue.

Parameters:

Name

Type

Description

address

string

the ethereum address of the plan contract to be withdrawn

callback?

invoked with the transaction hash when it becomes available, normally much earlier than the function completion

Returns: Promise‹IEthBalanceEvent[]›

a collection of BalanceEventType with details about the transaction

Static init

▸ init(web3: Web3): Promise‹TepuiEthereumClient›

Initialize and return a new TepuiEthereumClient

Parameters:

Name

Type

Description

web3

Web3

a Web3 object that has been initialized with a wallet provider.

Returns: Promise‹TepuiEthereumClient›

Last updated

Was this helpful?