Skip to content
This repository was archived by the owner on Mar 11, 2025. It is now read-only.

chore: Refactored Sygma Widget using @buildwithsygma/v3 #219

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 12 additions & 15 deletions packages/widget/index.html
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="src/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sygma Widget</title>
<script type="module" src="/src/index.ts"></script>
</head>

<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="src/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sygma Widget</title>
<script type="module" src="/src/index.ts"></script>
</head>

<body>
<sygmaprotocol-widget>
</sygmaprotocol-widget>
</body>

</html>
<body>
<sygmaprotocol-widget environment="testnet"></sygmaprotocol-widget>
</body>
</html>
8 changes: 4 additions & 4 deletions packages/widget/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@
},
"author": "Sygmaprotocol Product Team",
"dependencies": {
"@buildwithsygma/core": "^1.3.1",
"@buildwithsygma/evm": "^1.4.1",
"@buildwithsygma/substrate": "^1.0.4",
"@buildwithsygma/sygma-contracts": "^2.5.1",
"@buildwithsygma/sygma-sdk-core": "^2.10.0",
"@ethersproject/abstract-signer": "^5.7.0",
"@ethersproject/contracts": "^5.7.0",
"@ethersproject/providers": "^5.7.2",
"@ethersproject/transactions": "^5.7.0",
"@buildwithsygma/utils": "^1.2.1",
"@lit/context": "^1.1.0",
"@lit/reactive-element": "^2.0.3",
"@polkadot-onboard/core": "^1.1.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Domain } from '@buildwithsygma/sygma-sdk-core';
import type { Domain } from '@buildwithsygma/core';
import { consume } from '@lit/context';
import type { HTMLTemplateResult, PropertyValues, TemplateResult } from 'lit';
import { html } from 'lit';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,17 @@
import {
Network,
type EthereumConfig,
type Resource,
type SubstrateConfig
} from '@buildwithsygma/sygma-sdk-core';
import { type Resource } from '@buildwithsygma/sygma-sdk-core';
import type { PropertyValues } from '@lit/reactive-element';
import { BigNumber, utils } from 'ethers';
import type { HTMLTemplateResult, PropertyDeclaration } from 'lit';
import { html } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';
import { customElement, property } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { when } from 'lit/directives/when.js';
import { networkIconsMap } from '../../assets';
import { DEFAULT_ETH_DECIMALS, INPUT_DEBOUNCE_TIME } from '../../constants';
import {
BALANCE_UPDATE_KEY,
TokenBalanceController
} from '../../controllers/wallet-manager/token-balance';
import { tokenBalanceToNumber } from '../../utils/token';
import type { DropdownOption } from '../common/dropdown/dropdown';
import { BaseComponent } from '../common/base-component';
import { debounce } from '../../utils';
import { styles } from './styles';
import { EthereumConfig, SubstrateConfig } from '@buildwithsygma/core';
import { BigNumber } from 'ethers';
import { tokenBalanceToNumber } from '../../utils/token';

@customElement('sygma-resource-amount-selector')
export class ResourceAmountSelector extends BaseComponent {
Expand All @@ -37,125 +27,45 @@ export class ResourceAmountSelector extends BaseComponent {
preselectedToken?: string;

@property({ attribute: false })
/**
* amount is in the lowest denomination (it's up to parent component to get resource decimals)
*/
onResourceSelected: (resource: Resource, amount: BigNumber) => void =
() => {};
onResourceSelected: (resource: Resource) => void = () => {};

@property({ attribute: false })
onAmountChanged: (amount: string) => void = () => {};

@property({ type: Object })
sourceDomainConfig?: EthereumConfig | SubstrateConfig;

@state() selectedResource: Resource | null = null;
@state() validationMessage: string | null = null;
@state() amount: string = '';
@property() selectedResource: Resource | null = null;
@property() validationMessage: string | null = null;
@property() amount: string = '';

tokenBalanceController = new TokenBalanceController(this);

_useMaxBalance = (): void => {
this.amount = tokenBalanceToNumber(
this.tokenBalanceController.balance,
this.tokenBalanceController.decimals
);
if (this.selectedResource) {
this.onResourceSelected(
this.selectedResource,
utils.parseUnits(
this.amount.toString(),
this.selectedResource.decimals ?? DEFAULT_ETH_DECIMALS
)
);
}
};

_onInputAmountChangeHandler = (value: string): void => {
if (value === '') {
value = '0';
}
try {
const amount = utils.parseUnits(
value,
this.tokenBalanceController.decimals
);
this.amount = value;
if (!this._validateAmount(value)) return;
if (this.selectedResource) {
this.onResourceSelected(this.selectedResource, BigNumber.from(amount));
}
} catch (error) {
this.validationMessage = 'Invalid amount value';
}
};

debouncedHandler = debounce(
this._onInputAmountChangeHandler,
INPUT_DEBOUNCE_TIME
);
@property() tokenBalance?: BigNumber;

requestUpdate(
name?: PropertyKey,
oldValue?: unknown,
options?: PropertyDeclaration<unknown, unknown>
): void {
super.requestUpdate(name, oldValue, options);
if (name === BALANCE_UPDATE_KEY) {
this._validateAmount(String(this.amount));
}
}

_onResourceSelectedHandler = (option?: DropdownOption<Resource>): void => {
if (option) {
this.selectedResource = option.value;
this.amount = '';
this.tokenBalanceController.startBalanceUpdates(
this.selectedResource,
this.sourceDomainConfig?.type === Network.SUBSTRATE
? this.sourceDomainConfig
: undefined
);
} else {
this.selectedResource = null;
this.tokenBalanceController.resetBalance();
}
};

_validateAmount(amount: string): boolean {
if (amount === '') {
amount = '0';
}
try {
const parsedAmount = utils.parseUnits(
amount,
this.tokenBalanceController.decimals
);

if (parsedAmount.lte(BigNumber.from(0))) {
this.validationMessage = 'Amount must be greater than 0';
return false;
}

if (parsedAmount.gt(this.tokenBalanceController.balance)) {
this.validationMessage = 'Amount exceeds account balance';
return false;
}

this.validationMessage = null;
return true;
} catch (error) {
this.validationMessage = 'Invalid amount value';
return false;
_renderAccountBalance(): HTMLTemplateResult {
if (this.tokenBalance && this.selectedResource) {
return html`
<section class="balanceContent">
<span
>${tokenBalanceToNumber(
this.tokenBalance,
this.selectedResource.decimals!,
4
)}</span
>
<button class="maxButton">Max</button>
</section>
`;
}
}

_renderAccountBalance(): HTMLTemplateResult {
return html`
<section class="balanceContent">
<span
>${`${tokenBalanceToNumber(this.tokenBalanceController.balance, this.tokenBalanceController.decimals, 4)}`}</span
>
<button class="maxButton" @click=${this._useMaxBalance}>Max</button>
</section>
`;
return html``;
}

_renderErrorMessages(): HTMLTemplateResult {
Expand All @@ -180,8 +90,7 @@ export class ResourceAmountSelector extends BaseComponent {
updated(changedProperties: PropertyValues<this>): void {
if (changedProperties.has('selectedResource')) {
if (changedProperties.get('selectedResource') !== null) {
this.tokenBalanceController.resetBalance();
this.amount = '';
this.onAmountChanged('');
}
}
}
Expand All @@ -204,17 +113,17 @@ export class ResourceAmountSelector extends BaseComponent {
type="number"
class="amountSelectorInput"
placeholder="0.000"
@input=${(event: Event) => {
this.debouncedHandler((event.target as HTMLInputElement).value);
}}
@input=${(evt: Event) =>
this.onAmountChanged((evt.target as HTMLInputElement).value)}
.disabled=${this.disabled}
.value=${this.amount}
/>
<section class="selectorSection">
<dropdown-component
.placeholder=${'Select token'}
?disabled=${this.disabled}
.onOptionSelected=${this._onResourceSelectedHandler}
.onOptionSelected=${(item: DropdownOption<Resource>) =>
this.onResourceSelected(item.value)}
.options=${this._normalizeOptions()}
></dropdown-component>
</section>
Expand Down
Loading
Loading